text:
package org.innovateuk.ifs.project.invite;

import org.innovateuk.ifs.commons.error.CommonFailureKeys;
import org.innovateuk.ifs.invite.resource.ProjectUserInviteResource;
import org.innovateuk.ifs.invite.service.ProjectInviteRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.project.projectdetails.viewmodel.JoinAProjectViewModel;
import org.innovateuk.ifs.registration.projectinvite.controller.AcceptProjectInviteController;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.innovateuk.ifs.util.EncryptedCookieService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import javax.servlet.http.Cookie;

import static org.innovateuk.ifs.BaseControllerMockMVCTest.setupMockMvc;
import static org.innovateuk.ifs.util.CookieTestUtil.*;
import static org.innovateuk.ifs.commons.rest.RestResult.restFailure;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.invite.builder.ProjectUserInviteResourceBuilder.newProjectUserInviteResource;
import static org.innovateuk.ifs.invite.constant.InviteStatus.OPENED;
import static org.innovateuk.ifs.invite.constant.InviteStatus.SENT;
import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.innovateuk.ifs.registration.projectinvite.controller.AcceptProjectInviteController.*;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(MockitoJUnitRunner.Silent.class)
public class AcceptProjectInviteControllerTest {

    @InjectMocks
    private AcceptProjectInviteController acceptProjectInviteController;

    @Mock
    private ProjectInviteRestService projectInviteRestServiceMock;

    @Mock
    private EncryptedCookieService cookieUtil;

    @Mock
    private Environment env;

    @Mock
    private MessageSource messageSource;

    @Mock
    private OrganisationRestService organisationRestService;

    private MockMvc mockMvc;

    private UserResource loggedInUser;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = setupMockMvc(acceptProjectInviteController, () -> loggedInUser, env, messageSource, a -> {});
        setupEncryptedCookieService(cookieUtil);
    }

    @Test
    public void testInviteEntryPageWhenHashIsInvalid() throws Exception {
        String hash = "invalid-hash";
        when(projectInviteRestServiceMock.getInviteByHash(hash)).thenReturn(restFailure(CommonFailureKeys.GENERAL_NOT_FOUND));

        mockMvc.perform(get(ACCEPT_INVITE_MAPPING + hash))
                .andExpect(status().is2xxSuccessful())
                .andExpect(cookie().doesNotExist(AcceptProjectInviteController.INVITE_HASH))
                .andExpect(view().name(AcceptProjectInviteController.ACCEPT_INVITE_FAILURE));
    }

    @Test
    public void testFailureUserExistsButIsLoggedInWithTheWrongUser() throws Exception {
        loggedInUser = newUserResource().withEmail("loggedInUser@example.com").build();
        UserResource inviteUser = newUserResource().withEmail("inviteUser@example.com").build();
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(SENT).withEmail(inviteUser.getEmail()).build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(true));
        mockMvc.perform(get(ACCEPT_INVITE_MAPPING + invite.getHash()))
                .andExpect(status().is2xxSuccessful())
                // Currently we tell them to log out and try again as there is not currently a way of forcing this
                .andExpect(cookie().doesNotExist(AcceptProjectInviteController.INVITE_HASH))
                .andExpect(view().name(AcceptProjectInviteController.ACCEPT_INVITE_FAILURE));
    }

    @Test
    public void testFailureInviteAlreadyAccepted() throws Exception {
        UserResource inviteUser = newUserResource().withEmail("email@example.com").build();
        loggedInUser = inviteUser;
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(OPENED).withEmail(inviteUser.getEmail()).build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(true));
        mockMvc.perform(get(ACCEPT_INVITE_MAPPING + invite.getHash()))
                .andExpect(status().is2xxSuccessful())
                // Currently we tell them to log out and try again as there is not currently a way of forcing this
                .andExpect(cookie().doesNotExist(AcceptProjectInviteController.INVITE_HASH))
                .andExpect(view().name(AcceptProjectInviteController.ACCEPT_INVITE_FAILURE));
    }

    @Test
    public void testInviteEntryUserExistsButIsNotLoggedIn() throws Exception {
        loggedInUser = null; // No one logged in.
        UserResource user = newUserResource().withEmail("email@example.com").build();
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(SENT).withEmail(user.getEmail()).build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(true));
        MvcResult result = mockMvc.perform(get(ACCEPT_INVITE_MAPPING + invite.getHash()))
                .andExpect(status().is2xxSuccessful())
                .andExpect(cookie().exists(AcceptProjectInviteController.INVITE_HASH))
                .andExpect(view().name(ACCEPT_INVITE_USER_EXISTS_BUT_NOT_LOGGED_IN_VIEW))
                .andReturn();

        assertEquals(invite.getHash(), getDecryptedCookieValue(result.getResponse().getCookies(), AcceptProjectInviteController.INVITE_HASH));
    }

    @Test
    public void testInviteEntryUserExistsAndIsLoggedIn() throws Exception {
        UserResource inviteUser = newUserResource().withEmail("inviteUser@example.com").build();
        loggedInUser = inviteUser;
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(SENT).withEmail(inviteUser.getEmail()).build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(true));
        MvcResult result = mockMvc.perform(get(ACCEPT_INVITE_MAPPING + invite.getHash()))
                .andExpect(status().is3xxRedirection())
                .andExpect(cookie().exists(AcceptProjectInviteController.INVITE_HASH))
                .andExpect(redirectedUrl(ACCEPT_INVITE_USER_EXIST_SHOW_PROJECT_MAPPING))
                .andReturn();

        assertEquals(invite.getHash(), getDecryptedCookieValue(result.getResponse().getCookies(), AcceptProjectInviteController.INVITE_HASH));
    }

    @Test
    public void testInviteEntryUserDoesNotExistAndNotLoggedIn() throws Exception {
        loggedInUser = null;
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(SENT).withEmail("doesNotYetExist@example.com").build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(false));
        mockMvc.perform(get(ACCEPT_INVITE_MAPPING + invite.getHash()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl(ACCEPT_INVITE_USER_DOES_NOT_YET_EXIST_SHOW_PROJECT_MAPPING));
    }

    @Test
    public void testAcceptInviteUserDoesNotYetExistShowProject() throws Exception {
        loggedInUser = null;
        OrganisationResource organisation = newOrganisationResource().build();
        ProjectUserInviteResource invite = newProjectUserInviteResource().withHash("hash").withStatus(SENT).withEmail("doesNotYetExist@example.com").withProjectName("project name").withOrganisation(organisation.getId()).build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(false));
        when(organisationRestService.getOrganisationByIdForAnonymousUserFlow(invite.getOrganisation())).thenReturn(restSuccess(organisation));
        when(organisationRestService.getOrganisationById(anyLong())).thenReturn(restSuccess(organisation));
        MvcResult mvcResult = mockMvc.perform(get(ACCEPT_INVITE_USER_DOES_NOT_YET_EXIST_SHOW_PROJECT_MAPPING).cookie(new Cookie(AcceptProjectInviteController.INVITE_HASH, encryptor.encrypt(invite.getHash()))))
                .andExpect(status().is2xxSuccessful())
                .andExpect(view().name(ACCEPT_INVITE_SHOW_PROJECT)).andReturn();
        JoinAProjectViewModel model = (JoinAProjectViewModel)mvcResult.getModelAndView().getModel().get("model");
        Boolean userExists = (Boolean)mvcResult.getModelAndView().getModel().get("userExists");
        assertEquals(model.getProjectName(), invite.getProjectName());
        assertFalse(model.getProjectName(), userExists);
    }

    @Test
    public void testAcceptInviteUserDoesExistShowProject() throws Exception {
        UserResource inviteUser = newUserResource().withEmail("doesExist@example.com").build();
        loggedInUser = inviteUser;
        OrganisationResource organisation = newOrganisationResource().build();
        ProjectUserInviteResource invite = newProjectUserInviteResource().
                withHash("hash").
                withStatus(SENT).
                withEmail(inviteUser.getEmail()).
                withProjectName("project name").
                withOrganisation(organisation.getId()).
                build();
        when(projectInviteRestServiceMock.getInviteByHash(invite.getHash())).thenReturn(restSuccess(invite));
        when(projectInviteRestServiceMock.checkExistingUser(invite.getHash())).thenReturn(restSuccess(true));
        when(organisationRestService.getOrganisationByIdForAnonymousUserFlow(invite.getOrganisation())).thenReturn(restSuccess(organisation));
        when(organisationRestService.getOrganisationById(anyLong())).thenReturn(restSuccess(organisation));
        MvcResult mvcResult = mockMvc.perform(get(ACCEPT_INVITE_USER_EXIST_SHOW_PROJECT_MAPPING).cookie(new Cookie(AcceptProjectInviteController.INVITE_HASH, encryptor.encrypt(invite.getHash()))))
                .andExpect(status().is2xxSuccessful())
                .andExpect(view().name(ACCEPT_INVITE_SHOW_PROJECT)).andReturn();
        JoinAProjectViewModel model = (JoinAProjectViewModel)mvcResult.getModelAndView().getModel().get("model");
        Boolean userExists = (Boolean)mvcResult.getModelAndView().getModel().get("userExists");
        assertEquals(model.getProjectName(), invite.getProjectName());
        assertTrue(model.getProjectName(), userExists);
    }
}


text:
package de.ids_mannheim.korap.web.controller;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.fasterxml.jackson.databind.JsonNode;
import javax.ws.rs.core.Response;

import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;

public class QueryReferenceSearchTest {

    /*@Test
    public void testSearchWithVCRefEqual () throws KustvaktException {
        Response response = target().path(API_VERSION).path("search")
                .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
                .queryParam("cq", "referTo \"dory/dory-q\"")
                .get();

        String ent = response.readEntity(String.class);
        JsonNode node = JsonUtils.readTree(ent);
        assertTrue(node.at("/matches").size() > 0);
    }
*/
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../../test_helper', __FILE__)

describe "Paths" do
  let(:root) { Dir.mktmpdir }
  let(:paths) { Spontaneous::Paths.new(root) }
  it "creates paths that are marked as ensure" do
    paths.add :compiled_assets, "private/assets", ensure: true
    File.exist?(File.join(root, "private/assets")).must_equal true
  end
end


text:
package net.snowflake.client.core;

import com.google.common.base.Strings;
import net.snowflake.client.log.SFLogger;
import net.snowflake.client.log.SFLoggerFactory;

public class CredentialManager {
  private static final SFLogger logger = SFLoggerFactory.getLogger(CredentialManager.class);

  private SecureStorageManager secureStorageManager;

  private static final String ID_TOKEN = "ID_TOKEN";
  private static final String MFA_TOKEN = "MFATOKEN";

  private CredentialManager() {
    initSecureStorageManager();
  }

  private void initSecureStorageManager() {
    try {
      if (Constants.getOS() == Constants.OS.MAC) {
        secureStorageManager = SecureStorageAppleManager.builder();
      } else if (Constants.getOS() == Constants.OS.WINDOWS) {
        secureStorageManager = SecureStorageWindowsManager.builder();
      } else if (Constants.getOS() == Constants.OS.LINUX) {
        secureStorageManager = SecureStorageLinuxManager.getInstance();
      } else {
        logger.error("Unsupported Operating System. Expected: OSX, Windows, Linux", false);
      }
    } catch (NoClassDefFoundError error) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
    }
  }

