text:
void printUsage() {

    NSString *processName = [[NSProcessInfo processInfo] processName];
    NSString *processNamePadding = [@"" stringByPaddingToLength:processName.length
                                                     withString:@" "
                                                startingAtIndex:0];

    printf("%s by Daniel Kennett\n\n", processName.UTF8String);

    printf("Outputs a header file containing symbols for the given .strings\n");
    printf("file's keys.\n\n");

    printf("Usage: %s -strings <strings file path>\n", processName.UTF8String);
    printf("       %s -out <output file path> \n", processNamePadding.UTF8String);
    printf("       %s -skipwriteifunchanged <YES/NO> \n\n", processNamePadding.UTF8String);

    printf("  -strings  The path to a valid .strings file.\n\n");

    printf("  -out      The path to write the output header file to. Missing\n");
    printf("            directories will be created along the way. If a file\n");
    printf("            already exists at the given path, it will be\n");
    printf("            overwritten.\n\n");

    printf("  -skipwriteifunchanged   Pass YES to this to skip output writing\n");
    printf("                          if a file already exists at -out with\n");
    printf("                          the same contents as would be written.");

    printf("\n\n");
}

#pragma mark - Main

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSString *inputFilePath = [[NSUserDefaults standardUserDefaults] valueForKey:@"strings"];
        NSString *outputFilePath = [[NSUserDefaults standardUserDefaults] valueForKey:@"out"];
        BOOL skipWriteIfUnchanged = [[NSUserDefaults standardUserDefaults] boolForKey:@"skipwriteifunchanged"];
        NSFileManager *fileManager = [NSFileManager defaultManager];

        setbuf(stdout, NULL);

        if (inputFilePath.length == 0 || outputFilePath.length == 0) {
            printUsage();
            exit(EXIT_FAILURE);
        }

        if (![fileManager fileExistsAtPath:inputFilePath]) {
            printf("ERROR: Input file %s doesn't exist.\n", [inputFilePath UTF8String]);
            exit(EXIT_FAILURE);
        }

        NSError *error = nil;
        NSData *plistData = [NSData dataWithContentsOfFile:inputFilePath
                                                   options:0
                                                     error:&error];

        if (error != nil) {
            printf("ERROR: Reading input file failed with error: %s\n", error.localizedDescription.UTF8String);
            exit(EXIT_FAILURE);
        }

        id plist = [NSPropertyListSerialization propertyListWithData:plistData
                                                             options:0
                                                              format:nil
                                                               error:&error];

        if (error != nil) {
            printf("ERROR: Reading input file failed with error: %s\n", error.localizedDescription.UTF8String);
            exit(EXIT_FAILURE);
        }

        if (![plist isKindOfClass:[NSDictionary class]]) {
            printf("ERROR: Strings file contained unexpected root object type.");
            exit(EXIT_FAILURE);
        }

        NSMutableString *fileContents = [NSMutableString new];

        [fileContents appendFormat:@"// Generated by %@\n", [[NSProcessInfo processInfo] processName]];
        [fileContents appendFormat:@"// Source file: %@\n", inputFilePath];
        [fileContents appendString:@"// WARNING: This file was auto-generated. Do not modify by hand.\n\n"];

        [fileContents appendString:@"#import <Foundation/Foundation.h>\n\n"];

        NSCharacterSet *unsafeCharacters = [NSCharacterSet characterSetWithCharactersInString:@"."];

        for (NSString *key in plist) {
            NSString *safeKey = [[key componentsSeparatedByCharactersInSet:unsafeCharacters] componentsJoinedByString:@"_"];
            [fileContents appendString:[NSString stringWithFormat:@"static NSString * const %@ = @\"%@\";\n", safeKey, key]];
        }

        NSString *parentPath = [outputFilePath stringByDeletingLastPathComponent];
        if (![fileManager fileExistsAtPath:parentPath]) {
            if (![fileManager createDirectoryAtPath:parentPath
                        withIntermediateDirectories:YES
                                         attributes:nil
                                              error:&error]) {
                printf("ERROR: Creating parent directory failed with error: %s\n", error.localizedDescription.UTF8String);
                exit(EXIT_FAILURE);
            }
        }

        NSData *dataToWrite = [fileContents dataUsingEncoding:NSUTF8StringEncoding];

        if (skipWriteIfUnchanged && [fileManager fileExistsAtPath:outputFilePath]) {
            NSData *existingData = [NSData dataWithContentsOfFile:outputFilePath];

            if (existingData != nil && [dataToWrite isEqual:existingData]) {
                printf("File already exists at -out with the same contents as we'd write. Skipping.\n");
                exit(EXIT_SUCCESS);
            }
        }

        if (![dataToWrite writeToFile:outputFilePath options:NSDataWritingAtomic error:&error]) {
            printf("ERROR: Writing output file failed with error: %s\n", error.localizedDescription.UTF8String);
            exit(EXIT_FAILURE);
        }

        exit(EXIT_SUCCESS);

    }
    return 0;
}


text:
namespace {

const char kGetTokenPairValidResponse[] =
    "{"
    "  \"refresh_token\": \"rt1\","
    "  \"access_token\": \"at1\","
    "  \"expires_in\": 3600,"
    "  \"token_type\": \"Bearer\""
    "}";

}  // namespace

