text:
// Type definitions for non-npm package Google Google Cloud OS Login API v1alpha 1.0
// Project: https://cloud.google.com/compute/docs/oslogin/rest/
// Definitions by: Bolisov Alexey <https://github.com/Bolisov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://oslogin.googleapis.com/$discovery/rest?version=v1alpha

/// <reference types="gapi.client" />

declare namespace gapi.client {
    /** Load Google Cloud OS Login API v1alpha */
    function load(name: "oslogin", version: "v1alpha"): PromiseLike<void>;
    function load(name: "oslogin", version: "v1alpha", callback: () => any): void;

    const users: oslogin.UsersResource;

    namespace oslogin {
        interface ImportSshPublicKeyResponse {
            /** The login profile information for the user. */
            loginProfile?: LoginProfile;
        }
        interface LoginProfile {
            /** A unique user ID for identifying the user. */
            name?: string;
            /** The list of POSIX accounts associated with the Directory API user. */
            posixAccounts?: PosixAccount[];
            /** A map from SSH public key fingerprint to the associated key object. */
            sshPublicKeys?: Record<string, SshPublicKey>;
            /** Indicates if the user is suspended. */
            suspended?: boolean;
        }
        interface PosixAccount {
            /** The GECOS (user information) entry for this account. */
            gecos?: string;
            /** The default group ID. */
            gid?: string;
            /** The path to the home directory for this account. */
            homeDirectory?: string;
            /** Only one POSIX account can be marked as primary. */
            primary?: boolean;
            /** The path to the logic shell for this account. */
            shell?: string;
            /**
             * System identifier for which account the username or uid applies to.
             * By default, the empty value is used.
             */
            systemId?: string;
            /** The user ID. */
            uid?: string;
            /** The username of the POSIX account. */
            username?: string;
        }
        interface SshPublicKey {
            /** An expiration time in microseconds since epoch. */
            expirationTimeUsec?: string;
            /**
             * The SHA-256 fingerprint of the SSH public key.
             * Output only.
             */
            fingerprint?: string;
            /**
             * Public key text in SSH format, defined by
             * RFC4253
             * section 6.6.
             */
            key?: string;
        }
        interface SshPublicKeysResource {
            /** Deletes an SSH public key. */
            delete(request: {
                /** V1 error format. */
                "$.xgafv"?: string;
                /** OAuth access token. */
                access_token?: string;
                /** Data format for response. */
                alt?: string;
                /** OAuth bearer token. */
                bearer_token?: string;
                /** JSONP */
                callback?: string;
                /** Selector specifying which fields to include in a partial response. */
                fields?: string;
                /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
                key?: string;
                /**
                 * The fingerprint of the public key to update. Public keys are identified by
                 * their SHA-256 fingerprint. The fingerprint of the public key is in format
                 * `users/{user}/sshPublicKeys/{fingerprint}`.
                 */
                name: string;
                /** OAuth 2.0 token for the current user. */
                oauth_token?: string;
                /** Pretty-print response. */
                pp?: boolean;
                /** Returns response with indentations and line breaks. */
                prettyPrint?: boolean;
                /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
                quotaUser?: string;
                /** Legacy upload protocol for media (e.g. "media", "multipart"). */
                uploadType?: string;
                /** Upload protocol for media (e.g. "raw", "multipart"). */
                upload_protocol?: string;
            }): Request<{}>;
            /** Retrieves an SSH public key. */
            get(request: {
                /** V1 error format. */
                "$.xgafv"?: string;
                /** OAuth access token. */
                access_token?: string;
                /** Data format for response. */
                alt?: string;
                /** OAuth bearer token. */
                bearer_token?: string;
                /** JSONP */
                callback?: string;
                /** Selector specifying which fields to include in a partial response. */
                fields?: string;
                /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
                key?: string;
                /**
                 * The fingerprint of the public key to retrieve. Public keys are identified
                 * by their SHA-256 fingerprint. The fingerprint of the public key is in
                 * format `users/{user}/sshPublicKeys/{fingerprint}`.
                 */
                name: string;
                /** OAuth 2.0 token for the current user. */
                oauth_token?: string;
                /** Pretty-print response. */
                pp?: boolean;
                /** Returns response with indentations and line breaks. */
                prettyPrint?: boolean;
                /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
                quotaUser?: string;
                /** Legacy upload protocol for media (e.g. "media", "multipart"). */
                uploadType?: string;
                /** Upload protocol for media (e.g. "raw", "multipart"). */
                upload_protocol?: string;
            }): Request<SshPublicKey>;
            /**
             * Updates an SSH public key and returns the profile information. This method
             * supports patch semantics.
             */
            patch(request: {
                /** V1 error format. */
                "$.xgafv"?: string;
                /** OAuth access token. */
                access_token?: string;
                /** Data format for response. */
                alt?: string;
                /** OAuth bearer token. */
                bearer_token?: string;
                /** JSONP */
                callback?: string;
                /** Selector specifying which fields to include in a partial response. */
                fields?: string;
                /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
                key?: string;
                /**
                 * The fingerprint of the public key to update. Public keys are identified by
                 * their SHA-256 fingerprint. The fingerprint of the public key is in format
                 * `users/{user}/sshPublicKeys/{fingerprint}`.
                 */
                name: string;
                /** OAuth 2.0 token for the current user. */
                oauth_token?: string;
                /** Pretty-print response. */
                pp?: boolean;
                /** Returns response with indentations and line breaks. */
                prettyPrint?: boolean;
                /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
                quotaUser?: string;
                /** Mask to control which fields get updated. Updates all if not present. */
                updateMask?: string;
                /** Legacy upload protocol for media (e.g. "media", "multipart"). */
                uploadType?: string;
                /** Upload protocol for media (e.g. "raw", "multipart"). */
                upload_protocol?: string;
            }): Request<SshPublicKey>;
        }
        interface UsersResource {
            /**
             * Retrieves the profile information used for logging in to a virtual machine
             * on Google Compute Engine.
             */
            getLoginProfile(request: {
                /** V1 error format. */
                "$.xgafv"?: string;
                /** OAuth access token. */
                access_token?: string;
                /** Data format for response. */
                alt?: string;
                /** OAuth bearer token. */
                bearer_token?: string;
                /** JSONP */
                callback?: string;
                /** Selector specifying which fields to include in a partial response. */
                fields?: string;
                /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
                key?: string;
                /** The unique ID for the user in format `users/{user}`. */
                name: string;
                /** OAuth 2.0 token for the current user. */
                oauth_token?: string;
                /** Pretty-print response. */
                pp?: boolean;
                /** Returns response with indentations and line breaks. */
                prettyPrint?: boolean;
                /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
                quotaUser?: string;
                /** Legacy upload protocol for media (e.g. "media", "multipart"). */
                uploadType?: string;
                /** Upload protocol for media (e.g. "raw", "multipart"). */
                upload_protocol?: string;
            }): Request<LoginProfile>;
            /**
             * Adds an SSH public key and returns the profile information. Default POSIX
             * account information is set when no username and UID exist as part of the
             * login profile.
             */
            importSshPublicKey(request: {
                /** V1 error format. */
                "$.xgafv"?: string;
                /** OAuth access token. */
                access_token?: string;
                /** Data format for response. */
                alt?: string;
                /** OAuth bearer token. */
                bearer_token?: string;
                /** JSONP */
                callback?: string;
                /** Selector specifying which fields to include in a partial response. */
                fields?: string;
                /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
                key?: string;
                /** OAuth 2.0 token for the current user. */
                oauth_token?: string;
                /** The unique ID for the user in format `users/{user}`. */
                parent: string;
                /** Pretty-print response. */
                pp?: boolean;
                /** Returns response with indentations and line breaks. */
                prettyPrint?: boolean;
                /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
                quotaUser?: string;
                /** Legacy upload protocol for media (e.g. "media", "multipart"). */
                uploadType?: string;
                /** Upload protocol for media (e.g. "raw", "multipart"). */
                upload_protocol?: string;
            }): Request<ImportSshPublicKeyResponse>;
            sshPublicKeys: SshPublicKeysResource;
        }
    }
}


text:
During this lab, you will use the [Visual Recognition][visual_recognition] service to train a classifier and recognize images.

