text:
#import <TargetConditionals.h>
#if TARGET_OS_IOS

#import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthSettings.h"
#import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRMultiFactorResolver.h"
#import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
#import "FirebaseCore/Extension/FirebaseCoreInternal.h"

#import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
#import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
#import "FirebaseAuth/Sources/Backend/FIRAuthBackend+MultiFactor.h"
#import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigRequest.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigResponse.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeRequest.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeResponse.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientRequest.h"
#import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientResponse.h"
#import "FirebaseAuth/Sources/Backend/RPC/MultiFactor/Enroll/FIRStartMFAEnrollmentRequest.h"
#import "FirebaseAuth/Sources/Backend/RPC/MultiFactor/Enroll/FIRStartMFAEnrollmentResponse.h"
#import "FirebaseAuth/Sources/Backend/RPC/Proto/Phone/FIRAuthProtoStartMFAPhoneRequestInfo.h"
#import "FirebaseAuth/Sources/MultiFactor/FIRMultiFactorSession+Internal.h"
#import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSToken.h"
#import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSTokenManager.h"
#import "FirebaseAuth/Sources/SystemService/FIRAuthAppCredential.h"
#import "FirebaseAuth/Sources/SystemService/FIRAuthAppCredentialManager.h"
#import "FirebaseAuth/Sources/SystemService/FIRAuthNotificationManager.h"
#import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
#import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
#import "FirebaseAuth/Sources/Utilities/FIRAuthWebUtils.h"

#if TARGET_OS_IOS
#import "FirebaseAuth/Sources/AuthProvider/Phone/FIRPhoneAuthCredential_Internal.h"
#import "FirebaseAuth/Sources/MultiFactor/Phone/FIRPhoneMultiFactorInfo+Internal.h"
#endif

NS_ASSUME_NONNULL_BEGIN

/** @typedef FIRReCAPTCHAURLCallBack
    @brief The callback invoked at the end of the flow to fetch a reCAPTCHA URL.
    @param reCAPTCHAURL The reCAPTCHA URL.
    @param error The error that occurred while fetching the reCAPTCHAURL, if any.
 */
typedef void (^FIRReCAPTCHAURLCallBack)(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error);

/** @typedef FIRVerifyClientCallback
    @brief The callback invoked at the end of a client verification flow.
    @param appCredential credential that proves the identity of the app during a phone
        authentication flow.
    @param error The error that occurred while verifying the app, if any.
 */
typedef void (^FIRVerifyClientCallback)(FIRAuthAppCredential *_Nullable appCredential,
                                        NSString *_Nullable reCAPTCHAToken,
                                        NSError *_Nullable error);

/** @typedef FIRFetchAuthDomainCallback
    @brief The callback invoked at the end of the flow to fetch the Auth domain.
    @param authDomain The Auth domain.
    @param error The error that occurred while fetching the auth domain, if any.
 */
typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain,
                                           NSError *_Nullable error);

/** @var kauthTypeVerifyApp
    @brief The auth type to be specified in the app verification request.
 */
static NSString *const kAuthTypeVerifyApp = @"verifyApp";

/** @var kCustomUrlSchemePrefix
    @brief The prefix to append to the Firebase app ID custom callback scheme..
 */
static NSString *const kCustomUrlSchemePrefix = @"app-";

/** @var kReCAPTCHAURLStringFormat
    @brief The format of the URL used to open the reCAPTCHA page during app verification.
 */
NSString *const kReCAPTCHAURLStringFormat = @"https://%@/__/auth/handler?";

extern NSString *const FIRPhoneMultiFactorID;

@implementation FIRPhoneAuthProvider {
  /** @var _auth
      @brief The auth instance used for verifying the phone number.
   */
  FIRAuth *_auth;

  /** @var _callbackScheme
      @brief The callback URL scheme used for reCAPTCHA fallback.
   */
  NSString *_callbackScheme;

  /** @var _usingClientIDScheme
      @brief True if the reverse client ID is registered as a custom URL scheme, and false
     otherwise.
   */
  BOOL _usingClientIDScheme;
}

/** @fn initWithAuth:
    @brief returns an instance of @c FIRPhoneAuthProvider associated with the provided auth
          instance.
    @return An Instance of @c FIRPhoneAuthProvider.
   */
- (nullable instancetype)initWithAuth:(FIRAuth *)auth {
  self = [super init];
  if (self) {
    _auth = auth;
    if (_auth.app.options.clientID) {
      NSString *reverseClientIDScheme =
          [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
               reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
      if ([FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:reverseClientIDScheme]) {
        _callbackScheme = reverseClientIDScheme;
        _usingClientIDScheme = YES;
      }
    }
    if (!_usingClientIDScheme) {
      _callbackScheme = [kCustomUrlSchemePrefix
          stringByAppendingString:[_auth.app.options.googleAppID
                                      stringByReplacingOccurrencesOfString:@":"
                                                                withString:@"-"]];
    }
  }
  return self;
}

- (void)verifyPhoneNumber:(NSString *)phoneNumber
               UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
               completion:(nullable FIRVerificationResultCallback)completion {
  if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:_callbackScheme]) {
    [NSException raise:NSInternalInconsistencyException
                format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
                       _callbackScheme];
  }
  dispatch_async(FIRAuthGlobalWorkQueue(), ^{
    FIRVerificationResultCallback callBackOnMainThread =
        ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
          if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
              completion(verificationID, error);
            });
          }
        };
    [self
        internalVerifyPhoneNumber:phoneNumber
                       UIDelegate:UIDelegate
                       completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) {
                         if (!error) {
                           callBackOnMainThread(verificationID, nil);
                           return;
                         } else {
                           callBackOnMainThread(nil, error);
                           return;
                         }
                       }];
  });
}

- (void)verifyPhoneNumberWithMultiFactorInfo:(FIRPhoneMultiFactorInfo *)phoneMultiFactorInfo
                                  UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                          multiFactorSession:(nullable FIRMultiFactorSession *)session
                                  completion:(nullable FIRVerificationResultCallback)completion {
  session.multiFactorInfo = phoneMultiFactorInfo;
  [self verifyPhoneNumber:phoneMultiFactorInfo.phoneNumber
               UIDelegate:UIDelegate
       multiFactorSession:session
               completion:completion];
}

- (void)verifyPhoneNumber:(NSString *)phoneNumber
               UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
       multiFactorSession:(nullable FIRMultiFactorSession *)session
               completion:(nullable FIRVerificationResultCallback)completion {
  if (!session) {
    [self verifyPhoneNumber:phoneNumber UIDelegate:UIDelegate completion:completion];
    return;
  }

  if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:_callbackScheme]) {
    [NSException raise:NSInternalInconsistencyException
                format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
                       _callbackScheme];
  }
  dispatch_async(FIRAuthGlobalWorkQueue(), ^{
    FIRVerificationResultCallback callBackOnMainThread =
        ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
          if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
              completion(verificationID, error);
            });
          }
        };
    [self
        internalVerifyPhoneNumber:phoneNumber
                       UIDelegate:UIDelegate
               multiFactorSession:session
                       completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) {
                         if (!error) {
                           callBackOnMainThread(verificationID, nil);
                           return;
                         } else {
                           callBackOnMainThread(nil, error);
                           return;
                         }
                       }];
  });
}

- (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID
                                        verificationCode:(NSString *)verificationCode {
  return [[FIRPhoneAuthCredential alloc] initWithProviderID:FIRPhoneAuthProviderID
                                             verificationID:verificationID
                                           verificationCode:verificationCode];
}

+ (instancetype)provider {
  return [[self alloc] initWithAuth:[FIRAuth auth]];
}

+ (instancetype)providerWithAuth:(FIRAuth *)auth {
  return [[self alloc] initWithAuth:auth];
}

#pragma mark - Internal Methods

/** @fn reCAPTCHATokenForURL:error:
    @brief Parses the reCAPTCHA URL and returns the reCAPTCHA token.
    @param URL The url to be parsed for a reCAPTCHA token.
    @param error The error that occurred if any.
    @return The reCAPTCHA token if successful.
 */
- (nullable NSString *)reCAPTCHATokenForURL:(NSURL *)URL error:(NSError **_Nonnull)error {
  NSURLComponents *actualURLComponents = [NSURLComponents componentsWithURL:URL
                                                    resolvingAgainstBaseURL:NO];
  NSArray<NSURLQueryItem *> *queryItems = [actualURLComponents queryItems];
  NSString *deepLinkURL = [FIRAuthWebUtils queryItemValue:@"deep_link_id" from:queryItems];
  NSData *errorData;
  if (deepLinkURL) {
    actualURLComponents = [NSURLComponents componentsWithString:deepLinkURL];
    queryItems = [actualURLComponents queryItems];
    NSString *recaptchaToken = [FIRAuthWebUtils queryItemValue:@"recaptchaToken" from:queryItems];
    if (recaptchaToken) {
      return recaptchaToken;
    }
    NSString *firebaseError = [FIRAuthWebUtils queryItemValue:@"firebaseError" from:queryItems];
    errorData = [firebaseError dataUsingEncoding:NSUTF8StringEncoding];
  } else {
    errorData = nil;
  }
  if (error != NULL && errorData != nil) {
    NSError *jsonError;
    NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
                                                              options:0
                                                                error:&jsonError];
    if (jsonError) {
      *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
      return nil;
    }
    *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
                                                 message:errorDict[@"message"]];
    if (!*error) {
      NSString *reason;
      if (errorDict[@"code"] && errorDict[@"message"]) {
        reason =
            [NSString stringWithFormat:@"[%@] - %@", errorDict[@"code"], errorDict[@"message"]];
      } else {
        reason = [NSString stringWithFormat:@"An unknown error occurred with the following "
                                             "response: %@",
                                            deepLinkURL];
      }
      *error = [FIRAuthErrorUtils appVerificationUserInteractionFailureWithReason:reason];
    }
  }
  return nil;
}

