text:
package nl.ulso.magisto.io;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;

import static nl.ulso.magisto.io.FileSystemTestRunner.WORKING_DIRECTORY;
import static nl.ulso.magisto.io.FileSystemTestRunner.runFileSystemTest;
import static nl.ulso.magisto.io.Paths.createPath;
import static org.junit.Assert.*;

public class RealFileSystemTest {

    private final FileSystem fileSystem = new RealFileSystem();

    @Test
    public void testSourceDirectoryWithJavaCurrentWorkingDirectory() throws Exception {
        final Path expected = WORKING_DIRECTORY;
        final Path actual = fileSystem.resolveSourceDirectory(System.getProperty("user.dir"));
        assertEquals(expected, actual);
    }

    @Test(expected = NoSuchFileException.class)
    public void testSourceDirectoryExceptionForNonExistingDirectory() throws Exception {
        fileSystem.resolveSourceDirectory("foo");
    }

    @Test
    public void testResolvedSourceDirectoryIsRealPath() throws Exception {
        final Path expected = WORKING_DIRECTORY.resolve("src");
        final Path actual = fileSystem.resolveSourceDirectory("src");
        assertEquals(expected.toString(), actual.toString());
    }

    @Test(expected = IOException.class)
    public void testSourceDirectoryIsDirectory() throws Exception {
        fileSystem.resolveSourceDirectory("pom.xml");
    }

    @Test(expected = IOException.class)
    public void testSourceDirectoryIsReadable() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                // Make the directory unreadable
                Files.setPosixFilePermissions(path, Collections.<PosixFilePermission>emptySet());
            }

            @Override
            public void runTest(Path path) throws IOException {
                // IOException expected, since directory is not readable
                fileSystem.resolveSourceDirectory(path.toString());
            }
        });
    }

    @Test
    public void testTargetDirectoryWithNonExistingDirectoryIsRealPath() throws Exception {
        runFileSystemTest(new FileSystemTestWithoutTempDirectory() {
            @Override
            public void runTest(Path path) throws IOException {
                final Path actual = fileSystem.prepareTargetDirectory(path.toString());
                assertEquals(path.toString(), actual.toString());
            }
        });
    }

    @Test
    public void testTargetDirectoryWithExistingDirectoryIsRealPath() throws Exception {
        runFileSystemTest(new FileSystemTestWithEmptyTempDirectory() {
            @Override
            public void runTest(Path path) throws IOException {
                final Path actual = fileSystem.prepareTargetDirectory(path.toString());
                assertEquals(path.toString(), actual.toString());
            }
        });
    }

    @Test(expected = IOException.class)
    public void testTargetDirectoryIsDirectory() throws Exception {
        fileSystem.prepareTargetDirectory("pom.xml");
    }

    @Test(expected = IOException.class)
    public void testTargetDirectoryIsWritable() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.setPosixFilePermissions(path, Collections.<PosixFilePermission>emptySet());
            }

            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.prepareTargetDirectory(path.toString());
            }
        });
    }

    @Test(expected = IOException.class)
    public void testTargetDirectoryMustBeEmpty() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createFile(path.resolve("foo"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.prepareTargetDirectory(path.toString());
            }
        });
    }

    @Test
    public void testTargetDirectoryMustBeEmptyUnlessItIsAnExport() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createFile(path.resolve("foo"));
                Files.createFile(path.resolve(FileSystem.MAGISTO_EXPORT_MARKER_FILE));
            }

            @Override
            public void runTest(Path path) throws IOException {
                assertNotNull(fileSystem.prepareTargetDirectory(path.toString()));
            }
        });
    }

    @Test(expected = IOException.class)
    public void testTargetDirectoryContainsDirectory() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createDirectory(path.resolve("foo"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                assertNotNull(fileSystem.prepareTargetDirectory(path.toString()));
            }
        });
    }

    @Test
    public void testFindAllPaths() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createFile(path.resolve("foo"));
                Files.createDirectory(path.resolve("bar"));
                Files.createFile(path.resolve("bar").resolve("baz"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                final SortedSet<Path> paths = fileSystem.findAllPaths(path);
                assertEquals(3, paths.size());
                assertArrayEquals(new Path[]{
                        createPath("bar"),
                        createPath("bar", "baz"),
                        createPath("foo")}, paths.toArray());
            }
        });
    }

    @Test
    public void testSourceAndTargetDoNotOverlap() throws Exception {
        final Path source = WORKING_DIRECTORY.resolve("foo");
        final Path target = WORKING_DIRECTORY.resolve("bar");
        fileSystem.requireDistinct(source, target);
    }

    @Test(expected = IOException.class)
    public void testSourceInsideTarget() throws Exception {
        final Path source = WORKING_DIRECTORY.resolve("bar").resolve("foo");
        final Path target = WORKING_DIRECTORY.resolve("bar");
        fileSystem.requireDistinct(source, target);
    }

    @Test(expected = IOException.class)
    public void testTargetInsideSource() throws Exception {
        final Path source = WORKING_DIRECTORY.resolve("foo");
        final Path target = WORKING_DIRECTORY.resolve("foo").resolve("bar");
        fileSystem.requireDistinct(source, target);
    }

    @Test
    public void testTouchFileIsWritten() throws Exception {
        runFileSystemTest(new FileSystemTestWithEmptyTempDirectory() {
            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.writeTouchFile(path);
                assertTrue(Files.exists(resolveTouchFile(path)));
            }
        });
    }

    @Test
    public void testTouchFileIsReplaced() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createFile(resolveTouchFile(path));
            }

            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.writeTouchFile(path);
                assertTrue(Files.exists(resolveTouchFile(path)));
            }
        });
    }

    @Test
    public void testLastModified() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {

            private long now;

            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                now = System.currentTimeMillis() / 1000; // At least on OS X granularity is at seconds.
                Files.createFile(path.resolve("target"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                final long lastModifiedInMillis = fileSystem.getLastModifiedInMillis(path.resolve("target"));
                System.out.println("now = " + now);
                System.out.println("lastModifiedInMillis = " + lastModifiedInMillis);
                assertTrue(lastModifiedInMillis / 1000 >= now);
            }
        });
    }

    @Test
    public void testHiddenFilesAreSkipped() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createDirectory(path.resolve(".tmpdir"));
                Files.createFile(path.resolve(".tmpdir").resolve("file"));
                Files.createFile(path.resolve(".tmpfile"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                assertEquals(0, fileSystem.findAllPaths(path).size());
            }
        });
    }

    @Test
    public void testPathCopy() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {

            private Path source;
            private Path target;

            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                this.source = path.resolve("source");
                this.target = path.resolve("target");
                Files.createDirectory(source);
                Files.createFile(source.resolve("file"));
                Files.createDirectory(source.resolve("directory"));
                Files.createFile(source.resolve("directory").resolve("file"));
                Files.createDirectory(target);
            }

            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.copy(source, target, createPath("file"));
                fileSystem.copy(source, target, createPath("directory"));
                fileSystem.copy(source, target, createPath("directory").resolve("file"));
                // Bad test, it depends on code that's under test itself:
                assertEquals(3, fileSystem.findAllPaths(path.resolve("target")).size());
            }
        });
    }

    @Test
    public void testPathDelete() throws Exception {
        runFileSystemTest(new FileSystemTestWithPreparedDirectory() {
            @Override
            public void prepareTempDirectory(Path path) throws IOException {
                Files.createFile(path.resolve("file"));
                Files.createDirectory(path.resolve("directory"));
            }

            @Override
            public void runTest(Path path) throws IOException {
                fileSystem.delete(path, createPath("file"));
                fileSystem.delete(path, createPath("directory"));
                // Bad test, it depends on code that's under test itself:
                assertEquals(0, fileSystem.findAllPaths(path).size());
            }
        });
    }

    @Test
    public void testBufferedReaderForTextFile() throws Exception {
        final Path textFile = WORKING_DIRECTORY.resolve("README.md");
        final String line;
        try (final BufferedReader bufferedReader = fileSystem.newBufferedReaderForTextFile(textFile)) {
            line = bufferedReader.readLine();
        }
        assertEquals("# Magisto", line);
    }

    @Test
    public void testBufferedWriterForTextFile() throws Exception {
        runFileSystemTest(new FileSystemTestWithEmptyTempDirectory() {
            @Override
            public void runTest(Path path) throws IOException {
                final Path textFile = path.resolve("test.md");
                try (final BufferedWriter writer = fileSystem.newBufferedWriterForTextFile(textFile)) {
                    writer.write("# Test");
                }
                assertTrue(Files.exists(textFile));
                final List<String> strings = Files.readAllLines(textFile, Charset.forName("UTF-8"));
                assertEquals(1, strings.size());
                assertEquals("# Test", strings.get(0));
            }
        });
    }

    private Path resolveTouchFile(Path path) {
        return path.resolve(FileSystem.MAGISTO_EXPORT_MARKER_FILE);
    }
}


text:
import json

from django import forms
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _

from wagtail.admin.staticfiles import versioned_static
from wagtail.admin.widgets import AdminChooser
from wagtail.documents import get_document_model