class SigninManagerTest : public TokenServiceTestHarness {
 public:
  virtual void SetUp() OVERRIDE {
    prefs_.reset(new TestingPrefService);
    chrome::RegisterLocalState(prefs_.get());
    static_cast<TestingBrowserProcess*>(g_browser_process)->SetLocalState(
        prefs_.get());
    TokenServiceTestHarness::SetUp();
    manager_.reset(new SigninManager());
    google_login_success_.ListenFor(
        chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
        content::Source<Profile>(profile_.get()));
    google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED,
                                    content::Source<Profile>(profile_.get()));
  }

  virtual void TearDown() OVERRIDE {
    // Destroy the SigninManager here, because it relies on profile_ which is
    // freed in the base class.
    manager_.reset(NULL);
    static_cast<TestingBrowserProcess*>(g_browser_process)->SetLocalState(NULL);
    prefs_.reset(NULL);
    TokenServiceTestHarness::TearDown();
  }

  void SetupFetcherAndComplete(const std::string& url,
                               int response_code,
                               const net::ResponseCookies& cookies,
                               const std::string& response_string) {
    net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
    DCHECK(fetcher);
    DCHECK(fetcher->delegate());

    fetcher->set_url(GURL(url));
    fetcher->set_status(net::URLRequestStatus());
    fetcher->set_response_code(response_code);
    fetcher->SetResponseString(response_string);
    fetcher->set_cookies(cookies);
    fetcher->delegate()->OnURLFetchComplete(fetcher);
  }

  void SimulateValidResponseSignInWithOAuth() {
    // Simulate the correct StartClientOAuth response.  This involves
    // separate fetches.
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->client_oauth_url(), 200,
                            net::ResponseCookies(),
                            "{"
                            "  \"oauth2\": {"
                            "    \"refresh_token\": \"rt1\","
                            "    \"access_token\": \"at1\","
                            "    \"expires_in\": 3600,"
                            "    \"token_type\": \"Bearer\""
                            "  }"
                            "}");

    SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth1_login_url(), 200,
                            net::ResponseCookies(),
                            "SID=sid\nLSID=lsid\nAuth=auth_token");

    SimulateValidResponseGetClientInfo(false);
  }

  void SimulateSignInWithOAuthChallengeCaptcha() {
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth1_login_scope(), 200,
                            net::ResponseCookies(),
                            "{"
                            "  \"cause\" : \"NeedsAdditional\","
                            "  \"fallback\" : {"
                            "    \"name\" : \"Terminating\","
                            "    \"url\" : \"https://www.terminating.com\""
                            "  },"
                            "  \"challenge\" : {"
                            "    \"name\" : \"Captcha\","
                            "    \"image_url\" : \"http://www.image.com/\","
                            "    \"image_width\" : 640,"
                            "    \"image_height\" : 480,"
                            "    \"audio_url\" : \"http://www.audio.com/\","
                            "    \"challenge_token\" : \"challengetokenblob\""
                            "  }"
                            "}");
  }

  void SimulateSignInWithOAuthChallengeOtp() {
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth1_login_scope(), 200,
                            net::ResponseCookies(),
                            "{"
                            "  \"cause\" : \"NeedsAdditional\","
                            "  \"fallback\" : {"
                            "    \"name\" : \"Terminating\","
                            "    \"url\" : \"https://www.terminating.com\""
                            "  },"
                            "  \"challenge\" : {"
                            "    \"name\" : \"TwoStep\","
                            "    \"prompt_text\" : \"prompt_text\","
                            "    \"alternate_text\" : \"alternate_text\","
                            "    \"challenge_token\" : \"challengetokenblob\","
                            "    \"field_length\" : 10"
                            "  }"
                            "}");
  }

  void SimulateProvideOAuthChallengeResponseValid() {
    SimulateValidResponseSignInWithOAuth();
  }

  void SimulateValidResponseSignInWithCredentials() {
    // Simulate the correct StartOAuthLoginTokenFetch response.  This involves
    // two separate fetches.
    SetupFetcherAndComplete(
        GaiaUrls::GetInstance()->client_login_to_oauth2_url(), 200,
        net::ResponseCookies(), kGetTokenPairValidResponse);

    SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth2_token_url(), 200,
                            net::ResponseCookies(), kGetTokenPairValidResponse);

    // Simulate the correct StartOAuthLogin response.
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth1_login_url(), 200,
                            net::ResponseCookies(),
                            "SID=sid\nLSID=lsid\nAuth=auth_token");

    SimulateValidResponseGetClientInfo(false);
  }

  void SimulateValidResponseClientLogin(bool isGPlusUser) {
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->client_login_url(), 200,
                            net::ResponseCookies(),
                            "SID=sid\nLSID=lsid\nAuth=auth");
    SimulateValidResponseGetClientInfo(isGPlusUser);
  }

  void SimulateValidResponseGetClientInfo(bool isGPlusUser) {
    // Simulate the correct ClientLogin response.
    std::string response_string = isGPlusUser ?
        "email=user@gmail.com\nallServices=googleme" :
        "email=user@gmail.com\nallServices=";
    SetupFetcherAndComplete(GaiaUrls::GetInstance()->get_user_info_url(), 200,
                            net::ResponseCookies(), response_string);
  }

  net::TestURLFetcherFactory factory_;
  scoped_ptr<SigninManager> manager_;
  content::TestNotificationTracker google_login_success_;
  content::TestNotificationTracker google_login_failure_;
  scoped_ptr<TestingPrefService> prefs_;
};

// NOTE: ClientLogin's "StartSignin" is called after collecting credentials
//       from the user.
TEST_F(SigninManagerTest, SignInClientLogin) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignIn("user@gmail.com", "password", "", "");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseClientLogin(true);
  EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
  EXPECT_TRUE(profile_->GetPrefs()->GetBoolean(prefs::kIsGooglePlusUser));

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());
}

TEST_F(SigninManagerTest, Prohibited) {
  g_browser_process->local_state()->SetString(
      prefs::kGoogleServicesUsernamePattern, ".*@google.com");
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->IsAllowedUsername("test@google.com"));
  EXPECT_TRUE(manager_->IsAllowedUsername("happy@google.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername("test@invalid.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername("test@notgoogle.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername(""));
}

TEST_F(SigninManagerTest, TestAlternateWildcard) {
  // Test to make sure we accept "*@google.com" as a pattern (treat it as if
  // the admin entered ".*@google.com").
  g_browser_process->local_state()->SetString(
      prefs::kGoogleServicesUsernamePattern, "*@google.com");
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->IsAllowedUsername("test@google.com"));
  EXPECT_TRUE(manager_->IsAllowedUsername("happy@google.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername("test@invalid.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername("test@notgoogle.com"));
  EXPECT_FALSE(manager_->IsAllowedUsername(""));
}

TEST_F(SigninManagerTest, ProhibitedAtStartup) {
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
                                  "monkey@invalid.com");
  g_browser_process->local_state()->SetString(
      prefs::kGoogleServicesUsernamePattern, ".*@google.com");
  manager_->Initialize(profile_.get());
  // Currently signed in user is prohibited by policy, so should be signed out.
  EXPECT_EQ("", manager_->GetAuthenticatedUsername());
}

TEST_F(SigninManagerTest, ProhibitedAfterStartup) {
  std::string user("monkey@invalid.com");
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, user);
  manager_->Initialize(profile_.get());
  EXPECT_EQ(user, manager_->GetAuthenticatedUsername());
  // Update the profile - user should be signed out.
  g_browser_process->local_state()->SetString(
      prefs::kGoogleServicesUsernamePattern, ".*@google.com");
  EXPECT_EQ("", manager_->GetAuthenticatedUsername());
}