/** @fn internalVerifyPhoneNumber:completion:
    @brief Starts the phone number authentication flow by sending a verifcation code to the
        specified phone number.
    @param phoneNumber The phone number to be verified.
    @param completion The callback to be invoked when the verification flow is finished.
 */

- (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
                       UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                       completion:(nullable FIRVerificationResultCallback)completion {
  if (!phoneNumber.length) {
    completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
    return;
  }
  [_auth.notificationManager
      checkNotificationForwardingWithCallback:^(BOOL isNotificationBeingForwarded) {
        if (!isNotificationBeingForwarded) {
          completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
          return;
        }
        FIRVerificationResultCallback callback =
            ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
              if (completion) {
                completion(verificationID, error);
              }
            };
        [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
                                   retryOnInvalidAppCredential:YES
                                                    UIDelegate:UIDelegate
                                                      callback:callback];
      }];
}

- (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
                       UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
               multiFactorSession:(nullable FIRMultiFactorSession *)session
                       completion:(nullable FIRVerificationResultCallback)completion {
  if (!phoneNumber.length) {
    if (completion) {
      completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
    }
    return;
  }
  [_auth.notificationManager
      checkNotificationForwardingWithCallback:^(BOOL isNotificationBeingForwarded) {
        if (!isNotificationBeingForwarded) {
          if (completion) {
            completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
          }
          return;
        }
        FIRVerificationResultCallback callback =
            ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
              if (completion) {
                completion(verificationID, error);
              }
            };
        [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
                                   retryOnInvalidAppCredential:YES
                                                    UIDelegate:UIDelegate
                                            multiFactorSession:session
                                                      callback:callback];
      }];
}

/** @fn verifyClientAndSendVerificationCodeToPhoneNumber:retryOnInvalidAppCredential:callback:
    @brief Starts the flow to verify the client via silent push notification.
    @param retryOnInvalidAppCredential Whether of not the flow should be retried if an
        FIRAuthErrorCodeInvalidAppCredential error is returned from the backend.
    @param phoneNumber The phone number to be verified.
    @param callback The callback to be invoked on the global work queue when the flow is
        finished.
 */
- (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
                             retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
                                              UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                                                callback:(FIRVerificationResultCallback)callback {
  if (_auth.settings.isAppVerificationDisabledForTesting) {
    FIRSendVerificationCodeRequest *request =
        [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
                                                      appCredential:nil
                                                     reCAPTCHAToken:nil
                                               requestConfiguration:_auth.requestConfiguration];
    [FIRAuthBackend sendVerificationCode:request
                                callback:^(FIRSendVerificationCodeResponse *_Nullable response,
                                           NSError *_Nullable error) {
                                  callback(response.verificationID, error);
                                }];
    return;
  }
  [self
      verifyClientWithUIDelegate:UIDelegate
                      completion:^(FIRAuthAppCredential *_Nullable appCredential,
                                   NSString *_Nullable reCAPTCHAToken, NSError *_Nullable error) {
                        if (error) {
                          callback(nil, error);
                          return;
                        }
                        FIRSendVerificationCodeRequest *_Nullable request;
                        if (appCredential) {
                          request = [[FIRSendVerificationCodeRequest alloc]
                               initWithPhoneNumber:phoneNumber
                                     appCredential:appCredential
                                    reCAPTCHAToken:nil
                              requestConfiguration:self->_auth.requestConfiguration];
                        } else if (reCAPTCHAToken) {
                          request = [[FIRSendVerificationCodeRequest alloc]
                               initWithPhoneNumber:phoneNumber
                                     appCredential:nil
                                    reCAPTCHAToken:reCAPTCHAToken
                              requestConfiguration:self->_auth.requestConfiguration];
                        }
                        if (request) {
                          [FIRAuthBackend
                              sendVerificationCode:request
                                          callback:^(
                                              FIRSendVerificationCodeResponse *_Nullable response,
                                              NSError *_Nullable error) {
                                            if (error) {
                                              if (error.code ==
                                                  FIRAuthErrorCodeInvalidAppCredential) {
                                                if (retryOnInvalidAppCredential) {
                                                  [self->_auth
                                                          .appCredentialManager clearCredential];
                                                  [self
                                                      verifyClientAndSendVerificationCodeToPhoneNumber:
                                                          phoneNumber
                                                                           retryOnInvalidAppCredential:
                                                                               NO
                                                                                UIDelegate:
                                                                                UIDelegate
                                                                                callback:
                                                                                callback];
                                                  return;
                                                }
                                                callback(
                                                    nil,
                                                    [FIRAuthErrorUtils
                                                        unexpectedResponseWithDeserializedResponse:
                                                            nil
                                                                                underlyingError:
                                                                                error]);
                                                return;
                                              }
                                              callback(nil, error);
                                              return;
                                            }
                                            callback(response.verificationID, nil);
                                          }];
                        }
                      }];
}

- (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
                             retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
                                              UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                                      multiFactorSession:(nullable FIRMultiFactorSession *)session
                                                callback:(FIRVerificationResultCallback)callback {
  if (_auth.settings.isAppVerificationDisabledForTesting) {
    FIRSendVerificationCodeRequest *request =
        [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
                                                      appCredential:nil
                                                     reCAPTCHAToken:nil
                                               requestConfiguration:_auth.requestConfiguration];
    [FIRAuthBackend sendVerificationCode:request
                                callback:^(FIRSendVerificationCodeResponse *_Nullable response,
                                           NSError *_Nullable error) {
                                  callback(response.verificationID, error);
                                }];
    return;
  }

  [self
      verifyClientWithUIDelegate:UIDelegate
                      completion:^(FIRAuthAppCredential *_Nullable appCredential,
                                   NSString *_Nullable reCAPTCHAToken, NSError *_Nullable error) {
                        if (error) {
                          if (callback) {
                            callback(nil, error);
                          }
                          return;
                        }

                        NSString *IDToken = session.IDToken;
                        FIRAuthProtoStartMFAPhoneRequestInfo *startMFARequestInfo =
                            [[FIRAuthProtoStartMFAPhoneRequestInfo alloc]
                                initWithPhoneNumber:phoneNumber
                                      appCredential:appCredential
                                     reCAPTCHAToken:reCAPTCHAToken];
                        if (session.IDToken) {
                          FIRStartMFAEnrollmentRequest *request =
                              [[FIRStartMFAEnrollmentRequest alloc]
                                       initWithIDToken:IDToken
                                        enrollmentInfo:startMFARequestInfo
                                  requestConfiguration:self->_auth.requestConfiguration];
                          [FIRAuthBackend
                              startMultiFactorEnrollment:request
                                                callback:^(FIRStartMFAEnrollmentResponse
                                                               *_Nullable response,
                                                           NSError *_Nullable error) {
                                                  if (error) {
                                                    if (error.code ==
                                                        FIRAuthErrorCodeInvalidAppCredential) {
                                                      if (retryOnInvalidAppCredential) {
                                                        [self->_auth.appCredentialManager
                                                                clearCredential];
                                                        [self
                                                            verifyClientAndSendVerificationCodeToPhoneNumber:
                                                                phoneNumber
                                                                                retryOnInvalidAppCredential:
                                                                                NO
                                                                                UIDelegate:
                                                                                UIDelegate
                                                                                multiFactorSession:
                                                                                session
                                                                                callback:
                                                                                callback];
                                                        return;
                                                      }
                                                      if (callback) {
                                                        callback(
                                                            nil,
                                                            [FIRAuthErrorUtils
                                                                unexpectedResponseWithDeserializedResponse:
                                                                    nil
                                                                                underlyingError:
                                                                                error]);
                                                      }
                                                      return;
                                                    } else {
                                                      if (callback) {
                                                        callback(nil, error);
                                                      }
                                                    }
                                                  } else {
                                                    if (callback) {
                                                      callback(
                                                          response.enrollmentResponse.sessionInfo,
                                                          nil);
                                                    }
                                                  }
                                                }];
                        } else {
                          FIRStartMFASignInRequest *request = [[FIRStartMFASignInRequest alloc]
                              initWithMFAPendingCredential:session.MFAPendingCredential
                                           MFAEnrollmentID:session.multiFactorInfo.UID
                                                signInInfo:startMFARequestInfo
                                      requestConfiguration:self->_auth.requestConfiguration];
                          [FIRAuthBackend
                              startMultiFactorSignIn:request
                                            callback:^(
                                                FIRStartMFASignInResponse *_Nullable response,
                                                NSError *_Nullable error) {
                                              if (error) {
                                                if (error.code ==
                                                    FIRAuthErrorCodeInvalidAppCredential) {
                                                  if (retryOnInvalidAppCredential) {
                                                    [self->_auth
                                                            .appCredentialManager clearCredential];
                                                    [self
                                                        verifyClientAndSendVerificationCodeToPhoneNumber:
                                                            phoneNumber
                                                                             retryOnInvalidAppCredential:
                                                                                NO
                                                                                UIDelegate:
                                                                                UIDelegate
                                                                                multiFactorSession:
                                                                                session
                                                                                callback:
                                                                                callback];
                                                    return;
                                                  }
                                                  if (callback) {
                                                    callback(
                                                        nil,
                                                        [FIRAuthErrorUtils
                                                            unexpectedResponseWithDeserializedResponse:
                                                                nil
                                                                                underlyingError:
                                                                                error]);
                                                  }
                                                  return;
                                                } else {
                                                  if (callback) {
                                                    callback(nil, error);
                                                  }
                                                }
                                              } else {
                                                if (callback) {
                                                  callback(response.responseInfo.sessionInfo, nil);
                                                }
                                              }
                                            }];
                        }
                      }];
}

/** @fn verifyClientWithCompletion:completion:
    @brief Continues the flow to verify the client via silent push notification.
    @param completion The callback to be invoked when the client verification flow is finished.
 */
- (void)verifyClientWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                        completion:(FIRVerifyClientCallback)completion {
  if (_auth.appCredentialManager.credential) {
    completion(_auth.appCredentialManager.credential, nil, nil);
    return;
  }
  [_auth.tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token,
                                             NSError *_Nullable error) {
    if (!token) {
      [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
      return;
    }
    FIRVerifyClientRequest *request =
        [[FIRVerifyClientRequest alloc] initWithAppToken:token.string
                                               isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox
                                    requestConfiguration:self->_auth.requestConfiguration];
    [FIRAuthBackend
        verifyClient:request
            callback:^(FIRVerifyClientResponse *_Nullable response, NSError *_Nullable error) {
              if (error) {
                NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey];
                BOOL isInvalidAppCredential =
                    error.code == FIRAuthErrorCodeInternalError &&
                    underlyingError.code == FIRAuthErrorCodeInvalidAppCredential;
                if (error.code != FIRAuthErrorCodeMissingAppToken && !isInvalidAppCredential) {
                  completion(nil, nil, error);
                  return;
                } else {
                  [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
                  return;
                }
              }
              NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow];
              [self->_auth.appCredentialManager
                  didStartVerificationWithReceipt:response.receipt
                                          timeout:timeout
                                         callback:^(FIRAuthAppCredential *credential) {
                                           if (!credential.secret) {
                                             FIRLogWarning(kFIRLoggerAuth, @"I-AUT000014",
                                                           @"Failed to receive remote notification "
                                                           @"to verify app identity within "
                                                           @"%.0f second(s), falling back to "
                                                           @"reCAPTCHA verification.",
                                                           timeout);
                                             [self reCAPTCHAFlowWithUIDelegate:UIDelegate
                                                                    completion:completion];
                                             return;
                                           }
                                           completion(credential, nil, nil);
                                         }];
            }];
  }];
}

- (void)reCAPTCHAFlowWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                         completion:(FIRVerifyClientCallback)completion {
  NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  [self
      reCAPTCHAURLWithEventID:eventID
                   completion:^(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error) {
                     if (error) {
                       completion(nil, nil, error);
                       return;
                     }
                     FIRAuthURLCallbackMatcher callbackMatcher =
                         ^BOOL(NSURL *_Nullable callbackURL) {
                           return [FIRAuthWebUtils isExpectedCallbackURL:callbackURL
                                                                 eventID:eventID
                                                                authType:kAuthTypeVerifyApp
                                                          callbackScheme:self->_callbackScheme];
                         };
                     [self->_auth.authURLPresenter
                              presentURL:reCAPTCHAURL
                              UIDelegate:UIDelegate
                         callbackMatcher:callbackMatcher
                              completion:^(NSURL *_Nullable callbackURL, NSError *_Nullable error) {
                                if (error) {
                                  completion(nil, nil, error);
                                  return;
                                }
                                NSError *reCAPTCHAError;
                                NSString *reCAPTCHAToken =
                                    [self reCAPTCHATokenForURL:callbackURL error:&reCAPTCHAError];
                                if (!reCAPTCHAToken) {
                                  completion(nil, nil, reCAPTCHAError);
                                  return;
                                } else {
                                  completion(nil, reCAPTCHAToken, nil);
                                  return;
                                }
                              }];
                   }];
}

/** @fn reCAPTCHAURLWithEventID:completion:
    @brief Constructs a URL used for opening a reCAPTCHA app verification flow using a given event
        ID.
    @param eventID The event ID used for this purpose.
    @param completion The callback invoked after the URL has been constructed or an error
        has been encountered.
 */
- (void)reCAPTCHAURLWithEventID:(NSString *)eventID completion:(FIRReCAPTCHAURLCallBack)completion {
  [FIRAuthWebUtils
      fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
                                   completion:^(NSString *_Nullable authDomain,
                                                NSError *_Nullable error) {
                                     if (error) {
                                       if (completion) {
                                         completion(nil, error);
                                         return;
                                       }
                                     }
                                     NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
                                     NSString *clientID = self->_auth.app.options.clientID;
                                     NSString *appID = self->_auth.app.options.googleAppID;
                                     NSString *apiKey = self->_auth.requestConfiguration.APIKey;
                                     NSMutableArray<NSURLQueryItem *> *queryItems = [@[
                                       [NSURLQueryItem queryItemWithName:@"apiKey" value:apiKey],
                                       [NSURLQueryItem queryItemWithName:@"authType"
                                                                   value:kAuthTypeVerifyApp],
                                       [NSURLQueryItem queryItemWithName:@"ibi"
                                                                   value:bundleID ?: @""],
                                       [NSURLQueryItem
                                           queryItemWithName:@"v"
                                                       value:[FIRAuthBackend authUserAgent]],
                                       [NSURLQueryItem queryItemWithName:@"eventId" value:eventID]
                                     ] mutableCopy];
                                     if (self->_usingClientIDScheme) {
                                       [queryItems
                                           addObject:[NSURLQueryItem queryItemWithName:@"clientId"
                                                                                value:clientID]];
                                     } else {
                                       [queryItems
                                           addObject:[NSURLQueryItem queryItemWithName:@"appId"
                                                                                value:appID]];
                                     }

                                     if (self->_auth.requestConfiguration.languageCode) {
                                       [queryItems
                                           addObject:[NSURLQueryItem
                                                         queryItemWithName:@"hl"
                                                                     value:self->_auth
                                                                               .requestConfiguration
                                                                               .languageCode]];
                                     }
                                     NSURLComponents *components = [[NSURLComponents alloc]
                                         initWithString:
                                             [NSString stringWithFormat:kReCAPTCHAURLStringFormat,
                                                                        authDomain]];
                                     [components setQueryItems:queryItems];
                                     if (completion) {
                                       completion([components URL], nil);
                                     }
                                   }];
}

@end

NS_ASSUME_NONNULL_END

#endif


text:
var fs = require('fs'),
    path = require('path');

fs.readdirSync(__dirname).forEach(function(filename) {
  var name;
  name = path.basename(filename, '.js');
  if (name === 'index' || name[0] === '_') return;
  exports.__defineGetter__(name, function() {
    return require('./' + name);
  });
});

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function () {
            var PieInfo = new Object();
            var json = JSON.parse(json_text);
            var features = json['features'];
	        for (var i = 0; i < features.length; i++) {
	            var Id = features[i]['properties']['id'];
	            var X = features[i]['properties']['x'];
	            var Y = features[i]['properties']['y'];
	            var Type = features[i]['properties']['type']; Type = i; //TODEL
	            var Value = features[i]['properties']['value'];
	            if (!PieInfo[Id]) {
	                PieInfo[Id] = new Object();
	                PieInfo[Id][Type] = Value;
	                var popup = new L.Popup();
	                popup.setLatLng(new L.LatLng(Y, X));
	                popup.setContent("

");
	                map.addLayer(popup);
	            }
	            else {
	                PieInfo[Id][Type] = Value;
	            }
	        }
	        for (var key in PieInfo) {
	            var Values = new Array();
	            for (var cse in PieInfo[key]) { Values.push([cse, PieInfo[key][cse]]); }
	            var plot1 = $.jqplot(key, [Values], {
	                gridPadding: { top: 0, bottom: 0, left: 0, right: 0 },
	                seriesDefaults: { renderer: $.jqplot.PieRenderer, trendline: { show: false }, rendererOptions: { padding: 2, showDataLabels: true, dataLabels: 'value' }
	                }
	            });
	        }
	    });
        }