class AdminDocumentChooser(AdminChooser):
    choose_one_text = _('Choose a document')
    choose_another_text = _('Choose another document')
    link_to_chosen_text = _('Edit this document')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.document_model = get_document_model()

    def render_html(self, name, value, attrs):
        instance, value = self.get_instance_and_id(self.document_model, value)
        original_field_html = super().render_html(name, value, attrs)

        return render_to_string("wagtaildocs/widgets/document_chooser.html", {
            'widget': self,
            'original_field_html': original_field_html,
            'attrs': attrs,
            'value': value,
            'document': instance,
        })

    def render_js_init(self, id_, name, value):
        return "createDocumentChooser({0});".format(json.dumps(id_))

    @property
    def media(self):
        return forms.Media(js=[
            versioned_static('wagtaildocs/js/document-chooser-modal.js'),
            versioned_static('wagtaildocs/js/document-chooser.js'),
        ])

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="Value Path" >
        <ListPreference
            android:entries="@array/battery_valuepaths"
            android:entryValues="@array/battery_valuepaths"
            android:key="valuepath"
            android:summary="Select a Value Path"
            android:title="Value Path" />
    </PreferenceCategory>

</PreferenceScreen>


text:
package org.wildfly.camel.examples.activemq;

import java.io.File;
import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/orders/{country}")
public class OrdersResource {

    @GET
    public String get(@PathParam("country") String country) throws IOException {
		File datadir = new File(System.getProperty("jboss.server.data.dir"));
		File countrydir = datadir.toPath().resolve("orders/processed/" + country).toFile();
		return country + ": " + countrydir.list().length;
	}
}


text:
(function() {

// This function is converted to a string and becomes the preprocessor
function preprocessor(source, url, listenerName) {
  url = url ? url : '(eval)';
  url += listenerName ? '_' + listenerName : '';
  var prefix = 'window.__preprocessed = window.__preprocessed || [];\n';
  prefix += 'window.__preprocessed.push(\'' + url +'\');\n';
  var postfix = '\n//# sourceURL=' + url + '.js\n';
  return prefix + source + postfix;
}

function extractPreprocessedFiles(onExtracted) {
  var expr = 'window.__preprocessed';
  function onEval(files, isException) {
    if (isException)
      throw new Error('Eval failed for ' + expr, isException.value);
    onExtracted(files);
  }
  chrome.devtools.inspectedWindow.eval(expr, onEval);
}

function reloadWithPreprocessor(injectedScript) {
  var options = {
    ignoreCache: true,
    userAgent: undefined,
    injectedScript: '(' + injectedScript  + ')()',
    preprocessingScript: '(' + preprocessor + ')'
  };
  chrome.devtools.inspectedWindow.reload(options);
}

function demoPreprocessor() {
  function onLoaded() {
    extractPreprocessedFiles(updateUI);
  }
  var loadMonitor = new InspectedWindow.LoadMonitor(onLoaded);
  reloadWithPreprocessor(loadMonitor.injectedScript);
}

function listen() {
  var reloadButton = document.querySelector('.reload-button');
  reloadButton.addEventListener('click', demoPreprocessor);
}

window.addEventListener('load', listen);

function createRow(url) {
  var li = document.createElement('li');
  li.textContent = url;
  return li;
}

function updateUI(preprocessedFiles) {
  var rowContainer = document.querySelector('.js-preprocessed-urls');
  rowContainer.innerHTML = '';
  preprocessedFiles.forEach(function(url) {
    rowContainer.appendChild(createRow(url));
  });
}

})();


text:
@implementation ATLTravelSection

#pragma mark - Relations of the section

- (ATLVisit *)origin
{
    return (ATLVisit*)self.previousElement;
}

- (void)updateOrigin
{
    //empty: to be implemented in subclasses
}

- (ATLVisit *)destination
{
    return (ATLVisit*)self.nextElement;
}

- (void)updateDestination
{
    //empty: to be implemented in subclasses
}

- (BOOL)canSelectLocation:(ATLStation *)location
{
    return NO;
}

- (void)selectDestination:(ATLVisit *)destination At:(NSDate*)timestamp
{
    [self.journey addVisit:destination atIndex:(self.order + 1) / 2];
}

- (NSDate *)timeOfDeparture
{
    return self.origin.timeOfDeparture;
}

- (void)setTimeOfDeparture:(NSDate *)timeOfDeparture
{
    self.origin.timeOfDeparture = timeOfDeparture;
}

- (NSDate *)timeOfArrival
{
    return self.destination.timeOfArrival;
}

- (void)setTimeOfArrival:(NSDate *)timeOfArrival
{
    self.destination.timeOfArrival = timeOfArrival;
}

- (NSDate *)endTime
{
    return self.estimatedArrival;
}

- (NSArray *)visibleMissions
{
    // To be overwritten in subclasses
    return @[];
}

- (NSString *)serviceName
{
    return @"service";
}

@end


text:
<?php

namespace Assmat\DataSource\Repositories\Memory\Ligne\Templates\CongesPayes;

use Assmat\DataSource\Constants;
use Assmat\DataSource\Repositories\Memory\Ligne\Templates\AbstractTemplate;

class CpAcquis extends AbstractTemplate
{
    public function __construct()
    {
        parent::__construct();

        $this->ligneDTO->label = 'Congés payés aquis';
        $this->ligneDTO->typeId = Constants\Lignes\Type::CONGES_PAYES_ACQUIS;
        $this->ligneDTO->actionId = Constants\Lignes\Action::GAIN;
        $this->ligneDTO->contextId = Constants\Lignes\Context::CONGE_PAYE;
        $this->ligneDTO->quantite = 1;

        $this->ligneDTO->baseEditable = true;
    }
}


text:
Each line of Ruby you enter into a Pry session is recorded with a number in
the buffer history. Pry keeps this buffer history so that you can recall
parts of it for editing and subsequent execution.

If you use the `edit` command by itself, Pry will open the previous Ruby
statement in your default editor. But what if you want to edit a statement
from a while back? Or even a series of statements?

Use the `--in` flag with `edit` either specifying a single record in the
buffer history or a range of records.

```ruby
$ pry
[1] pry(main)> puts "Hello"
Hello
=> nil
[2] pry(main)> puts "World"
World
=> nil
[3] pry(main)> puts "People"
People
=> nil
[4] pry(main)> edit --in 1..2
Hello
World
=> nil
```


text:
package org.usergrid.rest.applications;

import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.usergrid.rest.exceptions.SecurityException.mappableSecurityException;
import static org.usergrid.security.oauth.ClientCredentialsInfo.getUUIDFromClientId;
import static org.usergrid.security.shiro.utils.SubjectUtils.isApplicationAdmin;
import static org.usergrid.services.ServiceParameter.addParameter;
import static org.usergrid.utils.StringUtils.stringOrSubstringAfterFirst;
import static org.usergrid.utils.StringUtils.stringOrSubstringBeforeFirst;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.amber.oauth2.common.error.OAuthError;
import org.apache.amber.oauth2.common.exception.OAuthProblemException;
import org.apache.amber.oauth2.common.message.OAuthResponse;
import org.apache.amber.oauth2.common.message.types.GrantType;
import org.apache.commons.lang.NotImplementedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.codec.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.usergrid.management.ApplicationInfo;
import org.usergrid.management.exceptions.DisabledAdminUserException;
import org.usergrid.management.exceptions.DisabledAppUserException;
import org.usergrid.management.exceptions.UnactivatedAdminUserException;
import org.usergrid.management.exceptions.UnactivatedAppUserException;
import org.usergrid.mq.QueueManager;
import org.usergrid.persistence.EntityManager;
import org.usergrid.persistence.Identifier;
import org.usergrid.persistence.SimpleEntityRef;
import org.usergrid.persistence.entities.Application;
import org.usergrid.persistence.entities.User;
import org.usergrid.rest.AbstractContextResource;
import org.usergrid.rest.applications.assets.AssetsResource;
import org.usergrid.rest.applications.events.EventsResource;
import org.usergrid.rest.applications.queues.QueueResource;
import org.usergrid.rest.applications.users.UsersResource;
import org.usergrid.rest.exceptions.AuthErrorInfo;
import org.usergrid.rest.exceptions.RedirectionException;
import org.usergrid.rest.security.annotations.RequireApplicationAccess;
import org.usergrid.security.oauth.AccessInfo;
import org.usergrid.security.oauth.ClientCredentialsInfo;

import com.sun.jersey.api.json.JSONWithPadding;
import com.sun.jersey.api.view.Viewable;

@Component("org.usergrid.rest.applications.ApplicationResource")
@Scope("prototype")
@Produces({ MediaType.APPLICATION_JSON, "application/javascript",
	"application/x-javascript", "text/ecmascript",
	"application/ecmascript", "text/jscript" })
public class ApplicationResource extends ServiceResource {

	public static final Logger logger = LoggerFactory
			.getLogger(ApplicationResource.class);

	UUID applicationId;
	QueueManager queues;

	public ApplicationResource() {
	}

	public ApplicationResource init(UUID applicationId) throws Exception {
		this.applicationId = applicationId;
		services = smf.getServiceManager(applicationId);
		queues = qmf.getQueueManager(applicationId);
		return this;
	}

	public QueueManager getQueues() {
		return queues;
	}

	@Override
	public UUID getApplicationId() {
		return applicationId;
	}

	@Path("auth")
	public AuthResource getAuthResource() throws Exception {
		return getSubResource(AuthResource.class);
	}

	@RequireApplicationAccess
	@Path("queues")
	public QueueResource getQueueResource() throws Exception {
		return getSubResource(QueueResource.class).init(queues, "");
	}

	@RequireApplicationAccess
	@Path("events")
	public EventsResource getEventsResource(@Context UriInfo ui)
			throws Exception {
		addParameter(getServiceParameters(), "events");

		PathSegment ps = getFirstPathSegment("events");
		if (ps != null) {
			addMatrixParams(getServiceParameters(), ui, ps);
		}

		return getSubResource(EventsResource.class);
	}