TEST_F(SigninManagerTest, SignInWithCredentials) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignInWithCredentials("0", "user@gmail.com", "password");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseSignInWithCredentials();
  EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());
}

TEST_F(SigninManagerTest, SignInWithCredentialsWrongEmail) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  // If the email address used to start the sign in does not match the
  // email address returned by /GetUserInfo, the sign in should fail.
  manager_->StartSignInWithCredentials("0", "user2@gmail.com", "password");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseSignInWithCredentials();
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  // Should go into token service and stop.
  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, SignInClientLoginNoGPlus) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignIn("username", "password", "", "");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseClientLogin(false);
  EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
  EXPECT_FALSE(profile_->GetPrefs()->GetBoolean(prefs::kIsGooglePlusUser));
}

TEST_F(SigninManagerTest, ClearTransientSigninData) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignIn("username", "password", "", "");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseClientLogin(false);

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());

  // Now clear the in memory data.
  manager_->ClearTransientSigninData();
  EXPECT_TRUE(manager_->last_result_.data.empty());
  EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());

  // Ensure preferences are not modified.
  EXPECT_FALSE(
     profile_->GetPrefs()->GetString(prefs::kGoogleServicesUsername).empty());

  // On reset it should be regenerated.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());

  // Now make sure we have the right user name.
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());
}

TEST_F(SigninManagerTest, SignOutClientLogin) {
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  SimulateValidResponseClientLogin(false);
  manager_->OnClientLoginSuccess(credentials_);

  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());
  manager_->SignOut();
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
  EXPECT_FALSE(profile_->GetPrefs()->GetBoolean(prefs::kIsGooglePlusUser));
  // Should not be persisted anymore
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
}

TEST_F(SigninManagerTest, SignInFailureClientLogin) {
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  // Should not be persisted
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
}

TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) {
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
  EXPECT_FALSE(manager_->possibly_invalid_username_.empty());

  manager_->ProvideSecondFactorAccessCode("access");
  SimulateValidResponseClientLogin(false);

  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, ProvideSecondFactorFailure) {
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error1);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
  EXPECT_FALSE(manager_->possibly_invalid_username_.empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error2(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  manager_->OnClientLoginFailure(error2);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(2U, google_login_failure_.size());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED);
  manager_->OnClientLoginFailure(error3);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(3U, google_login_failure_.size());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
}

TEST_F(SigninManagerTest, SignOutMidConnect) {
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  manager_->SignOut();
  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
}

TEST_F(SigninManagerTest, SignInWithOAuth) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignInWithOAuth("user@gmail.com", "password");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateValidResponseSignInWithOAuth();
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, SignInWithOAuthChallengeCaptcha) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignInWithOAuth("user@gmail.com", "password");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateSignInWithOAuthChallengeCaptcha();

  manager_->ProvideOAuthChallengeResponse(
      GoogleServiceAuthError::CAPTCHA_REQUIRED, "token", "solution");

  SimulateProvideOAuthChallengeResponseValid();
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());

  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, SignInWithOAuthChallengeOtp) {
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  manager_->StartSignInWithOAuth("user@gmail.com", "password");
  EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());

  SimulateSignInWithOAuthChallengeOtp();

  manager_->ProvideOAuthChallengeResponse(
      GoogleServiceAuthError::CAPTCHA_REQUIRED, "token", "solution");

  SimulateProvideOAuthChallengeResponseValid();
  EXPECT_EQ("user@gmail.com", manager_->GetAuthenticatedUsername());

  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

redpajama_set_name: RedPajamaGithub


text:
A button that transforms depending on the distance you tap from the center