  /** Helper function for tests to go back to normal settings. */
  void resetSecureStorageManager() {
    initSecureStorageManager();
  }

  /**
   * Testing purpose. Inject a mock manager.
   *
   * @param manager
   */
  void injectSecureStorageManager(SecureStorageManager manager) {
    secureStorageManager = manager;
  }

  private static class CredentialManagerHolder {
    private static final CredentialManager INSTANCE = new CredentialManager();
  }

  public static CredentialManager getInstance() {
    return CredentialManagerHolder.INSTANCE;
  }

  /**
   * Reuse the cached id token stored locally
   *
   * @param loginInput login input to attach id token
   */
  void fillCachedIdToken(SFLoginInput loginInput) throws SFException {
    fillCachedCredential(loginInput, ID_TOKEN);
  }

  /**
   * Reuse the cached mfa token stored locally
   *
   * @param loginInput login input to attach mfa token
   */
  void fillCachedMfaToken(SFLoginInput loginInput) throws SFException {
    fillCachedCredential(loginInput, MFA_TOKEN);
  }

  /**
   * Reuse the cached token stored locally
   *
   * @param loginInput login input to attach token
   * @param credType credential type to retrieve
   */
  synchronized void fillCachedCredential(SFLoginInput loginInput, String credType)
      throws SFException {
    if (secureStorageManager == null) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
      return;
    }

    String cred = null;
    try {
      cred =
          secureStorageManager.getCredential(
              loginInput.getHostFromServerUrl(), loginInput.getUserName(), credType);
    } catch (NoClassDefFoundError error) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
      return;
    }

    if (cred == null) {
      logger.debug("retrieved %s is null", credType);
    }

    // cred can be null
    if (credType == ID_TOKEN) {
      loginInput.setIdToken(cred);
    } else if (credType == MFA_TOKEN) {
      loginInput.setMfaToken(cred);
    } else {
      logger.debug("unrecognized type %s for local cached credential", credType);
    }
    return;
  }

  /**
   * Store ID Token
   *
   * @param loginInput loginInput to denote to the cache
   * @param loginOutput loginOutput to denote to the cache
   */
  void writeIdToken(SFLoginInput loginInput, SFLoginOutput loginOutput) throws SFException {
    writeTemporaryCredential(loginInput, loginOutput.getIdToken(), ID_TOKEN);
  }

  /**
   * Store MFA Token
   *
   * @param loginInput loginInput to denote to the cache
   * @param loginOutput loginOutput to denote to the cache
   */
  void writeMfaToken(SFLoginInput loginInput, SFLoginOutput loginOutput) throws SFException {
    writeTemporaryCredential(loginInput, loginOutput.getMfaToken(), MFA_TOKEN);
  }

  /**
   * Store the temporary credential
   *
   * @param loginInput loginInput to denote to the cache
   * @param cred the credential
   * @param credType type of the credential
   */
  synchronized void writeTemporaryCredential(SFLoginInput loginInput, String cred, String credType)
      throws SFException {
    if (Strings.isNullOrEmpty(cred)) {
      logger.debug("no %s is given.", credType);
      return; // no credential
    }

    if (secureStorageManager == null) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
      return;
    }

    try {
      secureStorageManager.setCredential(
          loginInput.getHostFromServerUrl(), loginInput.getUserName(), credType, cred);
    } catch (NoClassDefFoundError error) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
    }
  }

  /** Delete the id token cache */
  void deleteIdTokenCache(String host, String user) {
    deleteTemporaryCredential(host, user, ID_TOKEN);
  }

  /** Delete the mfa token cache */
  void deleteMfaTokenCache(String host, String user) {
    deleteTemporaryCredential(host, user, MFA_TOKEN);
  }

  /**
   * Delete the temporary credential
   *
   * @param host host name
   * @param user user name
   * @param credType type of the credential
   */
  synchronized void deleteTemporaryCredential(String host, String user, String credType) {
    if (secureStorageManager == null) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
      return;
    }

    try {
      secureStorageManager.deleteCredential(host, user, credType);
    } catch (NoClassDefFoundError error) {
      logger.info(
          "JNA jar files are needed for Secure Local Storage service. Please follow the Snowflake JDBC instruction for Secure Local Storage feature. Fall back to normal process.",
          false);
    }
  }
}


text:
struct timezone {
    int  tz_minuteswest; // minutes W of Greenwich
    int  tz_dsttime;     // type of dst correction
};

static inline int gettimeofday(struct timeval *tv, struct timezone *tz) {
    FILETIME ft;
    unsigned __int64 tmpres = 0;
    static int tzflag;

    if (NULL != tv) {
        GetSystemTimeAsFileTime(&ft);

        tmpres |= ft.dwHighDateTime;
        tmpres <<= 32;
        tmpres |= ft.dwLowDateTime;

        //converting file time to unix epoch
        tmpres -= DELTA_EPOCH_IN_MICROSECS;
        tmpres /= 10;  //convert into microseconds
        tv->tv_sec = (long)(tmpres / 1000000UL);
        tv->tv_usec = (long)(tmpres % 1000000UL);
    }

    if (NULL != tz) {
        if (!tzflag) {
            _tzset();
            tzflag++;
        }
        tz->tz_minuteswest = _timezone / 60;
        tz->tz_dsttime = _daylight;
    }
    return 0;
}
#endif

static inline unsigned long long nanoClock (void) { // actually returns microseconds
    struct timeval t;
    gettimeofday(&t, (struct timezone*)0);
    return t.tv_usec + t.tv_sec * 1000000ULL;
}

namespace RDKit {
    namespace FMCS {

#ifdef VERBOSE_STATISTICS_ON

// compute statistics of really very very fast calls.
// It a bit decrease overal performance, but might be interested for investigation purpose (only)
//#define VERBOSE_STATISTICS_FASTCALLS_ON

        struct ExecStatistics {
            unsigned TotalSteps, MCSFoundStep;
            unsigned long long   MCSFoundTime;
            unsigned InitialSeed, MismatchedInitialSeed;
            unsigned Seed, RemainingSizeRejected;
            unsigned SeedCheck, SingleBondExcluded;
            unsigned MatchCall, MatchCallTrue;
            unsigned FastMatchCall, FastMatchCallTrue, SlowMatchCallTrue;
            unsigned ExactMatchCall, ExactMatchCallTrue;   // hash cache
            unsigned FindHashInCache, HashKeyFoundInCache;
            unsigned AtomCompareCalls, BondCompareCalls;    // long long
            unsigned AtomFunctorCalls, BondFunctorCalls;    // long long
            unsigned WrongCompositionRejected, WrongCompositionDetected;
            unsigned DupCacheFound, DupCacheFoundMatch;

            ExecStatistics() : TotalSteps(0), MCSFoundStep(0)
                , MCSFoundTime(nanoClock())
                , InitialSeed(0), MismatchedInitialSeed(0)
                , Seed(0), RemainingSizeRejected(0)
                , SeedCheck(0), SingleBondExcluded(0), MatchCall(0), MatchCallTrue(0)
                , FastMatchCall(0), FastMatchCallTrue(0), SlowMatchCallTrue(0)
                , ExactMatchCall(0), ExactMatchCallTrue(0)
                , FindHashInCache(0), HashKeyFoundInCache(0)
                , AtomCompareCalls(0), BondCompareCalls(0)
                , AtomFunctorCalls(0), BondFunctorCalls(0)
                , WrongCompositionRejected(0), WrongCompositionDetected(0)
                , DupCacheFound(0), DupCacheFoundMatch(0)
            {}
        };
#endif

    }
}


text:
package push

import (
	"fmt"
	"net/http"

	"github.com/eyecuelab/kit/config"
	"github.com/eyecuelab/kit/log"
	"github.com/sideshow/apns2"
	"github.com/sideshow/apns2/certificate"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"os"
)

const (
	alertTemplate = `{"aps":{"alert":"%v"}}`
	defautFile    = `/etc/eyecue_keys/push.p12`
)

var (
	client *apns2.Client
	topic  string
)

func init() {
	cobra.OnInitialize(setup, connectClient)
}

func setup() {
	viper.SetDefault("push_key_file", defautFile)
}

func connectClient() {
	topic = config.RequiredString("push_topic")
	keyFile := viper.GetString("push_key_file")

	if keyFile == "" {
		log.Warnf("No push key location provided")
		return
	}

	if _, err := os.Stat(keyFile); os.IsNotExist(err) {
		log.Warnf("No push key found at: %s", keyFile)
		return
	}

	cert, err := certificate.FromP12File(keyFile, "")

	if err != nil {
		log.Fatal(err)
	}
	client = apns2.NewClient(cert).Production()
}

func push(token string, payload string) error {
	notification := &apns2.Notification{
		DeviceToken: token,
		Topic:       topic,
		Payload:     payload,
	}

	res, err := client.Push(notification)

	if err != nil {
		return err
	}

	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("push error: %v", res.Reason)
	}
	return nil
}

func Alert(token string, message string) error {
	return push(token, fmt.Sprintf(alertTemplate, message))
}


text:
4.3.6: Example - Random Number Generator

Our final example of an iterator is short and simple, it is a random number generator.

    type Rnd struct {
        seed int64
        cur  float64
        gen  *rand.Rand
    }

    func Rand() *Rnd {
        var r Rnd
        r.seed = time.Now().UnixNano()
        r.First()
        return &r
    }

The structure contains the seed used to generate the sequence, the current value (a floating number in the [0..1] range) and a reference to Go's random number generator.

The constructor simply seeds a random sequence from the current time and generates the first value.

    func (r *Rnd) First() error {
        r.gen = rand.New(rand.NewSource(r.seed))
        r.cur = r.gen.Float64()
        return nil
    }

    func (r *Rnd) Next() error {
        r.cur = r.gen.Float64()
        return nil
    }

The iterator is a *BoundedAtStart* iterator, i.e. it has a beginning and can easily be restored to it through the *First()* method. The *Next()* generates the next random value.

    func (r *Rnd) AtEnd() bool {
        return false
    }

    func (r *Rnd) Error() error {
        return nil
    }

This iterator represents an infinite stream of values on the form *[rval1, rval2, ...)*, therefore the only job of the *AtEnd()* method is to return *false*.

    func (r *Rnd) Value() interface{} {
        return r.cur
    }

    func (r *Rnd) Float64() float64 {
        return r.cur
    }

The iterator has a special type casting function so we can read *float64* values from it without have to do the type assertion ourselves.

    func (r *Rnd) SetSeed(seed int64) {
        r.seed = seed
        r.First()
    }

    func (r *Rnd) Seed() int64 {
        return r.seed
    }

Lastsly, the iterator provids methods to retrieve the seeding used to generate the sequence, as well as reset and iterator to a previously saved seeding value.

A sampel usage is as follows:

    fmt.Print("A quarted of random pairs: ")
    ritr1, ritr2 := Rand(), Rand()
    for i := 0; i < 4; i++ {
        r1 := ritr1.Float64()
        r2 := ritr2.Float64()
        fmt.Printf("(%f, %f), ", r1, r2)
        ritr1.Next()
        ritr2.Next()
    }
    seed1, seed2 := ritr1.Seed(), ritr2.Seed()
    fmt.Println("")

    fmt.Print("A quarted of another random pairs: ")
    ritr1, ritr2 = Rand(), Rand()
    for i := 0; i < 4; i++ {
        r1 := ritr1.Float64()
        r2 := ritr2.Float64()
        fmt.Printf("(%f, %f), ", r1, r2)
        ritr1.Next()
        ritr2.Next()
    }
    fmt.Println("")

    fmt.Print("The first quarted of random pairs: ")
    ritr1.SetSeed(seed1)
    ritr2.SetSeed(seed2)
    for i := 0; i < 4; i++ {
        r1 := ritr1.Float64()
        r2 := ritr2.Float64()
        fmt.Printf("(%f, %f), ", r1, r2)
        ritr1.Next()
        ritr2.Next()
    }