	@RequireApplicationAccess
	@Path("event")
	public EventsResource getEventResource(@Context UriInfo ui)
			throws Exception {
		return getEventsResource(ui);
	}

	@RequireApplicationAccess
	@Path("assets")
	public AssetsResource getAssetsResource(@Context UriInfo ui)
			throws Exception {
		logger.debug("in assets n applicationResource");
		addParameter(getServiceParameters(), "assets");

		PathSegment ps = getFirstPathSegment("assets");
		if (ps != null) {
			addMatrixParams(getServiceParameters(), ui, ps);
		}

		return getSubResource(AssetsResource.class);
	}

	@RequireApplicationAccess
	@Path("asset")
	public AssetsResource getAssetResource(@Context UriInfo ui)
			throws Exception {
		// TODO change to singular
		logger.debug("in asset in applicationResource");
		return getAssetsResource(ui);
	}

	@Path("users")
	public UsersResource getUsers(@Context UriInfo ui) throws Exception {
		logger.debug("ApplicationResource.getUsers");
		addParameter(getServiceParameters(), "users");

		PathSegment ps = getFirstPathSegment("users");
		if (ps != null) {
			addMatrixParams(getServiceParameters(), ui, ps);
		}

		return getSubResource(UsersResource.class);
	}

	@Path("user")
	public UsersResource getUsers2(@Context UriInfo ui) throws Exception {
		return getUsers(ui);
	}

	@GET
	@Path("token")
	public Response getAccessToken(@Context UriInfo ui,
			@HeaderParam("Authorization") String authorization,
			@QueryParam("grant_type") String grant_type,
			@QueryParam("username") String username,
			@QueryParam("password") String password,
			@QueryParam("pin") String pin,
			@QueryParam("client_id") String client_id,
			@QueryParam("client_secret") String client_secret,
			@QueryParam("code") String code,
			@QueryParam("ttl") long ttl,
			@QueryParam("redirect_uri") String redirect_uri,
			@QueryParam("callback") @DefaultValue("") String callback)
					throws Exception {

		logger.debug("ApplicationResource.getAccessToken");

		User user = null;

		try {

			if (authorization != null) {
				String type = stringOrSubstringBeforeFirst(authorization, ' ')
						.toUpperCase();
				if ("BASIC".equals(type)) {
					String token = stringOrSubstringAfterFirst(authorization,
							' ');
					String[] values = Base64.decodeToString(token).split(":");
					if (values.length >= 2) {
						client_id = values[0];
						client_secret = values[1];
					}
				}
			}

			// do checking for different grant types
			String errorDescription = "invalid username or password";
			if (GrantType.PASSWORD.toString().equals(grant_type)) {
				try {
					user = management.verifyAppUserPasswordCredentials(
							services.getApplicationId(), username, password);
				} catch (UnactivatedAppUserException uaue) {
					errorDescription = "user not activated";
				} catch (DisabledAppUserException daue) {
					errorDescription = "user disabled";
				} catch (Exception e1) {
				}
			} else if ("pin".equals(grant_type)) {
				try {
					user = management.verifyAppUserPinCredentials(
							services.getApplicationId(), username, pin);
				} catch (Exception e1) {
				}
			} else if ("client_credentials".equals(grant_type)) {
				try {
					AccessInfo access_info = management.authorizeClient(
							client_id, client_secret, ttl);
					if (access_info != null) {
						return Response
								.status(SC_OK)
								.type(jsonMediaType(callback))
								.entity(wrapWithCallback(access_info, callback))
								.build();
					}
				} catch (Exception e1) {
				}
			} else if ("authorization_code".equals(grant_type)) {
				AccessInfo access_info = new AccessInfo();
				access_info.setAccessToken(code);
				return Response.status(SC_OK).type(jsonMediaType(callback))
						.entity(wrapWithCallback(access_info, callback))
						.build();
			}

			if (user == null) {
				OAuthResponse response = OAuthResponse
						.errorResponse(SC_BAD_REQUEST)
						.setError(OAuthError.TokenResponse.INVALID_GRANT)
						.setErrorDescription(errorDescription)
						.buildJSONMessage();
				return Response.status(response.getResponseStatus())
						.type(jsonMediaType(callback))
						.entity(wrapWithCallback(response.getBody(), callback))
						.build();
			}

			String token = management.getAccessTokenForAppUser(
					services.getApplicationId(), user.getUuid(), ttl);

			AccessInfo access_info = new AccessInfo()
			.withExpiresIn(tokens.getMaxTokenAgeInSeconds(token))
			.withAccessToken(token).withProperty("user", user);

			return Response.status(SC_OK).type(jsonMediaType(callback))
					.entity(wrapWithCallback(access_info, callback)).build();

		} catch (OAuthProblemException e) {
			logger.error("OAuth Error", e);
			OAuthResponse res = OAuthResponse.errorResponse(SC_BAD_REQUEST)
					.error(e).buildJSONMessage();
			return Response.status(res.getResponseStatus())
					.type(jsonMediaType(callback))
					.entity(wrapWithCallback(res.getBody(), callback)).build();
		}
	}

	@POST
	@Path("token")
	@Consumes(APPLICATION_FORM_URLENCODED)
	public Response getAccessTokenPost(@Context UriInfo ui,
			@HeaderParam("Authorization") String authorization,
			@FormParam("grant_type") String grant_type,
			@FormParam("username") String username,
			@FormParam("password") String password,
			@FormParam("pin") String pin,
			@FormParam("client_id") String client_id,
			@FormParam("client_secret") String client_secret,
			@FormParam("code") String code,
			@FormParam("ttl") long ttl,
			@FormParam("redirect_uri") String redirect_uri,
			@QueryParam("callback") @DefaultValue("") String callback)
					throws Exception {

		logger.debug("ApplicationResource.getAccessTokenPost");

		return getAccessToken(ui, authorization, grant_type, username, password, pin,
				client_id, client_secret, code, ttl, redirect_uri, callback);
	}

	@POST
	@Path("token")
	@Consumes(APPLICATION_JSON)
	public Response getAccessTokenPostJson(@Context UriInfo ui,
			@HeaderParam("Authorization") String authorization,
			Map<String, Object> json,
			@QueryParam("callback") @DefaultValue("") String callback)
					throws Exception {

		String grant_type = (String) json.get("grant_type");
		String username = (String) json.get("username");
		String password = (String) json.get("password");
		String client_id = (String) json.get("client_id");
		String client_secret = (String) json.get("client_secret");
		String pin = (String) json.get("pin");
		String code = (String) json.get("code");
		String redirect_uri = (String) json.get("redirect_uri");
		long ttl = 0;

		if (json.get("ttl") != null) {
			try {
				ttl = Long.parseLong(json.get("ttl").toString());
			} catch (NumberFormatException nfe) {
				throw new IllegalArgumentException("ttl must be a number >= 0");
			}
		}

		return getAccessToken(ui, authorization, grant_type, username, password, pin,
				client_id, client_secret, code, ttl, redirect_uri, callback);
	}

	@GET
	@Path("credentials")
	@RequireApplicationAccess
	public JSONWithPadding getKeys(@Context UriInfo ui,
			@QueryParam("callback") @DefaultValue("callback") String callback)
					throws Exception {

		logger.debug("AuthResource.keys");

		if (!isApplicationAdmin(Identifier.fromUUID(applicationId))) {
			throw new UnauthorizedException();
		}

		ClientCredentialsInfo kp = new ClientCredentialsInfo(
				management.getClientIdForApplication(services
						.getApplicationId()),
						management.getClientSecretForApplication(services
								.getApplicationId()));

		return new JSONWithPadding(createApiResponse().withCredentials(kp)
				.withAction("get application keys").withSuccess(), callback);
	}

	@POST
	@Path("credentials")
	@RequireApplicationAccess
	@Produces(MediaType.TEXT_HTML)
	public JSONWithPadding generateKeys(@Context UriInfo ui,
			@QueryParam("callback") @DefaultValue("callback") String callback)
					throws Exception {

		logger.debug("AuthResource.keys");

		if (!isApplicationAdmin(Identifier.fromUUID(applicationId))) {
			throw new UnauthorizedException();
		}

		ClientCredentialsInfo kp = new ClientCredentialsInfo(
				management.getClientIdForApplication(services
						.getApplicationId()),
						management.newClientSecretForApplication(services
								.getApplicationId()));

		return new JSONWithPadding(createApiResponse().withCredentials(kp)
				.withAction("generate application keys").withSuccess(),
				callback);
	}

	@GET
	@Path("authorize")
	public Viewable showAuthorizeForm(@Context UriInfo ui,
			@QueryParam("response_type") String response_type,
			@QueryParam("client_id") String client_id,
			@QueryParam("redirect_uri") String redirect_uri,
			@QueryParam("scope") String scope, @QueryParam("state") String state) {

		try {
			UUID uuid = getUUIDFromClientId(client_id);
			if (uuid == null) {
				throw mappableSecurityException(AuthErrorInfo.OAUTH2_INVALID_CLIENT, "Unable to authenticate (OAuth). Invalid client_id");
			}

			responseType = response_type;
			clientId = client_id;
			redirectUri = redirect_uri;
			this.scope = scope;
			this.state = state;

			ApplicationInfo app = management.getApplicationInfo(applicationId);
			applicationName = app.getName();

			return handleViewable("authorize_form", this);
		} catch (RedirectionException e) {
			throw e;
		} catch (Exception e) {
			return handleViewable("error", e);
		}
	}

