Installs an after-prepare build hook to copy the app/App_Resources/Android/google-services.json to platform/android on build.
Installs before-checkForChange build hook to detect changes in environment and copy GoogleServices.plist on build.
425956
function writeGoogleServiceCopyHook() {
  // Install after-prepare hook
  console.log("Install google-service.json after-prepare copy hook.");
  try {
    var afterPrepareScriptContent =
        `
var path = require("path");
var fs = require("fs");

module.exports = function($logger, $projectData, hookArgs) {

return new Promise(function(resolve, reject) {

        /* Decide whether to prepare for dev or prod environment */

        var isReleaseBuild = (hookArgs.appFilesUpdaterOptions && hookArgs.appFilesUpdaterOptions.release) ? true : false;
        var validProdEnvs = ['prod','production'];
        var isProdEnv = false; // building with --env.prod or --env.production flag

        if (hookArgs.platformSpecificData.env) {
            Object.keys(hookArgs.platformSpecificData.env).forEach((key) => {
                if (validProdEnvs.indexOf(key)>-1) { isProdEnv=true; }
            });
        }

        var buildType = isReleaseBuild || isProdEnv ? 'production' : 'development';

        /* Create info file in platforms dir so we can detect changes in environment and force prepare if needed */

        var npfInfoPath = path.join($projectData.platformsDir, hookArgs.platform.toLowerCase(), ".pluginfirebaseinfo");
        var npfInfo = {
            buildType: buildType,
        };

        try { fs.writeFileSync(npfInfoPath, JSON.stringify(npfInfo)); }
        catch (err) {
            $logger.info('nativescript-plugin-firebase: unable to create '+npfInfoPath+', prepare will be forced next time!');
        }


        /* Handle preparing of Google Services files */

        if (hookArgs.platform.toLowerCase() === 'android') {
            var destinationGoogleJson = path.join($projectData.platformsDir, "android", "app", "google-services.json");
            var destinationGoogleJsonAlt = path.join($projectData.platformsDir, "android", "google-services.json");
            var sourceGoogleJson = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json");
            var sourceGoogleJsonProd = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.prod");
            var sourceGoogleJsonDev = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.dev");

            // ensure we have both dev/prod versions so we never overwrite singlular google-services.json
            if (fs.existsSync(sourceGoogleJsonProd) && fs.existsSync(sourceGoogleJsonDev)) {
                if (buildType==='production') { sourceGoogleJson = sourceGoogleJsonProd; } // use prod version
                else { sourceGoogleJson = sourceGoogleJsonDev; } // use dev version
            }

            // copy correct version to destination
            if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJson))) {
                $logger.out("Copy " + sourceGoogleJson + " to " + destinationGoogleJson + ".");
                fs.writeFileSync(destinationGoogleJson, fs.readFileSync(sourceGoogleJson));
                resolve();
            } else if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJsonAlt))) {
                // NativeScript < 4 doesn't have the 'app' folder
                $logger.out("Copy " + sourceGoogleJson + " to " + destinationGoogleJsonAlt + ".");
                fs.writeFileSync(destinationGoogleJsonAlt, fs.readFileSync(sourceGoogleJson));
                resolve();
            } else {
                $logger.warn("Unable to copy google-services.json.");
                reject();
            }
        } else if (hookArgs.platform.toLowerCase() === 'ios') {
            // we have copied our GoogleService-Info.plist during before-checkForChanges hook, here we delete it to avoid changes in git
            var destinationGooglePlist = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");
            var sourceGooglePlistProd = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
            var sourceGooglePlistDev = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");

            // if we have both dev/prod versions, let's remove GoogleService-Info.plist in destination dir
            if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
                if (fs.existsSync(destinationGooglePlist)) { fs.unlinkSync(destinationGooglePlist); }
                resolve();
            } else { // single GoogleService-Info.plist modus
                resolve();
            }
        } else {
            resolve();
        }
    });
};
`;
    var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-copy-google-services.js");
    var afterPrepareDirPath = path.dirname(scriptPath);
    var hooksDirPath = path.dirname(afterPrepareDirPath);
    if (!fs.existsSync(afterPrepareDirPath)) {
      if (!fs.existsSync(hooksDirPath)) {
        fs.mkdirSync(hooksDirPath);
      }
      fs.mkdirSync(afterPrepareDirPath);
    }
    fs.writeFileSync(scriptPath, afterPrepareScriptContent);
  } catch (e) {
    console.log("Failed to install google-service.json after-prepare copy hook.");
    console.log(e);
  }

  /*
     Install before-checkForChanges hook
  */

  console.log("Install google-service.json before-checkForChanges copy hook.");
  try {
    var beforeCheckForChangesContent =
        `
var path = require("path");
var fs = require("fs");

module.exports = function($logger, $projectData, hookArgs) {
    return new Promise(function(resolve, reject) {

        /* Decide whether to prepare for dev or prod environment */

        var isReleaseBuild = hookArgs['checkForChangesOpts']['projectData']['$options']['argv']['release'] || false;
        var validProdEnvs = ['prod','production'];
        var isProdEnv = false; // building with --env.prod or --env.production flag

        var env = hookArgs['checkForChangesOpts']['projectData']['$options']['argv']['env'];
        if (env) {
            Object.keys(env).forEach((key) => {
                if (validProdEnvs.indexOf(key)>-1) { isProdEnv=true; }
            });
        }

        var buildType = isReleaseBuild || isProdEnv ? 'production' : 'development';

        /*
            Detect if we have nativescript-plugin-firebase temp file created during after-prepare hook, so we know
            for which environment {development|prod} the project was prepared. If needed, we delete the NS .nsprepareinfo
            file so we force a new prepare
        */
        var platform = hookArgs['checkForChangesOpts']['platform'].toLowerCase(); // ios | android
        var platformsDir = hookArgs['checkForChangesOpts']['projectData']['platformsDir'];
        var appResourcesDirectoryPath = hookArgs['checkForChangesOpts']['projectData']['appResourcesDirectoryPath'];
        var forcePrepare = true; // whether to force NS to run prepare, defaults to true
        var npfInfoPath = path.join(platformsDir, platform, ".pluginfirebaseinfo");
        var nsPrepareInfoPath = path.join(platformsDir, platform, ".nsprepareinfo");
        var copyPlistOpts = { platform, appResourcesDirectoryPath, buildType, $logger }

        if (fs.existsSync(npfInfoPath)) {
            var npfInfo = undefined;
            try { npfInfo = JSON.parse(fs.readFileSync(npfInfoPath, 'utf8')); }
            catch (e) { $logger.info('nativescript-plugin-firebase: error reading '+npfInfoPath); }

            if (npfInfo && npfInfo.hasOwnProperty('buildType') && npfInfo.buildType===buildType) {
                $logger.info('nativescript-plugin-firebase: building for same environment, not forcing prepare.');
                forcePrepare=false;
            }
        } else { $logger.info('nativescript-plugin-firebase: '+npfInfoPath+' not found, forcing prepare!'); }

        if (forcePrepare) {
            $logger.info('nativescript-plugin-firebase: running release build or change in environment detected, forcing prepare!');

            if (fs.existsSync(npfInfoPath)) { fs.unlinkSync(npfInfoPath); }
            if (fs.existsSync(nsPrepareInfoPath)) { fs.unlinkSync(nsPrepareInfoPath); }

            if (copyPlist(copyPlistOpts)) { resolve(); } else { reject(); }
        } else { resolve(); }
    });
};

/*
    Handle preparing of Google Services files for iOS
*/
var copyPlist = function(copyPlistOpts) {
    if (copyPlistOpts.platform === 'android') { return true; }
    else if (copyPlistOpts.platform === 'ios') {
        var sourceGooglePlistProd = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
        var sourceGooglePlistDev = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");
        var destinationGooglePlist = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");

        // if we have both dev/prod versions, we copy (or overwrite) GoogleService-Info.plist in destination dir
        if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
            if (copyPlistOpts.buildType==='production') { // use prod version
                copyPlistOpts.$logger.out("nativescript-plugin-firebase: copy " + sourceGooglePlistProd + " to " + destinationGooglePlist + ".");
                fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistProd));
                return true;
            } else { // use dev version
                copyPlistOpts.$logger.out("nativescript-plugin-firebase: copy " + sourceGooglePlistDev + " to " + destinationGooglePlist + ".");
                fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistDev));
                return true;
            }
        } else if (!fs.existsSync(destinationGooglePlist)) { // single GoogleService-Info.plist modus but missing`;
    if (externalPushClientOnly) {
      beforeCheckForChangesContent += `
            return true; // this is a push-only project, so this is allowed`;
    } else {
      beforeCheckForChangesContent += `
            copyPlistOpts.$logger.warn("nativescript-plugin-firebase: " + destinationGooglePlist + " does not exist. Please follow the installation instructions from the documentation");
            return false;`;
    }
    beforeCheckForChangesContent += `
        } else {
            return true; // single GoogleService-Info.plist modus
        }
    } else { return true; }
}
`;
    var scriptPath = path.join(appRoot, "hooks", "before-checkForChanges", "firebase-copy-google-services.js");
    var afterPrepareDirPath = path.dirname(scriptPath);
    var hooksDirPath = path.dirname(afterPrepareDirPath);
    if (!fs.existsSync(afterPrepareDirPath)) {
      if (!fs.existsSync(hooksDirPath)) {
        fs.mkdirSync(hooksDirPath);
      }
      fs.mkdirSync(afterPrepareDirPath);
    }
    fs.writeFileSync(scriptPath, beforeCheckForChangesContent);
  } catch (e) {
    console.log("Failed to install google-service.json before-checkForChanges copy hook.");
    console.log(e);
  }
}
29272
function runRebase(options) {
    const platforms = detectPorting(options.platform);
    if (platforms.length <= 0) {
        return Promise.resolve();
    } else {
        const target = platforms[0];
        options.platform = target;
        runBuild(options)
        .then(() => {
            if ('dev' !== target) {
                const srcDir = path.join(__dirname, '..', config.dir.pkg, config.dir.porting + '_' + target);
                const dstDir = path.join(__dirname, '..', config.dir.pkg, config.dir.porting);
                if (fs.existsSync(srcDir)) {
                    fs.moveSync(srcDir, dstDir);
                }
            }
        })
        .catch((reason) => {
            console.error(reason);
            process.exit(1);
        });
    }
}
676219
void putApp(Context context) {
    try {
      PackageManager packageManager = context.getPackageManager();
      PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
      Map<String, Object> app = createMap();
      putUndefinedIfNull(app, APP_NAME_KEY, packageInfo.applicationInfo.loadLabel(packageManager));
      putUndefinedIfNull(app, APP_VERSION_KEY, packageInfo.versionName);
      putUndefinedIfNull(app, APP_NAMESPACE_KEY, packageInfo.packageName);
      app.put(APP_BUILD_KEY, String.valueOf(packageInfo.versionCode));
      put(APP_KEY, app);
    } catch (PackageManager.NameNotFoundException e) {
      // ignore
    }
  }