We generate three list of a quarted of a pair of random numbers, where the first sequence and the last sequence are the same.

Get the source at [GitHub](https://github.com/mg/hog/blob/master/c4/random.go). The *Random* iterator is also awailable in the [iterator library](https://github.com/mg/i/blob/master/igen/rand.go) as a *RandomAccess* iterator.


text:
package org.apache.camel.component.spring.ws.filter.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.component.spring.ws.filter.MessageFilter;
import org.springframework.ws.WebServiceMessage;

/**
 * This filter is a composition of basic message filters
 */
public class CompositeMessageFilter implements MessageFilter {

    private List<MessageFilter> filters = new ArrayList<>();

    @Override
    public void filterProducer(Exchange exchange, WebServiceMessage response) {
        for (MessageFilter filter : filters) {
            filter.filterProducer(exchange, response);
        }
    }

    @Override
    public void filterConsumer(Exchange exchange, WebServiceMessage response) {
        for (MessageFilter filter : filters) {
            filter.filterConsumer(exchange, response);
        }
    }

    public void setFilters(List<MessageFilter> filters) {
        this.filters = filters;
    }

    public List<MessageFilter> getFilters() {
        return filters;
    }
}


text:
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from rest_framework import routers, serializers, viewsets

from photos.models import Photo, Favorite

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all()
    serializer_class = PhotoSerializer

class FavoriteSerializer(serializers.ModelSerializer):
    photo = PhotoSerializer()

    class Meta:
        model = Favorite

class FavoriteViewSet(viewsets.ModelViewSet):
    queryset = Favorite.objects.all()
    serializer_class = FavoriteSerializer

    def create(self, request, *args, **kwargs):
        """
        Customize `create` to return all favorite objects instead of just the
        newly created one.
        """
        # Create the new favorite object
        photo = get_object_or_404(Photo, id=request.data['photo_id'])
        Favorite.objects.create(id=request.data['id'], photo=photo)

        # Return all favorite objects
        serializer = self.get_serializer(Favorite.objects.all(), many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def destroy(self, request, *args, **kwargs):
        """
        Customize `destroy` to also return all favorite objects.
        """
        # Delete the favorite object
        super(FavoriteViewSet, self).destroy(request, *args, **kwargs)

        # Return all favorite objects
        serializer = self.get_serializer(Favorite.objects.all(), many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

router = routers.DefaultRouter()
router.register(r'photos', PhotoViewSet)
router.register(r'favorites', FavoriteViewSet)


text:
(function () {
    "use strict";

    describe("Tomato", function () {
        it("initially is set to 25", function () {
            var tomato = new Tomato();
            expect(tomato.minutesLeft()).toEqual(25);
            expect(tomato.status()).toEqual("session");
        });

        it("initially is set to 25 even after update", function () {
            var tomato = new Tomato();
            tomato.update(1000);
            expect(tomato.minutesLeft()).toEqual(25);
        });

        it("is set to 24 when one minute passed after being started", function () {
            var tomato = new Tomato();
            tomato.start(1000);
            tomato.update(1060);
            expect(tomato.minutesLeft()).toEqual(24);
        });

        it("is set to 25 when 30 seconds passed after being started", function () {
            var tomato = new Tomato();
            tomato.start(1000);
            tomato.update(1030);
            expect(tomato.minutesLeft()).toEqual(25);
        });

        it("is set to 25 when it is stopped", function () {
            var tomato = new Tomato();
            tomato.start(1000);
            tomato.update(1060);
            tomato.stop();
            expect(tomato.minutesLeft()).toEqual(25);
        });

        it("is started after toggled once", function () {
            var tomato = new Tomato();
            tomato.toggle(1000);
            tomato.update(1060);
            expect(tomato.minutesLeft()).toEqual(24);
        });

        it("is stopped after toggled twice", function () {
            var tomato = new Tomato();
            tomato.toggle(1000);
            tomato.update(1060);
            tomato.toggle(1120);
            expect(tomato.minutesLeft()).toEqual(25);
        });

        it("is stopped after 25 minutes and switches to pause", function () {
            var message = "";
            var tomato = new Tomato(function () {
                message = tomato.status() + " time!";
            });

            tomato.start(1000);

            tomato.update(2499);
            expect(tomato.minutesLeft()).toEqual(1);
            expect(message).toEqual("");

            tomato.update(2500);
            expect(tomato.minutesLeft()).toEqual(5);
            expect(message).toEqual("pause time!");
            expect(tomato.status()).toEqual("pause");
        });

        it("is stopped after 50 minutes and switches to pause", function () {
            var message = "";
            var tomato = new Tomato(function () {
                message = tomato.status() + " time!";
            });

            tomato.start(1000);

            tomato.update(4000);
            expect(tomato.minutesLeft()).toEqual(5);
            expect(message).toEqual("pause time!");
            expect(tomato.status()).toEqual("pause");
        });

        it("is stopped after 5 minutes in pause and switches to session", function () {
            var tomato = new Tomato();
            tomato.start(1000);
            tomato.update(2500);

            tomato.start(2600);
            tomato.update(2900);

            expect(tomato.status()).toEqual("session");
        });

        it("can have custom session time", function () {
            var settings = new Settings();
            var tomato = new Tomato(null, settings);
            settings.decreaseSessionTime();

            tomato.start(1000);
            tomato.update(2440);

            expect(tomato.status()).toEqual("pause");
        });

        it("can have custom pause time", function () {
            var settings = new Settings();
            var tomato = new Tomato(null, settings);
            settings.decreasePauseTime();
            tomato.start(1000);
            tomato.update(2500);

            tomato.start(2600);
            tomato.update(2840);

            expect(tomato.status()).toEqual("session");
        });

    });
})();


text:
using UnityEngine;
using System.Collections;

public class quadSection : manipObject {
  public int ID = 0;

  int texSize = 64;
  Texture2D tex, texB;
  Renderer texrend;
  Color32[] texpixels;
  filterDeviceInterface _deviceInterface;

  float width = .1f;
  float height = .1f;
  float depth = .2f;

  float edgeMin = -.04f;
  float edgeMax = .26f;

  public bool toggled = true;
  float hue = .0875f;

  public override void Awake() {
    base.Awake();
    _deviceInterface = GetComponentInParent<filterDeviceInterface>();
    texrend = GetComponent<Renderer>();

    tex = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false);
    texB = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false);
    texpixels = new Color32[texSize * texSize];

    GenerateOutline();
    tex.SetPixels32(texpixels);
    GenerateFlat();
    texB.SetPixels32(texpixels);
    tex.Apply(false);
    texB.Apply(false);

    texrend.material.mainTexture = texB;

    Color c = Color.HSVToRGB(hue, 182 / 255f, 229 / 255f);
    texrend.material.SetColor("_TintColor", c);
    texrend.material.SetFloat("_EmissionGain", .1f);

    setToggle(toggled);
    transform.localScale = new Vector3(width, height, depth);
  }

  bool outlined = false;
  void toggleOutline() {
    outlined = !outlined;
    if (outlined) texrend.material.mainTexture = tex;
    else texrend.material.mainTexture = texB;
  }

  public void getPercentages(out float percentA, out float percentB) {
    float amount = edgeMax - edgeMin;
    float edgeA = transform.localPosition.x - width / 2 - gap;
    float edgeB = transform.localPosition.x + width / 2 + gap;

    percentA = (edgeA - edgeMin) / amount;
    percentB = (edgeB - edgeMin) / amount;
  }

  float getX(float per) {
    return per * (edgeMax - edgeMin) + edgeMin;
  }

  void setOutline(bool on) {
    if (on) texrend.material.mainTexture = tex;
    else texrend.material.mainTexture = texB;
  }

  void GenerateOutline() {
    for (int i = 0; i < texSize; i++) {
      for (int i2 = 0; i2 < texSize; i2++) {
        byte s = 50;
        if (i == 0 || i == texSize - 1 || i2 == 0 || i2 == texSize - 1) s = 255;
        texpixels[i2 * texSize + i] = new Color32(s, s, s, s);
      }
    }
  }

  void GenerateFlat() {
    for (int i = 0; i < texSize; i++) {
      for (int i2 = 0; i2 < texSize; i2++) {
        byte s = 50;
        texpixels[i2 * texSize + i] = new Color32(s, s, s, s);
      }

    }
  }

  enum vizstate {
    off,
    on,
    selected_off,
    selected_on,
    grab_on,
    grab_off
  };

  vizstate curvizstate = vizstate.off;

  void setVizState(vizstate s) {
    switch (s) {
      case vizstate.off:
        setOutline(false);
        texrend.material.SetFloat("_EmissionGain", .1f);
        break;
      case vizstate.on:
        setOutline(false);
        texrend.material.SetFloat("_EmissionGain", .3f);
        break;
      case vizstate.selected_off:
        setOutline(true);
        texrend.material.SetFloat("_EmissionGain", .1f);
        break;
      case vizstate.selected_on:
        setOutline(true);
        texrend.material.SetFloat("_EmissionGain", .3f);
        break;
      case vizstate.grab_off:
        setOutline(true);
        texrend.material.SetFloat("_EmissionGain", .15f);
        break;
      case vizstate.grab_on:
        setOutline(true);
        texrend.material.SetFloat("_EmissionGain", .5f);
        break;
      default:
        break;
    }
  }

  public void setToggle(bool on) {
    toggled = on;
    if (curState == manipState.none) setVizState(toggled ? vizstate.on : vizstate.off);
    else if (curState == manipState.selected) setVizState(toggled ? vizstate.selected_on : vizstate.selected_off);
    else setVizState(toggled ? vizstate.grab_on : vizstate.grab_off);
  }

  bool updateWidth(float w, int dir) {
    Vector3 p = transform.localPosition;

    float delta = width;

    width = Mathf.Clamp(w, .01f, .28f);
    delta = delta - width;
    p.x += dir * delta / 2;

    transform.localScale = new Vector3(width, height, depth);
    transform.localPosition = p;

    if (width == .01f) return false;
    else return true;
  }

  float offset = 0;
  public override void grabUpdate(Transform t) {
    float modW = transform.parent.InverseTransformPoint(manipulatorObj.position).x - offset;

    if (ID == 0) {
      updateWidth(startWidth + modW, -1);
      Vector3 p = transform.localPosition;
      _deviceInterface.quads[1].updateEdge(-1, p.x + width / 2 + gap);
    } else if (ID == 2) {
      updateWidth(startWidth - modW, 1);
      Vector3 p = transform.localPosition;
      _deviceInterface.quads[1].updateEdge(1, p.x - width / 2 - gap);
    } else {
      updatePosition(startX + modW);
    }
  }

  float gap = .01f;
  public void updateEdge(int edge, float xPos) {
    Vector3 pos = transform.localPosition;
    float amount = width - ((pos.x + edge * width / 2) - xPos) * edge;
    bool check = updateWidth(amount, -edge);

    if (!check && ID == 1) //the middle one is as small as it's going to be so start shifting over
    {
      updatePosition(transform.localPosition.x + (width - amount) * -edge);
    }
  }

  public void setupPercents(float p0, float p1) //just for center quad
  {
    updateEdge(-1, getX(p0));
    updateEdge(1, getX(p1));
    updatePosition(getX((p1 - p0) / 2 + p0));
  }

  public void updatePercentage(float p) {
    if (ID == 1) {
      p = Mathf.Lerp(edgeMin + gap + width / 2, edgeMax - gap - width / 2, p);
      updatePosition(p);
    } else if (ID == 0) {
      float w = Mathf.Lerp(.01f, .28f - _deviceInterface.quads[2].width, p);
      updateWidth(w, -1);
      Vector3 pos = transform.localPosition;
      _deviceInterface.quads[1].updateEdge(-1, pos.x + width / 2 + gap);

    } else if (ID == 2) {
      float w = Mathf.Lerp(.01f, .28f - _deviceInterface.quads[0].width, p);
      updateWidth(w, 1);
      Vector3 pos = transform.localPosition;
      _deviceInterface.quads[1].updateEdge(1, pos.x - width / 2 - gap);

    }
  }

  public void updatePosition(float x) {
    Vector3 p = transform.localPosition;
    p.x = Mathf.Clamp(x, edgeMin + gap + width / 2, edgeMax - gap - width / 2);

    _deviceInterface.quads[0].updateEdge(1, p.x - width / 2 - gap);
    _deviceInterface.quads[2].updateEdge(-1, p.x + width / 2 + gap);
    transform.localPosition = p;
  }

  float startWidth = 0;
  float startX = 0;
  public override void setState(manipState state) {
    curState = state;
    if (curState == manipState.none) {
      setVizState(toggled ? vizstate.on : vizstate.off);
    } else if (curState == manipState.selected) {
      setVizState(toggled ? vizstate.selected_on : vizstate.selected_off);
    } else if (curState == manipState.grabbed) {

      setVizState(toggled ? vizstate.grab_on : vizstate.grab_off);

      startWidth = width;
      startX = transform.localPosition.x;
      offset = transform.parent.InverseTransformPoint(manipulatorObj.position).x;
    }
  }
}


text:
import React from 'react'
import ReactDOM from 'react-dom'

import scatterThings from './prepare'
import App from './App'

scatterThings(); // draw the img

ReactDOM.render(<App/>, document.querySelector('#mount-app'));


text:
import unittest
from flask import current_app, url_for
from app import create_app

class BasicsTestCase(unittest.TestCase):

    def setUp(self):
        self.app = create_app("testing")
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client()

    def tearDown(self):
        self.app_context.pop()

    def test_app_exists(self):
        assert current_app is not None

    def test_app_is_testing(self):
        assert current_app.config['TESTING']

    def test_404_page(self):
        response = self.client.get('/invalid_page')
        assert 'Not Found' in response.data


text:
package org.apache.spark.sql.hive.thriftserver

import java.sql.SQLException
import java.util.concurrent.atomic.AtomicBoolean

import org.apache.hive.service.cli.HiveSQLException

import org.apache.spark.TaskKilled
import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}
import org.apache.spark.sql.internal.SQLConf