	@POST
	@Path("authorize")
	@Produces(MediaType.TEXT_HTML)
	public Viewable handleAuthorizeForm(@Context UriInfo ui,
			@FormParam("response_type") String response_type,
			@FormParam("client_id") String client_id,
			@FormParam("redirect_uri") String redirect_uri,
			@FormParam("scope") String scope, @FormParam("state") String state,
			@FormParam("username") String username,
			@FormParam("password") String password) {

		try {
			responseType = response_type;
			clientId = client_id;
			redirectUri = redirect_uri;
			this.scope = scope;
			this.state = state;

			User user = null;
			String errorDescription = "Username or password do not match";
			try {
				user = management.verifyAppUserPasswordCredentials(
						services.getApplicationId(), username, password);
			} catch (UnactivatedAdminUserException uaue) {
				errorDescription = "user not activated";
			} catch (DisabledAdminUserException daue) {
				errorDescription = "user disabled";
			} catch (Exception e1) {
			}

			if ((user != null) && isNotBlank(redirect_uri)) {
				String authorizationCode = management.getAccessTokenForAppUser(services.getApplicationId(), user.getUuid(), 0);
				redirect_uri = buildRedirectUriWithAuthCode(redirect_uri, state, authorizationCode);

				throw new RedirectionException(redirect_uri);
			} else {
				errorMsg = errorDescription;
			}

			ApplicationInfo app = management.getApplicationInfo(applicationId);
			applicationName = app.getName();

			return handleViewable("authorize_form", this);
		} catch (RedirectionException e) {
			throw e;
		} catch (Exception e) {
			return handleViewable("error", e);
		}
	}

	@DELETE
	@RequireApplicationAccess
	@Override
	public JSONWithPadding executeDelete(@Context UriInfo ui,
			@QueryParam("callback") @DefaultValue("callback") String callback)
					throws Exception {

		logger.debug("ApplicationResource.executeDelete");

		throw new NotImplementedException("Application delete is not allowed yet");
	}

	String errorMsg = "";
	String applicationName;
	String responseType;
	String clientId;
	String redirectUri;
	String scope;
	String state;

	public String getErrorMsg() {
		return errorMsg;
	}

	public String getApplicationName() {
		return applicationName;
	}

	public String getResponseType() {
		return responseType;
	}

	public String getClientId() {
		return clientId;
	}

	public String getRedirectUri() {
		return redirectUri;
	}

	public String getScope() {
		return scope;
	}

	public String getState() {
		return state;
	}

	// todo: find a mechanism to move these methods into the push notifications
	// project
	@RequireApplicationAccess
	@Path("notifiers")
	public AbstractContextResource getNotifiersResource(@Context UriInfo ui)
			throws Exception {

		Class cls = Class
				.forName("org.usergrid.rest.applications.notifiers.NotifiersResource");

		logger.debug("NotifiersResource.getNotifiersResource");
		addParameter(getServiceParameters(), "notifiers");

		PathSegment ps = getFirstPathSegment("notifiers");
		if (ps != null) {
			addMatrixParams(getServiceParameters(), ui, ps);
		}

		return getSubResource(cls);
	}

	@RequireApplicationAccess
	@Path("notifier")
	public AbstractContextResource getNotifierResource(@Context UriInfo ui)
			throws Exception {
		return getNotifiersResource(ui);
	}

	private String buildRedirectUriWithAuthCode(String redirect_uri, String state, String authorizationCode) throws UnsupportedEncodingException {
		if (!redirect_uri.contains("?")) {
			redirect_uri += "?";
		} else {
			redirect_uri += "&";
		}
		redirect_uri += "code=" + authorizationCode;

		if (isNotBlank(state)) {
			redirect_uri += "&state=" + URLEncoder.encode(state, "UTF-8");
		}

		return redirect_uri;
	}

	//mAX /APM integration
	public static final String APIGEE_MOBILE_APM_CONFIG_JSON_KEY= "apigeeMobileConfig";
	@GET
	@Path("apm/apigeeMobileConfig")
	public JSONWithPadding getAPMConfig(@Context UriInfo ui,
			@QueryParam("callback") @DefaultValue("callback") String callback) throws Exception {
		EntityManager em = (EntityManager) emf.getEntityManager(applicationId);
		Object value = em.getProperty(new SimpleEntityRef(Application.ENTITY_TYPE, applicationId), APIGEE_MOBILE_APM_CONFIG_JSON_KEY);
		//If there is no apm configuration then try to create apm config on the fly
		if (value == null)
			value = management.registerAppWithAPM(management.getOrganizationForApplication(applicationId),
					management.getApplicationInfo(applicationId));
		return new JSONWithPadding(value, callback);
	}

}


text:
"""Solar Radiation Calculation Logic"""

import datetime, dateutil.parser, json, math, os, pytz, urllib, yaml
from base_plugin import BasePlugin

class SolarRadiation(BasePlugin):
    """Plugin to calculate solar radiation by provided latitude"""

    def __init__(self):
        super(SolarRadiation, self).__init__(self)
        self.sunrise = None
        self.sunset = None

        self._timezone = None
        self._today = None

    @property
    def plugin_name(self):
       return 'Calculate Solar Radiation Plugin'

    @property
    def has_valid_data(self):
        return self.sunrise and self.sunset

    @property
    def config_file_name(self):
        return '{}/solar_radiaton.yaml'.format(os.path.dirname(os.path.abspath(__file__)))

    @property
    def is_date_today(self):
        """Checks if date is the same as plugin has at start"""
        return self.today == self.current_date.date()

    @property
    def timezone(self):
        """Checks if timezone was populated otherwise loads it from config"""
        if not self._timezone:
            self._timezone = pytz.timezone(self.config['TIME_ZONE'] or pytz.utc)

        return self._timezone

    @property
    def today(self):
        """Populates initial today's date"""
        if not self._today:
            self._today = self.current_date.date()

        return self._today

    @property
    def current_date(self):
        """Get currents date for provided timezone"""
        return datetime.datetime.now(tz=self.timezone)

    @property
    def current_hour(self):
        """Gets current hour and minutes as float result"""
        current_time =  self.current_date.time()
        return current_time.hour + current_time.minute / 60.0

    @property
    def is_day(self):
        """Checks if currently is a day time"""
        return self.sunrise <= self.current_date <= self.sunset

    @property
    def day_of_year(self):
        """Gets day of year"""
        return self.current_date.timetuple().tm_yday

    @property
    def sunrise_sunset_url(self):
        """Returns link for Sunrise/Sunset API with provided latitude and longitude"""
        return 'https://api.sunrise-sunset.org/json?lat={0}&lng={1}&date=today&formatted=0'.format(self.latitude, self.config['LONGITUDE'])

    @property
    def latitude(self):
        """Returns latitude from config"""
        return self.config['LATITUDE'] if self.config else None

    @staticmethod
    def declination_angle(day):
        """Declination's angle is measured north or south of the celestial equator, along the hour circle passing through the point in question.

        The declination angle, varies seasonally due to the tilt of the Earth on its axis of rotation and the rotation of the Earth around the sun.
        http://www.pveducation.org/pvcdrom/properties-of-sunlight/declination-angle

        Args:
            day (number): day of year

        Returns:
            float: declination angle degrees
        """
        return 23.45 * math.sin(math.radians(360.0 / 365 * (day - 81)))

    @staticmethod
    def air_mass(hour, day, latitude):
        """The Air Mass is the path length which light takes through the atmosphere normalized to the shortest possible path length.

        The Air Mass quantifies the reduction in the power of light as it passes through the atmosphere and is absorbed by air and dust.
        http://www.pveducation.org/pvcdrom/properties-of-sunlight/air-mass

        Args:
            hour (float): local solar time
            day (number): day of year
            latitude (float): latitude value between -90 and 90 degrees

        Returns:
            float: path length which light takes through the atmosphere
        """
        declination_angle = math.radians(SolarRadiation.declination_angle(day));
        hour_angle = math.radians(SolarRadiation.hour_angle(hour));
        elevation_angle = SolarRadiation.elevation_angle(hour_angle, declination_angle, latitude)
        declination = math.radians(90) - elevation_angle;
        return 1 / (1E-4 + math.cos(declination))

    @staticmethod
    def hour_angle(hour):
        """The Hour Angle converts the local solar time (LST) into the number of degrees which the sun moves across the sky.

        By definition, the Hour Angle is 0 at solar noon. Since the Earth rotates 15 per hour,
        each hour away from solar noon corresponds to an angular motion of the sun in the sky of 15.
        In the morning the hour angle is negative, in the afternoon the hour angle is positive.
        https://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time

        Args:
            hour (float): local solar time

        Returns:
            float: number of degrees which the sun moves across the sky
        """
        return 15 * (hour - 12);

    @staticmethod
    def elevation_angle(hour_angle, declanation_angle, latitude):
        """The elevation angle (used interchangeably with altitude angle) is the angular height of the sun in the sky measured from the horizontal.

        http://www.pveducation.org/pvcdrom/properties-of-sunlight/elevation-angle
        Args:
            hour_angle (float): hour angle in radians
            declanation_angle(float): declanation angle in radians
            latitude (float): latitude value between -90 and 90 degrees
        Returns:
            float: elevation angle in radians
        """
        return math.asin(math.sin(declanation_angle) * math.sin(latitude) + math.cos(declanation_angle) * math.cos(latitude) * math.cos(hour_angle))

    def get_sunrise_sunset(self):
        """Gets sunrise and sunset from API by provided latitude and longitude.

        If date is the same, sunrise and sunset values are set return existing values, without calling API.

        Returns:
            tuple: sunrise and sunset in timezone provided in config
        """
        if (self.config and (not self.sunrise or not self.sunset or not self.is_date_today)):
            self._today = self.current_date.date()
            try:
                response = urllib.urlopen(self.sunrise_sunset_url)
                data = json.loads(response.read())
                result = data['results']
                sunrise = result['sunrise']
                sunset = result['sunset']

                # Convert to provided in config timezone, as API returns in UTC by default
                self.sunrise = dateutil.parser.parse(sunrise).astimezone(self.timezone)
                self.sunset = dateutil.parser.parse(sunset).astimezone(self.timezone)
            except Exception as error:
                self.errors.append(error)

        return (self.sunrise, self.sunset)

    def calcluate_solar_radiation(self):
        """Calculates current date and time solar radiation.

        http://www.pveducation.org/pvcdrom/properties-of-sunlight/calculation-of-solar-insolation

        Returns:
            float: solar radiation in W/m2
        """
        if (self.config):
            self.get_sunrise_sunset()

            if self.is_day:
                air_mass = SolarRadiation.air_mass(self.current_hour, self.day_of_year, self.latitude)
                result = math.pow(0.7, air_mass)
                result = 1353 * math.pow(result, 0.678)

                # We ignore case more than 1100 W/m2, because the peak solar radiation is 1 kW/m2
                # http://www.pveducation.org/pvcdrom/average-solar-radiation
                return 0 if result > 1100 else result

            return 0

        return None

    def get_data(self):
        result = {}

        if not self.config:
            self.parse_config()

        # Dictionary data for Weather Underground upload
        solar_radiation = self.calcluate_solar_radiation()
        if self.has_valid_data and solar_radiation is not None:
            result['solarradiation'] = round(solar_radiation, 1)

        return result