text:
package com.github.dm.jrt.core.runner;

import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;

/**
 * Scheduled executor unit tests.
 * <p>
 * Created by davide-maestroni on 05/24/2016.
 */
public class ScheduledThreadExecutorTest {

  @Test
  public void testEquals() {

    final ExecutorService pool = Executors.newCachedThreadPool();
    final ScheduledThreadExecutor executor = new ScheduledThreadExecutor(pool);
    assertThat(executor).isEqualTo(executor);
    assertThat(executor).isNotEqualTo(null);
    assertThat(executor).isNotEqualTo("test");
    assertThat(executor).isNotEqualTo(new ScheduledThreadExecutor(Executors.newCachedThreadPool()));
    assertThat(executor).isEqualTo(new ScheduledThreadExecutor(pool));
    assertThat(executor.hashCode()).isEqualTo(new ScheduledThreadExecutor(pool).hashCode());
  }

  @Test
  public void testUnsupportedMethods() {

    final ScheduledThreadExecutor executor =
        new ScheduledThreadExecutor(Executors.newCachedThreadPool());
    try {
      executor.schedule(new Callable<Object>() {

        public Object call() throws Exception {

          return null;
        }
      }, 0, TimeUnit.MILLISECONDS);
      fail();

    } catch (final UnsupportedOperationException ignored) {

    }

    try {
      executor.scheduleAtFixedRate(new Runnable() {

        public void run() {

        }
      }, 0, 1, TimeUnit.SECONDS);
      fail();

    } catch (final UnsupportedOperationException ignored) {

    }

    try {
      executor.scheduleWithFixedDelay(new Runnable() {

        public void run() {

        }
      }, 0, 1, TimeUnit.SECONDS);
      fail();

    } catch (final UnsupportedOperationException ignored) {

    }
  }
}


text:
package com.graphhopper.routing;

import com.graphhopper.routing.ev.BooleanEncodedValue;
import com.graphhopper.routing.ev.DecimalEncodedValue;
import com.graphhopper.routing.ev.EnumEncodedValue;
import com.graphhopper.routing.ev.RoadClass;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.shapes.GHPoint;

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