trait ThriftServerWithSparkContextSuite extends SharedThriftServer {

  test("the scratch dir will be deleted during server start but recreated with new operation") {
    assert(tempScratchDir.exists())
  }

  test("SPARK-29911: Uncache cached tables when session closed") {
    val cacheManager = spark.sharedState.cacheManager
    val globalTempDB = spark.sharedState.globalTempViewManager.database
    withJdbcStatement { statement =>
      statement.execute("CACHE TABLE tempTbl AS SELECT 1")
    }
    // the cached data of local temporary view should be uncached
    assert(cacheManager.isEmpty)
    try {
      withJdbcStatement { statement =>
        statement.execute("CREATE GLOBAL TEMP VIEW globalTempTbl AS SELECT 1, 2")
        statement.execute(s"CACHE TABLE $globalTempDB.globalTempTbl")
      }
      // the cached data of global temporary view shouldn't be uncached
      assert(!cacheManager.isEmpty)
    } finally {
      withJdbcStatement { statement =>
        statement.execute(s"UNCACHE TABLE IF EXISTS $globalTempDB.globalTempTbl")
      }
      assert(cacheManager.isEmpty)
    }
  }

  test("Full stack traces as error message for jdbc or thrift client") {
    val sql = "select date_sub(date'2011-11-11', '1.2')"
    withCLIServiceClient { client =>
      val sessionHandle = client.openSession(user, "")

      val confOverlay = new java.util.HashMap[java.lang.String, java.lang.String]
      val e = intercept[HiveSQLException] {
        client.executeStatement(
          sessionHandle,
          sql,
          confOverlay)
      }

      assert(e.getMessage
        .contains("The second argument of 'date_sub' function needs to be an integer."))
      assert(!e.getMessage.contains("" +
        "java.lang.NumberFormatException: invalid input syntax for type numeric: 1.2"))
    }

    withJdbcStatement { statement =>
      val e = intercept[SQLException] {
        statement.executeQuery(sql)
      }
      assert(e.getMessage
        .contains("The second argument of 'date_sub' function needs to be an integer."))
      assert(e.getMessage.contains("" +
        "java.lang.NumberFormatException: invalid input syntax for type numeric: 1.2"))
    }
  }

  test("SPARK-33526: Add config to control if cancel invoke interrupt task on thriftserver") {
    withJdbcStatement { statement =>
      val forceCancel = new AtomicBoolean(false)
      val listener = new SparkListener {
        override def onTaskEnd(taskEnd: SparkListenerTaskEnd): Unit = {
          assert(taskEnd.reason.isInstanceOf[TaskKilled])
          if (forceCancel.get()) {
            assert(System.currentTimeMillis() - taskEnd.taskInfo.launchTime < 1000)
          } else {
            // avoid accuracy, we check 2s instead of 3s.
            assert(System.currentTimeMillis() - taskEnd.taskInfo.launchTime >= 2000)
          }
        }
      }

      spark.sparkContext.addSparkListener(listener)
      try {
        Seq(true, false).foreach { force =>
          statement.setQueryTimeout(0)
          statement.execute(s"SET ${SQLConf.THRIFTSERVER_FORCE_CANCEL.key}=$force")
          statement.setQueryTimeout(1)
          forceCancel.set(force)
          val e = intercept[SQLException] {
            statement.execute("select java_method('java.lang.Thread', 'sleep', 3000L)")
          }.getMessage
          assert(e.contains("Query timed out"))
        }
      } finally {
        spark.sparkContext.removeSparkListener(listener)
      }
    }
  }
}

class ThriftServerWithSparkContextInBinarySuite extends ThriftServerWithSparkContextSuite {
  override def mode: ServerMode.Value = ServerMode.binary
}

class ThriftServerWithSparkContextInHttpSuite extends ThriftServerWithSparkContextSuite {
  override def mode: ServerMode.Value = ServerMode.http
}


text:
package com.longwu.ijkplayer.utlis;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * Created by 龙五 on 2016/12/10.
 */
public class SharedPreferencesUtils {

    private static final String TAG = SharedPreferencesUtils.class.getSimpleName();
    private static Context context;
    private static String name;
    private static SharedPreferences mSp;

    private final static String SP_NAME = "longwu";
    private static SharedPreferences sp;