text:
from importlib import import_module

from django.apps import AppConfig as BaseAppConfig

class AppConfig(BaseAppConfig):

    name = "scraper_monitor"

    def ready(self):
        import_module("scraper_monitor.receivers")


text:
package com.grapp.soosec.di.components;

import com.google.gson.Gson;
import com.grapp.library.concurrent.XLazy;
import com.grapp.soosec.di.modules.ApplicationModule;
import com.grapp.soosec.di.modules.NetModule;
import com.grapp.soosec.api.IRemoteService;

import javax.inject.Singleton;

import dagger.Component;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

@Singleton
@Component(modules = {ApplicationModule.class, NetModule.class})
public interface NetComponent {
    Cache cache();

    OkHttpClient httpClient();

    Gson gson();

    Retrofit retrofit();

    IRemoteService createRemoveSvc();
    XLazy<IRemoteService> createLazyRemoveSvc();
}


text:
using namespace std;

const map<string, string> oppisites {{"True",  "False"},
                                     {"False", "True"}};

inline void use_io_optimizations()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
}

int main()
{
    use_io_optimizations();

    string value;
    unsigned int negations {0};

    while (cin >> value && value == "not")
    {
        ++negations;
    }

    cout << (negations % 2 ? oppisites.at(value) : value) << '\n';

    return 0;
}


text:
"""Use a convolutional neural network on
the challenge data."""
import glob
import csv
import numpy as np
import random

import tflearn
from astropy.io import fits as pyfits
from sklearn import metrics
from conv_net import conv_network

def load_images_labels(filenames, name_prefix, name_suffix,
                       start_num, end_num, label_file, vrb=False):
    filenumbers = [int(filename[len(name_prefix):-len(name_suffix)])
                   for filename in filenames]
    filtered_files = [(number, name) for number, name
                      in zip(filenumbers, filenames)
                      if start_num <= number <= end_num]

    images = np.array([np.array(pyfits.getdata(name))
                       for number, name in filtered_files])
    image_dim = images.shape[1:]
    images = images.reshape((-1,) + image_dim + (1,))

    if vrb:
        print "Read", images.shape[0], "images with dimensions", image_dim

    labels = {int(row['ID']): int(row['is_lens'])
              for row in csv.DictReader(open(label_file))}
    labels = [labels[number] for number, name in filtered_files]
    assert set(labels) == {0, 1}, set(labels)
    labels = np.array([[0, 1] if label else [1, 0]
                       for label in labels])

    assert labels.shape[0] == images.shape[0], (labels.shape[0], images.shape[0])

    if vrb:
        print labels[:,1].sum(), "lenses found,", labels[:,0].sum(), "non-lenses found"

    return images, labels

def train_test_split(X, y, test_size, vrb=False):
    indices = range(X.shape[0])
    random.shuffle(indices)
    num_test = int(test_size * X.shape[0])
    X_test = X[indices[:num_test], :]
    X_train = X[indices[num_test:], :]
    y_test = y[indices[:num_test], :]
    y_train = y[indices[num_test:], :]

    if vrb:
        print "X_train.shape =", X_train.shape
        print "X_test.shape =", X_test.shape
        print "y_train.shape =", y_train.shape
        print "y_test.shape =", y_test.shape

    return X_train, X_test, y_train, y_test

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('image_file_prefix')
    parser.add_argument('start_num', type=int)
    parser.add_argument('end_num', type=int)
    parser.add_argument('label_file')
    parser.add_argument('n_epoch', type=int)
    args = parser.parse_args()

    filenames = glob.glob(args.image_file_prefix + '*.fits')
    X, y = load_images_labels(filenames, args.image_file_prefix, '.fits',
                              args.start_num, args.end_num, args.label_file,
                              vrb=True)
    print
    X_train, X_test, y_train, y_test \
        = train_test_split(X, y, test_size = 0.2, vrb=True)
    del X, y

    network = conv_network(X_train.shape[1:3], 2)
    model = tflearn.DNN(network, tensorboard_verbose=0)
    model.fit({'input': X_train}, {'target' : y_train},
              n_epoch=args.n_epoch,
              validation_set=({'input': X_test}, {'target': y_test}),
              snapshot_step=100, show_metric=True,
              run_id='convnet_challenge')

    train_probability = np.array(model.predict(X_train))[:,1]
    test_probability = np.array(model.predict(X_test))[:,1]

    train_predict = (train_probability > 0.5).astype(int)
    test_predict = (test_probability > 0.5).astype(int)

    train_score = metrics.accuracy_score(y_train[:,1], train_predict)
    train_confusion_matrix = metrics.confusion_matrix(y_train[:,1], train_predict)
    train_auc = metrics.roc_auc_score(y_train[:,1], train_probability)

    test_score = metrics.accuracy_score(y_test[:,1], test_predict)
    test_confusion_matrix = metrics.confusion_matrix(y_test[:,1], test_predict)
    test_auc = metrics.roc_auc_score(y_test[:,1], test_probability)

    print 'Train Accuracy: {0:f}'.format(train_score)
    print 'Test Accuracy: {0:f}'.format(test_score)
    print
    print 'Train Confusion Matrix:'
    print train_confusion_matrix
    print
    print 'Test Confusion Matrix:'
    print test_confusion_matrix
    print
    print 'Train AUC: {0:f}'.format(train_auc)
    print 'Test AUC: {0:f}'.format(test_auc)


text:
package s3_blob_store_test

import (
	"net/http"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"

	"github.com/cloudfoundry-incubator/ltc/blob_store/s3_blob_store"
	config_package "github.com/cloudfoundry-incubator/ltc/config"
)

var _ = Describe("S3BlobStore", func() {
	var (
		verifier   *s3_blob_store.Verifier
		fakeServer *ghttp.Server
		config     *config_package.Config
	)

	BeforeEach(func() {
		fakeServer = ghttp.NewServer()
		verifier = &s3_blob_store.Verifier{fakeServer.URL()}
		config = config_package.New(nil)
		config.SetS3BlobStore("some-access-key", "some-secret-key", "bucket", "some-region")
	})

	Describe("Verify", func() {
		Context("when the blob store credentials are valid", func() {
			It("returns authorized as true", func() {
				responseBody := `
					 <?xml version="1.0" encoding="UTF-8"?>
					 <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
						 <Name>bucket</Name>
						 <Prefix/>
						 <Marker/>
						 <MaxKeys>1000</MaxKeys>
						 <IsTruncated>false</IsTruncated>
					 </ListBucketResult>
				 `

				fakeServer.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/bucket"),
					ghttp.RespondWith(http.StatusOK, responseBody, http.Header{"Content-Type": []string{"application/xml"}}),
				))

				authorized, err := verifier.Verify(config)
				Expect(err).NotTo(HaveOccurred())
				Expect(authorized).To(BeTrue())

				Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
			})
		})

		Context("when the blob store credentials are incorrect", func() {
			It("returns authorized as false", func() {
				fakeServer.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/bucket"),
					ghttp.RespondWith(http.StatusForbidden, nil),
				))

				authorized, err := verifier.Verify(config)
				Expect(err).NotTo(HaveOccurred())
				Expect(authorized).To(BeFalse())

				Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
			})
		})

		Context("when the blob store is inaccessible", func() {
			It("returns an error", func() {
				fakeServer.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/bucket"),
					ghttp.RespondWith(http.StatusBadRequest, nil),
				))
				_, err := verifier.Verify(config)
				Expect(err).To(HaveOccurred())
			})
		})
	})
})