/**
 * This class handles the outgoing edges for a single turn instruction.
 * There are different sets of edges.
 * The previous edge is the edge we are coming from.
 * The current edge is the edge we turn on.
 * The allowedAlternativeTurns contains all edges that the current vehicle is allowed(*) to turn on to, excluding the prev edge and the current edge.
 * The visibleAlternativeTurns contains all edges surrounding this turn instruction, without the prev edge and the current edge.
 * (*): This might not consider turn restrictions, but only simple access values.
 * Here is an example:
 * <pre>
 * A --> B --> C
 *       ^
 *       |
 *       X
 * </pre>
 * For the route from A->B->C and baseNode=B, adjacentNode=C:
 * - the previous edge is A->B
 * - the current edge is B->C
 * - the allowedAlternativeTurns are B->C => return value of {@link #getAllowedTurns()} is 1
 * - the visibleAlternativeTurns are B->X and B->C => return values of {@link #getVisibleTurns()} is 2
 *
 * @author Robin Boldt
 */
class InstructionsOutgoingEdges {

    private final EdgeIteratorState prevEdge;
    private final EdgeIteratorState currentEdge;
    // Outgoing edges that we would be allowed to turn on
    private final List<EdgeIteratorState> allowedAlternativeTurns;
    // All outgoing edges, including oneways in the wrong direction
    private final List<EdgeIteratorState> visibleAlternativeTurns;
    private final DecimalEncodedValue maxSpeedEnc;
    private final EnumEncodedValue<RoadClass> roadClassEnc;
    private final BooleanEncodedValue roadClassLinkEnc;
    private final NodeAccess nodeAccess;
    private final Weighting weighting;

    public InstructionsOutgoingEdges(EdgeIteratorState prevEdge,
                                     EdgeIteratorState currentEdge,
                                     Weighting weighting,
                                     DecimalEncodedValue maxSpeedEnc,
                                     EnumEncodedValue<RoadClass> roadClassEnc,
                                     BooleanEncodedValue roadClassLinkEnc,
                                     EdgeExplorer allExplorer,
                                     NodeAccess nodeAccess,
                                     int prevNode,
                                     int baseNode,
                                     int adjNode) {
        this.prevEdge = prevEdge;
        this.currentEdge = currentEdge;
        this.weighting = weighting;
        this.maxSpeedEnc = maxSpeedEnc;
        this.roadClassEnc = roadClassEnc;
        this.roadClassLinkEnc = roadClassLinkEnc;
        this.nodeAccess = nodeAccess;

        visibleAlternativeTurns = new ArrayList<>();
        allowedAlternativeTurns = new ArrayList<>();
        EdgeIterator edgeIter = allExplorer.setBaseNode(baseNode);
        while (edgeIter.next()) {
            if (edgeIter.getAdjNode() != prevNode && edgeIter.getAdjNode() != adjNode) {
                if (Double.isFinite(weighting.calcEdgeWeightWithAccess(edgeIter, false))) {
                    EdgeIteratorState tmpEdge = edgeIter.detach(false);
                    allowedAlternativeTurns.add(tmpEdge);
                    visibleAlternativeTurns.add(tmpEdge);
                } else if (Double.isFinite(weighting.calcEdgeWeightWithAccess(edgeIter, true))) {
                    visibleAlternativeTurns.add(edgeIter.detach(false));
                }
            }
        }
    }

    /**
     * This method calculates the number of allowed outgoing edges, which could be considered the number of possible
     * roads one might take at the intersection. This excludes the road you are coming from and inaccessible roads.
     */
    public int getAllowedTurns() {
        return 1 + allowedAlternativeTurns.size();
    }

    /**
     * This method calculates the number of all outgoing edges, which could be considered the number of roads you see
     * at the intersection. This excludes the road you are coming from and also inaccessible roads.
     */
    public int getVisibleTurns() {
        return 1 + visibleAlternativeTurns.size();
    }

    /**
     * Checks if the outgoing edges are slower by the provided factor. If they are, this indicates, that we are staying
     * on the prominent street that one would follow anyway.
     */
    public boolean outgoingEdgesAreSlowerByFactor(double factor) {
        double tmpSpeed = getSpeed(currentEdge);
        double pathSpeed = getSpeed(prevEdge);

        // speed change indicates that we change road types
        if (Math.abs(pathSpeed - tmpSpeed) >= 1) {
            return false;
        }

        double maxSurroundingSpeed = -1;

        for (EdgeIteratorState edge : allowedAlternativeTurns) {
            tmpSpeed = getSpeed(edge);
            if (tmpSpeed > maxSurroundingSpeed) {
                maxSurroundingSpeed = tmpSpeed;
            }
        }

        // surrounding streets need to be slower by a factor and call round() so that tiny differences are ignored
        return Math.round(maxSurroundingSpeed * factor) < Math.round(pathSpeed);
    }

    /**
     * Will return the tagged maxspeed, if available, if not, we use the average speed
     * TODO: Should we rely only on the tagged maxspeed?
     */
    private double getSpeed(EdgeIteratorState edge) {
        double maxSpeed = edge.get(maxSpeedEnc);
        if (Double.isInfinite(maxSpeed))
            return edge.getDistance() / weighting.calcEdgeMillis(edge, false) * 3600;
        return maxSpeed;
    }

    /**
     * Returns an edge that has more or less in the same orientation as the prevEdge, but is not the currentEdge.
     * If there is one, this indicates that we might need an instruction to help finding the correct edge out of the different choices.
     * If there is none, return null.
     */
    public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) {
        int tmpSign;
        for (EdgeIteratorState edge : allowedAlternativeTurns) {
            GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess);
            tmpSign = InstructionsHelper.calculateSign(prevLat, prevLon, point.getLat(), point.getLon(), prevOrientation);
            if (Math.abs(tmpSign) <= 1) {
                return edge;
            }
        }
        return null;
    }

    /**
     * If the name and prevName changes this method checks if either the current street is continued on a
     * different edge or if the edge we are turning onto is continued on a different edge.
     * If either of these properties is true, we can be quite certain that a turn instruction should be provided.
     */
    public boolean isLeavingCurrentStreet(String prevName, String name) {
        if (InstructionsHelper.isNameSimilar(name, prevName)) {
            return false;
        }

        boolean roadClassOrLinkChange = !isTheSameRoadClassAndLink(prevEdge, currentEdge);
        for (EdgeIteratorState edge : allowedAlternativeTurns) {
            String edgeName = edge.getName();
            // leave the current street
            if (InstructionsHelper.isNameSimilar(prevName, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(prevEdge, edge))) {
                return true;
            }
            // enter a different street
            if (InstructionsHelper.isNameSimilar(name, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(currentEdge, edge))) {
                return true;
            }
        }
        return false;
    }

    private boolean isTheSameRoadClassAndLink(EdgeIteratorState edge1, EdgeIteratorState edge2) {
        return edge1.get(roadClassEnc) == edge2.get(roadClassEnc) && edge1.get(roadClassLinkEnc) == edge2.get(roadClassLinkEnc);
    }

}


text:
import { Component, Input } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { BOOLEAN_FIELD_EDITORS, BooleanFieldPropertiesDto, FieldDto } from '@app/shared';

@Component({
    selector: 'sqx-boolean-ui[field][fieldForm][properties]',
    styleUrls: ['boolean-ui.component.scss'],
    templateUrl: 'boolean-ui.component.html',
})
export class BooleanUIComponent {
    public readonly editors = BOOLEAN_FIELD_EDITORS;

    @Input()
    public fieldForm!: UntypedFormGroup;

    @Input()
    public field!: FieldDto;

    @Input()
    public properties!: BooleanFieldPropertiesDto;
}


text:
package org.apache.pig.builtin;

import java.io.IOException;

import org.apache.pig.EvalFunc;
import org.apache.pig.PigWarning;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;

/**
 * upper-case the first character of a string
 */
public class UCFIRST extends EvalFunc<String> {
    @Override
    public String exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0) {
            return null;
        }
        try {
            String str = (String) input.get(0);
            if (str == null) return null;
            if (str.length() == 0) return str;
            return Character.toUpperCase(str.charAt(0))+str.substring(1);
        } catch (ExecException e) {
            warn("Error reading input: " + e.getMessage(), PigWarning.UDF_WARNING_1);
            return null;
        }
    }

    @Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(null, DataType.CHARARRAY));
    }

    @Override
    public boolean allowCompileTimeCalculation() {
        return true;
    }
}


text:
package com.helger.wsclient.mock;

import java.io.File;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

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

import com.helger.xml.microdom.IMicroDocument;
import com.helger.xml.microdom.IMicroElement;
import com.helger.xml.microdom.serialize.MicroReader;

import jakarta.jws.WebService;

/**
 * Test class that checks if the file sun-jaxws.xml is correct.
 *
 * @author Philip Helger
 */
public final class WSTestHelper
{
  public static final String SUN_JAXWS_XML = "sun-jaxws.xml";

  private static final Logger LOGGER = LoggerFactory.getLogger (WSTestHelper.class);

  private WSTestHelper ()
  {}