## Demo
![alt tag](http://i.giphy.com/QrVru4Ae1GjzW.gif)

## Installation

Manually

Add DepthButton.swift into your project

CocoaPods

To be implemented soon...

## Usage

Two usage methods:

Create instance of DepthButton progromatically

OR

Add UIButton element to storyboard, assign class to DepthButton

 Chageable properties:

rotateOnTouch : enables rotate transformation, true by default

rotationModifier : changes severity of rotation transform, 45 by default

scaleOnTouch : enables scaling of button, true by default

scalePercentage : changes scale percentage when scaleOnTouch is enabled, .95 by default


text:
package sun.awt.image;

import java.awt.image.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.util.Hashtable;

public abstract class InputStreamImageSource implements ImageProducer,
                                                        ImageFetchable
{
    ImageConsumerQueue consumers;

    ImageDecoder decoder;
    ImageDecoder decoders;

    boolean awaitingFetch = false;

    abstract boolean checkSecurity(Object context, boolean quiet);

    int countConsumers(ImageConsumerQueue cq) {
        int i = 0;
        while (cq != null) {
            i++;
            cq = cq.next;
        }
        return i;
    }

    synchronized int countConsumers() {
        ImageDecoder id = decoders;
        int i = countConsumers(consumers);
        while (id != null) {
            i += countConsumers(id.queue);
            id = id.next;
        }
        return i;
    }

    public void addConsumer(ImageConsumer ic) {
        addConsumer(ic, false);
    }

    synchronized void printQueue(ImageConsumerQueue cq, String prefix) {
        while (cq != null) {
            System.out.println(prefix+cq);
            cq = cq.next;
        }
    }

    synchronized void printQueues(String title) {
        System.out.println(title+"[ -----------");
        printQueue(consumers, "  ");
        for (ImageDecoder id = decoders; id != null; id = id.next) {
            System.out.println("    "+id);
            printQueue(id.queue, "      ");
        }
        System.out.println("----------- ]"+title);
    }

    synchronized void addConsumer(ImageConsumer ic, boolean produce) {
        checkSecurity(null, false);
        for (ImageDecoder id = decoders; id != null; id = id.next) {
            if (id.isConsumer(ic)) {
                // This consumer is already being fed.
                return;
            }
        }
        ImageConsumerQueue cq = consumers;
        while (cq != null && cq.consumer != ic) {
            cq = cq.next;
        }
        if (cq == null) {
            cq = new ImageConsumerQueue(this, ic);
            cq.next = consumers;
            consumers = cq;
        } else {
            if (!cq.secure) {
                Object context = null;
                @SuppressWarnings("removal")
                SecurityManager security = System.getSecurityManager();
                if (security != null) {
                    context = security.getSecurityContext();
                }
                if (cq.securityContext == null) {
                    cq.securityContext = context;
                } else if (!cq.securityContext.equals(context)) {
                    // If there are two different security contexts that both
                    // have a handle on the same ImageConsumer, then there has
                    // been a security breach and whether or not they trade
                    // image data is small fish compared to what they could be
                    // trading.  Throw a Security exception anyway...
                    errorConsumer(cq, false);
                    throw new SecurityException("Applets are trading image data!");
                }
            }
            cq.interested = true;
        }
        if (produce && decoder == null) {
            startProduction();
        }
    }

    public synchronized boolean isConsumer(ImageConsumer ic) {
        for (ImageDecoder id = decoders; id != null; id = id.next) {
            if (id.isConsumer(ic)) {
                return true;
            }
        }
        return ImageConsumerQueue.isConsumer(consumers, ic);
    }

    private void errorAllConsumers(ImageConsumerQueue cq, boolean needReload) {
        while (cq != null) {
            if (cq.interested) {
                errorConsumer(cq, needReload);
            }
            cq = cq.next;
        }
    }

    private void errorConsumer(ImageConsumerQueue cq, boolean needReload) {
        cq.consumer.imageComplete(ImageConsumer.IMAGEERROR);
        if ( needReload && cq.consumer instanceof ImageRepresentation) {
            ((ImageRepresentation)cq.consumer).image.flush();
        }
        removeConsumer(cq.consumer);
    }

    public synchronized void removeConsumer(ImageConsumer ic) {
        for (ImageDecoder id = decoders; id != null; id = id.next) {
            id.removeConsumer(ic);
        }
        consumers = ImageConsumerQueue.removeConsumer(consumers, ic, false);
    }

    public void startProduction(ImageConsumer ic) {
        addConsumer(ic, true);
    }

    private synchronized void startProduction() {
        if (!awaitingFetch) {
            if (ImageFetcher.add(this)) {
                awaitingFetch = true;
            } else {
                ImageConsumerQueue cq = consumers;
                consumers = null;
                errorAllConsumers(cq, false);
            }
        }
    }

    private synchronized void stopProduction() {
        if (awaitingFetch) {
            ImageFetcher.remove(this);
            awaitingFetch = false;
        }
    }

    public void requestTopDownLeftRightResend(ImageConsumer ic) {
    }

    protected abstract ImageDecoder getDecoder();

    protected ImageDecoder decoderForType(InputStream is,
                                          String content_type) {
        // Don't believe the content type - file extensions can
        // lie.
        /*
        if (content_type.equals("image/gif")) {
            return new GifImageDecoder(this, is);
        } else if (content_type.equals("image/jpeg")) {
            return new JPEGImageDecoder(this, is);
        } else if (content_type.equals("image/x-xbitmap")) {
            return new XbmImageDecoder(this, is);
        }
        else if (content_type == URL.content_jpeg) {
            return new JpegImageDecoder(this, is);
        } else if (content_type == URL.content_xbitmap) {
            return new XbmImageDecoder(this, is);
        } else if (content_type == URL.content_xpixmap) {
            return new Xpm2ImageDecoder(this, is);
        }
        */

        return null;
    }

    protected ImageDecoder getDecoder(InputStream is) {
        if (!is.markSupported())
            is = new BufferedInputStream(is);
        try {
          /* changed to support png
             is.mark(6);
             */
          is.mark(8);
            int c1 = is.read();
            int c2 = is.read();
            int c3 = is.read();
            int c4 = is.read();
            int c5 = is.read();
            int c6 = is.read();
            // added to support png
            int c7 = is.read();
            int c8 = is.read();
            // end of adding
            is.reset();
            is.mark(-1);

            if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8') {
                return new GifImageDecoder(this, is);
            } else if (c1 == '\377' && c2 == '\330' && c3 == '\377') {
                return new JPEGImageDecoder(this, is);
            } else if (c1 == '#' && c2 == 'd' && c3 == 'e' && c4 == 'f') {
                return new XbmImageDecoder(this, is);
//          } else if (c1 == '!' && c2 == ' ' && c3 == 'X' && c4 == 'P' &&
//                     c5 == 'M' && c6 == '2') {
//              return new Xpm2ImageDecoder(this, is);
                // added to support png
            } else if (c1 == 137 && c2 == 80 && c3 == 78 &&
                c4 == 71 && c5 == 13 && c6 == 10 &&
                c7 == 26 && c8 == 10) {
                return new PNGImageDecoder(this, is);
            }
            // end of adding
        } catch (IOException e) {
        }

        return null;
    }

    public void doFetch() {
        synchronized (this) {
            if (consumers == null) {
                awaitingFetch = false;
                return;
            }
        }
        ImageDecoder imgd = getDecoder();
        if (imgd == null) {
            badDecoder();
        } else {
            setDecoder(imgd);
            try {
                imgd.produceImage();
            } catch (IOException e) {
                e.printStackTrace();
                // the finally clause will send an error.
            } catch (ImageFormatException e) {
                e.printStackTrace();
                // the finally clause will send an error.
            } finally {
                removeDecoder(imgd);
                if ( Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) {
                    errorAllConsumers(imgd.queue, true);
                } else {
                    errorAllConsumers(imgd.queue, false);
            }
        }
    }
    }

    private void badDecoder() {
        ImageConsumerQueue cq;
        synchronized (this) {
            cq = consumers;
            consumers = null;
            awaitingFetch = false;
        }
        errorAllConsumers(cq, false);
    }

    private void setDecoder(ImageDecoder mydecoder) {
        ImageConsumerQueue cq;
        synchronized (this) {
            mydecoder.next = decoders;
            decoders = mydecoder;
            decoder = mydecoder;
            cq = consumers;
            mydecoder.queue = cq;
            consumers = null;
            awaitingFetch = false;
        }
        while (cq != null) {
            if (cq.interested) {
                // Now that there is a decoder, security may have changed
                // so reverify it here, just in case.
                if (!checkSecurity(cq.securityContext, true)) {
                    errorConsumer(cq, false);
                }
            }
            cq = cq.next;
        }
    }

    private synchronized void removeDecoder(ImageDecoder mydecoder) {
        doneDecoding(mydecoder);
        ImageDecoder idprev = null;
        for (ImageDecoder id = decoders; id != null; id = id.next) {
            if (id == mydecoder) {
                if (idprev == null) {
                    decoders = id.next;
                } else {
                    idprev.next = id.next;
                }
                break;
            }
            idprev = id;
        }
    }

    synchronized void doneDecoding(ImageDecoder mydecoder) {
        if (decoder == mydecoder) {
            decoder = null;
            if (consumers != null) {
                startProduction();
            }
        }
    }

    void latchConsumers(ImageDecoder id) {
        doneDecoding(id);
    }

    synchronized void flush() {
        decoder = null;
    }
}