text:
package org.thingsboard.server.queue.common;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class AbstractTbQueueTemplate {
    protected static final String REQUEST_ID_HEADER = "requestId";
    protected static final String RESPONSE_TOPIC_HEADER = "responseTopic";
    protected static final String EXPIRE_TS_HEADER = "expireTs";

    protected byte[] uuidToBytes(UUID uuid) {
        ByteBuffer buf = ByteBuffer.allocate(16);
        buf.putLong(uuid.getMostSignificantBits());
        buf.putLong(uuid.getLeastSignificantBits());
        return buf.array();
    }

    protected static UUID bytesToUuid(byte[] bytes) {
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        long firstLong = bb.getLong();
        long secondLong = bb.getLong();
        return new UUID(firstLong, secondLong);
    }

    protected byte[] stringToBytes(String string) {
        return string.getBytes(StandardCharsets.UTF_8);
    }

    protected String bytesToString(byte[] data) {
        return new String(data, StandardCharsets.UTF_8);
    }

    protected static byte[] longToBytes(long x) {
        ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
        longBuffer.putLong(0, x);
        return longBuffer.array();
    }

    protected static long bytesToLong(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getLong();
    }
}


text:
from . import SimConcretizationStrategy

class SimConcretizationStrategySingle(SimConcretizationStrategy):
    """
    Concretization strategy that ensures a single solution for an address.
    """

    def _concretize(self, memory, addr):
        addrs = self._eval(memory, addr, 2)
        if len(addrs) == 1:
            return addrs


text:
{% extends 'index.html' %}

{% block login %}

      <form class="form-signin" action="/auth/login/" method="post">
          {% csrf_token %}

Форма авторизации:

        Username
        <input type="text" name="username" id="username"  class="form-control" placeholder="Логин" required autofocus>
        Password
        <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required>
       {% if login_error %}
         {{ login_error }}
       {% endif %}
         <button class="btn btn-lg btn-primary btn-block" type="submit">Войти</button>
      </form>

{% endblock %}


text:
// ----------------------------------------------------------------------- PLATFORM
#include "utils/src/common/platform.h"
// ----------------------------------------------------------------------- INCLUDES
#ifdef COMPILER_VISUAL_STUDIO
	#pragma warning(disable : 4786)
#endif // COMPILER_VISUAL_STUDIO
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOLogic
// --------------------------------------------------------------------------------
template <class Order>
inline RDOLogic<Order>::RDOLogic(const LPRDORuntime& pRuntime, LPIBaseOperationContainer pParent)
	: m_pCondition    (NULL )
	, m_lastCondition (false)
	, m_pFirst        (NULL )
	, m_pParent       (pParent ? pParent : (pRuntime ? pRuntime->m_pMetaLogic : LPIBaseOperationContainer(NULL)))
	, m_multithreading(false)
{}

template <class Order>
inline RDOLogic<Order>::~RDOLogic()
{}

template <class Order>
inline void RDOLogic<Order>::init(const LPRDORuntime& pRuntime)
{
	if (pRuntime)
	{
		pRuntime->appendLogic(this, m_pParent);
	}
}

template <class Order>
inline void RDOLogic<Order>::setCondition(const LPRDOCalc& pCondition)
{
	m_pCondition = pCondition;
}

template <class Order>
inline void RDOLogic<Order>::setMultithreading(bool multithreading)
{
	m_multithreading = multithreading;
}

template <class Order>
inline void RDOLogic<Order>::onStart(const LPRDORuntime& pRuntime)
{
	m_lastCondition = checkSelfCondition(pRuntime);
	if (m_lastCondition)
	{
		start(pRuntime);
	}
}

template <class Order>
inline void RDOLogic<Order>::onStop(const LPRDORuntime& pRuntime)
{
	m_lastCondition = false;
	stop(pRuntime);
}

template <class Order>
inline bool RDOLogic<Order>::onCheckCondition(const LPRDORuntime& pRuntime)
{
	bool condition = checkSelfCondition(pRuntime);
	if (condition != m_lastCondition)
	{
		m_lastCondition = condition;
		if (condition)
		{
			start(pRuntime);
		}
		else
		{
			stop(pRuntime);
		}
	}

	if (!condition)
		return false;

	m_pFirst = Order::sort(pRuntime, m_childList);
	return m_pFirst ? true : false;
}

template <class Order>
inline IBaseOperation::BOResult RDOLogic<Order>::onDoOperation(const LPRDORuntime& pRuntime)
{
	if (m_lastCondition)
	{
		if (!m_pFirst)
			return IBaseOperation::BOR_cant_run;

		IBaseOperation::BOResult result = m_pFirst->onDoOperation(pRuntime);
		if (result == IBaseOperation::BOR_must_continue)
			pRuntime->setMustContinueOpr(m_pFirst);

		return result;
	}
	else
	{
		return IBaseOperation::BOR_cant_run;
	}
}

template <class Order>
inline IBaseOperation::BOResult RDOLogic<Order>::onContinue(const LPRDORuntime& pRuntime)
{
	for(ChildList::iterator it = m_childList.begin(); it != m_childList.end(); ++it)
	{
		if ((*it)->onContinue(pRuntime) == IBaseOperation::BOR_must_continue)
			return IBaseOperation::BOR_must_continue;
	}
	return IBaseOperation::BOR_cant_run;
}

template <class Order>
inline bool RDOLogic<Order>::checkSelfCondition(const LPRDORuntime& pRuntime)
{
	return m_pCondition
		? m_pCondition->calcValue(pRuntime).getAsBool()
		: true;
}

template <class Order>
inline void RDOLogic<Order>::start(const LPRDORuntime& pRuntime)
{
	for(ChildList::iterator it = m_childList.begin(); it != m_childList.end(); ++it)
	{
		(*it)->onStart(pRuntime);
	}
}

template <class Order>
inline void RDOLogic<Order>::stop(const LPRDORuntime& pRuntime)
{
	for(ChildList::iterator it = m_childList.begin(); it != m_childList.end(); ++it)
	{
		(*it)->onStop(pRuntime);
	}
}

template <class Order>
inline bool RDOLogic<Order>::empty() const
{
	return m_childList.empty();
}

template <class Order>
inline typename RDOLogic<Order>::Iterator RDOLogic<Order>::begin()
{
	return m_childList.begin();
}

template <class Order>
inline typename RDOLogic<Order>::Iterator RDOLogic<Order>::end()
{
	return m_childList.end();
}

template <class Order>
inline typename RDOLogic<Order>::CIterator RDOLogic<Order>::begin() const
{
	return m_childList.begin();
}

template <class Order>
inline typename RDOLogic<Order>::CIterator RDOLogic<Order>::end() const
{
	return m_childList.end();
}

template <class Order>
inline LPIBaseOperation& RDOLogic<Order>::back()
{
	return m_childList.back();
}

template <class Order>
inline void RDOLogic<Order>::append(const Item& item)
{
	m_childList.push_back(item);
}

template <class Order>
inline void RDOLogic<Order>::clear()
{
	m_childList.clear();
}

CLOSE_RDO_RUNTIME_NAMESPACE


text:
package org.apache.solr.core;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.NativeFSLockFactory;
import org.apache.lucene.store.SimpleFSLockFactory;
import org.apache.lucene.util.Version;
import org.apache.solr.SolrTestCaseJ4;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {

  @Before
  public void setUp() throws Exception {
    super.setUp();

    System.setProperty("solr.directoryFactory", "org.apache.solr.core.SimpleFSDirectoryFactory");

    //explicitly creates the temp dataDir so we know where the index will be located
    createTempDir();

    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_40, null);
    Directory directory = newFSDirectory(new File(dataDir, "index"));
    //creates a new index on the known location
    new IndexWriter(
        directory,
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE)
    ).close();
    directory.close();
  }

  @Test
  public void testSimpleLockErrorOnStartup() throws Exception {

    Directory directory = newFSDirectory(new File(dataDir, "index"), new SimpleFSLockFactory());
    //creates a new IndexWriter without releasing the lock yet
    IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_40, null));

    try {
      //opening a new core on the same index
      initCore("solrconfig-simplelock.xml", "schema.xml");
      fail("Expected " + LockObtainFailedException.class.getSimpleName());
    } catch (Throwable t) {
      assertTrue(t instanceof RuntimeException);
      assertNotNull(t.getCause());
      assertTrue(t.getCause() instanceof RuntimeException);
      assertNotNull(t.getCause().getCause());
      assertTrue(t.getCause().getCause() instanceof LockObtainFailedException);
    } finally {
      indexWriter.close();
      directory.close();
      deleteCore();
    }
  }

  @Test
  public void testNativeLockErrorOnStartup() throws Exception {

    Directory directory = newFSDirectory(new File(dataDir, "index"), new NativeFSLockFactory());
    //creates a new IndexWriter without releasing the lock yet
    IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_40, null));

    try {
      //opening a new core on the same index
      initCore("solrconfig-nativelock.xml", "schema.xml");
      fail("Expected " + LockObtainFailedException.class.getSimpleName());
    } catch(Throwable t) {
      assertTrue(t instanceof RuntimeException);
      assertNotNull(t.getCause());
      assertTrue(t.getCause() instanceof RuntimeException);
      assertNotNull(t.getCause().getCause());
      assertTrue(t.getCause().getCause() instanceof  LockObtainFailedException);
    } finally {
      indexWriter.close();
      directory.close();
      deleteCore();
    }
  }
}


text:
from rest_framework import generics
from users.models import User
from rest_framework.response import Response
from rest_framework import status
from django.core.exceptions import ObjectDoesNotExist

# Create your views here.
class UserAuth(generics.GenericAPIView):

    def get(self, serializer):
        username = self.request.query_params.get('username', None)
        pwd = self.request.query_params.get('password', None)
        if username and pwd:
            try:
                user = User.objects.get(username=username)
                if user and user.check_password(pwd):
                    res = { "token" : user.auth_token.key }
                    return Response(res)
            except ObjectDoesNotExist:
                return Response({"error": "User does not exist"}, status=status.HTTP_404_NOT_FOUND)

        return Response({"error": "Invalid query_params"}, status=status.HTTP_400_BAD_REQUEST)