    private static SharedPreferences getSp(Context context)
    {
        if (sp == null)
        {
            sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        return sp;
    }

    /**
     * 获取boolean 数据
     *
     * @param context
     * @param key
     * @return 如果没有值,返回false
     */
    public static boolean getBoolean(Context context, String key)
    {
        SharedPreferences sp = getSp(context);
        return sp.getBoolean(key, false);
    }

    /**
     * 获取boolean 数据
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static boolean getBoolean(Context context, String key, boolean defValue)
    {
        SharedPreferences sp = getSp(context);
        return sp.getBoolean(key, defValue);
    }

    /**
     * 存boolean缓存
     *
     * @param context
     * @param key
     * @param value
     */
    public static void setBoolean(Context context, String key, boolean value)
    {
        SharedPreferences sp = getSp(context);
        Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * 获取String 数据
     *
     * @param context
     * @param key
     * @return 如果没有值,返回null
     */
    public static String getString(Context context, String key)
    {
        SharedPreferences sp = getSp(context);
        return sp.getString(key, null);
    }

    /**
     * 获取String 数据
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static String getString(Context context, String key, String defValue)
    {
        SharedPreferences sp = getSp(context);
        return sp.getString(key, defValue);
    }

    /**
     * 存String缓存
     *
     * @param context
     * @param key
     * @param value
     */
    public static void setString(Context context, String key, String value)
    {
        SharedPreferences sp = getSp(context);
        Editor editor = sp.edit();
        editor.putString(key, value);
        editor.commit();
    }
//    /**
//     * 获取String 数据
//     *
//     * @param context
//     * @param key
//     * @param defValue
//     * @return
//     */
//    public static String getlist(Context context, String key, String defValue)
//    {
//        SharedPreferences sp = getSp(context);
//        return sp.getString(key, defValue);
//    }
//
//    /**
//     * 存String缓存
//     *
//     * @param context
//     * @param key
//     * @param value
//     */
//    public static void setString(Context context, String key, String value)
//    {
//        SharedPreferences sp = getSp(context);
//        Editor editor = sp.edit();
//        editor.putString(key, value);
//        editor.commit();
//    }
    /**
     * 获取int 数据
     *
     * @param context
     * @param key
     * @return 如果没有值,返回-1
     */
    public static int getInt(Context context, String key)
    {
        SharedPreferences sp = getSp(context);
        return sp.getInt(key, -1);
    }

    /**
     * 获取int 数据
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static int getInt(Context context, String key, int defValue)
    {
        SharedPreferences sp = getSp(context);
        return sp.getInt(key, defValue);
    }

    /**
     * 存int缓存
     *
     * @param context
     * @param key
     * @param value
     */
    public static void setInt(Context context, String key, int value)
    {
        SharedPreferences sp = getSp(context);
        Editor editor = sp.edit();
        editor.putInt(key, value);
        editor.commit();
    }
}


text:
// promises ES6 cleaning

function applyForVisa(documents) {
	console.log('Processing on Application...');
	let promise =  new Promise(function(resolve, reject) {
		setTimeout(function() {
			Math.random() > 0 ? resolve({}) : reject('Visa is denaid: did not have enough documents');
		}, 2000);
	});
	return promise;
}

function getVisa(visa) {
	console.info('Visa received');
	return new Promise(function(resolve, reject){
		setTimeout(() => resolve(visa), 2000);
	});
}

function bookHotel(visa) {
	console.log(visa);
	console.log('Booking hotel');
	return Promise.resolve(visa);
}

function buyTickets(booking) {
	console.log('Buy tickets');
	console.log('Booking', booking);
}

applyForVisa({})
	.then(getVisa)
	.then(bookHotel)
	.then(buyTickets)
	.catch(error => console.error(error));

// promises
/* function applyForVisa(documents) {
	console.log('Processing on Application...');
	let promise =  new Promise(function(resolve, reject) {
		setTimeout(function() {
			Math.random() > .5 ? resolve({}) : reject('Visa is denaid: did not have enough documents');
		}, 2000);
	});
	return promise;
}

function bookHotel() {}

function buyTickets() {}

applyForVisa({})
	.then( function(visa) {
		console.info('Visa received');
	},
	function(reason) {
		console.error(reason);
	});
*/

// callbacks
/*function applyForVisa(documents, resolve, reject) {
	console.log('Processing on Application...');
	setTimeout(function() {
		Math.random() > .5 ? resolve({}) : reject('Visa is denaid: did not have enough documents');
	}, 2000);
}

function bookHotel() {

}

function buyTickets() {

}

applyForVisa({}, function(visa) {
	console.info('Visa received');
	// calback hell
	bookHotel(visa, function(reservation) {
		buyTickets(reservation, function() {

		}, function() {

		})
	}, function(error){

	})
},
function(reason) {
	console.error(reason);
});
*/


text:
public class Test011 {
	public static void main(String[] args) {
		int a = 5;
		char c = 'a';
		boolean b = true;
		float f = 5.12f;
		double d = 4.12;
		String author = "lkk";
		String book = "Crazy java";

		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
		System.out.println(d);
		System.out.println(f);
		System.out.println(author);
		System.out.println(book);
	}

}


text:
package com.google.cloud.teleport.v2.elasticsearch.transforms;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.auto.value.AutoValue;
import com.google.cloud.teleport.v2.elasticsearch.options.ElasticsearchWriteOptions;
import com.google.cloud.teleport.v2.elasticsearch.transforms.ValueExtractorTransform.BooleanValueExtractorFn;
import com.google.cloud.teleport.v2.elasticsearch.transforms.ValueExtractorTransform.StringValueExtractorFn;
import com.google.cloud.teleport.v2.elasticsearch.utils.ConnectionInformation;
import com.google.cloud.teleport.v2.elasticsearch.utils.ElasticsearchIO;
import com.google.cloud.teleport.v2.elasticsearch.utils.ElasticsearchIO.Write.FieldValueExtractFn;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PDone;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.Duration;

/**
 * The {@link WriteToElasticsearch} class writes a {@link PCollection} of strings to Elasticsearch
 * using the following options.
 *
 * <ul>
 *   <li>{@link ElasticsearchWriteOptions#getConnectionUrl()} - CloudId or URL.
 *   <li>{@link ElasticsearchWriteOptions#getIndex()} ()} ()} ()} - Elasticsearch write index.
 *   <li>{@link ElasticsearchWriteOptions#getBatchSize()} - batch size in number of documents
 *       (Default:1000).
 *   <li>{@link ElasticsearchWriteOptions#getBatchSizeBytes()} - batch size in number of bytes
 *       (Default:5242880).
 *   <li>{@link ElasticsearchWriteOptions#getMaxRetryAttempts()} - optional: maximum retry attempts
 *       for {@link ElasticsearchIO.RetryConfiguration}.
 *   <li>{@link ElasticsearchWriteOptions#getMaxRetryDuration()} - optional: maximum retry duration
 *       for {@link ElasticsearchIO.RetryConfiguration}.
 * </ul>
 *
 * For {@link ElasticsearchIO#write()} with {@link ValueExtractorTransform.ValueExtractorFn} if the
 * function returns null then the index or type provided as {@link ConnectionInformation}.
 */
@AutoValue
public abstract class WriteToElasticsearch extends PTransform<PCollection<String>, PDone> {

  /**
   * The {@link StringFieldValueExtractFn} class is a class implementation for {@link
   * FieldValueExtractFn} to extract a property by name.
   */
  @AutoValue
  abstract static class StringFieldValueExtractFn implements FieldValueExtractFn {

    @Nullable
    abstract String propertyName();

    public static Builder newBuilder() {
      return new AutoValue_WriteToElasticsearch_StringFieldValueExtractFn.Builder();
    }

    @Override
    public String apply(JsonNode input) {
      if (propertyName() == null) {
        return null;
      }
      return input.get(propertyName()).asText();
    }

    /** Builder for {@link StringFieldValueExtractFn}. */
    @AutoValue.Builder
    public abstract static class Builder {
      public abstract Builder setPropertyName(String propertyName);

      public abstract StringFieldValueExtractFn build();
    }
  }
  /** Convert provided long to {@link Duration}. */
  private static Duration getDuration(Long milliseconds) {
    return new Duration(milliseconds);
  }

  public static Builder newBuilder() {
    return new AutoValue_WriteToElasticsearch.Builder();
  }

  public abstract ElasticsearchWriteOptions options();

  /**
   * Types have been removed in ES 7.0. Default will be _doc. See
   * https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html"
   */
  private static final String DOCUMENT_TYPE = "_doc";

  @Override
  public PDone expand(PCollection<String> jsonStrings) {
    ConnectionInformation connectionInformation =
        new ConnectionInformation(options().getConnectionUrl());

    ElasticsearchIO.ConnectionConfiguration config =
        ElasticsearchIO.ConnectionConfiguration.create(
            new String[] {connectionInformation.getElasticsearchURL().toString()},
            options().getIndex(),
            DOCUMENT_TYPE);

    // If username and password are not blank, use them instead of ApiKey
    if (StringUtils.isNotBlank(options().getElasticsearchUsername())
        && StringUtils.isNotBlank(options().getElasticsearchPassword())) {
      config =
          config
              .withUsername(options().getElasticsearchUsername())
              .withPassword(options().getElasticsearchPassword());
    } else {
      config = config.withApiKey(options().getApiKey());
    }

    ElasticsearchIO.Write elasticsearchWriter =
        ElasticsearchIO.write()
            .withConnectionConfiguration(config)
            .withMaxBatchSize(options().getBatchSize())
            .withMaxBatchSizeBytes(options().getBatchSizeBytes());

    if (options().getPropertyAsId() != null) {
      StringFieldValueExtractFn idFn =
          StringFieldValueExtractFn.newBuilder()
              .setPropertyName(options().getPropertyAsId())
              .build();

      elasticsearchWriter = elasticsearchWriter.withIdFn(idFn);
    } else if (options().getJavaScriptIdFnGcsPath() != null
        && options().getJavaScriptIdFnName() != null) {
      StringValueExtractorFn idFn =
          StringValueExtractorFn.newBuilder()
              .setFileSystemPath(options().getJavaScriptIdFnGcsPath())
              .setFunctionName(options().getJavaScriptIdFnName())
              .build();

      elasticsearchWriter = elasticsearchWriter.withIdFn(idFn);
    }

    if (options().getPropertyAsIndex() != null) {
      StringFieldValueExtractFn indexFn =
          StringFieldValueExtractFn.newBuilder()
              .setPropertyName(options().getPropertyAsIndex())
              .build();

      elasticsearchWriter = elasticsearchWriter.withIndexFn(indexFn);
    } else if (options().getJavaScriptIndexFnGcsPath() != null
        && options().getJavaScriptIndexFnName() != null) {
      StringValueExtractorFn indexFn =
          StringValueExtractorFn.newBuilder()
              .setFileSystemPath(options().getJavaScriptIndexFnGcsPath())
              .setFunctionName(options().getJavaScriptIndexFnName())
              .build();

      elasticsearchWriter = elasticsearchWriter.withIndexFn(indexFn);
    }

    if (options().getJavaScriptTypeFnGcsPath() != null
        && options().getJavaScriptTypeFnName() != null) {
      StringValueExtractorFn typeFn =
          StringValueExtractorFn.newBuilder()
              .setFileSystemPath(options().getJavaScriptTypeFnGcsPath())
              .setFunctionName(options().getJavaScriptTypeFnName())
              .build();

      elasticsearchWriter = elasticsearchWriter.withTypeFn(typeFn);
    }

    if (options().getJavaScriptIsDeleteFnGcsPath() != null
        && options().getJavaScriptIsDeleteFnName() != null) {
      BooleanValueExtractorFn isDeleteFn =
          BooleanValueExtractorFn.newBuilder()
              .setFileSystemPath(options().getJavaScriptIsDeleteFnGcsPath())
              .setFunctionName(options().getJavaScriptIsDeleteFnName())
              .build();

      elasticsearchWriter = elasticsearchWriter.withIsDeleteFn(isDeleteFn);
    }

    if (options().getUsePartialUpdate() != null) {
      elasticsearchWriter =
          elasticsearchWriter.withUsePartialUpdate(
              Boolean.TRUE.equals(options().getUsePartialUpdate()));
    }

    if (options().getBulkInsertMethod() != null) {
      elasticsearchWriter =
          elasticsearchWriter.withBulkInsertMethod(options().getBulkInsertMethod());
    }

    if (Optional.ofNullable(options().getMaxRetryAttempts()).isPresent()) {
      elasticsearchWriter =
          elasticsearchWriter.withRetryConfiguration(
              ElasticsearchIO.RetryConfiguration.create(
                  options().getMaxRetryAttempts(), getDuration(options().getMaxRetryDuration())));
    }

    return jsonStrings.apply("WriteDocuments", elasticsearchWriter);
  }

  /** Builder for {@link WriteToElasticsearch}. */
  @AutoValue.Builder
  public abstract static class Builder {
    public abstract Builder setOptions(ElasticsearchWriteOptions options);

    abstract ElasticsearchWriteOptions options();

    abstract WriteToElasticsearch autoBuild();

    public WriteToElasticsearch build() {

      checkArgument(options().getConnectionUrl() != null, "ConnectionUrl is required.");

      checkArgument(options().getApiKey() != null, "ApiKey is required.");

      checkArgument(options().getIndex() != null, "Elasticsearch index should not be null.");

      checkArgument(
          options().getBatchSize() > 0, "Batch size must be > 0. Got: " + options().getBatchSize());

      checkArgument(
          options().getBatchSizeBytes() > 0,
          "Batch size bytes must be > 0. Got: " + options().getBatchSizeBytes());

      /* Check that both {@link RetryConfiguration} parameters are supplied. */
      if (options().getMaxRetryAttempts() != null || options().getMaxRetryDuration() != null) {
        checkArgument(
            options().getMaxRetryDuration() != null && options().getMaxRetryAttempts() != null,
            "Both max retry duration and max attempts must be supplied.");
      }

      return autoBuild();
    }
  }
}


text:
package builtinpluginconsts

const (
	namePrefixFieldSpecs = `
namePrefix:
- path: metadata/name
`
)


text:
@import Cocoa;
@import WebKit;

@class AppController;

@interface TabbedWebView : WebView <WebPolicyDelegate> {
	BOOL openLinksInNewBrowser;
	BOOL isFeedRedirect;
	BOOL isDownload;
}

// Public functions
+(NSString *)userAgent;
-(void)initTabbedWebView;
-(void)setOpenLinksInNewBrowser:(BOOL)flag;
-(void)keyDown:(NSEvent *)theEvent;
-(void)printDocument:(id)sender;
-(void)abortJavascript;
-(void)useUserPrefsForJavascript;
-(void)forceJavascript;
@property (nonatomic, getter=isFeedRedirect, readonly) BOOL feedRedirect;
@property (nonatomic, getter=isDownload, readonly) BOOL download;
-(void)scrollToTop;
-(void)scrollToBottom;

@end


text:
<?php

namespace FOS\UserBundle\Propel;

class UserTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('Propel')) {
            $this->markTestSkipped('Propel not installed');
        }
    }

    public function testSerialize()
    {
        $group = new Group();
        $group->setName('Developers');

        $user = new User();
        $user->setEmail('foobar@example.com');
        $user->setPassword('123456');
        $user->addGroup($group);
        $user->save();

        $userId = $user->getId();
        $this->assertInternalType('int', $userId);

        $serialized = serialize($user);
        UserPeer::clearInstancePool();
        $this->assertCount(0, UserPeer::$instances);

        $unserialized = unserialize($serialized);
        $fetchedUser = UserQuery::create()->findOneById($userId);

        $this->assertInstanceOf('FOS\UserBundle\Propel\User', $unserialized);
        $this->assertCount(1, UserPeer::$instances);
        $this->assertTrue($fetchedUser->equals($unserialized));

        $this->assertCount(1, $unserialized->getGroups());
    }
}