text:
var Blueprint   = require('ember-cli/lib/models/blueprint');
var SilentError = require('ember-cli/lib/errors/silent');
var chalk       = require('chalk');
var fs          = require('fs-extra');
var inflection  = require('inflection');
var path        = require('path');
var EOL         = require('os').EOL;
var _           = require('lodash');

var KIND_MAP = {
  auth: 'AuthRoute',
  base: 'BaseRoute',
  ember: 'Ember.Route'
},
KIND_PATH = {
  auth: "import AuthRoute from 'app/routes/auth';",
  base: "import BaseRoute from 'app/routes/base';",
  ember: 'ember'
};

module.exports = {
  beforeInstall: function(options) {
    var type = options.type;

    if (type && !/^(resource|route)$/.test(type)) {
      throw new SilentError('Unknown route type "' + type + '". Should be "route" or "resource".');
    }
  },

  afterInstall: function(options) {
    var entity  = options.entity;
    var isIndex = /index$/.test(entity.name);

    if (!isIndex && !options.dryRun) {
      addRouteToRouter(entity.name, {
        type: options.type
      });

      addImportToTranslations(entity.name, {
        type: options.type
      });
    }
  },

  beforeUninstall: function(options) {
    var type = options.type,
    kind = options.kind;

    if (type && !/^(resource|route)$/.test(type)) {
      throw new SilentError('Unknown route type "' + type + '". Should be "route" or "resource".');
    }

    if (kind && !TYPE_MAP[kind]) {
      throw new SilentError('Unknown route kind "' + kind + '". Should be "base", "auth", or "ember".');
    }

  },

  afterUninstall: function(options) {
    var entity  = options.entity;
    var isIndex = /index$/.test(entity.name);

    if (!isIndex && !options.dryRun) {
      removeRouteFromRouter(entity.name, {
        type: options.type
      });

      removeImportFromTranslations(entity.name, {
        type: options.type
      });
    }
  },

  locals: function(options) {
    var kindClass,
    kindPath;

    if (options.kind) {
      kindClass = KIND_MAP[options.kind];

      if (options.kind !== 'ember'){

        kindPath = KIND_PATH[options.kind];

      }

    } else {
      this.ui.writeLine(chalk.yellow('Warning: no route "kind" was specified, defaulting to authenticated route.'));
      kindClass = KIND_MAP.auth;
      kindPath = KIND_PATH.auth;
    }

    return {
      kindClass: kindClass,
      kindPath: kindPath
    };
  }
};

function removeRouteFromRouter(name, options) {
  var type       = options.type || 'route';
  var routerPath = path.join(process.cwd(), 'app', 'router.js');
  var oldContent = fs.readFileSync(routerPath, 'utf-8');
  var existence  = new RegExp("(?:route|resource)\\s*\\(\\s*(['\"])" + name + "\\1");
  var newContent;
  var plural;

  if (!existence.test(oldContent)) {
    return;
  }

  if (name === 'basic') { return; }

  switch (type) {
    case 'route':
      var re = new RegExp('\\s*this.route\\((["\'])'+ name +'(["\'])\\);');
      newContent = oldContent.replace(re, '');
      break;
    case 'resource':
      plural = inflection.pluralize(name);

      if (plural === name) {
        var re = new RegExp('\\s*this.resource\\((["\'])'+ name +'(["\'])\\);');
        newContent = oldContent.replace(re, '');
      } else {
        var re = new RegExp('\\s*this.resource\\((["\'])'+ name +'(["\']),.*\\);');
        newContent = oldContent.replace(re, '');
      }
      break;
  }

  fs.writeFileSync(routerPath, newContent);
}

function addRouteToRouter(name, options) {
  var type       = options.type || 'route';
  var routerPath = path.join(process.cwd(), 'app', 'router.js');
  var oldContent = fs.readFileSync(routerPath, 'utf-8');
  var existence  = new RegExp("(?:route|resource)\\s*\\(\\s*(['\"])" + name + "\\1");
  var newContent;
  var plural;

  if (existence.test(oldContent)) {
    return;
  }

  if (name === 'basic') { return; }

  switch (type) {
    case 'route':
      newContent = oldContent.replace(
        /(map\(function\(\) {[\s\S]+)}\)/,
        "$1  this.route('" + name + "');" + EOL + "})"
      );
      break;
    case 'resource':
      plural = inflection.pluralize(name);

      if (plural === name) {
        newContent = oldContent.replace(
          /(map\(function\(\) {[\s\S]+)}\)/,
          "$1  this.resource('" + name + "');" + EOL + "})"
        );
      } else {
        newContent = oldContent.replace(
          /(map\(function\(\) {[\s\S]+)}\)/,
          "$1  this.resource('" + name + "', { path: '" + plural + "/:" + name + "_id' });" + EOL + "})"
        );
      }
      break;
  }

  fs.writeFileSync(routerPath, newContent);
}