602045
def after_init_app(self, app: FlaskUnchained):
        
        self.set_json_encoder(app)
        app.before_first_request(self.register_model_resources)
752062
def _build_app(args, extra_args):
    

    if not args.remote:
        # LOCAL BUILD

        try:
            output = build_and_upload_locally(
                args.src_dir,
                args.mode,
                overwrite=args.overwrite,
                archive=args.archive,
                publish=args.publish,
                destination_override=args.destination,
                version_override=args.version_override,
                bill_to_override=args.bill_to,
                use_temp_build_project=args.use_temp_build_project,
                do_parallel_build=args.parallel_build,
                do_version_autonumbering=args.version_autonumbering,
                do_try_update=args.update,
                dx_toolkit_autodep=args.dx_toolkit_autodep,
                do_check_syntax=args.check_syntax,
                ensure_upload=args.ensure_upload,
                force_symlinks=args.force_symlinks,
                dry_run=args.dry_run,
                confirm=args.confirm,
                return_object_dump=args.json,
                region=args.region,
                **extra_args
                )

            if output is not None and args.run is None:
                print(json.dumps(output))
        except dxpy.app_builder.AppBuilderException as e:
            # AppBuilderException represents errors during app or applet building
            # that could reasonably have been anticipated by the user.
            print("Error: %s" % (e.args,), file=sys.stderr)
            sys.exit(3)
        except dxpy.exceptions.DXAPIError as e:
            print("Error: %s" % (e,), file=sys.stderr)
            sys.exit(3)

        if args.dry_run:
            return None

        return output['id']

    else:
        # REMOTE BUILD

        try:
            app_json = _parse_app_spec(args.src_dir)
            _check_suggestions(app_json, publish=args.publish)
            _verify_app_source_dir(args.src_dir, args.mode)
            if args.mode == "app" and not args.dry_run:
                dxpy.executable_builder.verify_developer_rights('app-' + app_json['name'])
        except dxpy.app_builder.AppBuilderException as e:
            print("Error: %s" % (e.args,), file=sys.stderr)
            sys.exit(3)

        # The following flags might be useful in conjunction with
        # --remote. To enable these, we need to learn how to pass these
        # options through to the interior call of dx_build_app(let).
        if args.dry_run:
            parser.error('--remote cannot be combined with --dry-run')
        if args.overwrite:
            parser.error('--remote cannot be combined with --overwrite/-f')
        if args.archive:
            parser.error('--remote cannot be combined with --archive/-a')

        # The following flags are probably not useful in conjunction
        # with --remote.
        if args.json:
            parser.error('--remote cannot be combined with --json')
        if not args.use_temp_build_project:
            parser.error('--remote cannot be combined with --no-temp-build-project')

        if isinstance(args.region, list) and len(args.region) > 1:
            parser.error('--region can only be specified once for remote builds')
        region = args.region[0] if args.region is not None else None

        more_kwargs = {}
        if args.version_override:
            more_kwargs['version_override'] = args.version_override
        if args.bill_to:
            more_kwargs['bill_to_override'] = args.bill_to
        if not args.version_autonumbering:
            more_kwargs['do_version_autonumbering'] = False
        if not args.update:
            more_kwargs['do_try_update'] = False
        if not args.parallel_build:
            more_kwargs['do_parallel_build'] = False
        if not args.check_syntax:
            more_kwargs['do_check_syntax'] = False

        return _build_app_remote(args.mode, args.src_dir, destination_override=args.destination,
                                 publish=args.publish, dx_toolkit_autodep=args.dx_toolkit_autodep,
                                 region=region, watch=args.watch, **more_kwargs)