text:
/*This file has been prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
 *
 * \brief FreeRTOS serial port for AVR32 UC3.
 *
 * - Compiler:           IAR EWAVR32 and GNU GCC for AVR32
 * - Supported devices:  All AVR32 devices can be used.
 * - AppNote:
 *
 * \author               Atmel Corporation: http://www.atmel.com \n
 *                       Support and FAQ: http://support.atmel.no/
 *
 *****************************************************************************/

/* Copyright (c) 2007, Atmel Corporation All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. The name of ATMEL may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY AND
 * SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
  BASIC INTERRUPT DRIVEN SERIAL PORT DRIVER FOR USART0.
*/

/* Scheduler includes. */
#include "FreeRTOS.h"
#include "queue.h"
#include "task.h"

/* Demo application includes. */
#include "serial.h"
#include <avr32/io.h>
#include "board.h"
#include "gpio.h"

/*-----------------------------------------------------------*/

/* Constants to setup and access the USART. */
#define serINVALID_COMPORT_HANDLER        ( ( xComPortHandle ) 0 )
#define serINVALID_QUEUE                  ( ( xQueueHandle ) 0 )
#define serHANDLE                         ( ( xComPortHandle ) 1 )
#define serNO_BLOCK                       ( ( portTickType ) 0 )

/*-----------------------------------------------------------*/

/* Queues used to hold received characters, and characters waiting to be
transmitted. */
static xQueueHandle xRxedChars;
static xQueueHandle xCharsForTx;

/*-----------------------------------------------------------*/

/* Forward declaration. */
static void vprvSerialCreateQueues( unsigned portBASE_TYPE uxQueueLength,
        xQueueHandle *pxRxedChars,
        xQueueHandle *pxCharsForTx );

/*-----------------------------------------------------------*/

#if __GNUC__
__attribute__((__noinline__))
#elif __ICCAVR32__
#pragma optimize = no_inline
#endif
static portBASE_TYPE prvUSART0_ISR_NonNakedBehaviour( void )
{
  /* Now we can declare the local variables. */
  signed portCHAR     cChar;
  portBASE_TYPE     xHigherPriorityTaskWoken = pdFALSE;
  unsigned portLONG     ulStatus;
  volatile avr32_usart_t  *usart0 = &AVR32_USART0;
  portBASE_TYPE retstatus;

  /* What caused the interrupt? */
  ulStatus = usart0->csr & usart0->imr;

  if (ulStatus & AVR32_USART_CSR_TXRDY_MASK)
  {
    /* The interrupt was caused by the THR becoming empty.  Are there any
       more characters to transmit? */
    /* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
      calls in a critical section . */
    portENTER_CRITICAL();
    retstatus = xQueueReceiveFromISR(xCharsForTx, &cChar, &xHigherPriorityTaskWoken);
    portEXIT_CRITICAL();
    if (retstatus == pdTRUE)
    {
      /* A character was retrieved from the queue so can be sent to the
         THR now. */
      usart0->thr = cChar;
    }
    else
    {
      /* Queue empty, nothing to send so turn off the Tx interrupt. */
      usart0->idr = AVR32_USART_IDR_TXRDY_MASK;
    }
  }

  if (ulStatus & AVR32_USART_CSR_RXRDY_MASK)
  {
    /* The interrupt was caused by the receiver getting data. */
    cChar = usart0->rhr; //TODO

    /* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
      calls in a critical section . */
    portENTER_CRITICAL();
	xQueueSendFromISR(xRxedChars, &cChar, &xHigherPriorityTaskWoken);
    portEXIT_CRITICAL();
  }

  /* The return value will be used by portEXIT_SWITCHING_ISR() to know if it
  should perform a vTaskSwitchContext(). */
  return ( xHigherPriorityTaskWoken );
}

/*
 * USART0 interrupt service routine.
 */
#if __GNUC__
__attribute__((__naked__))
#elif __ICCAVR32__
#pragma shadow_registers = full   // Naked.
#endif
static void vUSART0_ISR( void )
{

 /* This ISR can cause a context switch, so the first statement must be a
  call to the portENTER_SWITCHING_ISR() macro.  This must be BEFORE any
  variable declarations. */
  portENTER_SWITCHING_ISR();
  prvUSART0_ISR_NonNakedBehaviour();
 /* Exit the ISR.  If a task was woken by either a character being received
  or transmitted then a context switch will occur. */
  portEXIT_SWITCHING_ISR();
}
/*-----------------------------------------------------------*/

/*
 * Init the serial port for the Minimal implementation.
 */
xComPortHandle xSerialPortInitMinimal( unsigned portLONG ulWantedBaud, unsigned portBASE_TYPE uxQueueLength )
{
  static const gpio_map_t USART0_GPIO_MAP =
  {
    { AVR32_USART0_RXD_0_PIN, AVR32_USART0_RXD_0_FUNCTION },
    { AVR32_USART0_TXD_0_PIN, AVR32_USART0_TXD_0_FUNCTION }
  };

  xComPortHandle    xReturn = serHANDLE;
  volatile avr32_usart_t  *usart0 = &AVR32_USART0;
  int                           cd; /* USART0 Clock Divider. */

  /* Create the rx and tx queues. */
  vprvSerialCreateQueues( uxQueueLength, &xRxedChars, &xCharsForTx );

  /* Configure USART0. */
  if( ( xRxedChars != serINVALID_QUEUE ) &&
      ( xCharsForTx != serINVALID_QUEUE ) &&
      ( ulWantedBaud != ( unsigned portLONG ) 0 ) )
  {
    portENTER_CRITICAL();
    {
      /**
       ** Reset USART0.
       **/
      /* Disable all USART0 interrupt sources to begin... */
      usart0->idr = 0xFFFFFFFF;

      /* Reset mode and other registers that could cause unpredictable
         behaviour after reset */
      usart0->mr = 0; /* Reset Mode register. */
      usart0->rtor = 0; /* Reset Receiver Time-out register. */
      usart0->ttgr = 0; /* Reset Transmitter Timeguard register. */

      /* Shutdown RX and TX, reset status bits, reset iterations in CSR, reset NACK
         and turn off DTR and RTS */
      usart0->cr = AVR32_USART_CR_RSTRX_MASK   |
                   AVR32_USART_CR_RSTTX_MASK   |
                   AVR32_USART_CR_RXDIS_MASK   |
                   AVR32_USART_CR_TXDIS_MASK   |
                   AVR32_USART_CR_RSTSTA_MASK  |
                   AVR32_USART_CR_RSTIT_MASK   |
                   AVR32_USART_CR_RSTNACK_MASK |
                   AVR32_USART_CR_DTRDIS_MASK  |
                   AVR32_USART_CR_RTSDIS_MASK;

      /**
       ** Configure USART0.
       **/
      /* Enable USART0 RXD & TXD pins. */
      gpio_enable_module( USART0_GPIO_MAP, sizeof( USART0_GPIO_MAP ) / sizeof( USART0_GPIO_MAP[0] ) );

      /* Set the USART0 baudrate to be as close as possible to the wanted baudrate. */
      /*
       *             ** BAUDRATE CALCULATION **
       *
       *                 Selected Clock                       Selected Clock
       *     baudrate = ----------------   or     baudrate = ----------------
       *                    16 x CD                              8 x CD
       *
       *       (with 16x oversampling)              (with 8x oversampling)
       */
      if ( ulWantedBaud < (configCPU_CLOCK_HZ/16)  ){
        /* Use 8x oversampling */
        usart0->mr |= (1<<AVR32_USART_MR_OVER_OFFSET);
        cd = configCPU_CLOCK_HZ / (8*ulWantedBaud);

        if (cd < 2) {
          return serINVALID_COMPORT_HANDLER;
        }
        usart0->brgr = (cd << AVR32_USART_BRGR_CD_OFFSET);
      } else {
        /* Use 16x oversampling */
        usart0->mr &= ~(1<<AVR32_USART_MR_OVER_OFFSET);
        cd =  configCPU_CLOCK_HZ / (16*ulWantedBaud);

        if (cd > 65535) {
          /* Baudrate is too low */
          return serINVALID_COMPORT_HANDLER;
        }
      }
      usart0->brgr = (cd << AVR32_USART_BRGR_CD_OFFSET);

      /* Set the USART0 Mode register: Mode=Normal(0), Clk selection=MCK(0),
         CHRL=8,  SYNC=0(asynchronous), PAR=None, NBSTOP=1, CHMODE=0, MSBF=0,
         MODE9=0, CKLO=0, OVER(previously done when setting the baudrate),
         other fields not used in this mode. */
      usart0->mr |= ((8-5) << AVR32_USART_MR_CHRL_OFFSET  ) |
                    (   4  << AVR32_USART_MR_PAR_OFFSET   ) |
                    (   1  << AVR32_USART_MR_NBSTOP_OFFSET);

      /* Write the Transmit Timeguard Register */
      usart0->ttgr = 0;

      // Register the USART0 interrupt handler to the interrupt controller and
      // enable the USART0 interrupt.
      INTC_register_interrupt((__int_handler)&vUSART0_ISR, AVR32_USART0_IRQ, INT1);

      /* Enable USART0 interrupt sources (but not Tx for now)... */
      usart0->ier = AVR32_USART_IER_RXRDY_MASK;

      /* Enable receiver and transmitter... */
      usart0->cr |= AVR32_USART_CR_TXEN_MASK | AVR32_USART_CR_RXEN_MASK;
    }
    portEXIT_CRITICAL();
  }
  else
  {
    xReturn = serINVALID_COMPORT_HANDLER;
  }

  return xReturn;
}
/*-----------------------------------------------------------*/

signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed portCHAR *pcRxedChar, portTickType xBlockTime )
{
  /* The port handle is not required as this driver only supports UART0. */
  ( void ) pxPort;

  /* Get the next character from the buffer.  Return false if no characters
  are available, or arrive before xBlockTime expires. */
  if( xQueueReceive( xRxedChars, pcRxedChar, xBlockTime ) )
  {
    return pdTRUE;
  }
  else
  {
    return pdFALSE;
  }
}
/*-----------------------------------------------------------*/

void vSerialPutString( xComPortHandle pxPort, const signed portCHAR * const pcString, unsigned portSHORT usStringLength )
{
signed portCHAR *pxNext;

  /* NOTE: This implementation does not handle the queue being full as no
  block time is used! */

  /* The port handle is not required as this driver only supports UART0. */
  ( void ) pxPort;

  /* Send each character in the string, one at a time. */
  pxNext = ( signed portCHAR * ) pcString;
  while( *pxNext )
  {
    xSerialPutChar( pxPort, *pxNext, serNO_BLOCK );
    pxNext++;
  }
}
/*-----------------------------------------------------------*/

signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed portCHAR cOutChar, portTickType xBlockTime )
{
volatile avr32_usart_t  *usart0 = &AVR32_USART0;

  /* Place the character in the queue of characters to be transmitted. */
  if( xQueueSend( xCharsForTx, &cOutChar, xBlockTime ) != pdPASS )
  {
    return pdFAIL;
  }

  /* Turn on the Tx interrupt so the ISR will remove the character from the
  queue and send it.   This does not need to be in a critical section as
  if the interrupt has already removed the character the next interrupt
  will simply turn off the Tx interrupt again. */
  usart0->ier = (1 << AVR32_USART_IER_TXRDY_OFFSET);

  return pdPASS;
}
/*-----------------------------------------------------------*/

void vSerialClose( xComPortHandle xPort )
{
  /* Not supported as not required by the demo application. */
}
/*-----------------------------------------------------------*/

/*###########################################################*/

/*
 * Create the rx and tx queues.
 */
static void vprvSerialCreateQueues(  unsigned portBASE_TYPE uxQueueLength, xQueueHandle *pxRxedChars, xQueueHandle *pxCharsForTx )
{
  /* Create the queues used to hold Rx and Tx characters. */
  xRxedChars = xQueueCreate( uxQueueLength, ( unsigned portBASE_TYPE ) sizeof( signed portCHAR ) );
  xCharsForTx = xQueueCreate( uxQueueLength + 1, ( unsigned portBASE_TYPE ) sizeof( signed portCHAR ) );

  /* Pass back a reference to the queues so the serial API file can
  post/receive characters. */
  *pxRxedChars = xRxedChars;
  *pxCharsForTx = xCharsForTx;
}
/*-----------------------------------------------------------*/


text:
using System;
using System.Collections.Generic;
using AForge.Math;
using BasicLoader;
using BasicLoader.Interface;
using CADLoader;
using CADLoader.Implementation.Parser;

namespace STPLoader.Implementation.Model
{
    /// <summary>
    ///
    /// </summary>
    public class StpFile : IStpModel
	{
        /// <summary>
        ///
        /// </summary>
		private StpHeader _header;
        /// <summary>
        ///
        /// </summary>
		private StpData _data;

        private readonly IList<Facet> _facets;
        private readonly IList<Vector3> _vertices;
        private readonly IList<int> _triangles;
        private readonly IList<IPart> _parts;

        /// <summary>
        ///
        /// </summary>
	    public StpHeader Header
	    {
	        get { return _header; }
            set { _header = value; }
	    }

        /// <summary>
        ///
        /// </summary>
        public StpData Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public override string ToString()
        {
            return String.Format("<StpFile({0}, {1})>", Header, Data);
        }

        public IList<T> All<T>() where T : Entity.Entity
        {
            return _data.All<T>();
        }

        public IDictionary<long, Entity.Entity> All()
        {
            return _data.All();
        }

        public Entity.Entity Get(long id)
        {
            return _data.Get(id);
        }

        public T Get<T>(long id) where T : Entity.Entity
        {
            return _data.Get<T>(id);
        }

        public IList<IPart> Parts
        {
            get { return _parts; }
        }

        public IConstraint GetConstraint(IModel a, IModel b)
        {
            throw new NotImplementedException();
        }

        public IList<Facet> Facets
        {
            get { return _facets; }
        }

        public IList<Vector3> Vertices
        {
            get { return _vertices; }
        }

        public IList<int> Triangles
        {
            get { return _triangles; }
        }

        public string Name
        {
            get { return Header.Name.Name; }
        }
	}

}


text:
include ../make/bazel.mk

build:
	$(BAZEL) build --config=mayberemote go/k8s-checker/...

release:
	$(BAZEL) run --config=mayberemote //k8s-checker:push_k8s_checker_container

push: release
	$(BAZEL) run --config=mayberemote //kube/go/pushk -- --use-temp-checkout k8s-checker

push_public: release
	$(BAZEL) run --config=mayberemote //kube/go/pushk -- --only-cluster skia-public k8s-checker

push_corp: release
	$(BAZEL) run --config=mayberemote //kube/go/pushk -- --only-cluster skia-corp k8s-checker


text:
package net.jxta.endpoint;

/**
 *  A MessageSender is a MessageTransport that is able to send messages to
 *  remote peers using some protocol. MessageSenders provide facilities for
 *  sending point-to-point (unicast) messages.
 *
 *
MessageSenders additionally describe themselves in terms of their
 *  abilities.
 *

 *
{@link #isConnectionOriented()}

Indicates that the
 *  Message Transport can provide efficient transport of a series of messages to
 *  the same destination

 *
{link@ #allowRouting()}

Indicates that the Message Transport
 *  can be used in the routing of messages to destinations which are not
 *  directly reachable via this transport.

 *

 *
 *  @see net.jxta.endpoint.MessageTransport
 *  @see net.jxta.endpoint.Message
 *  @see net.jxta.endpoint.Messenger
 *  @see net.jxta.endpoint.EndpointService
 *  @see net.jxta.endpoint.MessageReceiver
 *  @see net.jxta.endpoint.MessagePropagater
 */
public interface MessageSender extends MessageTransport {

    /**
     *  Returns the {@link EndpointAddress} which will be used as the source
     *  address for all messages sent by this message sender. This is the
     *  "preferred" address to which replies should be sent. This address is not
     *  necessarily the best or only address by which the peer may be reached.
     *
     *
The public address may also be for a different message transport.
     *
     *  @return an EndpointAddress containing the public address for this
     *  message receiver.
     */
    public EndpointAddress getPublicAddress();

    /**
     *  Returns {@code true} if the Message Transport is connection oriented
     *  (like TCP/IP). Indicates that the Message Transport can provide
     *  efficient transport of a series of messages to the same destination.
     *
     *  @return {@code true} if the Message Transport is connection oriented.
     */
    public boolean isConnectionOriented();

    /**
     *  Returns true if the Message Transport can be used by the EndpointRouter.
     *  Indicates that the Message Transport can be used in the routing of
     *  messages to destinations which are not directly reachable via this
     *  transport.
     *
     *
More specifically, this Message Transport will be used to route
     *  messages who's final destination is not one of the endpoint
     *  addresses available from {@code getReachableEndpointAddresses}.
     *
     * @return <tt>true</tt> if the protocol can be used by the EndpointRouter
     */
    public boolean allowsRouting();

    /**
     *  Return a {@link Messenger} for sending messages to the specified
     *  destination {@link EndpointAddress}.
     *  @param dest The destination address for which a messenger is requested.
//     *  @param hint An optional hint for the transport to use when creating the
//     *  messenger. The format of the hint is specific to each Message Transport
//     *  and may be {@code null} if no hint is provided.
     *  @return a Messenger or {@code null} if the destination is not reachable.
     */
    public Messenger getMessenger(EndpointAddress dest);
//    public Messenger getMessenger(EndpointAddress dest, Object hint);

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeronaema hispidulum f. hispidulum

### Remarks
null


text:
$DebugPreference = "SilentlyContinue"

$here = Split-Path -Parent $MyInvocation.MyCommand.Definition
$src = Resolve-Path -Path "$($here)\.."
Function New-MockUpdate($UpdateID, $Title) {
  $properties = @{
    Operation = Get-Random -Minimum 1 -Maximum 3
    ResultCode = Get-Random -Minimum 0 -Maximum 6
    Date = [DateTime]::Now
    UpdateIdentity = @{
      RevisionNumber = Get-Random -Minimum 1 -Maximum 11
      UpdateID = [GUID]::NewGuid().ToString()
    }
    Title = "Mock Update Title $(Get-Random)"
    ServiceID = [GUID]::NewGuid().ToString()
    Categories = @() # TODO
    HResult = Get-Random -Minimum 0 -Maximum 32768
    Description = "Mock Description $(Get-Random)"
    UnmappedResultCode = Get-Random -Minimum 0 -Maximum 32768

    ClientApplicationID = "Mock ClientApplicationID $(Get-Random)"
    ServerSelection = Get-Random -Minimum 0 -Maximum 4
    UninstallationSteps = @("Mock UninstallationStep $(Get-Random)")
    UninstallationNotes = "Mock UninstallationNotes $(Get-Random)"
    SupportUrl = "Mock SupportUrl $(Get-Random)"
  }

  if (-Not [String]::IsNullOrEmpty($UpdateID)) { $properties.UpdateIdentity.UpdateID = $UpdateID}
  if (-Not [String]::IsNullOrEmpty($Title)) { $properties.Title = $Title}

  New-Object -TypeName PSObject -Property $properties
}
Function New-MockUpdateSession($UpdateCount = 0, $UpdateObjects = @()) {
  $mock = New-Object -TypeName PSObject

  $mock | Add-Member -MemberType NoteProperty -Name MockGetTotalHistoryCount -Value $UpdateCount | Out-Null

  # Create a random update list
  $Updates = $UpdateObjects
  While ($Updates.Count -lt $UpdateCount) {
    $Updates += New-MockUpdate
  }
  $mock | Add-Member -MemberType NoteProperty -Name MockQueryHistory -Value $Updates | Out-Null

  # The following are methods not a properties and we can't do closures so just mirror the mock properties
  $mock | Add-Member -MemberType ScriptMethod -Name GetTotalHistoryCount -Value { $this.MockGetTotalHistoryCount } | Out-Null
  $mock | Add-Member -MemberType ScriptMethod -Name QueryHistory -Value { param($start, $count) $this.MockQueryHistory[$start..($start + $count - 1)] } | Out-Null

  Write-Output $mock
}


text:
/**
  * Automatically generated file. Please do not edit.
  * @author Highcharts Config Generator by Karasiq
  * @see [[http://api.highcharts.com/highstock]]
  */
package com.highstock.config

import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._

/**
  * @note JavaScript name: colorAxis-dataClasses
  */
@js.annotation.ScalaJSDefined
class ColorAxisDataClasses extends com.highcharts.HighchartsGenericObject {

  /**
    *
The color of each data class. If not set, the color is pulled
    * from the global or chart-specific colors array. In
    * styled mode, this option is ignored. Instead, use colors defined
    * in CSS.

    * @example Explicit colors
    */
  val color: js.UndefOr[String | js.Object] = js.undefined

  /**
    *
The start of the value range that the data class represents,
    * relating to the point value.

    *
The range of each dataClass is closed in both ends, but can be
    * overridden by the next dataClass.

    */
  val from: js.UndefOr[Double] = js.undefined

  /**
    *
The name of the data class as it appears in the legend.
    * If no name is given, it is automatically created based on the
    * from and to values. For full programmatic control,
    * legend.labelFormatter can be used.
    * In the formatter, this.from and this.to can be accessed.

    * @example Named data classes
Formatted data classes
    */
  val name: js.UndefOr[String] = js.undefined