function addImportToTranslations(name, options) {
  var filePath = path.join(process.cwd(), 'app', 'translations', 'main.js'),
  oldContent = fs.readFileSync(filePath, 'utf-8'),
  existence  = new RegExp("import .*" + name, 'gi'),
  newContent,
 // importName = name.replace(/(.*)\/(.*)$/, '$2'); // gets last path name
  importName = name.replace(/[/]/gi, '_');

  var langs = ['en', 'es'];

  if (existence.test(oldContent)) {
    return;
  }

  newContent = oldContent.replace(
    /(\/\/ @imports[\s\S]+)(\/\/ @endImports)/,
    "$1import en_" + importName + " from 'app/translations/en/routes/" + name + "';" + "\n" +
    "import es_" + importName + " from 'app/translations/es/routes/" + name + "';" + EOL + "$2"
  );

  _.each(langs, function(l, i) {
    newContent = newContent.replace(
      new RegExp("\(\.\*extend\.\*\)\+\(\\)\)\(\.\*\\/\\/ @extend \("+l+"\)\)", 'gi'),
      "$1, $4_"+importName+")$3"
    );
  });

  fs.writeFileSync(filePath, newContent);
}

function removeImportFromTranslations(name, options) {
  var filePath = path.join(process.cwd(), 'app', 'translations', 'main.js'),
  oldContent = fs.readFileSync(filePath, 'utf-8'),
  existence  = new RegExp("import.*" + name + '.*', 'gi'),
  newContent,
  importName = name.replace(/[/]/gi, '_');

  if (!existence.test(oldContent)) {
    return;
  }

  var re = new RegExp("import.*" + name + '.*\\n', 'gi'),
  newContent = oldContent.replace(re, '');

  re = new RegExp('\,\*\\s\*\\\w+_\?' + importName, 'gi'),
  newContent = newContent.replace(re, '');

  fs.writeFileSync(filePath, newContent);
}


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Handling of tcp listening sockets
 *
 * PHP version 5
 *
 * @category  Sockets
 * @package   SocketHandler
 * @author    Björn Enochsson <bonan@g33k.se>
 * @copyright 2003-2012 Björn Enochsson <bonan@g33k.se>
 * @license   http://en.wikipedia.org/wiki/BSD_licenses#2-clause_license_.28.22Simplified_BSD_License.22_or_.22FreeBSD_License.22.29 2 clause BSD license
 * @link      http://neotor.se/
 */

/**
 * Server for TCP that listens to a specified port and makes a callback when a new client connects
 *
 * PHP version 5
 *
 * @category  Sockets
 * @package   SocketHandler
 * @author    Björn Enochsson <bonan@g33k.se>
 * @copyright 2003-2012 Björn Enochsson <bonan@g33k.se>
 * @license   http://en.wikipedia.org/wiki/BSD_licenses#2-clause_license_.28.22Simplified_BSD_License.22_or_.22FreeBSD_License.22.29 2 clause BSD license
 * @link      http://neotor.se/
 */

class TCPServer extends SocketHandler
{
    /**
     * The constructor, creates the socket and starts listening
     *
     * @param integer $port Port to bind to
     * @param string $bind IP address to bind to
     * @return
     */
    public function __construct($port, $bind='0.0.0.0')
    {
        $socket = stream_socket_server(
            "tcp://$bind:$port",
            $this->errno,
            $this->errstr
        );

        if (false === $socket) {
            throw new TCPServerException($this->errno);
        }

        $this->meta['bind'] = $bind;
        $this->meta['port'] = $port;

        parent::__construct($socket);

    }

    /**
     * Accepts a new connection, creates a handler for it and passes it to the callback
     *
     * @return Boolean true on success
     */
    public function readData()
    {
        $newSock = stream_socket_accept($this->socket);
        $handler = 'SocketHandler';
        if (isset($this->meta['handler']) && class_exists($this->meta['handler'])) {
            $handler = $this->meta['handler'];
        }
        $newHandler = new $handler($newSock);
        $this->callback($newHandler);
        return true;
    }

}

/**
 * Exception thrown when TCPServer encouters an error
 *
 * PHP version 5
 *
 * @category  Sockets
 * @package   SocketHandler
 * @author    Björn Enochsson <bonan@g33k.se>
 * @copyright 2003-2012 Björn Enochsson <bonan@g33k.se>
 * @license   http://en.wikipedia.org/wiki/BSD_licenses#2-clause_license_.28.22Simplified_BSD_License.22_or_.22FreeBSD_License.22.29 2 clause BSD license
 * @link      http://neotor.se/
 */
class TCPServerException extends Exception
{
    /**
     * The constructor
     *
     * @param mixed $msg Error message
     * @return void
     */
    public function __construct($msg)
    {
        parent::__construct($msg);
    }
}


text:
<?php

namespace Enqueue\Consumption;

use Enqueue\Consumption\Context\ProcessorException;

interface ProcessorExceptionExtensionInterface
{
    /**
     * Execute if a processor throws an exception.
     * The result could be set, if result is not set the exception is thrown again.
     */
    public function onProcessorException(ProcessorException $context): void;
}


text:
/**
 * @file simulation.hpp
 * @author Albert Uchytil, Tomas Coufal
 * @brief Class which takes care of the simulation
 */

#include "simulation.hpp"

Simulation::Simulation(Model *m): model(m) {
    calendar = new Calendar();
}
Simulation::~Simulation() {
    delete calendar;
    if (model != NULL)
        delete model;
}

/**
 * Run the simulation
 *
 * The core function of model simulation. Does the setup (inital planning of
 * events, generators planning). Then iterates through the calendar and one by
 * one process the events. After each event is proceed check if the rest of
 * planned events are still feasible. Then it plans the newly available events.
 * Iteration stops if the endtime is reached or the calendar is empty.
 */