text:
package org.roche.antibody.ui.propertytyble;

/**
 * All used KEYS in the {@link DomainTableModel} should be stored here. Only this way, it is possible to store them with
 * the generated GraphML and refer to this information later on!
 *
 * @author Stefan Klostermann: Stefan DOT Klostermann AT roche DOT com, Roche Pharma Research and Early
 *         Development - Informatics, Roche Innovation Center Penzberg
 * @author Clemens Wrzodek: clemens DOT wrzodek AT roche DOT com
 *
 * @version $Id$
 */
public final class TableDataKeys {

  // "> CHAIN"
  public static final String NAME = "NAME";

  public static final String SEQUENCE_LENGTH = "SEQUENCE LENGTH";

  public static final String SEQUENCE = "SEQUENCE";

  public static final String ORIGINAL_SEQUENCE = "ORIGINAL SEQUENCE";

  // "> DOMAIN"
  public static final String USER_LABEL = "USER LABEL";

  public static final String USER_COMMENT = "USER COMMENT";

  public static final String START_POS_ON_CHAIN = "START POS ON CHAIN";

  public static final String END_POS_ON_CHAIN = "END POS ON CHAIN";

  public static final String START_POS_ON_TEMPLATE = "START POS ON TEMPLATE";

  public static final String END_POS_ON_TEMPLATE = "END POS ON TEMPLATE";

  public static final String LENGTH = "LENGTH";

  public static final String IDENTITY_TO_LIB_DOM = "IDENTITY TO LIB. DOM.";

  public static final String COVERAGE_OF_LIB_DOM = "COVERAGE OF LIB. DOM.";

  public static final String LEADING_SEQUENCE = "LEADING SEQUENCE";

  public static final String SEQUENCE_DE_FACTO = "SEQUENCE (DE FACTO)";

  public static final String TRAILING_SEQUENCE = "TRAILING SEQUENCE";

  public static final String PARATOPE = "Paratope";

  /**
   * XXX: "> ANNOTATIONS" Stored with prefix "ANNOTATION_" in the Library.
   */
  public static final String ANNOTATION_PREFIX = "ANNOTATION_";

  /**
   * XXX: "> MUTATIONS" Stored with prefix "MUTATION_" in the Library.
   */
  public static final String MUTATION_PREFIX = "MUTATION_";

  /**
   * XXX: "> UNKNOWN MUTATIONS" Stored with prefix "UNKNOWN_MUTATION_" in the Library.
   */
  public static final String UNKNOWN_MUTATION_PREFIX = "UNKNOWN_MUTATION_";

  // "> CYS BRIDGES"
  public static final String CYS_POS = "CYS POS";

  public static final String CYS_BRIDGES = "CYS BRIDGES";

  public static final String FREE_CYS = "FREE CYS";

  // "> OTHER BRIDGES"
  public static final String GENERAL = "GENERAL";

  public static final String RECOGNIZED_DOMAIN_FROM_LIBRARY = "> RECOGNIZED DOMAIN FROM LIBRARY";

  public static final String NAME_IN_LIB = "NAME IN LIB";

  public static final String SHORT_NAME = "SHORT NAME";

  public static final String SPECIES = "SPECIES";

  public static final String HUMANNESS = "HUMANNESS";

  public static final String CHAIN = "CHAIN";

  public static final String DOMAIN_TYPE = "DOMAIN TYPE";

  public static final String SEQUENCE_LENGTH_IN_LIB = "SEQUENCE LENGTH IN LIB";

  public static final String CYS_COUNT = "CYS COUNT";

  public static final String PATTERN = "PATTERN";

  public static final String COMMENT = "COMMENT";

  public static final String SEQUENCE_TEMPLATE = "SEQUENCE (TEMPLATE)";

  /**
   * @return all keys for the "> Chain" section in the table.
   */
  public static String[] getChainSectionKeys() {
    return new String[] {NAME, SEQUENCE_LENGTH, SEQUENCE, ORIGINAL_SEQUENCE};
  }

  /**
   * @return all keys for the "> Domain" section in the table. Note that USER_LABEL and USER_COMMENT should be EDITABLE!
   */
  public static String[] getDomainSectionKeys() {
    return new String[] {USER_LABEL, USER_COMMENT, START_POS_ON_CHAIN, END_POS_ON_CHAIN, LENGTH, START_POS_ON_TEMPLATE,
        END_POS_ON_TEMPLATE, IDENTITY_TO_LIB_DOM,
        COVERAGE_OF_LIB_DOM, LEADING_SEQUENCE, SEQUENCE_DE_FACTO, TRAILING_SEQUENCE, PARATOPE};
  }

  /**
   * @return all keys for the "> CysBridgeData" ection in the table.
   */
  public static String[] getCysBridgeSectionKeys() {
    return new String[] {
        // > CysBridgeData
        CYS_POS, CYS_BRIDGES, FREE_CYS
    };
  }

  /**
   * @return all keys for the "> OTHER BRIDGES" section in the table.
   */
  public static String[] getOtherBridgeSectionKeys() {
    return new String[] {
        // > OTHER BRIDGES data
        GENERAL
    };
  }

  /**
   * @return all keys for the "> RECOGNIZED DOMAIN FROM LIBRARY" section in the table.
   */
  public static String[] getLibrarySectionKeys() {
    return new String[] {
        // > RECOGNIZED DOMAIN FROM LIBRARY data
        NAME_IN_LIB, SHORT_NAME, SPECIES, HUMANNESS, CHAIN, DOMAIN_TYPE, SEQUENCE_LENGTH_IN_LIB, CYS_COUNT, PATTERN,
        COMMENT, SEQUENCE_TEMPLATE
    };
  }
}


text:
using System;
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class PullRequest
    {
        /// <summary>
        /// The URL for this pull request.
        /// </summary>
        public Uri Url { get; set; }

        /// <summary>
        /// The URL for the pull request page.
        /// </summary>
        public Uri HtmlUrl { get; set; }

        /// <summary>
        /// The URL for the pull request's diff (.diff) file.
        /// </summary>
        public Uri DiffUrl { get; set; }

        /// <summary>
        /// The URL for the pull request's patch (.patch) file.
        /// </summary>
        public Uri PatchUrl { get; set; }

        /// <summary>
        /// The URL for the specific pull request issue.
        /// </summary>
        public Uri IssueUrl { get; set; }

        /// <summary>
        /// The URL for the pull request statuses.
        /// </summary>
        public Uri StatusesUrl { get; set; }

        /// <summary>
        /// The pull request number.
        /// </summary>
        public int Number { get; set; }

        /// <summary>
        /// Whether the pull request is open or closed. The default is <see cref="ItemState.Open"/>.
        /// </summary>
        public ItemState State { get; set; }

        /// <summary>
        /// Title of the pull request.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// The body (content) contained within the pull request.
        /// </summary>
        public string Body { get; set; }

        /// <summary>
        /// When the pull request was created.
        /// </summary>
        public DateTimeOffset CreatedAt { get; set; }

        /// <summary>
        /// When the pull request was last updated.
        /// </summary>
        public DateTimeOffset UpdatedAt { get; set; }

        /// <summary>
        /// When the pull request was closed.
        /// </summary>
        public DateTimeOffset? ClosedAt { get; set; }

        /// <summary>
        /// When the pull request was merged.
        /// </summary>
        public DateTimeOffset? MergedAt { get; set; }

        /// <summary>
        /// The HEAD reference for the pull request.
        /// </summary>
        public GitReference Head { get; set; }

        /// <summary>
        /// The BASE reference for the pull request.
        /// </summary>
        public GitReference Base { get; set; }

        /// <summary>
        /// The user who created the pull request.
        /// </summary>
        public User User { get; set; }

        /// <summary>
        /// The SHA of the merge commit.
        /// </summary>
        public string MergeCommitSha { get; set; }

        /// <summary>
        /// Whether or not the pull request has been merged.
        /// </summary>
        public bool Merged { get; set; }

        /// <summary>
        /// Whether or not the pull request can be merged.
        /// </summary>
        public bool? Mergeable { get; set; }

        /// <summary>
        /// The user who merged the pull request.
        /// </summary>
        public User MergedBy { get; set; }

        /// <summary>
        /// Total number of comments contained in the pull request.
        /// </summary>
        public int Comments { get; set; }

        /// <summary>
        /// Total number of commits contained in the pull request.
        /// </summary>
        public int Commits { get; set; }

        /// <summary>
        /// Total number of additions contained in the pull request.
        /// </summary>
        public int Additions { get; set; }

        /// <summary>
        /// Total number of deletions contained in the pull request.
        /// </summary>
        public int Deletions { get; set; }

        /// <summary>
        /// Total number of files changed in the pull request.
        /// </summary>
        public int ChangedFiles { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                return String.Format(CultureInfo.InvariantCulture, "Number: {0} State: {1}", Number, State);
            }
        }
    }
}


text:
#ifndef QTSCROLLEVENT_H
#define QTSCROLLEVENT_H

#include <QEvent>
#include <QPointF>
#include <QSizeF>
#include <QRectF>
#include <QScopedPointer>

class QtScrollPrepareEventPrivate;
class QtScrollPrepareEvent : public QEvent
{
public:
    enum { ScrollPrepare = 15056 }; // random number

    QtScrollPrepareEvent(const QPointF &startPos);
    ~QtScrollPrepareEvent();

    QPointF startPos() const;

    QSizeF viewportSize() const;
    QRectF contentPosRange() const;
    QPointF contentPos() const;