  @Nonnegative
  public static int testIfAllSunJaxwsFilesAreValid (@Nonnull final String sBaseDir, final boolean bContinueOnError)
  {
    final int nTotalImplementationCount = 0;
    final File aFile = new File (sBaseDir, SUN_JAXWS_XML);
    if (aFile.isFile ())
    {
      LOGGER.info ("Checking file " + aFile.getAbsolutePath ());

      final IMicroDocument aDoc = MicroReader.readMicroXML (aFile);
      if (aDoc == null)
      {
        final String sMsg = "The file is invalid XML!";
        LOGGER.warn (sMsg);
        if (!bContinueOnError)
          throw new IllegalStateException (sMsg);
      }
      else
      {
        for (final IMicroElement eEndpoint : aDoc.getDocumentElement ().getAllChildElements ("endpoint"))
        {
          final String sName = eEndpoint.getAttributeValue ("name");
          final String sImplementation = eEndpoint.getAttributeValue ("implementation");

          // Check if implementation class exists
          Class <?> aImplClass = null;
          try
          {
            aImplClass = Class.forName (sImplementation);
          }
          catch (final Exception ex)
          {
            final String sMsg = "The implementation class '" +
                                sImplementation +
                                "' of endpoint '" +
                                sName +
                                "' is invalid - " +
                                ex.getMessage ();
            LOGGER.warn (sMsg);
            if (!bContinueOnError)
              throw new IllegalStateException (sMsg);
          }

          if (aImplClass != null)
          {
            if (LOGGER.isDebugEnabled ())
              LOGGER.debug ("Implementation class '" + sImplementation + "' found");

            final WebService aWebService = aImplClass.getAnnotation (WebService.class);
            if (aWebService == null)
            {
              final String sMsg = "The implementation class '" + sImplementation + "' is missing the @WebService annotation";
              LOGGER.warn (sMsg);
              if (!bContinueOnError)
                throw new IllegalStateException (sMsg);
            }
            else
            {
              final String sEndpointInterface = aWebService.endpointInterface ();

              // Check if interface exists
              Class <?> aInterfaceClass = null;
              try
              {
                aInterfaceClass = Class.forName (sEndpointInterface);
              }
              catch (final Exception ex)
              {
                final String sMsg = "The endpoint interface class '" +
                                    sEndpointInterface +
                                    "' of implementation class '" +
                                    sImplementation +
                                    "' is invalid - " +
                                    ex.getMessage ();
                LOGGER.warn (sMsg);
                if (!bContinueOnError)
                  throw new IllegalStateException (sMsg);
              }

              if (aInterfaceClass != null)
              {
                if (!aInterfaceClass.isInterface ())
                {
                  final String sMsg = "The endpoint interface class '" +
                                      sEndpointInterface +
                                      "' of endpoint '" +
                                      sName +
                                      "' is not an interface!";
                  LOGGER.warn (sMsg);
                  if (!bContinueOnError)
                    throw new IllegalStateException (sMsg);
                }
              }
            }
          }
        }
      }
    }
    return nTotalImplementationCount;
  }

  @Nonnegative
  public static int testIfAllSunJaxwsFilesAreValid (final boolean bContinueOnError)
  {
    int ret = 0;
    ret += testIfAllSunJaxwsFilesAreValid ("src/main/resources/WEB-INF", bContinueOnError);
    ret += testIfAllSunJaxwsFilesAreValid ("src/main/webapp/WEB-INF", bContinueOnError);
    return ret;
  }

  public static void testIfAllSunJaxwsFilesAreValid ()
  {
    testIfAllSunJaxwsFilesAreValid (false);
  }
}


text:
'use strict'

// Packages dependencies
const express = require('express')
const router = express.Router()
// const ejwt = require('express-jwt')
const jwt = require('jsonwebtoken')

// Exports
module.exports = function (UsersApiPackage, app, config, db, auth) {
  // TODO: isAuthorized && isRevoked
  // const isAuthenticated = ejwt({ secret: process.env.JWT_SECRET || 'shhh' })

  // const auth = {
  //   authenticate: ejwt({ secret: process.env.JWT_SECRET || 'shhh' })
  // }

  function checkSequelizeError (next, err) {
    if (err && err.name) {
      if (['ValidationError', 'SequelizeUniqueConstraintError'].indexOf() === -1) {
        if (!err.errors) return next(err)
        const error400 = new Error(err.errors[0].message)
        error400.code = 'BAD_REQUEST'
        return next(error400)
      }
      return next(err)
    }
    next(err)
  }

  function userValidation (req, update) {
    // VALIDATION
    if (update === true) {
      req.checkBody('email', 'email must be a valid email address').optional().isEmail()
      req.checkBody('password', 'password cannot be empty').optional().notEmpty()
    } else {
      req.checkBody('email', 'email must be a valid email address').isEmail()
      req.checkBody('password', 'password is required').notEmpty()
    }

    req.checkBody('firstname', 'firstname cannot be empty').optional().notEmpty()
    req.checkBody('lastname', 'lastname cannot be empty').optional().notEmpty()
    req.checkBody('roles', 'roles cannot be empty').optional().notEmpty()

    // SANITIZE
    req.sanitizeBody('email').trim()
    req.sanitizeBody('firstname').trim()
    req.sanitizeBody('lastname').trim()
    req.sanitizeBody('roles').trim()

    const errors = req.validationErrors()
    if (errors) {
      const error400 = new Error(errors[0].msg)
      error400.code = 'BAD_REQUEST'
      return error400
    }

    return null
  }

  // Get Users
  router.get('/users', (req, res, next) => {
    const User = db.models.User

    User
      .findAll()
      .then(users => {
        res.json(users.map(user => {
          return user.toJSON()
        }))
      })
      .catch(next)
  })

  // Add User
  router.post('/users', (req, res, next) => {
    const User = db.models.User
    const userParams = req.body

    // VALIDATION
    const error = userValidation(req)
    if (error) return next(error)

    // TODO: Check the invitation code

    if (!userParams.roles) userParams.roles = 'authenticated'

    User
      .create(req.body)
      .then(user => {
        res.status(201).json(user.get({plain: true}))
      })
      .catch(checkSequelizeError.bind(null, next))
  })

  // Update User
  router.put('/users/:id', (req, res, next) => {
    const User = db.models.User

    // VALIDATION
    const error = userValidation(req, true)
    if (error) return next(error)

    User
      .update(req.body, {
        where: { id: req.params.id }
      })
      .then(affectedRows => {
        // TODO: check why affectedRows is an array instead Integer
        if (affectedRows[0] < 1) throw null
        res.status(202).json({ updated: affectedRows[0] })
      })
      .catch(checkSequelizeError.bind(null, next))
  })

  // Delete User
  router.delete('/users/:id', (req, res, next) => {
    const User = db.models.User

    return User
      .destroy({
        where: { id: req.params.id }
      })
      .catch(next)
  })

  // User auth
  router.post('/users/authenticate', (req, res, next) => {
    const User = db.models.User

    req.checkBody('email', 'email must be a valid email address').notEmpty().isEmail()
    req.checkBody('password', 'password is required').notEmpty()

    const errors = req.validationErrors()
    if (errors) {
      const error400 = new Error(errors[0].msg)
      error400.code = 'BAD_REQUEST'
      return next(error400)
    }

    // find the user
    User
      .findOne({
        where: { email: req.body.email }
      })
      .then(user => {
        if (!user) {
          const error401User = new Error('Authentication failed because user has not been found')
          error401User.code = 'UNAUTHORIZED'
          return next(error401User)
        } else if (user) {
          // check if password matches
          if (user.get('hashed_password') !== user.hashPassword(req.body.password)) {
            const error401Passowrd = new Error('Authentication failed because password is wrong')
            error401Passowrd.code = 'UNAUTHORIZED'
            return next(error401Passowrd)
          } else {
            // if user is found and password is right create a token
            const token = jwt.sign(user.toJSON(), process.env.JWT_SECRET || 'shhh', {
              expiresInMinutes: 1440 // expires in 24 hours
            })

            // return the information including token as JSON
            res
              .status(202)
              .json({
                token: token
              })
          }
        }
      })
      .catch(next)
  })

  return router
}


text:
module Main where

import TestHarness
import SimpleTests

main :: IO ()
main = runTests allTests


text:
package org.nd4j.parameterserver.distributed.messages;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.agrona.concurrent.UnsafeBuffer;
import org.nd4j.linalg.util.SerializationUtils;
import org.nd4j.parameterserver.distributed.conf.VoidConfiguration;
import org.nd4j.parameterserver.distributed.enums.NodeRole;
import org.nd4j.parameterserver.distributed.logic.completion.Clipboard;
import org.nd4j.parameterserver.distributed.logic.Storage;
import org.nd4j.parameterserver.distributed.training.TrainingDriver;
import org.nd4j.parameterserver.distributed.transport.Transport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Simple wrapper for multiple request messages OF THE SAME TYPE being stacked into single message
 *
 * @author raver119@gmail.com
 */
@Slf4j
@Deprecated
public class Frame<T extends TrainingMessage> implements Serializable, Iterable<T>, VoidMessage {

    @Getter(AccessLevel.PROTECTED)
    @Setter(AccessLevel.PROTECTED)
    protected List<T> list = new ArrayList<T>();

    @Getter
    protected long originatorId;
    @Getter
    @Setter
    protected short targetId;
    @Getter
    @Setter
    protected long taskId;

    protected transient VoidConfiguration voidConfiguration;
    protected transient Clipboard clipboard;
    protected transient Transport transport;
    protected transient Storage storage;
    protected transient NodeRole role;
    protected transient short shardIndex;
    protected transient TrainingDriver<? extends TrainingMessage> trainer;

    @Getter
    @Setter(AccessLevel.PRIVATE)
    protected transient int retransmitCount = 0;

    protected Frame() {

    }

    public Frame(long taskId) {
        this.taskId = taskId;
    }

    public Frame(@NonNull T message) {
        this();
        list.add(message);
    }

    @Override
    public void setOriginatorId(long id) {
        this.originatorId = id;
        if (list != null)
            list.forEach((msg) -> {
                msg.setOriginatorId(this.getOriginatorId());
            });
    }

    /**
     * This method adds single TrainingMessage to this Frame
     *
     * PLEASE NOTE: This method is synchronized
     * @param message
     */
    public synchronized void stackMessage(@NonNull T message) {
        stackMessageUnlocked(message);
    }

    private void stackMessageUnlocked(@NonNull T message) {
        if (message.isJoinSupported()) {
            int index = list.indexOf(message);
            if (index >= 0)
                list.get(index).joinMessage(message);
            else {
                message.setFrameId(this.getTaskId());
                list.add(message);
            }
        } else {
            message.setFrameId(this.getTaskId());
            list.add(message);
        }
    }