void Simulation::Start() {
    debug("simulation", "starting");
    // randomize seed
    RandomizeSeed();

    // setup
    this->simtime = 0;

    // initial planning
    this->PlanGenerators();
    this->PlanEvents();

    // simulate
    while (!calendar->Empty()) {
        // get event from calendar and simulate the transition
        Event * e = calendar->GetEvent();
        this->simtime = e->GetTime();
        // print status
        cout << "\rCurrent simulation time = " << fixed << setprecision(5) <<this->simtime;
        //end simulation if endtime reached
        if (this->simtime >= this->endtime) {
            DeleteEvent(e);
            debug("simulation", "endtime reached");
            break;
        }
        // take action and make the transition
        this->PerformEvent(e);
        // check if events are feasible
        this->CheckEvents();
        // plan newly available events
        this->PlanEvents();
    }
    cout << "\n";
    debug("simulation", "done");
}

/**
 * Setting endtime
 *
 * Before the simulation run the endtime has to be set.
 * @param endtime double number that defines the end time of simulation
 */
void Simulation::SetEndtime(double t) {
    this->endtime = t;
}

/**
 * Plan events
 *
 * Looks for feasible transitions and transition groups (probability transitions).
 * Takes each transition and checks it's feasibility. Is so, creates event and
 * adds it to the calendar. The same it does for the probability transition. It
 * rolls for probability, picks right transition.
 */
void Simulation::PlanEvents() {
    debug("simulation", "planning events");
    // normal transitions (priority, timed)
    std::vector<Transition*>::iterator trans_it;
    std::vector<Transition*> trans = this->model->GetTransitions();
    Event* event;

    // get all transitions
    for(trans_it = trans.begin(); trans_it != trans.end(); trans_it++) {
        // if transition is feasible, plan it
        if ((*trans_it)->IsFeasible() && (*trans_it)->IsFeasibleNow()) {
            event = this->CreateEvent(*trans_it);
            this->calendar->AppendEvent(event);
        }
    }

    // probability transitions, grouped -> pick one based on the roll
    std::vector<ProbTrans*>::iterator probtrans_it;
    std::vector<ProbTrans*> probtrans = this->model->GetProbGroups();
    Transition * t;

    // get all transitions
    for(probtrans_it = probtrans.begin(); probtrans_it != probtrans.end(); probtrans_it++) {
        // roll the dice and pick transition within group
        t = (*probtrans_it)->PickTransition(RollPercentage());
        // if transition is feasible, plan it
        if (t->IsFeasible()) {
            event = this->CreateEvent(t);
            this->calendar->AppendEvent(event);
        }
    }
    debug("simulation", "all events planned, done");
}

/**
 * Planning of generators
 *
 * Generations are stored in separate vector in model. That's because generators
 * should be planned before the simulation starts for whole simulation run time.
 * For each generator it's creating events in the spacing defined by the
 * generator's attributes (type: whether constant time or exponential
 * distribution, value: time/mean) until the end time is reached. The setup
 * presumes the first token is generated after the first transition time not at
 * the start of simulation. It also plans one event more after the end time (this
 * is for the purposes of checking if endtime is reached during the simulation run)
 */
void Simulation::PlanGenerators() {
    debug("simulation", "planning generators");
    std::vector<Transition*>::iterator gen_it;
    std::vector<Transition*> gens = this->model->GetGenerators();
    Event* event;
    double time = this->simtime;
    std::vector<Token*> * tokens;
    double duration;

    // get each generator
    for(gen_it = gens.begin(); gen_it != gens.end(); gen_it++) {
        // from the beginning of the universe until apocalypse
        time = this->simtime;
        while (time < this->endtime) {
            // set time of event
            if ((*gen_it)->Type == TransType::TimeConstant)
                duration = (*gen_it)->Value;
            else
                duration = GenerateDelayExp((*gen_it)->Value);
            time = time + duration;
            // create and plan event
            tokens =  new std::vector<Token*>;
            event = new Event(time, duration, (*gen_it), tokens);
            this->calendar->AppendEvent(event);
        }
    }
    debug("simulation", "all generators planned, done");
}

/**
 * Event creation
 *
 * Needs a pointer to transition that should be proceed. Each transition has
 * input connections and these point to the places with tokens. These tokens are
 * added to newly created vector and set as planned. Time for the event is set to
 * current simulation time plus transition time (fixed or generated)
 * @param trans Transition pointer
 */
Event * Simulation::CreateEvent(Transition * trans) {
    debug("simulator", "creating new event");
    //reserve tokens
    std::vector<Connection*>::iterator conn_it;
    std::vector<Token*> * tokens = new std::vector<Token*>;
    Token * token;
    // for each input connection grab all tokens needed
    for (conn_it = trans->Inputs.begin(); conn_it != trans->Inputs.end(); conn_it++) {
        for (int i = 0; i < (*conn_it)->Capacity; i++) {
            token = (*conn_it)->Pl->GetToken();
            tokens->push_back(token);
            token->SetPlanned();
        }
    }

    //set time
    //default time is for instant transition TransType::Priority
    double time = this->simtime;
    double duration = 0;
    if (trans->Type == TransType::TimeConstant) {
        duration = trans->Value;
    }
    else if (trans->Type == TransType::TimeGenerated) {
        duration = GenerateDelayExp(trans->Value);
    }
    time = time + duration;
    Event * event = new Event(time, duration, trans, tokens);
    debug("simulator", "new event created");
    return event;
}

/**
 * Delete token
 *
 * The function pop's the token from model, place and destroys it.
 * @param t Tkoen that should be removed
 */
void Simulation::PopToken(Token * t) {
    debug("simulator", "removing token");
    this->model->RemoveToken(t);
    Place * p = t->Location;
    p->RemoveToken(t);
    delete t;
    debug("simulator", "removed token");
}

/**
 * Delete event
 *
 * Completely destroy event and it's properties (tokens)
 * @param event that should be destroyed
 */
void Simulation::DeleteEvent(Event * event) {
    std::vector<Token *>::iterator t;
    for (t = event->Tokens->begin(); t != event->Tokens->end(); t++) {
        PopToken(*t);
    }
    event->Tokens->clear();
    delete event;
}