737495
def post_run(self, outline=False, dump=False, *args, **kwargs):
        """"""
        hooks = self.context.config.post_build
        handle_hooks(
            "post_build",
            hooks,
            self.provider,
            self.context,
            dump,
            outline
        )
447883
function prepBuildFiles(root) {
    var propertiesObj = readProjectProperties(path.join(PLATFORM_DIR, 'project.properties'));
    var subProjects = propertiesObj.libs;
    // Update dependencies within build.gradle.
    var buildGradle = fs.readFileSync(path.join(PLATFORM_DIR, 'plugin-build.gradle'), 'utf-8');
    var depsList = '';
    subProjects.forEach(function (p) {
        var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');
        depsList += 'debugCompile project(path: "' + libName + '", configuration: "debug")\n';
        depsList += 'releaseCompile project(path: "' + libName + '", configuration: "release")\n';
    });
    // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390
    var SYSTEM_LIBRARY_MAPPINGS = [
        [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],
        [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']
    ];
    propertiesObj.systemLibs.forEach(function (p) {
        var mavenRef;
        // It's already in gradle form if it has two ':'s
        if (/:.*:/.exec(p)) {
            mavenRef = p;
        } else {
            for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {
                var pair = SYSTEM_LIBRARY_MAPPINGS[i];
                if (pair[0].exec(p)) {
                    mavenRef = p.replace(pair[0], pair[1]);
                    break;
                }
            }
            if (!mavenRef) {
                throw new error('Unsupported system library (does not work with gradle): ' + p);
            }
        }
        depsList += 'compile "' + mavenRef + '"\n';
    });
    buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + '    $2');
    var includeList = '';
    propertiesObj.gradleIncludes.forEach(function (includePath) {
        includeList += 'apply from: "$projectDir/../../platforms/android/' + includePath + '"\n';
    });
    buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');
    fs.writeFileSync(path.join(PLATFORM_DIR, 'plugin-build.gradle'), buildGradle);
}
610341
@Override
    public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) {
        Map<String, String> envVars = returnEnvironmentVars(build, listener);
        if (envVars != null) {
            LOGGER.log(Level.FINE, "Job: " + build.getFullDisplayName() + " Attempting to send GitHub commit status");

            try {
                returnGhprbSimpleStatus(envVars).onEnvironmentSetup(build, listener, repo);
            } catch (GhprbCommitStatusException e) {
                e.printStackTrace();
            }
        }

        return new Environment() {
        };
    }