    /**
     * This method adds multiple messages to this frame
     *
     * PLEASE NOTE: This method is synchronized
     * @param messages
     */
    public synchronized void stackMessages(@NonNull Collection<T> messages) {
        for (T message : messages) {
            stackMessageUnlocked(message);
        }
    }

    /**
     * This method adds multiple messages to this frame
     *
     * PLEASE NOTE: This method is synchronized
     * @param messages
     */
    public synchronized void stackMessages(T... messages) {
        for (T message : messages) {
            if (message != null)
                stackMessageUnlocked(message);
        }
    }

    public Collection<T> getMessages() {
        return list;
    }

    public int size() {
        return list.size();
    }

    @Override
    public Iterator<T> iterator() {
        return list.iterator();
    }

    @Override
    public int getMessageType() {
        return 3;
    }

    @Override
    public byte[] asBytes() {
        return SerializationUtils.toByteArray(this);
    }

    @Override
    public UnsafeBuffer asUnsafeBuffer() {
        return new UnsafeBuffer(asBytes());
    }

    @Override
    public void attachContext(@NonNull VoidConfiguration voidConfiguration,
                    @NonNull TrainingDriver<? extends TrainingMessage> trainer, @NonNull Clipboard clipboard,
                    @NonNull Transport transport, @NonNull Storage storage, @NonNull NodeRole role, short shardIndex) {
        this.voidConfiguration = voidConfiguration;
        this.clipboard = clipboard;
        this.transport = transport;
        this.storage = storage;
        this.role = role;
        this.shardIndex = shardIndex;
        this.trainer = trainer;
    }

    @Override
    public void extractContext(@NonNull BaseVoidMessage message) {
        this.voidConfiguration = message.voidConfiguration;
        this.clipboard = message.clipboard;
        this.transport = message.transport;
        this.storage = message.storage;
        this.role = message.role;
        this.shardIndex = message.shardIndex;
        this.trainer = message.trainer;
        this.originatorId = message.originatorId;
    }

    @Override
    public void processMessage() {
        //        log.info("Processing frame {} of {} messages... Originator: {}", this.getTaskId(), list.size(), originatorId);

        // we register all messages first
        //      if(list == null || trainer == null)
        //          return;
        if (trainer != null && transport != null)
            list.forEach((message) -> {
                trainer.addCompletionHook(getOriginatorId(), getTaskId(), message.getTaskId());
            });

        //list.parallelStream().forEach((message) -> {
        for (TrainingMessage message : list) {
            if (trainer != null && transport != null)
                message.attachContext(voidConfiguration, trainer, clipboard, transport, storage, role, shardIndex);

            // if there's more then 1 round should be applied
            for (int i = 0; i < message.getCounter(); i++) {
                //log.info("Firing message {}; originator: {}; frameId: {}; taskId: {}", message.getClass().getSimpleName(), message.getOriginatorId(), message.getFrameId(), message.getTaskId());
                message.processMessage();
            }
        } ;
    }

    @Override
    public boolean isJoinSupported() {
        return false;
    }

    @Override
    public void joinMessage(VoidMessage message) {
        // no-op
    }

    @Override
    public boolean isBlockingMessage() {
        return true;
    }

    @Override
    public void incrementRetransmitCount() {
        retransmitCount++;
    }
}


text:
using System;
using System.Collections.Generic;
using Org.Apache.REEF.IMRU.OnREEF.Parameters;
using Org.Apache.REEF.Network.Group.Driver.Impl;
using Org.Apache.REEF.Tang.Formats;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Util;
using Org.Apache.REEF.Utilities.Diagnostics;
using Org.Apache.REEF.Utilities.Logging;

namespace Org.Apache.REEF.IMRU.API
{
    /// <summary>
    /// Use this class to create an IMRU Job Definition.
    /// </summary>
    /// <seealso cref="IMRUJobDefinition" />
    public sealed class IMRUJobDefinitionBuilder
    {
        private static readonly Logger Logger = Logger.GetLogger(typeof(IMRUJobDefinitionBuilder));

        private string _jobName;
        private int _numberOfMappers;
        private int _memoryPerMapper;
        private int _updateTaskMemory;
        private int _coresPerMapper;
        private int _updateTaskCores;
        private IConfiguration _mapFunctionConfiguration;
        private IConfiguration _mapInputCodecConfiguration;
        private IConfiguration _updateFunctionCodecsConfiguration;
        private IConfiguration _reduceFunctionConfiguration;
        private IConfiguration _updateFunctionConfiguration;
        private IConfiguration _mapOutputPipelineDataConverterConfiguration;
        private IConfiguration _mapInputPipelineDataConverterConfiguration;
        private IConfiguration _partitionedDatasetConfiguration;
        private IConfiguration _resultHandlerConfiguration;
        private readonly ISet<IConfiguration> _perMapConfigGeneratorConfig;
        private bool _invokeGC;

        private static readonly IConfiguration EmptyConfiguration =
            TangFactory.GetTang().NewConfigurationBuilder().Build();

        /// <summary>
        /// Constructor
        /// </summary>
        public IMRUJobDefinitionBuilder()
        {
            _mapInputPipelineDataConverterConfiguration = EmptyConfiguration;
            _mapOutputPipelineDataConverterConfiguration = EmptyConfiguration;
            _partitionedDatasetConfiguration = EmptyConfiguration;
            _resultHandlerConfiguration = EmptyConfiguration;
            _memoryPerMapper = 512;
            _updateTaskMemory = 512;
            _coresPerMapper = 1;
            _updateTaskCores = 1;
            _invokeGC = true;
            _perMapConfigGeneratorConfig = new HashSet<IConfiguration>();
        }

        /// <summary>
        /// Set the name of the job.
        /// </summary>
        /// <param name="name">the name of the job</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetJobName(string name)
        {
            _jobName = name;
            return this;
        }