/**
 * Perform event
 *
 * Processing the event. At first it checks if the transition is feasible at the
 * time it should be proceed. It increments the counter of processed events,
 * destroys all tokens on input places and adds new one to the output places
 * (the amount is based on the connection capacity)
 * @param event The event that should be proceed
 */
void Simulation::PerformEvent(Event * event) {
    std::ostringstream s;
    s << "[" << this->simtime << "] started processing event on transition: " << event->GetTransitionPtr()->Id;
    debug("simulator", s.str());
    //check again if the event can be performed
    //input tokens are already reservated, but the output places could not have enough capacity
    if (! event->GetTransitionPtr()->IsFeasibleNow()) {
        DeleteEvent(event);
        return;
    }
    // increment the proceed events counter
    this->calendar->IncProceed();
    event->GetTransitionPtr()->Apply(event->GetDuration());
    // remove tokens from model and places
    std::vector<Token*>::iterator token_it;
    for (token_it = event->Tokens->begin(); token_it != event->Tokens->end(); token_it++) {
        PopToken(*token_it);
    }
    // create new tokens and add them to outputs of the transition
    std::vector<Connection*>::iterator conn_it;
    Token * token;
    for (conn_it = event->GetTransitionPtr()->Outputs.begin(); conn_it != event->GetTransitionPtr()->Outputs.end(); conn_it++) {
        for (int i = 0; i < (*conn_it)->Capacity; i++) {
            token = model->NewToken();
            (*conn_it)->Pl->AddToken(token);
        }
    }
    // destroy event
    delete event;
    debug("simulator", "event proceed");
}

/**
 * Discard event
 *
 * Remove the event from the calendar but instead of destroying the tokens it just
 * clears the "planned" flag no tokens, increments the counter of removed tokens
 * and deletes the event from memory.
 * @param event Event that should be discarded
 */
void Simulation::DiscardEvent(Event * event) {
    debug("simulator", "discarding event");
    std::vector<Token*>::iterator token_it;
    for (token_it = event->Tokens->begin(); token_it != event->Tokens->end(); token_it++)
        (*token_it)->ClearPlanned();
    this->calendar->RemoveEvent(event);
    delete event;
    this->calendar->IncRemoved();
    debug("simulator", "event discarded");
}

/**
 * Check events
 *
 * Performs a checkup if all events in calendar are still doable. If not it
 * discards them.
 */
void Simulation::CheckEvents() {
    debug("simulator", "checking planned events if doable");
    std::multiset<Event*, compare>::iterator event_it;
    for (event_it = this->calendar->List.begin(); event_it != this->calendar->List.end(); event_it++) {
        // dont check for generators planned long time ahead (generators have 0 inputs)
        if ((*event_it)->Tokens->size() != 0 && !(*event_it)->GetTransitionPtr()->IsFeasibleNow()) {
            this->DiscardEvent(*event_it);
        }
    }
    debug("simulator", "check-up done");
}

/**
 * Print statistics
 *
 * For simulation these statistics are printed: simtime and endtime
 */
void Simulation::PrintStats() {
    Stats::PrintHeader("SIMULATION", "value");
    Stats::PrintRow("Model name", this->model->GetName());
    Stats::PrintRow("Simulation time", this->simtime);
    Stats::PrintRow("Simulation pre-set endtime", this->endtime);

    this->calendar->PrintStats();
    if (model != NULL)
        this->model->PrintStats();
}


text:
package org.olat.core.gui.components.form.flexible.elements;

import org.olat.core.gui.components.form.flexible.FormBaseComponentIdProvider;
import org.olat.core.gui.components.form.flexible.FormItem;

/**
 * @author patrickb
 */
public interface SelectionElement extends FormItem, FormBaseComponentIdProvider{

	/**
	 * @param which
	 * @return String
	 */
	public String getKey(int which);

	/**
	 * @param which
	 * @return String
	 */
	public String getValue(int which);

	/**
	 * @return integer
	 */
	public int getSize();

	/**
	 * @param which
	 * @return boolean
	 */
	public boolean isSelected(int which);

	/**
	 * @param key
	 * @param select
	 */
	public void select(String key, boolean select);

	/**
	 * whether multiple selection is allowed
	 * @return
	 */
	public boolean isMultiselect();

}


text:
<!DOCTYPE html>

    <title>DTTableViewDragDelegate Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          DTTableViewManager Docs

         (82% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

            Install in Dash

      DTTableViewManager Reference

      DTTableViewDragDelegate Class Reference

            Classes

                DTTableViewDataSource

                DTTableViewDelegate

                DTTableViewDelegateWrapper

                DTTableViewDragDelegate

                DTTableViewDropDelegate

                DTTableViewDropPlaceholderContext

                DTTableViewManager

                DTTableViewManagerAnomalyHandler

                TableViewUpdater

            Enumerations

                DTTableViewManagerAnomaly

                SupplementarySectionStyle

            Extensions

                ViewModelMapping

            Protocols

                DTTableViewManageable

            Structures

                TableViewConfiguration

DTTableViewDragDelegate

open class DTTableViewDragDelegate : DTTableViewDelegateWrapper, UITableViewDragDelegate

Object, that implements UITableViewDragDelegate methods for DTTableViewManager.

                    tableView(_:itemsForBeginning:at:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession,
                      at indexPath: IndexPath) -> [UIDragItem]

                    tableView(_:itemsForAddingTo:at:point:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, itemsForAddingTo session: UIDragSession,
                      at indexPath: IndexPath,
                      point: CGPoint) -> [UIDragItem]

                    tableView(_:dragPreviewParametersForRowAt:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, dragPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters?

                    tableView(_:dragSessionWillBegin:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession)

                    tableView(_:dragSessionDidEnd:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession)

                    tableView(_:dragSessionAllowsMoveOperation:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, dragSessionAllowsMoveOperation session: UIDragSession) -> Bool

                    tableView(_:dragSessionIsRestrictedToDraggingApplication:)

Implementation for UITableViewDragDelegate protocol

Declaration

Swift

open func tableView(_ tableView: UITableView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession) -> Bool

© 2020 Denys Telezhkin. All rights reserved. (Last updated: 2020-10-27)

Generated by jazzy ♪♫ v0.13.1, a Realm project.