  /**
    *
The end of the value range that the data class represents,
    * relating to the point value.

    *
The range of each dataClass is closed in both ends, but can be
    * overridden by the next dataClass.

    */
  val to: js.UndefOr[Double] = js.undefined
}

object ColorAxisDataClasses {
  /**
    * @param color
The color of each data class. If not set, the color is pulled. from the global or chart-specific colors array. In. styled mode, this option is ignored. Instead, use colors defined. in CSS.

    * @param from
The start of the value range that the data class represents,. relating to the point value.
.
The range of each dataClass is closed in both ends, but can be. overridden by the next dataClass.

    * @param name
The name of the data class as it appears in the legend.. If no name is given, it is automatically created based on the. from and to values. For full programmatic control,. legend.labelFormatter can be used.. In the formatter, this.from and this.to can be accessed.

    * @param to
The end of the value range that the data class represents,. relating to the point value.
.
The range of each dataClass is closed in both ends, but can be. overridden by the next dataClass.

    */
  def apply(color: js.UndefOr[String | js.Object] = js.undefined, from: js.UndefOr[Double] = js.undefined, name: js.UndefOr[String] = js.undefined, to: js.UndefOr[Double] = js.undefined): ColorAxisDataClasses = {
    val colorOuter: js.UndefOr[String | js.Object] = color
    val fromOuter: js.UndefOr[Double] = from
    val nameOuter: js.UndefOr[String] = name
    val toOuter: js.UndefOr[Double] = to
    com.highcharts.HighchartsGenericObject.toCleanObject(new ColorAxisDataClasses {
      override val color: js.UndefOr[String | js.Object] = colorOuter
      override val from: js.UndefOr[Double] = fromOuter
      override val name: js.UndefOr[String] = nameOuter
      override val to: js.UndefOr[Double] = toOuter
    })
  }
}


text:
package ${package}.${artifactId}.routes;

import io.swagger.annotations.*;
import com.google.gson.Gson;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ${package}.${artifactId}.pojos.*;

/**
 * Root resource (exposed at "resource" path)
 */
@Path("resource")
@Api(value = "/resource", description = "Resource")
@Produces(MediaType.APPLICATION_JSON)
public class Resource {
    // logger
    private static final Logger logger = LoggerFactory.getLogger(Resource.class);

    /**
     * Method handling HTTP GET requests. The returned object will be sent to
     * the client as "application/json" media type.
     *
     * @return ExampleResponse that will be returned as a application/json response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "A test operation", notes = "More notes about this method", response = ExampleResponse.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Got it"),
            @ApiResponse(code = 500, message = "Server is down!")
    })
    public ExampleResponse get() {
        return new ExampleResponse();
    }

    /**
     * Method handling HTTP POST requests. The returned object will be sent to
     * the client as "application/json" media type.
     *
     * @return ExampleResponse that will be returned as a application/json response.
     */
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "A test operation", notes = "More notes about this method", response = ExampleResponse.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Got it"),
            @ApiResponse(code = 500, message = "Server is down!")
    })
    public ExampleResponse post(ExampleRequest request) {
        logger.info("Server receieved: "+new Gson().toJson(request));

        return new ExampleResponse();
    }
}


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Form\EventListener;

use Oro\Bundle\WorkflowBundle\Form\EventListener\DefaultValuesListener;
use Oro\Component\ConfigExpression\ContextAccessor;
use Symfony\Component\Form\FormEvents;

class DefaultValuesListenerTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var \PHPUnit\Framework\MockObject\MockObject|ContextAccessor
     */
    protected $contextAccessor;

    /**
     * @var \PHPUnit\Framework\MockObject\MockObject
     */
    protected $workflowItem;

    /**
     * @var DefaultValuesListener
     */
    protected $listener;

    protected function setUp()
    {
        $this->contextAccessor = $this->getMockBuilder('Oro\Component\ConfigExpression\ContextAccessor')
            ->disableOriginalConstructor()
            ->getMock();

        $this->listener = new DefaultValuesListener($this->contextAccessor);
    }

    public function testGetSubscribedEvents()
    {
        $events = $this->listener->getSubscribedEvents();
        $this->assertCount(1, $events);
        $this->assertArrayHasKey(FormEvents::PRE_SET_DATA, $events);
    }

    public function testSetDefaultValues()
    {
        $workflowItem = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Entity\WorkflowItem')
            ->disableOriginalConstructor()
            ->getMock();
        $defaultValues = array('test' => 'value');

        $this->contextAccessor->expects($this->once())
            ->method('getValue')
            ->with($workflowItem, 'value')
            ->will($this->returnValue('testValue'));

        $data = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\WorkflowData')
            ->disableOriginalConstructor()
            ->getMock();
        $data->expects($this->once())
            ->method('set')
            ->with('test', 'testValue');
        $event = $this->getMockBuilder('Symfony\Component\Form\FormEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->once())
            ->method('getData')
            ->will($this->returnValue($data));

        $this->listener->initialize($workflowItem, $defaultValues);
        $this->listener->setDefaultValues($event);
    }
}


text:
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gorilla/schema"
	"github.com/trinchan/slackbot/robots"
)

func main() {
	http.HandleFunc("/slack", SlashCommandHandler)
	http.HandleFunc("/slack_hook", HookHandler)
	StartServer()
}

func HookHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	d := schema.NewDecoder()
	command := new(robots.OutgoingWebHook)
	err = d.Decode(command, r.PostForm)
	if err != nil {
		log.Println("Couldn't parse post request:", err)
	}
	c := strings.Split(command.Text, " ")
	command.Robot = c[1]
	command.Text = strings.Join(c[2:], " ")

	robot := GetRobot(command.Robot)
	if robot == nil {
		jsonResp(w, "No robot for that command yet :(")
		return
	}
	w.WriteHeader(http.StatusOK)
	jsonResp(w, robot.Run(&command.Payload))
}

func SlashCommandHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	d := schema.NewDecoder()
	command := new(robots.SlashCommand)
	err = d.Decode(command, r.PostForm)
	if err != nil {
		log.Println("Couldn't parse post request:", err)
	}
	command.Robot = command.Command[1:]
	robot := GetRobot(command.Robot)
	if robot == nil {
		plainResp(w, "No robot for that command yet :(")
		return
	}
	plainResp(w, robot.Run(&command.Payload))
}

func jsonResp(w http.ResponseWriter, msg string) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	resp := map[string]string{"text": msg}
	r, err := json.Marshal(resp)
	if err != nil {
		log.Println("Couldn't marshal hook response:", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(r)
}

func plainResp(w http.ResponseWriter, msg string) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Write([]byte(msg))
}

func StartServer() {
	port := robots.Config.Port
	log.Printf("Starting HTTP server on %d", port)
	err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
	if err != nil {
		log.Fatal("Server start error: ", err)
	}
}

func GetRobot(command string) robots.Robot {
	if r, ok := robots.Robots[command]; ok {
		return r
	}
	return nil
}


text:
package sf.browser.ui.runnables;

import sf.browser.providers.BookmarksProviderWrapper;
import android.app.Activity;
import android.graphics.Bitmap;

/**
 * Runnable to update database favicon.
 * @author user
 *
 */
public class FaviconUpdaterRunnable implements Runnable {

	private Activity mActivity;
	private String mUrl;
	private String mOriginalUrl;
	private Bitmap mFavIcon;

	public FaviconUpdaterRunnable(Activity activity, String url, String originalUrl, Bitmap favicon) {
		this.mActivity = activity;
		this.mUrl = url;
		this.mOriginalUrl = originalUrl;
		this.mFavIcon = favicon;
	}

	@Override
	public void run() {
		BookmarksProviderWrapper.updateFavicon(mActivity, mUrl, mOriginalUrl, mFavIcon);
	}

}


text:
package e2e

import (
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/coreos/etcd-operator/test/e2e/framework"
)

func TestResize(t *testing.T) {
	t.Run("resize etcd cluster", func(t *testing.T) {
		t.Run("resize 3->5", testResizeCluster3to5)
		t.Run("resize 5->3", testResizeCluster5to3)
	})
}

func testResizeCluster3to5(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	f := framework.Global
	testEtcd, err := createEtcdCluster(t, f, makeEtcdCluster("test-etcd-", 3))
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		if err := deleteEtcdCluster(t, f, testEtcd); err != nil {
			t.Fatal(err)
		}
	}()

	if _, err := waitUntilSizeReached(t, f, testEtcd.Name, 3, 60*time.Second); err != nil {
		t.Fatalf("failed to create 3 members etcd cluster: %v", err)
	}
	fmt.Println("reached to 3 members cluster")

	testEtcd.Spec.Size = 5
	if _, err := updateEtcdCluster(f, testEtcd); err != nil {
		t.Fatal(err)
	}

	if _, err := waitUntilSizeReached(t, f, testEtcd.Name, 5, 60*time.Second); err != nil {
		t.Fatalf("failed to resize to 5 members etcd cluster: %v", err)
	}
}

func testResizeCluster5to3(t *testing.T) {
	if os.Getenv(envParallelTest) == envParallelTestTrue {
		t.Parallel()
	}
	f := framework.Global
	testEtcd, err := createEtcdCluster(t, f, makeEtcdCluster("test-etcd-", 5))
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		if err := deleteEtcdCluster(t, f, testEtcd); err != nil {
			t.Fatal(err)
		}
	}()

	if _, err := waitUntilSizeReached(t, f, testEtcd.Name, 5, 90*time.Second); err != nil {
		t.Fatalf("failed to create 5 members etcd cluster: %v", err)
	}
	fmt.Println("reached to 5 members cluster")

	testEtcd.Spec.Size = 3
	if _, err := updateEtcdCluster(f, testEtcd); err != nil {
		t.Fatal(err)
	}

	if _, err := waitUntilSizeReached(t, f, testEtcd.Name, 3, 60*time.Second); err != nil {
		t.Fatalf("failed to resize to 3 members etcd cluster: %v", err)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;

namespace Dominio.Dtos
{
    [DataContract()]
    public partial class user_roleDTO
    {
        [DataMember()]
        public Int32 id { get; set; }

        [DataMember()]
        public Int32 user_id { get; set; }

        [DataMember()]
        public Int32 role_id { get; set; }

        [DataMember()]
        public roleDTO role { get; set; }

        [DataMember()]
        public userDTO user { get; set; }

        public user_roleDTO()
        {
        }

        public user_roleDTO(Int32 id, Int32 user_id, Int32 role_id, roleDTO role, userDTO user)
        {
			this.id = id;
			this.user_id = user_id;
			this.role_id = role_id;
			this.role = role;
			this.user = user;
        }
    }
}


text:
function save_Callback(hObj,~)
%save_Callback  Callback for handling QUATTRO save requests
%
%   save_Callback(H,EVENT)

    % Disable user controls
    hs  = guihandles(hObj);
    obj = getappdata(hs.figure_main,'qtExamObject');
    update_controls(hs.figure_main,'disable');

    % Determine save type
    objTag = get(hObj,'Tag');
    switch objTag
        case {'uipushtool_save_data','menu_save'}
            saveType = 'save';
        case 'menu_save_as'
            saveType = 'saveas';
        case {'menu_save_images','menu_save_maps','menu_save_rois'}
            saveType = objTag(11:end);
    end

    % Revert to original view for surgical planning exams
    isSurgery = strcmpi( getappdata(hs.figure_main,'examtype'), 'surgery' );
    if isSurgery
        vc = get(obj.h_view,'Value');
        vo = get_dicom_orientation(obj.headers(1,1),'ssd');
        obj.reformat(vo);
        setappdata(obj.h_view,'currentvalue',vo);
    end

    % Try to save exam
    try
        obj.save(saveType);
    catch ME
        rethrow(ME)
    end

    % Return to original format for surgical planning exams
    if isSurgery
        obj.reformat(vc);
        setappdata(obj.h_view,'currentvalue',vc);
    end

    % Enable user controls
    update_controls(hs.figure_main,'enable');

end %save_Callback