You can see a version of this app that is already running [here](https://visual-recognition-demo.mybluemix.net/).

So let's get started. The first thing to do is to build out the shell of our application in Bluemix.

## Creating a [IBM Bluemix][bluemix] Account

1. Go to https://bluemix.net/
2. Create a Bluemix account if required.
3. Log in with your IBM ID (the ID used to create your Bluemix account)

**Note:** The confirmation email from Bluemix mail take up to 1 hour.

## Deploy this sample application in Bluemix

1. Clone the repository into your computer and navigate to the new directory.

   ```none
   git clone https://github.com/watson-developer-cloud/visual-recognition-nodejs.git
   cd visual-recognition-nodejs
   ```

1. [Sign up][sign_up] in Bluemix or use an existing account.
1. If it is not already installed on your system, download and install the [Cloud-foundry CLI][cloud_foundry] tool.
1. Edit the `manifest.yml` file in the folder that contains your code and replace `visual-recognition` with a unique name for your application. The name that you specify determines the application's URL, such as `your-application-name.mybluemix.net`. The relevant portion of the `manifest.yml` file looks like the following:

    ```yml
    applications:
    - name: visual-recognition-demo
     command: npm start
     path: .
     memory: 512M
     env:
      NODE_ENV: production
    ```

1. Connect to Bluemix by running the following commands in a terminal window:

  ```none
  cf api https://api.ng.bluemix.net
  cf login
  ```

1. Create and retrieve service keys to access the [Visual Recognition][visual_recognition] service by running the following command:

  ```none
  cf create-service watson_vision_combined free visual-recognition-service
  cf create-service-key visual-recognition-service myKey
  cf service-key visual-recognition-service myKey
  ```

1. Provide the credentials from step 6 to the application by creating a `.env` file using this format:

  ```none
  VISUAL_RECOGNITION_API_KEY=<your-alchemy-api-key>
  ```

1. Install the dependencies you application need:

  ```none
  npm install
  ```

1. Start the application by running:

  ```none
  npm start
  ```

1. Test your application locally by going to: [http://localhost:3000/](http://localhost:3000/)

## Deploying your application to Bluemix

1. Push the updated application live by running the following command:

  ```none
  cf push
  ```

After completing the steps above, you are ready to test your application. Start a browser and enter the URL of your application.

                  <your-application-name>.mybluemix.net

You can also find your application name when you click on your application in Bluemix.

## Classifying Images in the Starter Application

The application is composed of two sections, a "Try" section and a "Train" section. The Try section will allow you to send an individual image to the Visual Recognition service to be classified.

Test out the existing service by selecting one of the provided images or pasting a URL for an image of your choice. You will see the service respond with a collection of recognized attributes about the image.

Next, try running the following image through the classifier by pasting the URL into the "Try" panel.

 * Fruitbowl: https://github.com/watson-developer-cloud/doc-tutorial-downloads/raw/master/visual-recognition/fruitbowl.jpg

You'll see that it's recognized some general attributes about the image, but we want it to be able to specifically recognize it as a **fruitbowl**. To do that, we will need to train a customer classifier.

## Training a Custom Classifier in the Starter App

Navigate over to the "Train" window in the application.

Here, you will see a collection of training sets that have been provided for you. If you select any one of these, you will see that set expand to show a series of classes that will be trained, as well as negative examples of that group. For example, the `Dog Breeds` classifier contains 4 classes of dogs to be identified, as well as a negative example data set of `Non-dogs`.

To train the service to specifically classify a fruitbowl, we are going to use two collections of images to teach Watson what to recognize when classifying a fruitbowl. Click on the "Use your Own" box, and afterward a series of boxes will appear to allow you to upload .zip files for the classes.

Download and select the following .zip files for the classifier:

 * Positive Class #1 (leftmost box) - [watson-labs.mybluemix.net/data/fruitbowl.zip](watson-labs.mybluemix.net/data/fruitbowl.zip)
 * Negative Class   (rightmost box) - [watson-labs.mybluemix.net/data/not-fruit-bowls.zip](watson-labs.mybluemix.net/data/fruitbowl.zip)

Once the two zip files are included, name the classifier "fruitbowl" and select the "Train your classifier" button

The classifier may take a couple minutes to train, and once it is complete the application will update to allow you to submit new images against that classifier. If you submit the original image that we used in the new prompt on the "Train" window, you will see that it will be specifically classified based on our new training!

# Congratulations

You have completed the Visual Recognition Lab! :bowtie:

 ![Congratulations](http://i.giphy.com/ENagATV1Gr9eg.gif)

[sign_up]: https://bluemix.net/registration
[bluemix]: https://console.ng.bluemix.net/
[wdc_services]: http://www.ibm.com/watson/developercloud/services-catalog.html
[visual_recognition]: http://www.ibm.com/watson/developercloud/doc/visual-recognition
[cloud_foundry]: https://github.com/cloudfoundry/cli

redpajama_set_name: RedPajamaGithub


text:
package com.raoulvdberge.refinedstorage.api.util;

import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;

import java.util.UUID;

/**
 * A helper for the changes in 1.6.
 */
public interface IOneSixMigrationHelper {
    /**
     * Migrates this disk over to the new 1.6 format *IF POSSIBLE*.
     * The given disk item needs to implement {@link com.raoulvdberge.refinedstorage.api.storage.disk.IStorageDiskProvider}!
     * This will call {@link com.raoulvdberge.refinedstorage.api.storage.disk.IStorageDiskProvider#setId(ItemStack, UUID)} on the disk, so make sure
     * a call to this method clears previous 1.5 and lower data, or this method will keep migrating constantly!
     * <p>
     * This will *ONLY* work with disks that were made using the IStorageDiskBehavior 1.5 API.
     * If you were using another method, you'll have to implement the migration code yourself.
     *
     * @param world the world
     * @param disk  the disk to attempt to migrate
     * @return true if it migrated, false otherwise
     */
    boolean migrateDisk(World world, ItemStack disk);

    /**
     * Migrates an entire disk inventory.
     * Loops over every slot in the inventory and calls {@link #migrateDisk(World, ItemStack)}.
     * All the docs from {@link #migrateDisk(World, ItemStack)} apply here as well!
     * Don't forget to mark your tile dirty if this call returns true!
     *
     * @param world   the world
     * @param handler the inventory
     * @return true if it migrated something in the inventory, false otherwise
     */
    boolean migrateDiskInventory(World world, IItemHandlerModifiable handler);

    /**
     * Migrates an entire pattern inventory.
     * Returns true if there were changes, and the caller should then mark their inventory dirty.
     *
     * @param handler the pattern inventory
     * @return true if a pattern has been converted, false otherwise
     */
    boolean migratePatternInventory(IItemHandler handler);

    /**
     * Migrates a single pattern stack.
     * Returns true if the stack was modified, and the caller should then mark their inventory dirty.
     * You most likely need {@link #migratePatternInventory(IItemHandler)}.
     *
     * @param pattern the pattern
     * @return true if the pattern has been converted, false otherwise
     */
    boolean migratePattern(ItemStack pattern);
}


text:
package org.apache.servicecomb.demo.springmvc.tests;

import org.apache.servicecomb.core.SCBEngine;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
public class SpringMvcSpringIntegrationTest extends SpringMvcIntegrationTestBase {
  @BeforeClass
  public static void init() {
    System.setProperty("servicecomb.uploads.directory", "/tmp");
    SpringApplication.run(SpringMvcSpringMain.class);
  }

  @AfterClass
  public static void shutdown() {
    SCBEngine.getInstance().destroy();
  }
}


text:
#ifndef __BASE64_H__
#define __BASE64_H__

/** @addtogroup Utilities
  * @{
  */

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief	Encode binary to base64 ASCII format.
 *
 * @param 	pSrc 	: Pointer to source binary data
 * @param	SrcLen	: Source data length in bytes
 * @param	pDest	: Pointer to ASCII destination buffer
 * @param	DstLen	: Destination buffer length in bytes
 *
 * @return	Number of bytes encoded
 */
int Base64Encode(uint8_t *pSrc, int SrcLen, char *pDest, int DstLen);

/** @} End of group Utilities */

#ifdef __cplusplus
}
#endif

#endif // __BASE64_H__


text:
<configuration>
  <loggers>
    <root level="INFO">
      <appenderRef ref="console"/>
    </root>
    <logger name="com.zaxxer.hikari.pool.PoolBase" level="WARN"/>
  </loggers>
  <appenders>
    <console name="console" target="SYSTEM_OUT">
      <patternLayout
        pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n"/>
    </console>
  </appenders>
</configuration>


text:
package hu.scelightapi.search;

import hu.scelight.search.Connection;
import hu.scelightapibase.util.IEnum;
import hu.scelightapibase.util.gui.HasRIcon;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Logical connection between filters.
 *
 * @author Andras Belicza
 *
 * @see IEnum
 */
public interface IConnection extends HasRIcon, IEnum {

	/** Logical AND. */
	IConnection         AND        = Connection.AND;

	/** Closing parenthesis, logical OR and opening parenthesis. */
	IConnection         C_OR_O     = Connection.C_OR_O;

	/** Logical OR. */
	IConnection         OR         = Connection.OR;

	/** Closing parenthesis and logical OR. */
	IConnection         C_OR       = Connection.C_OR;

	/** Logical OR and opening parenthesis. */
	IConnection         OR_O       = Connection.OR_O;

	/** Closing parenthesis and logical AND. */
	IConnection         C_AND      = Connection.C_AND;

	/** Closing parenthesis, logical AND and opening parenthesis. */
	IConnection         C_AND_O    = Connection.C_AND_O;

	/** Logical AND and opening parenthesis. */
	IConnection         AND_O      = Connection.AND_O;

	/** An unmodifiable list of all the connections. */
	List< IConnection > VALUE_LIST = Collections.unmodifiableList( Arrays.< IConnection > asList( Connection.VALUES ) );

	/**
	 * Tells if this connection opens a parenthesis (after).
	 *
	 * @return true if this connection opens a parenthesis (after); false otherwise
	 */
	boolean isOpening();

	/**
	 * Tells if this connection closes a parenthesis (before).
	 *
	 * @return true if this connection opens a parenthesis (after); false otherwise
	 */
	boolean isClosing();

	/**
	 * Returns the precedence of the logical connection.
	 *
	 * @return the precedence of the logical connection
	 */
	int getPrecedence();

	/**
	 * Returns an {@link IConnection} which is derived from this by removing the closing parenthesis.
	 *
	 * @return an {@link IConnection} which is derived from this by removing the closing parenthesis
	 */
	IConnection removeClosing();

	/**
	 * Returns an {@link IConnection} which is derived from this by removing the opening parenthesis.
	 *
	 * @return an {@link IConnection} which is derived from this by removing the opening parenthesis
	 */
	IConnection removeOpening();

}


text:
package com.sopnopriyo.application.web.rest;

import com.sopnopriyo.application.SopnopriyoApp;
import com.sopnopriyo.application.domain.Authority;
import com.sopnopriyo.application.domain.User;
import com.sopnopriyo.application.repository.UserRepository;
import com.sopnopriyo.application.security.AuthoritiesConstants;
import com.sopnopriyo.application.service.MailService;
import com.sopnopriyo.application.service.UserService;
import com.sopnopriyo.application.service.dto.UserDTO;
import com.sopnopriyo.application.service.mapper.UserMapper;
import com.sopnopriyo.application.web.rest.errors.ExceptionTranslator;
import com.sopnopriyo.application.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.*;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Test class for the UserResource REST controller.
 *
 * @see UserResource
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SopnopriyoApp.class)
public class UserResourceIntTest {

    private static final String DEFAULT_LOGIN = "johndoe";
    private static final String UPDATED_LOGIN = "jhipster";

    private static final Long DEFAULT_ID = 1L;

    private static final String DEFAULT_PASSWORD = "passjohndoe";
    private static final String UPDATED_PASSWORD = "passjhipster";

    private static final String DEFAULT_EMAIL = "johndoe@localhost";
    private static final String UPDATED_EMAIL = "jhipster@localhost";

    private static final String DEFAULT_FIRSTNAME = "john";
    private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";

    private static final String DEFAULT_LASTNAME = "doe";
    private static final String UPDATED_LASTNAME = "jhipsterLastName";

    private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
    private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";

    private static final String DEFAULT_LANGKEY = "en";
    private static final String UPDATED_LANGKEY = "fr";

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MailService mailService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    @Autowired
    private CacheManager cacheManager;

    private MockMvc restUserMockMvc;

    private User user;

    @Before
    public void setup() {
        cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
        cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
        UserResource userResource = new UserResource(userService, userRepository, mailService);

        this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setMessageConverters(jacksonMessageConverter)
            .build();
    }

    /**
     * Create a User.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which has a required relationship to the User entity.
     */
    public static User createEntity(EntityManager em) {
        User user = new User();
        user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
        user.setPassword(RandomStringUtils.random(60));
        user.setActivated(true);
        user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
        user.setFirstName(DEFAULT_FIRSTNAME);
        user.setLastName(DEFAULT_LASTNAME);
        user.setImageUrl(DEFAULT_IMAGEURL);
        user.setLangKey(DEFAULT_LANGKEY);
        return user;
    }

    @Before
    public void initTest() {
        user = createEntity(em);
        user.setLogin(DEFAULT_LOGIN);
        user.setEmail(DEFAULT_EMAIL);
    }

    @Test
    @Transactional
    public void createUser() throws Exception {
        int databaseSizeBeforeCreate = userRepository.findAll().size();

        // Create the User
        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setLogin(DEFAULT_LOGIN);
        managedUserVM.setPassword(DEFAULT_PASSWORD);
        managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
        managedUserVM.setLastName(DEFAULT_LASTNAME);
        managedUserVM.setEmail(DEFAULT_EMAIL);
        managedUserVM.setActivated(true);
        managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
        managedUserVM.setLangKey(DEFAULT_LANGKEY);
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        restUserMockMvc.perform(post("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isCreated());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeCreate + 1);
        User testUser = userList.get(userList.size() - 1);
        assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
        assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
        assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
    }

    @Test
    @Transactional
    public void createUserWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = userRepository.findAll().size();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setId(1L);
        managedUserVM.setLogin(DEFAULT_LOGIN);
        managedUserVM.setPassword(DEFAULT_PASSWORD);
        managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
        managedUserVM.setLastName(DEFAULT_LASTNAME);
        managedUserVM.setEmail(DEFAULT_EMAIL);
        managedUserVM.setActivated(true);
        managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
        managedUserVM.setLangKey(DEFAULT_LANGKEY);
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // An entity with an existing ID cannot be created, so this API call must fail
        restUserMockMvc.perform(post("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isBadRequest());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void createUserWithExistingLogin() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);
        int databaseSizeBeforeCreate = userRepository.findAll().size();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used
        managedUserVM.setPassword(DEFAULT_PASSWORD);
        managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
        managedUserVM.setLastName(DEFAULT_LASTNAME);
        managedUserVM.setEmail("anothermail@localhost");
        managedUserVM.setActivated(true);
        managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
        managedUserVM.setLangKey(DEFAULT_LANGKEY);
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // Create the User
        restUserMockMvc.perform(post("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isBadRequest());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void createUserWithExistingEmail() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);
        int databaseSizeBeforeCreate = userRepository.findAll().size();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setLogin("anotherlogin");
        managedUserVM.setPassword(DEFAULT_PASSWORD);
        managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
        managedUserVM.setLastName(DEFAULT_LASTNAME);
        managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used
        managedUserVM.setActivated(true);
        managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
        managedUserVM.setLangKey(DEFAULT_LANGKEY);
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // Create the User
        restUserMockMvc.perform(post("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isBadRequest());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void getAllUsers() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);

        // Get all the users
        restUserMockMvc.perform(get("/api/users?sort=id,desc")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
            .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
            .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
            .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
            .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
            .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
    }

    @Test
    @Transactional
    public void getUser() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);

        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();

        // Get the user
        restUserMockMvc.perform(get("/api/users/{login}", user.getLogin()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.login").value(user.getLogin()))
            .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
            .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
            .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
            .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
            .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));

        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull();
    }

    @Test
    @Transactional
    public void getNonExistingUser() throws Exception {
        restUserMockMvc.perform(get("/api/users/unknown"))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateUser() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);
        int databaseSizeBeforeUpdate = userRepository.findAll().size();

        // Update the user
        User updatedUser = userRepository.findById(user.getId()).get();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setId(updatedUser.getId());
        managedUserVM.setLogin(updatedUser.getLogin());
        managedUserVM.setPassword(UPDATED_PASSWORD);
        managedUserVM.setFirstName(UPDATED_FIRSTNAME);
        managedUserVM.setLastName(UPDATED_LASTNAME);
        managedUserVM.setEmail(UPDATED_EMAIL);
        managedUserVM.setActivated(updatedUser.getActivated());
        managedUserVM.setImageUrl(UPDATED_IMAGEURL);
        managedUserVM.setLangKey(UPDATED_LANGKEY);
        managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
        managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
        managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
        managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        restUserMockMvc.perform(put("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isOk());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeUpdate);
        User testUser = userList.get(userList.size() - 1);
        assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
        assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
        assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
        assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
        assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
    }

    @Test
    @Transactional
    public void updateUserLogin() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);
        int databaseSizeBeforeUpdate = userRepository.findAll().size();

        // Update the user
        User updatedUser = userRepository.findById(user.getId()).get();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setId(updatedUser.getId());
        managedUserVM.setLogin(UPDATED_LOGIN);
        managedUserVM.setPassword(UPDATED_PASSWORD);
        managedUserVM.setFirstName(UPDATED_FIRSTNAME);
        managedUserVM.setLastName(UPDATED_LASTNAME);
        managedUserVM.setEmail(UPDATED_EMAIL);
        managedUserVM.setActivated(updatedUser.getActivated());
        managedUserVM.setImageUrl(UPDATED_IMAGEURL);
        managedUserVM.setLangKey(UPDATED_LANGKEY);
        managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
        managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
        managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
        managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        restUserMockMvc.perform(put("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isOk());

        // Validate the User in the database
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeUpdate);
        User testUser = userList.get(userList.size() - 1);
        assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
        assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
        assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
        assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
        assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
        assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
    }

    @Test
    @Transactional
    public void updateUserExistingEmail() throws Exception {
        // Initialize the database with 2 users
        userRepository.saveAndFlush(user);

        User anotherUser = new User();
        anotherUser.setLogin("jhipster");
        anotherUser.setPassword(RandomStringUtils.random(60));
        anotherUser.setActivated(true);
        anotherUser.setEmail("jhipster@localhost");
        anotherUser.setFirstName("java");
        anotherUser.setLastName("hipster");
        anotherUser.setImageUrl("");
        anotherUser.setLangKey("en");
        userRepository.saveAndFlush(anotherUser);

        // Update the user
        User updatedUser = userRepository.findById(user.getId()).get();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setId(updatedUser.getId());
        managedUserVM.setLogin(updatedUser.getLogin());
        managedUserVM.setPassword(updatedUser.getPassword());
        managedUserVM.setFirstName(updatedUser.getFirstName());
        managedUserVM.setLastName(updatedUser.getLastName());
        managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser
        managedUserVM.setActivated(updatedUser.getActivated());
        managedUserVM.setImageUrl(updatedUser.getImageUrl());
        managedUserVM.setLangKey(updatedUser.getLangKey());
        managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
        managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
        managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
        managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        restUserMockMvc.perform(put("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isBadRequest());
    }

    @Test
    @Transactional
    public void updateUserExistingLogin() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);

        User anotherUser = new User();
        anotherUser.setLogin("jhipster");
        anotherUser.setPassword(RandomStringUtils.random(60));
        anotherUser.setActivated(true);
        anotherUser.setEmail("jhipster@localhost");
        anotherUser.setFirstName("java");
        anotherUser.setLastName("hipster");
        anotherUser.setImageUrl("");
        anotherUser.setLangKey("en");
        userRepository.saveAndFlush(anotherUser);

        // Update the user
        User updatedUser = userRepository.findById(user.getId()).get();

        ManagedUserVM managedUserVM = new ManagedUserVM();
        managedUserVM.setId(updatedUser.getId());
        managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser
        managedUserVM.setPassword(updatedUser.getPassword());
        managedUserVM.setFirstName(updatedUser.getFirstName());
        managedUserVM.setLastName(updatedUser.getLastName());
        managedUserVM.setEmail(updatedUser.getEmail());
        managedUserVM.setActivated(updatedUser.getActivated());
        managedUserVM.setImageUrl(updatedUser.getImageUrl());
        managedUserVM.setLangKey(updatedUser.getLangKey());
        managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
        managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
        managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
        managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
        managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        restUserMockMvc.perform(put("/api/users")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
            .andExpect(status().isBadRequest());
    }

    @Test
    @Transactional
    public void deleteUser() throws Exception {
        // Initialize the database
        userRepository.saveAndFlush(user);
        int databaseSizeBeforeDelete = userRepository.findAll().size();

        // Delete the user
        restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();

        // Validate the database is empty
        List<User> userList = userRepository.findAll();
        assertThat(userList).hasSize(databaseSizeBeforeDelete - 1);
    }

    @Test
    @Transactional
    public void getAllAuthorities() throws Exception {
        restUserMockMvc.perform(get("/api/users/authorities")
            .accept(TestUtil.APPLICATION_JSON_UTF8)
            .contentType(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)));
    }

    @Test
    @Transactional
    public void testUserEquals() throws Exception {
        TestUtil.equalsVerifier(User.class);
        User user1 = new User();
        user1.setId(1L);
        User user2 = new User();
        user2.setId(user1.getId());
        assertThat(user1).isEqualTo(user2);
        user2.setId(2L);
        assertThat(user1).isNotEqualTo(user2);
        user1.setId(null);
        assertThat(user1).isNotEqualTo(user2);
    }

    @Test
    public void testUserFromId() {
        assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
        assertThat(userMapper.userFromId(null)).isNull();
    }

    @Test
    public void testUserDTOtoUser() {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(DEFAULT_ID);
        userDTO.setLogin(DEFAULT_LOGIN);
        userDTO.setFirstName(DEFAULT_FIRSTNAME);
        userDTO.setLastName(DEFAULT_LASTNAME);
        userDTO.setEmail(DEFAULT_EMAIL);
        userDTO.setActivated(true);
        userDTO.setImageUrl(DEFAULT_IMAGEURL);
        userDTO.setLangKey(DEFAULT_LANGKEY);
        userDTO.setCreatedBy(DEFAULT_LOGIN);
        userDTO.setLastModifiedBy(DEFAULT_LOGIN);
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        User user = userMapper.userDTOToUser(userDTO);
        assertThat(user.getId()).isEqualTo(DEFAULT_ID);
        assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
        assertThat(user.getActivated()).isEqualTo(true);
        assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
        assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
        assertThat(user.getCreatedBy()).isNull();
        assertThat(user.getCreatedDate()).isNotNull();
        assertThat(user.getLastModifiedBy()).isNull();
        assertThat(user.getLastModifiedDate()).isNotNull();
        assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
    }

    @Test
    public void testUserToUserDTO() {
        user.setId(DEFAULT_ID);
        user.setCreatedBy(DEFAULT_LOGIN);
        user.setCreatedDate(Instant.now());
        user.setLastModifiedBy(DEFAULT_LOGIN);
        user.setLastModifiedDate(Instant.now());
        Set<Authority> authorities = new HashSet<>();
        Authority authority = new Authority();
        authority.setName(AuthoritiesConstants.USER);
        authorities.add(authority);
        user.setAuthorities(authorities);

        UserDTO userDTO = userMapper.userToUserDTO(user);

        assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
        assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
        assertThat(userDTO.isActivated()).isEqualTo(true);
        assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
        assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
        assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
        assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
        assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
        assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
        assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
        assertThat(userDTO.toString()).isNotNull();
    }

    @Test
    public void testAuthorityEquals() {
        Authority authorityA = new Authority();
        assertThat(authorityA).isEqualTo(authorityA);
        assertThat(authorityA).isNotEqualTo(null);
        assertThat(authorityA).isNotEqualTo(new Object());
        assertThat(authorityA.hashCode()).isEqualTo(0);
        assertThat(authorityA.toString()).isNotNull();

        Authority authorityB = new Authority();
        assertThat(authorityA).isEqualTo(authorityB);

        authorityB.setName(AuthoritiesConstants.ADMIN);
        assertThat(authorityA).isNotEqualTo(authorityB);

        authorityA.setName(AuthoritiesConstants.USER);
        assertThat(authorityA).isNotEqualTo(authorityB);

        authorityB.setName(AuthoritiesConstants.USER);
        assertThat(authorityA).isEqualTo(authorityB);
        assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode());
    }
}


text:
package com.google.gerrit.server.schema;

import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Set;

public class Schema_117 extends SchemaVersion {
  @Inject
  Schema_117(Provider<Schema_116> prior) {
    super(prior);
  }

  @Override
  protected void preUpdateSchema(ReviewDb db) throws OrmException, SQLException {
    JdbcSchema schema = (JdbcSchema) db;
    Connection connection = schema.getConnection();
    String tableName = "patch_sets";
    String oldColumnName = "push_certficate";
    String newColumnName = "push_certificate";
    Set<String> columns = schema.getDialect().listColumns(connection, tableName);
    if (columns.contains(oldColumnName)) {
      renameColumn(db, tableName, oldColumnName, newColumnName);
    }
    try (Statement stmt = schema.getConnection().createStatement()) {
      stmt.execute("ALTER TABLE " + tableName + " MODIFY " + newColumnName + " clob");
    } catch (SQLException e) {
      // Ignore.  Type may have already been modified manually.
    }
  }
}


text:
.class Lcom/htc/hfm/HfmClient$1;
.super Ljava/lang/Object;
.source "HfmClient.java"

# interfaces
.implements Landroid/content/ServiceConnection;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/hfm/HfmClient;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/htc/hfm/HfmClient;

# direct methods
.method constructor <init>(Lcom/htc/hfm/HfmClient;)V
    .locals 0
    .parameter

    .prologue
    .line 362
    iput-object p1, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V
    .locals 3
    .parameter "name"
    .parameter "binder"

    .prologue
    .line 374
    invoke-static {}, Lcom/htc/hfm/HfmClient;->access$000()Ljava/lang/String;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "onServiceConnected: name="

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 375
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    invoke-static {p2}, Lcom/htc/hfm/IHfmService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/htc/hfm/IHfmService;

    move-result-object v1

    #setter for: Lcom/htc/hfm/HfmClient;->mIHfmService:Lcom/htc/hfm/IHfmService;
    invoke-static {v0, v1}, Lcom/htc/hfm/HfmClient;->access$402(Lcom/htc/hfm/HfmClient;Lcom/htc/hfm/IHfmService;)Lcom/htc/hfm/IHfmService;

    .line 376
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    const/4 v1, 0x1

    #setter for: Lcom/htc/hfm/HfmClient;->mIsBound:Z
    invoke-static {v0, v1}, Lcom/htc/hfm/HfmClient;->access$302(Lcom/htc/hfm/HfmClient;Z)Z

    .line 377
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    #calls: Lcom/htc/hfm/HfmClient;->next()V
    invoke-static {v0}, Lcom/htc/hfm/HfmClient;->access$500(Lcom/htc/hfm/HfmClient;)V

    .line 378
    return-void
.end method

.method public onServiceDisconnected(Landroid/content/ComponentName;)V
    .locals 4
    .parameter "name"

    .prologue
    const/4 v3, 0x0

    .line 365
    invoke-static {}, Lcom/htc/hfm/HfmClient;->access$000()Ljava/lang/String;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "onServiceDisconnected: name="

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 366
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    #setter for: Lcom/htc/hfm/HfmClient;->mCurrentAction:Lcom/htc/hfm/HfmClient$Action;
    invoke-static {v0, v3}, Lcom/htc/hfm/HfmClient;->access$102(Lcom/htc/hfm/HfmClient;Lcom/htc/hfm/HfmClient$Action;)Lcom/htc/hfm/HfmClient$Action;

    .line 367
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    #setter for: Lcom/htc/hfm/HfmClient;->mSessionId:Ljava/lang/String;
    invoke-static {v0, v3}, Lcom/htc/hfm/HfmClient;->access$202(Lcom/htc/hfm/HfmClient;Ljava/lang/String;)Ljava/lang/String;

    .line 368
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    const/4 v1, 0x0

    #setter for: Lcom/htc/hfm/HfmClient;->mIsBound:Z
    invoke-static {v0, v1}, Lcom/htc/hfm/HfmClient;->access$302(Lcom/htc/hfm/HfmClient;Z)Z

    .line 369
    iget-object v0, p0, Lcom/htc/hfm/HfmClient$1;->this$0:Lcom/htc/hfm/HfmClient;

    #setter for: Lcom/htc/hfm/HfmClient;->mIHfmService:Lcom/htc/hfm/IHfmService;
    invoke-static {v0, v3}, Lcom/htc/hfm/HfmClient;->access$402(Lcom/htc/hfm/HfmClient;Lcom/htc/hfm/IHfmService;)Lcom/htc/hfm/IHfmService;

    .line 370
    return-void
.end method


text:
cd ~/Documents;
git clone https://ibm-bluemix-mobile-services:${GH_TOKEN}@github.com/ibm-bluemix-mobile-services/bms-pushnotifications-serversdk-nodejs.git;
cd bms-pushnotifications-serversdk-nodejs;
git remote rm origin;
git remote add origin https://ibm-bluemix-mobile-services:${GH_TOKEN}@github.com/ibm-bluemix-mobile-services/bms-pushnotifications-serversdk-nodejs.git;
echo $token >> $HOME/.npmrc;
version=$(jq '.version' package.json | tr -d '"');
git tag "${version}";
git push origin --tags;
npm publish;
echo "Published NodeJS server Push plugin version ${version}";


text:
neo_hwp
=======

Find the heaviest weighted path

This is an unmanaged extension.

1. Build it:

        mvn clean package

2. Copy target/hwp-1.0.jar to the plugins/ directory of your Neo4j server.

3. Configure Neo4j by adding a line to conf/neo4j-server.properties:

        org.neo4j.server.thirdparty_jaxrs_classes=org.neo4j.hwp=/ext

4. Start Neo4j server.

5. Query it over HTTP:

        curl http://localhost:7474/ext/service/hwp/A


text:
module Polyseerio
  module SDK
    # Instance methods.
    module Method
      def self.add_fact
        proc do |instance, key, value|
          instance._facts ||= {}

          instance._facts[key] = value
        end
      end
    end
  end
end


text:
package com.elegion.nbumakov.customviewexample;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

import com.elegion.nbumakov.customviewexample.util.IBearingAware;

/**
 * @author Nikita Bumakov
 */
public class CompassView extends View implements IBearingAware {

    //region ---------------------------------------- Variables

    private float northDirection; // in degrees

    private final Paint bitmapPaint = new Paint();
    private final Paint needlePaint = new Paint();

    private Canvas mCanvas;

    protected Bitmap mNeedleBitmap, mScaledRoseBitmap, mCanvasBitmap;

    protected int mCenterX, mCenterY, mSize;
    protected int mNeedleWidth = 8;

    //endregion

    public CompassView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        needlePaint.setAntiAlias(true);
        needlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        needlePaint.setStrokeWidth(1);

        bitmapPaint.setFilterBitmap(true);
        bitmapPaint.setAntiAlias(true);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mSize = Math.min(h, w);

        mCenterX = w / 2;
        mCenterY = h / 2;
        mNeedleWidth = mSize / 30;

        recycleBitmaps();

        mCanvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCanvasBitmap);

        mScaledRoseBitmap = getRouse();
        mNeedleBitmap = createNeedle();
    }

    @Override
    public void onDraw(Canvas drawCanvas) {
        mCanvasBitmap.eraseColor(Color.TRANSPARENT);

        mCanvas.save();
        mCanvas.translate(mCenterX, mCenterY);
        mCanvas.drawBitmap(mScaledRoseBitmap, -mCenterX, -mCenterY, bitmapPaint);

        drawNeedle(mCanvas, northDirection);
        mCanvas.restore();

        drawCanvas.drawBitmap(mCanvasBitmap, 0, 0, null);
    }

    private void drawNeedle(Canvas canvas, float direction) {
        canvas.rotate(direction);
        canvas.drawBitmap(mNeedleBitmap, -mNeedleBitmap.getWidth() / 2, -mNeedleBitmap.getHeight() / 2, bitmapPaint);
        canvas.rotate(-direction);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int size = width > height ? height : width;
        setMeasuredDimension(size, size);
    }

    @Override
    public void updateBearing(float bearing) {
        northDirection = -bearing;
        post(new Runnable() {
            @Override
            public void run() {
                invalidate();
            }
        });
    }

    //region ---------------------------------------- Helpers methods

    protected Bitmap getRouse() {
        Bitmap roseOrigin = BitmapFactory.decodeResource(getResources(), R.raw.compass_rose_pale);
        Bitmap scaled = Bitmap.createScaledBitmap(roseOrigin, mSize, mSize, true);
        roseOrigin.recycle();
        return scaled;
    }

    private Bitmap createNeedle() {
        Bitmap bitmap = Bitmap.createBitmap(mNeedleWidth * 3, mSize, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Path needlePath = createNeedlePath();

        canvas.translate(mNeedleWidth * 1.5f, mSize / 2);

        needlePaint.setARGB(200, 255, 0, 0);
        canvas.drawPath(needlePath, needlePaint);

        canvas.rotate(180);
        needlePaint.setARGB(200, 0, 0, 255);
        canvas.drawPath(needlePath, needlePaint);

        needlePaint.setColor(Color.argb(255, 255, 230, 110));
        canvas.drawCircle(0, 0, mNeedleWidth * 1.5f, needlePaint);

        return bitmap;
    }

    private Path createNeedlePath() {
        Path needlePath = new Path();
        needlePath.moveTo(-mNeedleWidth, 0);
        needlePath.lineTo(0, -mSize * 0.425f);
        needlePath.lineTo(mNeedleWidth, 0);
        needlePath.close();
        return needlePath;
    }

    //endregion

    private void recycleBitmaps() {
        if (mScaledRoseBitmap != null) {
            mScaledRoseBitmap.recycle();
        }
        if (mNeedleBitmap != null) {
            mNeedleBitmap.recycle();
        }
        if (mCanvasBitmap != null) {
            mCanvasBitmap.recycle();
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class PlayerCanvasController : MonoBehaviour {
    public TextMeshProUGUI playerName;

    void Awake()
    {
        playerName.text = GameManager.Instance.playerData.name;
    }
    public void OnClickStart()
    {
        SceneManager.LoadScene("GamePlay");
    }

}


text:
package gochimp3

const (
	root_path = "/"
)

type AccountContact struct {
	Company string `json:"company"`
	Addr1   string `json:"addr1"`
	Addr2   string `json:"addr2"`
	City    string `json:"city"`
	State   string `json:"state"`
	Zip     string `json:"zip"`
	Country string `json:"country"`
}

type IndustryStats struct {
	OpenRate   float64 `json:"open_rate"`
	BounceRate float64 `json:"bounce_rate"`
	ClickRate  float64 `json:"click_rate"`
}

// RootResponse - https://developer.mailchimp.com/documentation/mailchimp/reference/root/#read-get_root
type RootResponse struct {
	AccountID        string         `json:"account_id"`
	AccountName      string         `json:"account_name"`
	Email            string         `json:"email"`
	Role             string         `json:"role"`
	Contact          AccountContact `json:"contact"`
	ProEnabled       bool           `json:"pro_enabled"`
	LastLogin        string         `json:"last_login"`
	TotalSubscribers int            `json:"total_subscribers"`
	IndustyStats     IndustryStats  `json:"industry_stats"`
	Links            []Link         `json:"_links"`
}

// GetRoot queries the root of the API for stats
func (api *API) GetRoot(params *BasicQueryParams) (*RootResponse, error) {
	response := new(RootResponse)
	err := api.Request("GET", root_path, params, nil, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}


text:
'use strict';

// Module dependencies
const assert = require('assert');
const EventEmitter = require('events');
const path = require('path');
const _ = require('lodash');
const utils = require('./utils');

// Constants
const SUPPORT_ADAPTER_NAMES = ['express', 'socketio', 'rpc'];
const REQUIRED_PARAM_KEYS = ['name'];
const DEFAULT_UPLOAD_OPTIONS = { fields: [{ name: 'file', maxCount: 1 }] };
const PARAMETER_ENGINES = {};

class Action extends EventEmitter {
  static create(name, options, handler) {
    return new Action(name, options, handler);
  }

  static registerParameterEngine(name, parser) {
    PARAMETER_ENGINES[name] = parser;
  }

  constructor(name, options, handler) {
    super();

    this.name = name || options.name;
    assert(typeof this.name === 'string', 'Action name must be a valid string');
    assert(typeof handler === 'function', 'Action handler must be a valid function');

    // Parent reference
    this.parent = null;

    // Stack to be executed, must be composed before server starts
    this.stack = null;

    // Stack to be executed before sending response
    this.beforeRespondStack = null;

    // handler function
    this.handler = handler;

    // Action options
    this.options = options || {};

    // Parameters accpetance schema
    this._validateAndSetParams(options.params || options.accepts);

    // Set supported adapter(s)
    this._validateAndSetAdapters(options.adapters || options.adapter);

    // Action route config
    this._validateAndSetRoute(options.http || options.route);

    // Action description, notes for debug info and documentation usage
    this._validateAndSetDocumentation(options);

    this._determineWhetherHooksShouldBeSkiped();

    // File upload support: multipart/form-data
    this.upload = options.upload ? (
      options.upload === true ? DEFAULT_UPLOAD_OPTIONS : options.upload
    ) : false;

    // Extra attibutes that can be used by plugins to store customized data
    this.extra = options.extra || {};
  }

  // Validate whether params schema is valid
  _validateAndSetParams(params) {
    let errorMessages = [];
    let fullName = this.fullName();

    // let paramsEngine = params.

    function _buildParams(params, index) {
      index = index || '';
      params = params || [];
      if (!Array.isArray(params)) params = [params];

      _.each(params, function(param, i) {
        param = _.assign({}, param);

        _.each(REQUIRED_PARAM_KEYS, function(key) {
          if (!param[key]) {
            errorMessages.push(
              `\`${key}\` is missing for params of \`${fullName}\` action at position ${index}[${i}]`
            );
          }
        });

        // Check inner params
        if (param.params) {
          param.params = _buildParams(param.params, `[${i}].params`);
        }

        params[i] = param;
      });

      return params;
    }

    // Check params one by one
    params = _buildParams(params);

    // Throw out errors
    if (errorMessages.length) throw new Error(errorMessages.join('\n'));

    this.params = params;
  }

  // Validate and set adapters
  _validateAndSetAdapters(adapters) {
    // Assign default adapters
    if (!adapters) adapters = ['all'];

    // Convert adapters into an array
    if (!Array.isArray(adapters)) adapters = [adapters];

    // If `all` is included, then add all supported adapters
    if (~adapters.indexOf('all')) {
      this.adapters = SUPPORT_ADAPTER_NAMES.slice();
    }
    // Else check whether adapter names are valid
    else {
      this.adapters = adapters;
      // check adapter validation
      _.each(this.adapters, function(adapter) {
        assert(
          ~SUPPORT_ADAPTER_NAMES.indexOf(adapter),
          `Invalid adapter name found: '${adapter}'`
        );
      });
    }
  }

  // Validate and set route config
  _validateAndSetRoute(route) {
    this.route = route || {};
    // Set default verb
    if (!this.route.verb) this.route.verb = 'all';

    // Lowercase verb
    this.route.verb = String(this.route.verb).toLowerCase();

    // Set default path
    if (!this.route.path) this.route.path = '/';
  }

  // Validate and set documentation related options
  _validateAndSetDocumentation(options) {
    this.description = options.description || options.desc || this.name;
    this.notes = options.notes;
    this.documented = options.documented !== false;
  }

  // Determine whether hooks should be skiped, expecially for middlewarified action
  _determineWhetherHooksShouldBeSkiped() {
    // Skip beforeHooks and afterHooks or not, default is `true` when route.verb is `use` otherwise `false`
    this.skipHooks = this.route.verb === 'use';
    if (this.options.skipHooks === true) {
      this.skipHooks = true;
    } else if (this.options.skipHooks === false) {
      this.skipHooks = false;
    }
  }

  // Check whether a action is support a specific adapter
  isSupport(adapterName) {
    return !!~this.adapters.indexOf(adapterName);
  }

  fullPath() {
    if (this._fullPath) return this._fullPath;

    let segments = ['/'];
    if (this.parent && typeof this.parent.fullPath === 'function') {
      segments.push(this.parent.fullPath());
    }
    segments.push(this.route.path);
    return path.posix.join.apply(path, segments);
  }

  clone() {
    let action = new Action(this.name, _.assign({}, this.options), this.handler);

    action.stack = null;
    action.adapters = this.adapters.slice();
    action.skipHooks = !!this.skipHooks;
    action.parent = this.parent;
    // use internal Object.assign to keep params as an array
    action.params = Object.assign([], this.params);
    action.description = this.description;
    action.notes = this.notes;
    action.documented = !!this.documented;
    action.route = _.assign({}, this.route);
    action.upload = this.upload ? _.assign({}, this.upload) : this.upload;
    action.extra = _.assign({}, this.extra);

    // Copy all events
    utils.copyEvents(this, action);

    return action;
  }

  // Action fullname, including parent's fullname
  fullName() {
    if (this._fullName) return this._fullName;

    if (this.parent && typeof this.parent.fullName === 'function') {
      return `${this.parent.fullName()}.${this.name}`;
    } else {
      return this.name;
    }
  }

  // Invoke action
  invoke() {
    assert(
      this.stack,
      `Action: '${this.fullName()}' must be composed before invoking`
    );

    return this.stack.apply(null, arguments);
  }

  // Invoke before respond action
  invokeBeforeRespond() {
    assert(
      this.beforeRespondStack,
      `Action: '${this.fullName()}' must be composed before invoking before responding action`
    );

    return this.beforeRespondStack.apply(null, arguments);
  }

  // Compose hooks and action for stack manner
  //    hooks = { before, after, error, beforeRespond }
  compose(hooks) {
    hooks = hooks || {};

    let stack = []
      .concat(this.skipHooks ? [] : (hooks.before || []))
      .concat(this.handler)
      .concat(this.skipHooks ? [] : (hooks.after || []));

      // Error handler
    let errorHandler;
    if (hooks.error && hooks.error.length) errorHandler = utils.compose(hooks.error);

    // Composed stack
    this.stack = utils.compose(stack, errorHandler);

    // Add before Respond stack
    this.beforeRespondStack = utils.compose(hooks.beforeRespond || [], errorHandler);
  }
}

module.exports = Action;


text:
import webob

from nova.api.openstack.compute import cloudpipe as clup_v21
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_network

fake_networks = [fake_network.fake_network(1),
                 fake_network.fake_network(2)]

def fake_project_get_networks(context, project_id, associate=True):
    return fake_networks

def fake_network_update(context, network_id, values):
    for network in fake_networks:
        if network['id'] == network_id:
            for key in values:
                network[key] = values[key]

class CloudpipeUpdateTestV21(test.NoDBTestCase):
    bad_request = exception.ValidationError

    def setUp(self):
        super(CloudpipeUpdateTestV21, self).setUp()
        self.stub_out("nova.db.project_get_networks",
                      fake_project_get_networks)
        self.stub_out("nova.db.network_update", fake_network_update)
        self._setup()
        self.req = fakes.HTTPRequest.blank('')

    def _setup(self):
        self.controller = clup_v21.CloudpipeController()

    def _check_status(self, expected_status, res, controller_method):
        self.assertEqual(expected_status, controller_method.wsgi_code)

    def test_cloudpipe_configure_project(self):
        body = {"configure_project": {"vpn_ip": "1.2.3.4", "vpn_port": 222}}
        result = self.controller.update(self.req, 'configure-project',
                                           body=body)
        self._check_status(202, result, self.controller.update)
        self.assertEqual(fake_networks[0]['vpn_public_address'], "1.2.3.4")
        self.assertEqual(fake_networks[0]['vpn_public_port'], 222)

    def test_cloudpipe_configure_project_bad_url(self):
        body = {"configure_project": {"vpn_ip": "1.2.3.4", "vpn_port": 222}}
        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.update, self.req,
                          'configure-projectx', body=body)

    def test_cloudpipe_configure_project_bad_data(self):
        body = {"configure_project": {"vpn_ipxx": "1.2.3.4", "vpn_port": 222}}
        self.assertRaises(self.bad_request,
                          self.controller.update, self.req,
                          'configure-project', body=body)

    def test_cloudpipe_configure_project_bad_vpn_port(self):
        body = {"configure_project": {"vpn_ipxx": "1.2.3.4",
                                      "vpn_port": "foo"}}
        self.assertRaises(self.bad_request,
                          self.controller.update, self.req,
                          'configure-project', body=body)

    def test_cloudpipe_configure_project_vpn_port_with_empty_string(self):
        body = {"configure_project": {"vpn_ipxx": "1.2.3.4",
                                      "vpn_port": ""}}
        self.assertRaises(self.bad_request,
                          self.controller.update, self.req,
                          'configure-project', body=body)


text:
package org.test.shop.model.dao.view;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.test.shop.config.settings.NamedFilter;
import org.test.shop.controller.data.types.ScrollableSettings;
import org.test.shop.model.domain.SObject;
import org.test.shop.model.domain.entity.view.UserDetailView;
import org.test.shop.util.DaoUtil;
import org.test.shop.util.data.types.DateCompare;
import org.test.shop.util.data.types.FindByDateExample;
import org.test.shop.util.data.types.FindByExample;
import org.test.shop.util.data.types.TotalQuery;

@Repository
public class UserDetailViewDao {

	@PersistenceContext
	private EntityManager em;
	private String selectClause = "SELECT use0 FROM UserDetailView use0";
	private String updatePopularityClause = "UPDATE %s SET popularity = :popularity WHERE id = :id";
	private String shortName = "use0";
	private String className = "UserDetailView";
	private String tableName = "user_detail_view";

	public UserDetailView create(UserDetailView userdetailview) {
		em.persist(userdetailview);
		return userdetailview;
	}

	public UserDetailView update(UserDetailView userdetailview) {
		return em.merge(userdetailview);
	}

	public void popularityByKey(Object key) {
		UserDetailView userdetailview = findById(key, false);

		if(userdetailview != null){
			if (SObject.class.isAssignableFrom(UserDetailView.class)) {
				if (userdetailview.getPopularity() == null) {
					userdetailview.setPopularity(-1);
				}
				userdetailview.setPopularity(userdetailview.getPopularity() + 1);
				try {
					em.createNativeQuery(String.format(updatePopularityClause, tableName), UserDetailView.class)
							.setParameter("popularity", userdetailview.getPopularity())
							.setParameter("id", key)
							.executeUpdate();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	public void popularity(UserDetailView item) {
		UserDetailView userdetailview = null;
		if(item != null){
			userdetailview = findById(item.getId(), false);
		}

		if(userdetailview != null){
			if (SObject.class.isAssignableFrom(UserDetailView.class)) {
				if (userdetailview.getPopularity() == null) {
					userdetailview.setPopularity(-1);
				}
				userdetailview.setPopularity(userdetailview.getPopularity() + 1);

				try {
					em.createNativeQuery(String.format(updatePopularityClause, tableName), UserDetailView.class)
							.setParameter("popularity", userdetailview.getPopularity())
							.setParameter("id", item.getId())
							.executeUpdate();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	public Integer todayNumber(ScrollableSettings settings) throws Exception {
		String today = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
		Query query = em.createNativeQuery(
				String.format(
						"SELECT count(*) from %s %s WHERE %s.firmid = %s and CAST(%s.createon as DATE) = CAST('%s' as DATE)"
						, tableName, shortName, shortName, settings.getSasUser().getUser().getFirmid(), shortName, today
				)
		);

		return ((BigInteger) query.getSingleResult()).intValue();
	}

	public Integer total(ScrollableSettings settings) throws Exception {
		TotalQuery totalQuery = DaoUtil.total(settings, UserDetailView.class, em);

		return ((BigInteger) totalQuery.getQuery().getSingleResult()).intValue();
	}

	public List<UserDetailView> namedFilter(ScrollableSettings settings) {
		List<UserDetailView> userdetailviews = new ArrayList<UserDetailView>();

		try {
			userdetailviews = DaoUtil.sasQueryByNamedFilter(NamedFilter.Items.byName(settings.getNamedfilter(), UserDetailView.class), settings,
				UserDetailView.class, em).getResultList();
		} catch (Exception e){
			e.printStackTrace();
		}

		return userdetailviews;
	}

	@SuppressWarnings("unchecked")
	public List<UserDetailView> search(ScrollableSettings settings){
		if(settings.getFilter() == null || settings.getFilter().replaceAll("\\s+", "").length() == 0){
			return new ArrayList<UserDetailView>();
		}

		FindByExample findByExample = DaoUtil.search(new UserDetailView(), settings.getFilter(), UserDetailView.class, em);
		Query query = null;

		if (findByExample.getIsNativeQuery()) {
			String queryString = DaoUtil.sasQueryRaw(findByExample.getSelectClause(), settings, UserDetailView.class, em);
			query = em.createNativeQuery(queryString.replace("SELECT " + shortName, "SELECT *").replace(className, DaoUtil.readTableName(UserDetailView.class)), UserDetailView.class);

			if(queryString.contains(":firmid")){
				query.setParameter("firmid", settings.getSasUser().getUser().getFirmid());
			}
			else if(queryString.contains(":firm")){
				query.setParameter("firm", settings.getSasUser().getUser().getFirmid());
			}

		}
		else {
			query = DaoUtil.sasQuery(findByExample.getSelectClause(), settings, UserDetailView.class, em);
		}

		query.setParameter("filter", findByExample.getFilter());
		if(findByExample.getSelectClause().contains("filterForInteger")){
			query.setParameter("filterForInteger", findByExample.getFilterForInteger());
		}

		return query.setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<UserDetailView> findByExample(UserDetailView example, String delimitter, ScrollableSettings settings) {
		FindByExample findByExample = DaoUtil.findByExampleQueryRaw(example,
				UserDetailView.class, em, " " + delimitter + " ");
		Query query = DaoUtil.sasQuery(findByExample.getSelectClause(),
				settings, UserDetailView.class, em);
		for (String key : findByExample.getValues().keySet()) {
			query.setParameter(key, findByExample.getValues().get(key));
		}

		return query.setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<UserDetailView> findByExample2(UserDetailView example, DateCompare type) {
		FindByDateExample findByExample = DaoUtil.findByExample2(example, UserDetailView.class, em, type).init();
		return findByExample.getQuery().setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<UserDetailView> findAll(ScrollableSettings settings) {
		List<UserDetailView> userdetailviews = DaoUtil.sasQuery(selectClause, settings,
				UserDetailView.class, em).getResultList();

		if (settings.getList().size() > 0) {
			for (UserDetailView item : userdetailviews) {
				item.customInit(item, settings.getList());
			}
		}

		if (settings.getInitLists() || settings.getInitDicts()) {
			for (UserDetailView item : userdetailviews) {
				if (settings.getInitDicts()) {
					item.initDicts();
				}
				if (settings.getInitLists()) {
					item.initList();
				}
			}
		}

		return userdetailviews;
	}

	@SuppressWarnings("unchecked")
	public List<UserDetailView> findAllScrollable(ScrollableSettings settings) {
		List<UserDetailView> userdetailviews = DaoUtil
				.sasQuery(selectClause, settings, UserDetailView.class, em)
				.setFirstResult(
						(settings.getPageNumber() - 1) * settings.getPageSize())
				.setMaxResults(settings.getPageSize()).getResultList();

		if (settings.getList().size() > 0) {
			for (UserDetailView item : userdetailviews) {
				item.customInit(item, settings.getList());
			}
		}

		if (settings.getInitLists() || settings.getInitDicts()) {
			for (UserDetailView item : userdetailviews) {
				if (settings.getInitDicts()) {
					item.initDicts();
				}
				if (settings.getInitLists()) {
					item.initList();
				}
			}
		}

		return userdetailviews;
	}

	public UserDetailView findById(Object key, Boolean initAll) {
		UserDetailView item = em.find(UserDetailView.class, key);

		if(item != null){
			if (initAll) {
				item.init();
			}
		}

		return item;
	}

	public UserDetailView findById(ScrollableSettings settings) {
		UserDetailView item = em.find(UserDetailView.class, settings.getId());

		if(item != null){
			if (settings.getList().size() > 0) {
				item.customInit(item, settings.getList());
			}

			if (settings.getInitDicts()) {
				item.initDicts();
			}

			if (settings.getInitLists()) {
				item.initList();
			}

			try {
				item.specialInit();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return item;
	}

	public Boolean delete(Object id) {
		try {
			em.remove(em.getReference(UserDetailView.class, id));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

}


text:
/**
 * Automatically generated file. DO NOT MODIFY
 */
package com.braintreepayments.api.data;

public final class BuildConfig {
  public static final boolean DEBUG = false;
  public static final String APPLICATION_ID = "com.braintreepayments.api.data";
  public static final String BUILD_TYPE = "release";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 18;
  public static final String VERSION_NAME = "1.2.7";
}


text:
<!doctype html>

    <title>nehan5 layout test</title>
    <meta content="ja" name="content-language">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <link href="../css/nehan.css" rel="stylesheet">
    <link href="catalog5.css" rel="stylesheet">

	<textarea id="source"></textarea>


text:
<template name="plus_button">

</template>


text:
local module = require("hs.mouse.internal")
local fnutils = require("hs.fnutils")
local geometry = require("hs.geometry")
local screen = require("hs.screen")

-- private variables and methods -----------------------------------------

local check_list = {}

-- Public interface ------------------------------------------------------

--- hs.mouse.getAbsolutePosition() -> point
--- Function
--- Gets the absolute co-ordinates of the mouse pointer
---
--- Parameters:
---  * None
---
--- Returns:
---  * A point-table containing the absolute x and y co-ordinates of the mouse pointer
---
--- Notes:
---  * The co-ordinates returned by this function are in relation to the full size of your desktop. If you have multiple monitors, the desktop is a large virtual rectangle that contains them all (e.g. if you have two 1920x1080 monitors and the mouse is in the middle of the second monitor, the returned table would be `{ x=2879, y=540 }`)
---  * Multiple monitors of different sizes can cause the co-ordinates of some areas of the desktop to be negative. This is perfectly normal. 0,0 in the co-ordinates of the desktop is the top left of the primary monitor
function module.getAbsolutePosition()
    return module.get()
end

--- hs.mouse.setAbsolutePosition(point)
--- Function
--- Sets the absolute co-ordinates of the mouse pointer
---
--- Parameters:
---  * point - A point-table containing the absolute x and y co-ordinates to move the mouse pointer to
---
--- Returns:
---  * None
---
--- Notes:
---  * The co-ordinates given to this function must be in relation to the full size of your desktop. See the notes for `hs.mouse.get` for more information
function module.setAbsolutePosition(point)
    return module.set(point)
end

--- hs.mouse.getRelativePosition() -> point or nil
--- Function
--- Gets the co-ordinates of the mouse pointer, relative to the screen it is on
---
--- Parameters:
---  * None
---
--- Returns:
---  * A point-table containing the relative x and y co-ordinates of the mouse pointer, or nil if an error occured
---
--- Notes:
---  * The co-ordinates returned by this function are relative to the top left pixel of the screen the mouse is on (see `hs.mouse.getAbsolutePosition` if you need the location in the full desktop space)
function module.getRelativePosition()
    local screen = module.getCurrentScreen()
    if screen == nil then
        return nil
    end

    local frame = screen:fullFrame()
    local point = module.getAbsolutePosition()
    local rel = {}

    rel["x"] = point["x"] - frame["x"]
    rel["y"] = point["y"] - frame["y"]

    return rel
end

--- hs.mouse.setRelativePosition(point[, screen])
--- Function
--- Sets the co-ordinates of the mouse pointer, relative to a screen
---
--- Parameters:
---  * point - A point-table containing the relative x and y co-ordinates to move the mouse pointer to
---  * screen - An optional `hs.screen` object. Defaults to the screen the mouse pointer is currently on
---
--- Returns:
---  * None
function module.setRelativePosition(point, screen)
    if screen == nil then
        screen = module.getCurrentScreen()
        if screen == nil then
            print("ERROR: Unable to find the current screen")
            return nil
        end
    end

    local frame = screen:fullFrame()
    local abs = {}

    abs["x"] = frame["x"] + point["x"]
    abs["y"] = frame["y"] + point["y"]

    return module.set(abs)
end

--- hs.mouse.getCurrentScreen() -> screen or nil
--- Function
--- Gets the screen the mouse pointer is on
---
--- Parameters:
---  * None
---
--- Returns:
---  * An `hs.screen` object that the mouse pointer is on, or nil if an error occurred
function module.getCurrentScreen()
    local point = module.get()
    return fnutils.find(screen.allScreens(), function(aScreen) return geometry.isPointInRect(point, aScreen:fullFrame()) end)
end

-- Return Module Object --------------------------------------------------

return module


text:
const toBeArray = require('./toBeArray');

module.exports = (size, actual) => toBeArray(actual) && actual.length === size;


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>PathRequester</title>

PathRequester()

语法

Path$ = PathRequester(Title$, InitialPath$)

概要

Opens the standard path requester for the user to select a path.

参数

Title$

The title of the requester window.

InitialPath$

The initial path to use when the requester is opened.

返回值

The selected path, or an empty string if the requester has been canceled by the user.

备注

The path is returned with the terminating '\' on Windows, or the terminating '/' on Linux and OS X.

示例

  InitialPath$ = "C:\"   ; set initial path to display (could also be blank)
  Path$ = PathRequester("Please choose your path", InitialPath$)
  If Path$
    MessageRequester("Information", "You have selected following path:"+Chr(10)+Path$, 0)
  Else
    MessageRequester("Information", "The requester was canceled.", 0)
  EndIf

已支持操作系统
所有

<- OpenFileRequester() - Requester Index - SaveFileRequester() ->


text:
using System;
using Newtonsoft.Json;

namespace ThingsOfInternet.Dtos
{
    public class SparkFunctionResponse
    {
        [JsonProperty("id")]
        public string Id { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("last_app")]
        public string LastApp { get; set; }
        [JsonProperty("connected")]
        public bool Connected { get; set; }
        [JsonProperty("return_value")]
        public int ReturnValue { get; set; }
    }
}


text:
configure do
  # Log queries to STDOUT in development
  if Sinatra::Application.development?
    ActiveRecord::Base.logger = Logger.new(STDOUT)
  end

if development?
  set :database, {
    adapter: "sqlite3",
    database: "db/db.sqlite3"
    # adapter: "postgresql",
    # database: "dfsofepbaf97gv",
    # username: "smedpfnjsymgdd",
    # password: "bx4jbrw68K-IZhHlMi9KgvdalD",
    # host: "ec2-54-197-238-19.compute-1.amazonaws.com",
    # port: 5432,
    # pool: 5,
    # encoding: "unicode",
    # min_messages: "error"

  }
else
  set :database, ENV['DATABASE_URL']
end

  # Load all models from app/models, using autoload instead of require
  # See http://www.rubyinside.com/ruby-techniques-revealed-autoload-1652.html
  Dir[APP_ROOT.join('app', 'models', '*.rb')].each do |model_file|
    filename = File.basename(model_file).gsub('.rb', '')
    autoload ActiveSupport::Inflector.camelize(filename), model_file
  end

end


text:
<?php

// Simulate the Dev PHP.ini
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('track_errors', '1');

// If the Composer autoloader is found
if (is_file(__DIR__.'/../vendor/autoload.php'))
{
    // Load the Composer autoloader
    require_once __DIR__.'/../vendor/autoload.php';
}

// ****************************************************************************
// Remove everything below this line, it is just for testing
// ****************************************************************************

// ****************************************************************************
// If you can read this from your web browser, PHP is not working correctly :-(
// ****************************************************************************

echo 'PHP is working'.nl2br(PHP_EOL);

// Attempt to connect to MySQL
$mysqli = @new mysqli('127.0.0.1', 'root', '');

// If the MySQL connection failed
if ($mysqli->connect_error)
{
	// Output failed
	echo 'MySQL connection is NOT working with current credentials'.nl2br(PHP_EOL);
}
// Else the MySQL connection was successful
else
{
	// Output success
	echo 'MySQL connection is successful'.nl2br(PHP_EOL);
}

try
{
    // Attempt to connect to MongoDB
    $connection = @new MongoClient('mongodb://127.0.0.1:27017');

    // Output success
    echo 'MongoDB connection is successful'.nl2br(PHP_EOL);
}
catch (MongoConnectionException $e)
{
    // Output failed
    echo 'MongoDB connection is NOT working'.nl2br(PHP_EOL);
}

echo nl2br(PHP_EOL);
echo 'Click here to open Adminer for MySQL.'.nl2br(PHP_EOL);
echo 'Click here to open Genghis for MongoDB.'.nl2br(PHP_EOL);


text:
    curl --request DELETE \
         --header 'Authorization: Token some-secret' \
         --url 'https://snippets.glot.io/admin/users/8aa7e7fc-4d9b-4f97-a950-887b55ddcf1c'

#### Response
A successful delete returns a 204 No Content, with an empty body.


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:layout_marginTop="?attr/actionBarSize">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/create_account_title"
            android:id="@+id/title"
            style="@style/Base.TextAppearance.AppCompat.Display1"
            android:textColor="@color/textColorPrimary"
            android:layout_marginBottom="8dp" />

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/create_account_description"
            android:textColor="@color/textColorPrimary"
            android:nextFocusDown="@+id/password"
            android:layout_marginBottom="8dp" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/emailTIL"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:textColor="@color/textColorPrimary"
                android:textColorHint="@color/textColorPrimary"
                android:hint="@string/email"
                style="@style/Base.TextAppearance.AppCompat.Large" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/idTIL"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/id"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColor="@color/textColorPrimary"
                android:textColorHint="@color/textColorPrimary"
                android:hint="@string/id_hint"
                style="@style/Base.TextAppearance.AppCompat.Large" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/passwordTIL"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="4dp">

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:textColor="@color/textColorPrimary"
                android:textColorHint="@color/textColorPrimary"
                android:hint="@string/password"
                style="@style/Base.TextAppearance.AppCompat.Large" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/confirmPasswordTIL"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="4dp">

            <EditText
                android:id="@+id/confirmPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:textColor="@color/textColorPrimary"
                android:textColorHint="@color/textColorPrimary"
                android:hint="@string/confirmPassword"
                style="@style/Base.TextAppearance.AppCompat.Large" />

        </android.support.design.widget.TextInputLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <android.support.v7.widget.AppCompatCheckBox
                android:id="@+id/showPassword"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="@string/showPassword"
                android:textColor="@color/textColorPrimary"
                android:layout_weight="1"/>

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/createAccount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0"
                android:text="@string/create_account"
                android:layout_gravity="end" />

        </LinearLayout>

    </LinearLayout>

    <FrameLayout
        android:id="@+id/loadingLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        android:visibility="invisible">

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:layout_gravity="center" />
    </FrameLayout>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:title="@string/app_name"
        app:title="@string/app_name"
        android:layout_gravity="top"
        android:visibility="visible" />

</FrameLayout>