        /// <summary>
        /// Sets configuration of map function
        /// </summary>
        /// <param name="mapFunctionConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetMapFunctionConfiguration(IConfiguration mapFunctionConfiguration)
        {
            _mapFunctionConfiguration = mapFunctionConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of codec for TMapInput
        /// </summary>
        /// <param name="mapInputCodecConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetMapInputCodecConfiguration(IConfiguration mapInputCodecConfiguration)
        {
            _mapInputCodecConfiguration = mapInputCodecConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of codecs needed by Update function
        /// </summary>
        /// <param name="updateFunctionCodecsConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetUpdateFunctionCodecsConfiguration(
            IConfiguration updateFunctionCodecsConfiguration)
        {
            _updateFunctionCodecsConfiguration = updateFunctionCodecsConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of reduce function
        /// </summary>
        /// <param name="reduceFunctionConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetReduceFunctionConfiguration(IConfiguration reduceFunctionConfiguration)
        {
            _reduceFunctionConfiguration = reduceFunctionConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of update function
        /// </summary>
        /// <param name="updateFunctionConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetUpdateFunctionConfiguration(IConfiguration updateFunctionConfiguration)
        {
            _updateFunctionConfiguration = updateFunctionConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of PipelineDataConverter for Map output
        /// </summary>
        /// <param name="mapOutputPipelineDataConverterConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetMapOutputPipelineDataConverterConfiguration(
            IConfiguration mapOutputPipelineDataConverterConfiguration)
        {
            _mapOutputPipelineDataConverterConfiguration = mapOutputPipelineDataConverterConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of PipelineDataConverter for Map Input
        /// </summary>
        /// <param name="mapInputPipelineDataConverterConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetMapInputPipelineDataConverterConfiguration(
            IConfiguration mapInputPipelineDataConverterConfiguration)
        {
            _mapInputPipelineDataConverterConfiguration = mapInputPipelineDataConverterConfiguration;
            return this;
        }

        /// <summary>
        /// Sets configuration of partitioned dataset
        /// </summary>
        /// <param name="partitionedDatasetConfiguration">Configuration</param>
        /// <returns>this</returns>
        public IMRUJobDefinitionBuilder SetPartitionedDatasetConfiguration(
            IConfiguration partitionedDatasetConfiguration)
        {
            _partitionedDatasetConfiguration = partitionedDatasetConfiguration;
            return this;
        }

        /// <summary>
        /// Sets Number of mappers
        /// </summary>
        /// <param name="numberOfMappers">Number of mappers</param>
        /// <returns>this</returns>
        /// TODO: This is duplicate in a sense that it can be determined
        /// TODO: automatically from IPartitionedDataset. However, right now
        /// TODO: GroupComm. instantiated in IMRUDriver needs this parameter
        /// TODO: in constructor. This will be removed once we remove it from GroupComm.
        public IMRUJobDefinitionBuilder SetNumberOfMappers(int numberOfMappers)
        {
            _numberOfMappers = numberOfMappers;
            return this;
        }

        /// <summary>
        /// Sets mapper memory
        /// </summary>
        /// <param name="memory">memory in MB</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetMapperMemory(int memory)
        {
            _memoryPerMapper = memory;
            return this;
        }

        /// <summary>
        /// Set update task memory
        /// </summary>
        /// <param name="memory">memory in MB</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetUpdateTaskMemory(int memory)
        {
            _updateTaskMemory = memory;
            return this;
        }

        /// <summary>
        /// Sets cores for map tasks
        /// </summary>
        /// <param name="cores">number of cores</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetMapTaskCores(int cores)
        {
            _coresPerMapper = cores;
            return this;
        }

        /// <summary>
        /// Set update task cores
        /// </summary>
        /// <param name="cores">number of cores</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetUpdateTaskCores(int cores)
        {
            _updateTaskCores = cores;
            return this;
        }

        /// <summary>
        /// Sets Per Map Configuration
        /// </summary>
        /// <param name="perMapperConfig">Mapper configs</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetPerMapConfigurations(IConfiguration perMapperConfig)
        {
            _perMapConfigGeneratorConfig.Add(perMapperConfig);
            return this;
        }

        /// <summary>
        /// Sets Result handler Configuration
        /// </summary>
        /// <param name="resultHandlerConfig">Result handler config</param>
        /// <returns></returns>
        public IMRUJobDefinitionBuilder SetResultHandlerConfiguration(IConfiguration resultHandlerConfig)
        {
            _resultHandlerConfiguration = resultHandlerConfig;
            return this;
        }

        /// <summary>
        /// Whether to invoke Garbage Collector after each IMRU iteration
        /// </summary>
        /// <param name="invokeGC">variable telling whether to invoke or not</param>
        /// <returns>The modified definition builder</returns>
        public IMRUJobDefinitionBuilder InvokeGarbageCollectorAfterIteration(bool invokeGC)
        {
            _invokeGC = invokeGC;
            return this;
        }

        /// <summary>
        /// Instantiate the IMRUJobDefinition.
        /// </summary>
        /// <returns>The IMRUJobDefintion configured.</returns>
        /// <exception cref="NullReferenceException">If any of the required parameters is not set.</exception>
        public IMRUJobDefinition Build()
        {
            if (null == _jobName)
            {
                Exceptions.Throw(new NullReferenceException("Job name cannot be null"),
                    Logger);
            }

            if (null == _mapFunctionConfiguration)
            {
                Exceptions.Throw(new NullReferenceException("Map function configuration cannot be null"), Logger);
            }

            if (null == _mapInputCodecConfiguration)
            {
                Exceptions.Throw(new NullReferenceException("Map input codec configuration cannot be null"), Logger);
            }

            if (null == _updateFunctionCodecsConfiguration)
            {
                Exceptions.Throw(new NullReferenceException("Update function codecs configuration cannot be null"),
                    Logger);
            }

            if (null == _reduceFunctionConfiguration)
            {
                Exceptions.Throw(new NullReferenceException("Reduce function configuration cannot be null"), Logger);
            }

            if (null == _updateFunctionConfiguration)
            {
                Exceptions.Throw(new NullReferenceException("Update function configuration cannot be null"), Logger);
            }

            return new IMRUJobDefinition(
                _mapFunctionConfiguration,
                _mapInputCodecConfiguration,
                _updateFunctionCodecsConfiguration,
                _reduceFunctionConfiguration,
                _updateFunctionConfiguration,
                _mapOutputPipelineDataConverterConfiguration,
                _mapInputPipelineDataConverterConfiguration,
                _partitionedDatasetConfiguration,
                _resultHandlerConfiguration,
                _perMapConfigGeneratorConfig,
                _numberOfMappers,
                _memoryPerMapper,
                _updateTaskMemory,
                _coresPerMapper,
                _updateTaskCores,
                _jobName,
                _invokeGC);
        }
    }
}


text:
layout: post
title:  "Competition in the science year 2015 "citizens create the city of tomorrow""
weight:   6
thumbnail: /images/awards/buergerschaffenwissen_logo.png
type: award
categories: awards
---
"As part of the science year 2015 citizen science projects were invited to look for solutions and pursue issues of urban planning and the usage of urban areas."

Bürger schaffen Wissen


text:
package com.bazaarvoice.emodb.common.cassandra;

import com.google.common.base.Optional;
import io.dropwizard.util.Size;

/**
 * Configuration for a Cassandra keyspace.  The configuration can optionally be used to create a private connection
 * pool by use only by the keyspace.  By default it uses a connection pool shared by all keyspaces in the cluster.
 */
public class KeyspaceConfiguration implements ConnectionPoolConfiguration {

    private String _keyspaceMetric;

    /**
     * Custom connection pool configurations.  Overriding any value results in this keyspace using its own custom
     * connection pool separate from the cluster.  Leaving all values absent results in this keyspace using a
     * connection pool shared with any other keyspaces in the cluster not using a custom pool.
     */
    private Optional<Integer> _initialConnectionsPerHost = Optional.absent();
    private Optional<Integer> _maxConnectionsPerHost = Optional.absent();
    private Optional<Integer> _coreConnectionsPerHost = Optional.absent();
    private Optional<Integer> _socketTimeout = Optional.absent();
    private Optional<Integer> _connectTimeout = Optional.absent();
    private Optional<Integer> _maxFailoverCount = Optional.absent();
    private Optional<Integer> _connectionLimiterWindowSize = Optional.absent();
    private Optional<Integer> _connectionLimiterMaxPendingCount = Optional.absent();
    private Optional<Integer> _maxPendingConnectionsPerHost = Optional.absent();
    private Optional<Integer> _maxBlockedThreadsPerHost = Optional.absent();
    private Optional<Integer> _maxTimeoutCount = Optional.absent();
    private Optional<Integer> _timeoutWindow = Optional.absent();
    private Optional<Integer> _retrySuspendWindow = Optional.absent();
    private Optional<Integer> _retryDelaySlice = Optional.absent();
    private Optional<Integer> _retryMaxDelaySlice = Optional.absent();
    private Optional<Integer> _maxTimeoutWhenExhausted = Optional.absent();
    private Optional<Size> _maxThriftFrameSize = Optional.absent();

    public String getKeyspaceMetric() {
        return _keyspaceMetric;
    }

    public KeyspaceConfiguration setKeyspaceMetric(String keyspaceMetric) {
        _keyspaceMetric = keyspaceMetric;
        return this;
    }

    @Override
    public Optional<Integer> getInitialConnectionsPerHost() {
        return _initialConnectionsPerHost;
    }

    public KeyspaceConfiguration setInitialConnectionsPerHost(Optional<Integer> initialConnectionsPerHost) {
        _initialConnectionsPerHost = initialConnectionsPerHost;
        return this;
    }

    @Override
    public Optional<Integer> getMaxConnectionsPerHost() {
        return _maxConnectionsPerHost;
    }

    public KeyspaceConfiguration setMaxConnectionsPerHost(Optional<Integer> maxConnectionsPerHost) {
        _maxConnectionsPerHost = maxConnectionsPerHost;
        return this;
    }

    @Override
    public Optional<Integer> getCoreConnectionsPerHost() {
        return _coreConnectionsPerHost;
    }

    public KeyspaceConfiguration setCoreConnectionsPerHost(Optional<Integer> coreConnectionsPerHost) {
        _coreConnectionsPerHost = coreConnectionsPerHost;
        return this;
    }

    @Override
    public Optional<Integer> getSocketTimeout() {
        return _socketTimeout;
    }

    public KeyspaceConfiguration setSocketTimeout(Optional<Integer> socketTimeout) {
        _socketTimeout = socketTimeout;
        return this;
    }

    @Override
    public Optional<Integer> getConnectTimeout() {
        return _connectTimeout;
    }

    public KeyspaceConfiguration setConnectTimeout(Optional<Integer> connectTimeout) {
        _connectTimeout = connectTimeout;
        return this;
    }

    @Override
    public Optional<Integer> getMaxFailoverCount() {
        return _maxFailoverCount;
    }

    public KeyspaceConfiguration setMaxFailoverCount(Optional<Integer> maxFailoverCount) {
        _maxFailoverCount = maxFailoverCount;
        return this;
    }

    @Override
    public Optional<Integer> getConnectionLimiterWindowSize() {
        return _connectionLimiterWindowSize;
    }

    public KeyspaceConfiguration setConnectionLimiterWindowSize(Optional<Integer> connectionLimiterWindowSize) {
        _connectionLimiterWindowSize = connectionLimiterWindowSize;
        return this;
    }

    @Override
    public Optional<Integer> getConnectionLimiterMaxPendingCount() {
        return _connectionLimiterMaxPendingCount;
    }

    public KeyspaceConfiguration setConnectionLimiterMaxPendingCount(Optional<Integer> connectionLimiterMaxPendingCount) {
        _connectionLimiterMaxPendingCount = connectionLimiterMaxPendingCount;
        return this;
    }

    @Override
    public Optional<Integer> getMaxPendingConnectionsPerHost() {
        return _maxPendingConnectionsPerHost;
    }

    public KeyspaceConfiguration setMaxPendingConnectionsPerHost(Optional<Integer> maxPendingConnectionsPerHost) {
        _maxPendingConnectionsPerHost = maxPendingConnectionsPerHost;
        return this;
    }

    @Override
    public Optional<Integer> getMaxBlockedThreadsPerHost() {
        return _maxBlockedThreadsPerHost;
    }

    public KeyspaceConfiguration setMaxBlockedThreadsPerHost(Optional<Integer> maxBlockedThreadsPerHost) {
        _maxBlockedThreadsPerHost = maxBlockedThreadsPerHost;
        return this;
    }

    @Override
    public Optional<Integer> getMaxTimeoutCount() {
        return _maxTimeoutCount;
    }

    public KeyspaceConfiguration setMaxTimeoutCount(Optional<Integer> maxTimeoutCount) {
        _maxTimeoutCount = maxTimeoutCount;
        return this;
    }

    @Override
    public Optional<Integer> getTimeoutWindow() {
        return _timeoutWindow;
    }

    public KeyspaceConfiguration setTimeoutWindow(Optional<Integer> timeoutWindow) {
        _timeoutWindow = timeoutWindow;
        return this;
    }

    @Override
    public Optional<Integer> getRetrySuspendWindow() {
        return _retrySuspendWindow;
    }

    public KeyspaceConfiguration setRetrySuspendWindow(Optional<Integer> retrySuspendWindow) {
        _retrySuspendWindow = retrySuspendWindow;
        return this;
    }

    @Override
    public Optional<Integer> getRetryDelaySlice() {
        return _retryDelaySlice;
    }

    public KeyspaceConfiguration setRetryDelaySlice(Optional<Integer> retryDelaySlice) {
        _retryDelaySlice = retryDelaySlice;
        return this;
    }

    @Override
    public Optional<Integer> getRetryMaxDelaySlice() {
        return _retryMaxDelaySlice;
    }

    public KeyspaceConfiguration setRetryMaxDelaySlice(Optional<Integer> retryMaxDelaySlice) {
        _retryMaxDelaySlice = retryMaxDelaySlice;
        return this;
    }

    @Override
    public Optional<Integer> getMaxTimeoutWhenExhausted() {
        return _maxTimeoutWhenExhausted;
    }

    public KeyspaceConfiguration setMaxTimeoutWhenExhausted(Optional<Integer> maxTimeoutWhenExhausted) {
        _maxTimeoutWhenExhausted = maxTimeoutWhenExhausted;
        return this;
    }

    @Override
    public Optional<Size> getMaxThriftFrameSize() {
        return _maxThriftFrameSize;
    }

    public KeyspaceConfiguration setMaxThriftFrameSize(Optional<Size> maxThriftFrameSize) {
        _maxThriftFrameSize = maxThriftFrameSize;
        return this;
    }

    public boolean useSharedConnectionPool() {
        return !(getInitialConnectionsPerHost().isPresent() ||
                getMaxConnectionsPerHost().isPresent() ||
                getSocketTimeout().isPresent() ||
                getConnectTimeout().isPresent() ||
                getMaxFailoverCount().isPresent() ||
                getConnectionLimiterWindowSize().isPresent() ||
                getConnectionLimiterMaxPendingCount().isPresent() ||
                getMaxPendingConnectionsPerHost().isPresent() ||
                getMaxBlockedThreadsPerHost().isPresent() ||
                getMaxTimeoutCount().isPresent() ||
                getTimeoutWindow().isPresent() ||
                getRetrySuspendWindow().isPresent() ||
                getRetryDelaySlice().isPresent() ||
                getRetryMaxDelaySlice().isPresent() ||
                getMaxTimeoutWhenExhausted().isPresent() ||
                getMaxThriftFrameSize().isPresent());
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxBaseModNotificationsTemplate extends BxBaseModGeneralTemplate
{
    function __construct(&$oConfig, &$oDb)
    {
        parent::__construct($oConfig, $oDb);
    }

    public function getAddedCss($sType = '', $bDynamic = false)
    {
        $mixedResult = $this->addCss(array(
            'view.css',
            'view-media-tablet.css',
            'view-media-desktop.css',
        ), $bDynamic);

        if($bDynamic)
            return $mixedResult;
    }

    public function getAddedJs($sType = '', $bDynamic = false)
    {
        $mixedResult = $this->addJs(array(
            'jquery.anim.js',
            'main.js',
            'view.js',
        ), $bDynamic);

        if($bDynamic)
            return $mixedResult;
    }

    public function getCssJs($sType = '', $bDynamic = false)
    {
        return $this->getAddedCss($sType, $bDynamic) . $this->getAddedJs($sType, $bDynamic);
    }

    public function getJsCode($sType, $aParams = array(), $bWrap = true, $bDynamic = false)
    {
        $oModule = $this->getModule();

        $aParams = array_merge(array(
            'iOwnerId' => $oModule->_iOwnerId,
            'sAnimationEffect' => $this->_oConfig->getAnimationEffect(),
            'iAnimationSpeed' => $this->_oConfig->getAnimationSpeed(),
            'aHtmlIds' => $this->_oConfig->getHtmlIds($sType)
        ), $aParams);

        return $this->getCssJs($sType, $bDynamic) . parent::getJsCode($sType, $aParams, $bWrap);
    }

    public function getUnit(&$aEvent, $aBrowseParams = array())
    {
    	return '';
    }

    function unit($aData, $isCheckPrivateContent = true, $sTemplateName = 'unit.html')
    {
    	$this->getCssJs();

    	if($sTemplateName == 'unit.html')
    		return $this->getUnit($aData);

        $oModule = $this->getModule();
        $CNF = &$this->_oConfig->CNF;

        if ($isCheckPrivateContent && CHECK_ACTION_RESULT_ALLOWED !== ($sMsg = $oModule->isAllowedView($aData))) {
            $aVars = array (
                'summary' => $sMsg,
            );
            return $this->parseHtmlByName('unit_private.html', $aVars);
        }

        list($sAuthorName, $sAuthorUrl, $sAuthorIcon) = $oModule->getUserInfo($aData['object_id']);
        $bAuthorIcon = !empty($sAuthorIcon);

        // generate html
        $aVars = array (
            'id' => $aData['id'],
            'author' => $sAuthorName,
            'author_url' => $sAuthorUrl,
            'title' => bx_process_output($aData['title'], BX_DATA_HTML),
        	'item_url' => $this->_oConfig->getItemViewUrl($aData),
            'item_date' => bx_time_js($aData['date'], BX_FORMAT_DATE),
            'module_name' => _t($CNF['T']['txt_sample_single_ext']),
            'ts' => $aData['date'],
            'bx_if:show_icon' => array(
                'condition' => $bAuthorIcon,
                'content' => array(
                    'author_icon' => $sAuthorIcon
                )
            ),
            'bx_if:show_icon_empty' => array(
                'condition' => !$bAuthorIcon,
                'content' => array()
            ),
        );

        return $this->parseHtmlByName($sTemplateName, $aVars);
    }

}

/** @} */


text:
.. Sound Machine documentation master file, created by
   sphinx-quickstart on Thu Jun  2 23:13:26 2016.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Sound Machine!
=========================

Sound Machine is a python library for sound and music synthesis.
It uses the `sounddevice <http://python-sounddevice.readthedocs.io/en/0.3.3/>`_ library as an
output backend, but it can also write to wave files and output raw sample data.

Sound Machine is designed to make it very very easy to synthesize sounds and construct melodies,
once you understand its interfaces.

Install with ``pip install sound-machine``, view source at `github <https://github.com/rhelmot/sound-machine>`_

Contents:

.. toctree::
   :maxdepth: 2
   :glob:

   guide
   api

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
'''
    Scrape and ingest new otc transactions from FINRA otc bulletin board

    ** Note **
    This runs prospectively using the --most-recent argument
'''
import argparse

from modules.scrape_otc_raw import OTC_SCRAPE
from generic.generic_meta_enrich import GENERIC_META_ENRICH
from generic.logger import LOGGER

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='ingest_otc')
    parser.add_argument('--date', type=str, dest='date', action="store")
    parser.add_argument('--expected', type=str, dest='expected', action="store")
    parser.add_argument('--log-file',
                        type=str,
                        dest='log_file',
                        action='store',
                        required=True)
    parser.add_argument("--from-scratch",
                        action='store_true')
    parser.add_argument("--most-recent",
                        action='store_true')
    parser.add_argument("--config-path",
                        type=str,
                        action='store',
                        default='../config.json')
    parser.add_argument("--index",
                        type=str,
                        action='store')

    args = parser.parse_args()

    logger = LOGGER('scrape_otc', args.log_file).create_parent()

    logger.info('Starting otc scrape')
    otcs = OTC_SCRAPE(args)
    gme = GENERIC_META_ENRICH(args, 'scrape_otc')

    doc_count = otcs.main()
    gme.main(doc_count, 'ernest_otc_raw_cat')
    logger.info('Ending otc scrape')


text:
package kafka.producer

/**
 * A partitioner controls the mapping between user-provided keys and kafka partitions. Users can implement a custom
 * partitioner to change this mapping.
 *
 * Implementations will be constructed via reflection and are required to have a constructor that takes a single
 * VerifiableProperties instance--this allows passing configuration properties into the partitioner implementation.
 */
trait Partitioner {
  /**
   * Uses the key to calculate a partition bucket id for routing
   * the data to the appropriate broker partition
   * @return an integer between 0 and numPartitions-1
   */
  def partition(key: Any, numPartitions: Int): Int
}


text:
package main

import "fmt"

// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan int) {
	for i := 2; ; i++ {
		ch <- i  // Send 'i' to channel 'ch'.
	}
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
func filter(in, out chan int, prime int) {
	for {
		i := <-in;  // Receive value of new variable 'i' from 'in'.
		if i % prime != 0 {
			out <- i  // Send 'i' to channel 'out'.
		}
	}
}

// The prime sieve: Daisy-chain filter processes together.
func main() {
	ch := make(chan int);  // Create a new channel.
	go generate(ch);  // Start generate() as a goroutine.
	for {
		prime := <-ch;
		fmt.Println(prime);
		ch1 := make(chan int);
		go filter(ch, ch1, prime);
		ch = ch1
	}
}


text: [Online Version](https://rawgit.com/back2dos/wwx2014/master/index.html)


text:
<?php

/**
 * ツイートログのデータを削除する。
 *
 * @package VizualizerTwitter
 * @author Naohisa Minagawa <info@vizualizer.jp>
 */
class VizualizerTwitter_Module_Tweet_Log_Delete extends Vizualizer_Plugin_Module_Delete
{

    function execute($params)
    {
        $post = Vizualizer::request();
        if($post["delete"]){
            print_r($post["tweet_log_id"]);
            if(!is_array($post["tweet_log_id"])){
                $post->set("tweet_log_id", array($post["tweet_log_id"]));
            }
            $tweetLogIds = $post["tweet_log_id"];
            print_r($post["tweet_log_id"]);
            foreach($tweetLogIds as $tweetLogId){
                $post->set("delete", "1");
                $post->set("tweet_log_id", $tweetLogId);
                $loader = new Vizualizer_Plugin("twitter");
                $tweetLog = $loader->loadModel("TweetLog");
                $tweetLog->findByPrimaryKey($tweetLogId);
                $account = $tweetLog->account();
                $twitterId = $tweetLog->twitter_id;
                print_r($post);
                $this->executeImpl("Twitter", "TweetLog", "tweet_log_id");
                $account->getTwitter()->statuses_destroy_ID(array("id" => $twitterId));
            }
        }
    }
}