    void setViewportSize(const QSizeF &size);
    void setContentPosRange(const QRectF &rect);
    void setContentPos(const QPointF &pos);

private:
    QScopedPointer<QtScrollPrepareEventPrivate> d;
};

class QtScrollEventPrivate;
class QtScrollEvent : public QEvent
{
public:
    enum { Scroll = 15057 }; // random number

    enum ScrollState
    {
        ScrollStarted,
        ScrollUpdated,
        ScrollFinished
    };

    QtScrollEvent(const QPointF &contentPos, const QPointF &overshoot, ScrollState scrollState);
    ~QtScrollEvent();

    QPointF contentPos() const;
    QPointF overshootDistance() const;
    ScrollState scrollState() const;

private:
    QScopedPointer<QtScrollEventPrivate> d;
};

#endif // QTSCROLLEVENT_H


text:
namespace Poco {

class Foundation_API MutexImpl
{
protected:
	MutexImpl();
	MutexImpl(bool fast);
	~MutexImpl();
	void lockImpl();
	bool tryLockImpl();
	bool tryLockImpl(long milliseconds);
	void unlockImpl();

private:
	pthread_mutex_t _mutex;
};

class Foundation_API FastMutexImpl: public MutexImpl
{
protected:
	FastMutexImpl();
	~FastMutexImpl();
};

//
// inlines
//
inline void MutexImpl::lockImpl()
{
	if (pthread_mutex_lock(&_mutex))
		throw SystemException("cannot lock mutex");
}

inline bool MutexImpl::tryLockImpl()
{
	int rc = pthread_mutex_trylock(&_mutex);
	if (rc == 0)
		return true;
	else if (rc == EBUSY)
		return false;
	else
		throw SystemException("cannot lock mutex");
}

inline void MutexImpl::unlockImpl()
{
	if (pthread_mutex_unlock(&_mutex))
		throw SystemException("cannot unlock mutex");
}

} // namespace Poco

#endif // Foundation_Mutex_POSIX_INCLUDED


text:
package org.usc.demo.temp.bak;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Shunli
 */
public class Test19 {
    // private static int c = 0;

    public static void main(String[] args) {

        // Semaphore semp = new Semaphore(1);
        // while (true) {
        // System.out.println(semp.tryAcquire());
        //
        // semp.release();
        // }

        Lock lock = new ReentrantLock();
        System.out.println(lock.tryLock());
        System.out.println(lock.tryLock());
        System.out.println(lock.tryLock());
        // Thread t1 = new Thread() {
        // public void run() {
        // for (int i = 0; i < 10000; i++) {
        // if (!lock.tryLock()) {
        // c++;
        // }
        // lock.unlock();
        // }
        // }
        // };
        // t1.start();
        //
        // while (t1.isAlive()) {
        // System.out.println("xx"+c);
        // }

        String phone = "13712345678";
        System.out.println(showPhone(phone));
    }

    private static String showPhone(String phone) {
        boolean showFullPhone = false;
        if (showFullPhone) {
            return phone;
        }

        int start = 3;
        int end = 7;
        return StringUtils.overlay(phone, StringUtils.repeat("*", end - start), start, end);
    }
}


text:
package RESOURCE

import (
	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/pagination"
)

// ListOptsBuilder allows extensions to add additional parameters to
// the List request
type ListOptsBuilder interface {
	ToResourceListQuery() (string, error)
}

// ListOpts provides options to filter the List results.
type ListOpts struct {
}

// ToResourceListQuery formats a ListOpts into a query string.
func (opts ListOpts) ToResourceListQuery() (string, error) {
	q, err := gophercloud.BuildQueryString(opts)
	return q.String(), err
}

// List retrieves a list of RESOURCES.
func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
	url := listURL(client)
	if opts != nil {
		query, err := opts.ToResourceListQuery()
		if err != nil {
			return pagination.Pager{Err: err}
		}
		url += query
	}
	return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
		return ResourcePage{pagination.LinkedPageBase{PageResult: r}}
	})
}

// Get retrieves details of a RESOURCE.
func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {
	_, r.Err = client.Get(getURL(client, id), &r.Body, nil)
	return
}

// CreateOptsBuilder allows extensions to add additional parameters to
// the Create request.
type CreateOptsBuilder interface {
	ToResourceCreateMap() (map[string]interface{}, error)
}

// CreateOpts provides options used to create a RESOURCE.
type CreateOpts struct {
}

// ToResourceCreateMap formats a CreateOpts into a create request.
func (opts CreateOpts) ToResourceCreateMap() (map[string]interface{}, error) {
	return gophercloud.BuildRequestBody(opts, "resource")
}

// Create creates a new RESOURCE.
func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {
	b, err := opts.ToResourceCreateMap()
	if err != nil {
		r.Err = err
		return
	}
	_, r.Err = client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{201},
	})
	return
}

// Delete deletes a RESOURCE.
func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {
	_, r.Err = client.Delete(deleteURL(client, id), nil)
	return
}

// UpdateOptsBuilder allows extensions to add additional parameters to
// the Update request.
type UpdateOptsBuilder interface {
	ToResourceUpdateMap() (map[string]interface{}, error)
}

// UpdateOpts represents parameters to update a RESOURCE.
type UpdateOpts struct {
}

// ToUpdateCreateMap formats a UpdateOpts into an update request.
func (opts UpdateOpts) ToResourceUpdateMap() (map[string]interface{}, error) {
	return gophercloud.BuildRequestBody(opts, "resource")
}

// Update modifies the attributes of a RESOURCE.
func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) (r UpdateResult) {
	b, err := opts.ToResourceUpdateMap()
	if err != nil {
		r.Err = err
		return
	}
	_, r.Err = client.Patch(updateURL(client, id), b, &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{200},
	})
	return
}


text:
package org.apache.taverna.server.master.utils;

import static java.lang.System.currentTimeMillis;
import static java.lang.Thread.sleep;
import static org.apache.commons.logging.LogFactory.getLog;

import java.sql.DatabaseMetaData;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.datanucleus.store.rdbms.adapter.DerbyAdapter;
import org.datanucleus.store.rdbms.identifier.IdentifierFactory;
import org.datanucleus.store.rdbms.key.CandidateKey;
import org.datanucleus.store.rdbms.key.ForeignKey;
import org.datanucleus.store.rdbms.key.Index;
import org.datanucleus.store.rdbms.key.PrimaryKey;
import org.datanucleus.store.rdbms.sql.SQLTable;
import org.datanucleus.store.rdbms.table.Column;
import org.datanucleus.store.rdbms.table.Table;
import org.datanucleus.store.rdbms.table.TableImpl;
import org.datanucleus.store.rdbms.table.ViewImpl;

/**
 * Evil hack to allow logging of the DDL spat out to Derby.
 *
 * @author Donal Fellows
 */
public class LoggingDerbyAdapter extends DerbyAdapter {
	Log log = getLog("Taverna.Server.SQL");

	private StringBuilder ddl = new StringBuilder();
	private volatile long timeout;
	private Thread timer;

	private synchronized void logDDL() {
		if (ddl.length() > 0) {
			log.info("Data definition language:\n" + ddl);
			ddl.setLength(0);
		}
		timer = null;
	}

	private synchronized void doLog(String item) {
		ddl.append(item);
		if (!item.endsWith("\n"))
			ddl.append('\n');
		timeout = currentTimeMillis() + 5000;
		if (timer == null)
			timer = new OneShotThread("DDL logger timeout", new Runnable() {
				@Override
				public void run() {
					try {
						while (timeout > currentTimeMillis())
							sleep(1000);
					} catch (InterruptedException e) {
						// Ignore
					}
					logDDL();
				}
			});
	}

	/**
	 * Creates an Apache Derby adapter based on the given metadata which logs
	 * the DDL it creates.
	 */
	public LoggingDerbyAdapter(DatabaseMetaData metadata) {
		super(metadata);
	}

	@Override
	public String getCreateTableStatement(TableImpl table, Column[] columns,
			Properties props, IdentifierFactory factory) {
		String statement = super.getCreateTableStatement(table, columns, props,
				factory);
		doLog(statement);
		return statement;
	}

	@Override
	public String getCreateIndexStatement(Index index, IdentifierFactory factory) {
		String statement = super.getCreateIndexStatement(index, factory);
		doLog(statement);
		return statement;
	}

	@Override
	public String getAddCandidateKeyStatement(CandidateKey ck,
			IdentifierFactory factory) {
		String statement = super.getAddCandidateKeyStatement(ck, factory);
		doLog(statement);
		return statement;
	}

	@Override
	public String getAddPrimaryKeyStatement(PrimaryKey pk,
			IdentifierFactory factory) {
		String statement = super.getAddPrimaryKeyStatement(pk, factory);
		doLog(statement);
		return statement;
	}

	@Override
	public String getAddColumnStatement(Table table, Column col) {
		String statement = super.getAddColumnStatement(table, col);
		doLog(statement);
		return statement;
	}

	@Override
	public String getAddForeignKeyStatement(ForeignKey fk,
			IdentifierFactory factory) {
		String statement = super.getAddForeignKeyStatement(fk, factory);
		doLog(statement);
		return statement;
	}

	@Override
	public String getDeleteTableStatement(SQLTable tbl) {
		String statement = super.getDeleteTableStatement(tbl);
		doLog(statement);
		return statement;
	}

	@Override
	public String getDropTableStatement(Table table) {
		String statement = super.getDropTableStatement(table);
		doLog(statement);
		return statement;
	}

	@Override
	public String getDropViewStatement(ViewImpl view) {
		String statement = super.getDropViewStatement(view);
		doLog(statement);
		return statement;
	}
}