57797
function copyHooks() {
		var src = path.join(__dirname, 'hooks');
		var dest = path.join(process.env.PWD, 'hooks');

		return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json'))
			.then(function () {
				memFsEditor.copyTpl(src, dest, options);

				return pify(memFsEditor.commit.bind(memFsEditor))();
			})
			.then(function () {
				// Make all the scripts executable in the Cordova project
				fs.readdirSync(src).forEach(function (hook) {
					var hookPath = path.join(dest, hook);

					fs.readdirSync(hookPath).forEach(function (script) {
						fs.chmodSync(path.join(hookPath, script), '755');
					});
				});
			});
	}
806384
function buildAndRun(args) {
  process.chdir(path.join(args.root, 'android'));
  try {
    adb.getDevices().map((device) => tryRunAdbReverse(device));

    const cmd = process.platform.startsWith('win')
      ? 'gradlew.bat'
      : './gradlew';

    const gradleArgs = [];
    if (args.variant) {
      gradleArgs.push('install' +
        args.variant[0].toUpperCase() + args.variant.slice(1)
      );
    } else if (args.flavor) {
      console.warn(chalk.yellow(
        '--flavor has been deprecated. Use --variant instead'
      ));
      gradleArgs.push('install' +
        args.flavor[0].toUpperCase() + args.flavor.slice(1)
      );
    } else {
      gradleArgs.push('installDebug');
    }

    if (args.installDebug) {
      gradleArgs.push(args.installDebug);
    }

    console.log(chalk.bold(
      `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join(' ')}...`
    ));

    child_process.execFileSync(cmd, gradleArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n' +
      'Make sure you have an Android emulator running or a device connected and have\n' +
      'set up your Android development environment:\n' +
      'https://facebook.github.io/react-native/docs/android-setup.html'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    return Promise.reject();
  }

  try {
    const packageName = fs.readFileSync(
      'app/src/main/AndroidManifest.xml',
      'utf8'
    ).match(/package="(.+?)"/)[1];

    const adbPath = getAdbPath();

    const devices = adb.getDevices();

    if (devices && devices.length > 0) {
      devices.forEach((device) => {

        const adbArgs = ['-s', device, 'shell', 'am', 'start', '-n', packageName + '/.MainActivity'];

        console.log(chalk.bold(
          `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`
        ));

        child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
      });
    } else {
      // If we cannot execute based on adb devices output, fall back to
      // shell am start
      const fallbackAdbArgs = [
        'shell', 'am', 'start', '-n', packageName + '/.MainActivity'
      ];
      console.log(chalk.bold(
        `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`
      ));
      child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'});
    }

  } catch (e) {
    console.log(chalk.red(
      'adb invocation failed. Do you have adb in your PATH?'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    return Promise.reject();
  }
}
1180131
def prepare(self):
    
    self.src_folder = self.get_src_folder()
    st = os.stat('%s/gradlew' % self.path)
    os.chmod('%s/gradlew' % self.path, st.st_mode | stat.S_IEXEC)
1048382
def setup(build=True, installdir="MalmoPlatform"):
    """"""

    gradlew = './gradlew'
    if os.name == 'nt':
        gradlew = 'gradlew.bat'

    cwd = os.getcwd()
    os.chdir(installdir)
    os.chdir("Minecraft")
    try:
        # Create the version properties file.
        pathlib.Path("src/main/resources/version.properties").write_text("malmomod.version={}\n".format(malmo_version))
        # Optionally do a test build.
        if build:
            subprocess.check_call([gradlew, "setupDecompWorkspace", "build", "testClasses",
                                   "-x", "test", "--stacktrace", "-Pversion={}".format(malmo_version)])
        minecraft_dir = os.getcwd()
    finally:
        os.chdir(cwd)
    return minecraft_dir
503993
@SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    protected void onPrepareShow() {
        final int sdkVersion = android.os.Build.VERSION.SDK_INT;

        // Modify various attributes of the message TextView
        this.mTextView.setText(this.mStyle.message);
        this.mTextView.setTypeface(this.mTextView.getTypeface(), this.mStyle.messageTypefaceStyle);
        this.mTextView.setTextColor(this.mStyle.messageTextColor);
        this.mTextView.setTextSize(this.mStyle.messageTextSize);
        if (this.mStyle.messageIconResource > 0) {
            if (this.mStyle.messageIconPosition == Style.ICONPOSITION_LEFT) {
                this.mTextView.setCompoundDrawablesWithIntrinsicBounds(
                        this.mStyle.messageIconResource, 0, 0, 0);
            } else if (this.mStyle.messageIconPosition == Style.ICONPOSITION_TOP) {
                this.mTextView.setCompoundDrawablesWithIntrinsicBounds(
                        0, this.mStyle.messageIconResource, 0, 0);
            } else if (this.mStyle.messageIconPosition == Style.ICONPOSITION_RIGHT) {
                this.mTextView.setCompoundDrawablesWithIntrinsicBounds(
                        0, 0, this.mStyle.messageIconResource, 0);
            } else if (this.mStyle.messageIconPosition == Style.ICONPOSITION_BOTTOM) {
                this.mTextView.setCompoundDrawablesWithIntrinsicBounds(
                        0, 0, 0, this.mStyle.messageIconResource);
            }
        }

        // Handle depreciated API for setting the background
        if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
            this.mView.setBackground(BackgroundUtils.getBackground(this.mStyle, this.mStyle.color));
            // Give Lollipop devices a nice shadow (does not work with transparent backgrounds)
            if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) mView.setElevation(3f);
        } else this.mView.setBackgroundDrawable(BackgroundUtils.getBackground(this.mStyle, this.mStyle.color));

        // Make adjustments that are specific to Lollipop frames
        if (this.mStyle.frame == Style.FRAME_LOLLIPOP) {
            this.mTextView.setGravity(Gravity.START);

            // We are on a big screen device, show the SuperToast on the bottom left with padding
            if ((this.mContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
                    >= Configuration.SCREENLAYOUT_SIZE_LARGE) {
                this.mStyle.xOffset = BackgroundUtils.convertToDIP(12);
                this.mStyle.yOffset = BackgroundUtils.convertToDIP(12);
                this.mStyle.width = BackgroundUtils.convertToDIP(288);
                this.mStyle.gravity = Gravity.BOTTOM | Gravity.START;

                // Simple background shape with rounded corners
                final GradientDrawable gradientDrawable = new GradientDrawable();
                gradientDrawable.setCornerRadius(BackgroundUtils.convertToDIP(2));
                gradientDrawable.setColor(this.mStyle.color);

                // Handle depreciated API for setting the background
                if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) this.mView.setBackground(gradientDrawable);
                else this.mView.setBackgroundDrawable(gradientDrawable);

            // We are NOT on a big screen device, show the SuperToast on the bottom with NO padding
            } else {
                this.mStyle.yOffset = 0;
                this.mStyle.width = FrameLayout.LayoutParams.MATCH_PARENT;
            }
            
            // Set the priority color of the Lollipop frame if any
            if (this.mStyle.priorityColor != 0) {
                mView.findViewById(R.id.border).setVisibility(View.VISIBLE);
                mView.findViewById(R.id.border).setBackgroundColor(this.mStyle.priorityColor);
            }
        }
        // Used for PriorityQueue comparisons
        this.getStyle().timestamp = System.currentTimeMillis();
    }
80724
function createJsonPreprocessor(logger, basePath, config) {
  const log = logger.create('preprocessor.json');
  const conf = config || {};
  const stripPrefix = new RegExp(`^${(conf.stripPrefix || '')}`);

  return function(content, file, done) {
    log.debug('Processing "%s".', file.originalPath);

    // Build json path file.
    const jsonPath = file.originalPath
        .replace(`${basePath}/`, '')
        .replace(stripPrefix, '');

    const template = createTemplate(conf.varName || '__json__');

    // Update file path
    file.path = `${file.path}.js`;

    try {
      const o = JSON.parse(content.trim());
      done(util.format(template, jsonPath, JSON.stringify(o)));
    } catch (e) {
      log.error('Json representation of %s is not valid !', file.originalPath);
      done('');
    }
  };
}
318102
function updatePlatformConfig(platform) {
        var configData = parseConfigXml(platform),
            platformPath = path.join(rootdir, 'platforms', platform);

        _.each(configData, function (configItems, targetFileName) {
            var targetFilePath;
            if (platform === 'ios') {
                if (targetFileName.indexOf("Info.plist") > -1) {
                    targetFileName =  projectName + '-Info.plist';
                    targetFilePath = path.join(platformPath, projectName, targetFileName);
                    ensureBackup(targetFilePath, platform, targetFileName);
                    updateIosPlist(targetFilePath, configItems);
                }else if (targetFileName === "project.pbxproj") {
                    targetFilePath = path.join(platformPath, projectName + '.xcodeproj', targetFileName);
                    ensureBackup(targetFilePath, platform, targetFileName);
                    updateIosPbxProj(targetFilePath, configItems);
                    updateXCConfigs(configItems, platformPath);
                }

            } else if (platform === 'android' && targetFileName === 'AndroidManifest.xml') {
                targetFilePath = path.join(platformPath, targetFileName);
                ensureBackup(targetFilePath, platform, targetFileName);
                updateAndroidManifest(targetFilePath, configItems);
            } else if (platform === 'wp8') {
                targetFilePath = path.join(platformPath, targetFileName);
                ensureBackup(targetFilePath, platform, targetFileName);
                updateWp8Manifest(targetFilePath, configItems);
            }
        });
    }
1358449
def setup_app(app, api):
    """"""
    api.add_resource(
        KnwKBAllResource,
        '/api/knowledge'
    )
    api.add_resource(
        KnwKBResource,
        '/api/knowledge/<string:slug>'
    )
    api.add_resource(
        KnwKBMappingsResource,
        '/api/knowledge/<string:slug>/mappings'
    )
    api.add_resource(
        KnwKBMappingsToResource,
        '/api/knowledge/<string:slug>/mappings/to'
    )
    api.add_resource(
        KnwKBMappingsFromResource,
        '/api/knowledge/<string:slug>/mappings/from'
    )

    # for other urls, return "Method Not Allowed"
    api.add_resource(
        NotImplementedKnowledegeResource,
        '/api/knowledge/<string:slug>/<path:foo>'
    )
52344
function onInstall(event) {
  const preCacheApplication = async () => {
    const cache = await caches.open(CACHE_NAME);
    // Fetching these with addAll fails for CORS-restricted content, so we use
    // fetchAndCache with no-cors mode to work around it.

    // Optional resources: failure on these will NOT fail the Promise chain.
    // We will also not wait for them to be installed.
    for (const url of OPTIONAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      fetchAndCache(cache, request).catch(() => {});
    }

    // Critical resources: failure on these will fail the Promise chain.
    // The installation will not be complete until these are all cached.
    const criticalFetches = [];
    for (const url of CRITICAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      criticalFetches.push(fetchAndCache(cache, request));
    }
    return Promise.all(criticalFetches);
  };

  event.waitUntil(preCacheApplication());
}