答:
This uses a Set to check for the existence of each item in arr_must_exist.

It also uses a regex to get the "and" or the "," right, and a template literal to put the message together.

const arr_must_exist = ["1","2","3"];

function getMsg(arr_created) {
  const set = new Set(arr_created);
  const m = arr_must_exist.filter(s => !set.has(s))
                          .join(", ")
                          .replace(/, ([^,]+)$/, " and $1");

  return `Your choice ${m ? "must contain " + m : "is valid"}`;
}

console.log(getMsg(["2","4","7","8"]));
console.log(getMsg(["2","3","7","8"]));
console.log(getMsg(["4","5","7","8"]));
console.log(getMsg(["1","2","9","3"]));```

Title: How to compare two array and alert the result?

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)


来源: stackexchange

问:
C# Get Path/Filename by Handle (hWnd) 32 and 64bit
I got the following code to get path/filename by handle:

```<code>    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId);

    public static string GetProcessPath(IntPtr hwnd)
    {
        uint pid = 0;
        GetWindowThreadProcessId(hwnd, out pid);
        Process proc = Process.GetProcessById((int)pid);
        return proc.MainModule.FileName.ToString();
    }
</code>```

it works perfect in 32 bit but I get error in 64bit > "Only part of the ReadProcessMemory or WriteProcessMemory request was completed."
the project is compiled as x86 (platform target x86).

How can I fix it?

~Thanks Ron

答:
It appears from your question that you've currently compiled your program as a 32-bit application. However, the process you're trying to query (assuming you're running on a 64-bit version of Windows) is undoubtedly a 64-bit one. That kind of thing isn't allowed. Although you can run 32-bit applications on 64-bit versions of Windows, they run under the dedicated Windows on Windows (WOW64) subsystem. That's why you're getting a Win32Exception claiming that "Only part of a ReadProcessMemory or WriteProcessMemory request was completed". I agree it's not the most descriptive of error messages if you don't already know how Windows manages 32-bit and 64-bit processes, but armed with this knowledge it makes at least a little more sense.

The solution is to compile your application as a 64-bit application (x64), or for "Any CPU". Everything should work as expected after that. If possible, I suggest using "Any CPU", which will allow the application to run in 32-bit mode on 32-bit OSes and 64-bit on 64-bit OSes. Which is really the ideal set of circumstances, assuming that:

You've written your P/Invoke definitions correctly (i.e., using IntPtr where appropriate, instead of Integer).

You're not relying on 3rd-party DLLs (to which you don't have the source code) that were compiled as 32-bit.

ContentLicense: CC BY-SA 2.5

Body:
I got the following code to get path/filename by handle:

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId);

    public static string GetProcessPath(IntPtr hwnd)
    {
        uint pid = 0;
        GetWindowThreadProcessId(hwnd, out pid);
        Process proc = Process.GetProcessById((int)pid);
        return proc.MainModule.FileName.ToString();
    }

it works perfect in 32 bit but I get error in 64bit > "Only part of the ReadProcessMemory or WriteProcessMemory request was completed."
the project is compiled as x86 (platform target x86).

How can I fix it?

~Thanks Ron


问:
Android app crash with fatal error signal 4
I ran my app with 3 differents emulators:

API 25 and everything ok

API 21 and everything ok

API 19 and i got crash.

My app crash on api 19 emulator with error:

```<code>12-06 20:51:31.337    3105-3126/il.co.ngworkshop.studentGroup A/libc﹕ Fatal signal 4 (SIGILL) at 0x8a27f63c (code=1), thread 3126 (AsyncTask #2)
</code>```

I used cordova to create the android platform.

I try to found some clue with android studio debugger but nothing,
this is the logs i got when i ran android studio debugger:

https://pastebin.com/Akbxs1X5

This is the emulator crash:

and this is my manifest:

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="3000" android:versionName="0.0.3" package="il.co.ngworkshop.studentGroup" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:exported="true" android:launchMode="singleTop" android:name="com.gae.scaffolder.plugin.FCMPluginActivity">
            <intent-filter>
                <action android:name="FCM_PLUGIN_ACTIVITY" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <service android:name="com.gae.scaffolder.plugin.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="com.gae.scaffolder.plugin.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <receiver android:enabled="true" android:name="com.google.android.gms.analytics.AnalyticsReceiver">
            <intent-filter>
                <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
            </intent-filter>
        </receiver>
        <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.AnalyticsService" />
        <receiver android:enabled="true" android:exported="true" android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>
        <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.CampaignTrackingService" />
    </application>
    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
</code>```

build.gralde of cordovaLib module:

```<code>buildscript {
    repositories {
        mavenCentral()
        jcenter();
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'
    }

}
apply plugin: 'com.android.library'
ext {
    apply from: 'cordova.gradle'
    cdvCompileSdkVersion = privateHelpers.getProjectTarget()
    cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
android {
    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion
    publishNonDefault true
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
    defaultConfig {
        minSdkVersion 16
        versionCode 2
    }
    productFlavors {
    }
}

dependencies {
}
</code>```

build.gradle of android module:

```<code>/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

apply plugin: 'com.android.application'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'
    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    repositories {
        mavenCentral();
        jcenter()
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.14.1'
}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: 'CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
apply from: "cordova-plugin-crosswalk-webview/studentGroup-xwalk.gradle"
apply from: "cordova-plugin-fcm/studentGroup-FCMPlugin.gradle"
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }
    defaultConfig {
        applicationId privateHelpers.extractStringFromManifest("package")
        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
        minSdkVersion 16
        versionCode 2
    }
    lintOptions {
        abortOnError false;
    }
    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion
    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        productFlavors {
            armv7 {
                versionCode defaultConfig.versionCode * 10 + 2
                ndk {
                    abiFilters "armeabi-v7a", ""
                }
            }
            x86 {
                versionCode defaultConfig.versionCode * 10 + 4
                ndk {
                    abiFilters "x86", ""
                }
            }
            all {
                ndk {
                    abiFilters "all", ""
                }
            }
        }
    }
    /*

    ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!

    else if (!cdvVersionCode) {
      def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
      // Vary versionCode by the two most common API levels:
      // 14 is ICS, which is the lowest API level for many apps.
      // 20 is Lollipop, which is the lowest API level for the updatable system webview.
      if (minSdkVersion >= 20) {
        defaultConfig.versionCode += 9
      } else if (minSdkVersion >= 14) {
        defaultConfig.versionCode += 8
      }
    }
    */
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset"
                // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
    productFlavors {
        armv7 {
            minSdkVersion 16
            versionCode 2
        }
        x86 {
            minSdkVersion 16
            versionCode 2
        }
    }
}

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile project(path: 'CordovaLib', configuration: 'debug')
    releaseCompile project(path: 'CordovaLib', configuration: 'release')
    compile 'com.google.android.gms:play-services-analytics:9.0.0'
    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
        if (task.name == 'validateReleaseSigning' || task.name == 'validateSigningRelease') {
            promptForReleaseKeyPassword()
        }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}
</code>```

答:
In build.gradle of android Project, Mention minSdkVersion 19

```<code>android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "your_package_name"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I ran my app with 3 differents emulators:

API 25 and everything ok

API 21 and everything ok

API 19 and i got crash.

My app crash on api 19 emulator with error:

12-06 20:51:31.337    3105-3126/il.co.ngworkshop.studentGroup A/libc﹕ Fatal signal 4 (SIGILL) at 0x8a27f63c (code=1), thread 3126 (AsyncTask #2)

I used cordova to create the android platform.

I try to found some clue with android studio debugger but nothing,
this is the logs i got when i ran android studio debugger:

https://pastebin.com/Akbxs1X5

This is the emulator crash:

and this is my manifest:

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="3000" android:versionName="0.0.3" package="il.co.ngworkshop.studentGroup" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:exported="true" android:launchMode="singleTop" android:name="com.gae.scaffolder.plugin.FCMPluginActivity">
            <intent-filter>
                <action android:name="FCM_PLUGIN_ACTIVITY" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <service android:name="com.gae.scaffolder.plugin.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="com.gae.scaffolder.plugin.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <receiver android:enabled="true" android:name="com.google.android.gms.analytics.AnalyticsReceiver">
            <intent-filter>
                <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
            </intent-filter>
        </receiver>
        <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.AnalyticsService" />
        <receiver android:enabled="true" android:exported="true" android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>
        <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.CampaignTrackingService" />
    </application>
    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

build.gralde of cordovaLib module:

buildscript {
    repositories {
        mavenCentral()
        jcenter();
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'
    }

}
apply plugin: 'com.android.library'
ext {
    apply from: 'cordova.gradle'
    cdvCompileSdkVersion = privateHelpers.getProjectTarget()
    cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
android {
    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion
    publishNonDefault true
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
    defaultConfig {
        minSdkVersion 16
        versionCode 2
    }
    productFlavors {
    }
}

dependencies {
}

build.gradle of android module:

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

apply plugin: 'com.android.application'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'
    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    repositories {
        mavenCentral();
        jcenter()
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.14.1'
}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: 'CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
apply from: "cordova-plugin-crosswalk-webview/studentGroup-xwalk.gradle"
apply from: "cordova-plugin-fcm/studentGroup-FCMPlugin.gradle"
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }
    defaultConfig {
        applicationId privateHelpers.extractStringFromManifest("package")
        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
        minSdkVersion 16
        versionCode 2
    }
    lintOptions {
        abortOnError false;
    }
    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion
    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        productFlavors {
            armv7 {
                versionCode defaultConfig.versionCode * 10 + 2
                ndk {
                    abiFilters "armeabi-v7a", ""
                }
            }
            x86 {
                versionCode defaultConfig.versionCode * 10 + 4
                ndk {
                    abiFilters "x86", ""
                }
            }
            all {
                ndk {
                    abiFilters "all", ""
                }
            }
        }
    }
    /*

    ELSE NOTHING! DON'T MESS WITH THE VERSION CODE IF YOU DON'T HAVE TO!

    else if (!cdvVersionCode) {
      def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
      // Vary versionCode by the two most common API levels:
      // 14 is ICS, which is the lowest API level for many apps.
      // 20 is Lollipop, which is the lowest API level for the updatable system webview.
      if (minSdkVersion >= 20) {
        defaultConfig.versionCode += 9
      } else if (minSdkVersion >= 14) {
        defaultConfig.versionCode += 8
      }
    }
    */
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset"
                // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
    productFlavors {
        armv7 {
            minSdkVersion 16
            versionCode 2
        }
        x86 {
            minSdkVersion 16
            versionCode 2
        }
    }
}

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile project(path: 'CordovaLib', configuration: 'debug')
    releaseCompile project(path: 'CordovaLib', configuration: 'release')
    compile 'com.google.android.gms:play-services-analytics:9.0.0'
    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
        if (task.name == 'validateReleaseSigning' || task.name == 'validateSigningRelease') {
            promptForReleaseKeyPassword()
        }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}

Body:
In build.gradle of android Project, Mention minSdkVersion 19

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "your_package_name"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }


问:
About the u and u0 values from lmer in lme4 [R]
I am learning mixed models from https://www.cmm.bris.ac.uk/lemma/login/index.php and this question is regarding an exercise in Module 5.

The data has 33,988 observations from 508 schools. The student data is the first level and the school is the second level. I run the null model

```<code>nullmodel <- lmer(score ~ (1|schoolid), data = mydata, REML = FALSE)
</code>```

(I could not find an open access to the dataset. I guess since the question is more conceptual it should not matter)

Should the intercept estimate that we get by running the summary of the nullmodel not be equal to mean of the 'score'? I get the intercept estimate as 30.60 and the mean [mean(mydata$score)] as 31.09. The values are close but not same.

Also, is there an direct way to get u0, the school level residuals?

答:
Random intercept effect, u0, is normally distributed with mean 0 and variance of σ_u0^2.

The σ_u0^2 is between-school variance.

You can calculate σ_u0^2 using a direct way.

calculate the mean score of each school

calculate variance of these values

The variance is close to σ_u0^2.

Body:
I am learning mixed models from https://www.cmm.bris.ac.uk/lemma/login/index.php and this question is regarding an exercise in Module 5.

The data has 33,988 observations from 508 schools. The student data is the first level and the school is the second level. I run the null model

nullmodel <- lmer(score ~ (1|schoolid), data = mydata, REML = FALSE)

(I could not find an open access to the dataset. I guess since the question is more conceptual it should not matter)

Should the intercept estimate that we get by running the summary of the nullmodel not be equal to mean of the 'score'? I get the intercept estimate as 30.60 and the mean [mean(mydata$score)] as 31.09. The values are close but not same.

Also, is there an direct way to get u0, the school level residuals?


问:
How to count the length of a line in bash such that spaces for indentation are excluded?
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

```<code>    this is an example line
</code>```

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

答:
```<code>$ echo '    this is an example line' | awk '{gsub(/^ +/,""); print length}'
23
</code>```

Explanation:

gsub(/^ +/,"") - In short replace starting space chars with null in current record/row/line.

^ asserts position at start of the string,

 space as char

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy),

Body:
I wish to enforce a rule that no line in a python code would be more than 80  characters in length. For this I count the length of the entire line in file using a bash script. However, I need to exclude the starting spaces used for indentation. I wish to start counting from where the first character is seen in the line, until the last character: e.g:

    this is an example line

length() needs to return (31-8=23) rather than 31.

How do I accomplish this using a sed, awk, or grep query?

Body:
$ echo '    this is an example line' | awk '{gsub(/^ +/,""); print length}'
23

Explanation:

gsub(/^ +/,"") - In short replace starting space chars with null in current record/row/line.

^ asserts position at start of the string,

 space as char

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy),


问:
How to select a column name with a space in MySQL
I am working on a project where another developer created a table with column names like 'Business Name'. That is a space between two words. If I run a SELECT statement with 'Business Name' it says there is no column with name 'Business'.

How can I solve this problem?

答:
You need to use backtick instead of single quotes:

Single quote - 'Business Name' - Wrong

Backtick - `Business Name` - Correct

ContentLicense: CC BY-SA 4.0


问:
How to make a switch statement loop?
```<code>import java.util.LinkedList;
import java.util.Scanner;

public class Enrollment {
public static void main(String[] args) {
    LinkedList<Student> studentData = new LinkedList<Student>();
    LinkedList<Faculty> facultyData = new LinkedList<Faculty>();
    LinkedList<Course> courseData = new LinkedList<Course>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
    int userChoice = input.nextInt();
    input.nextLine();
    switch (userChoice) {

    case 1:
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

        System.out.println("Enter student address(only address number and street name) ");
        String sAddress = input.nextLine();

        System.out.println("Enter city, state, and zip code ");
        String sCityStateZip = input.nextLine();

        System.out.println("Enter student gender ");
        String sGender = input.nextLine();

        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }

        break;
    case 2:
        // code to add faculty
        System.out.println("Enter faculty name ");
        String fName = input.nextLine();

        System.out.println("Enter faculty age ");
        int fAge = input.nextInt();

        System.out.println("Enter faculty id ");
        int fID = input.nextInt();
        input.nextLine();

        System.out.println("Enter faculty degree ");
        String fDegree = input.nextLine();

        System.out.println("Enter faculty major ");
        String fMajor = input.nextLine();

        System.out.println("Enter faculty address ");
        String fAddress = input.nextLine();

        System.out.println("Enter faculty gender ");
        String fGender = input.nextLine();

        Faculty facultyInfo = new Faculty(fName, fAge, fID, fDegree, fMajor, fAddress, fGender);
        facultyData.add(facultyInfo);

        for (Faculty testClass : facultyData) {
            System.out.println(testClass);
        }
        break;
    case 3:
        // code to add course
        System.out.println("Enter course name ");
        String courseName = input.nextLine();

        System.out.println("Enter course ID ");
        int cID = input.nextInt();

        System.out.println("Enter number of credits ");
        int numOfCred = input.nextInt();

        System.out.println("Enter intstructor/faculty ID ");
        int instructorID = input.nextInt();

        System.out.println("Enter course year ");
        int year = input.nextInt();
        input.nextLine();

        System.out.println("Enter semester ");
        String semester = input.nextLine();

        System.out.println("Enter classroom size ");
        int size = input.nextInt();

        System.out.println("Enter course capacity ");
        int capacity = input.nextInt();

        Course courseInfo = new Course(courseName, cID, numOfCred, instructorID, year, semester, size, capacity);
        courseData.add(courseInfo);

        for (Course testClass : courseData) {
            System.out.println(testClass);
        }

        break;

    default:
        System.out.println("Invalid entry");
        break;
    }

}
</code>```

I am trying to make an enrollment system. Right now I have made the program so that it prompts the user to choose if they want to add a student, faculty, or course. Once the user picks an option and fills out the questions asked, the program ends. How can I make it loop so that after the user answers the questions, it brings them back to the first prompt where they are given the three choices of what they want to do?

答:
Put a loop around the entire switch, for example:

```<code>while(true){
  //entire switch statement here
}
</code>```

I'd also break your code up a bit with methods. If code is like a recipe, methods are small parts of the process that always perform the same, though might have different inputs - for example, you can beat an egg, beat cream, stir soup, stir sauce, stir flour - methods are typically named with something that sounds like an action (a verb) so if you hired a new young chef, who'd never seen cream before but knew how to beat things, you could hand him your cream and your eggs and tell him to beat them.. that's the idea of a method, that you take a small part of code that always does the same thing, though the inputs and outputs change, and make it a method. Input.nextLine() is a method of scanner. It always reads from the console (when the console is attached to the scanner) and gives a line of text, whatever text was typed.

Here's an example from your code:

```<code>private Student getStudentFromInput(Scanner input){
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

      //  ... blah blah and so on right the way to the bit where you make the student
        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);

        return studentInfo;
}
</code>```

That's a Method. It takes input parameters, does something with them, gives something back

You can now tidy up your switch statement to:

```<code>   case 1:

        Student studentInfo = getStudentFromInput(input);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }
        break;
</code>```

"But it's not really any different to before" you mit say - no it's not, because your code only ever calls the method from one place. The good part is, you could call that method from another place, to read in a student, without have to repeat all the lines of code again. It also stops our main (which is also a method) ending up ten thousand lines long by the time we've extended our program to handle entire towns of kinds of people and organisations. Try to always follow a rule that a method shouldn't be more than a couple of screens long. If it is, it's an indication your code needs breaking up into more methods, smaller units of work per se

Title: How to make a switch statement loop?

Body:
import java.util.LinkedList;
import java.util.Scanner;

public class Enrollment {
public static void main(String[] args) {
    LinkedList<Student> studentData = new LinkedList<Student>();
    LinkedList<Faculty> facultyData = new LinkedList<Faculty>();
    LinkedList<Course> courseData = new LinkedList<Course>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
    int userChoice = input.nextInt();
    input.nextLine();
    switch (userChoice) {

    case 1:
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

        System.out.println("Enter student address(only address number and street name) ");
        String sAddress = input.nextLine();

        System.out.println("Enter city, state, and zip code ");
        String sCityStateZip = input.nextLine();

        System.out.println("Enter student gender ");
        String sGender = input.nextLine();

        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }

        break;
    case 2:
        // code to add faculty
        System.out.println("Enter faculty name ");
        String fName = input.nextLine();

        System.out.println("Enter faculty age ");
        int fAge = input.nextInt();

        System.out.println("Enter faculty id ");
        int fID = input.nextInt();
        input.nextLine();

        System.out.println("Enter faculty degree ");
        String fDegree = input.nextLine();

        System.out.println("Enter faculty major ");
        String fMajor = input.nextLine();

        System.out.println("Enter faculty address ");
        String fAddress = input.nextLine();

        System.out.println("Enter faculty gender ");
        String fGender = input.nextLine();

        Faculty facultyInfo = new Faculty(fName, fAge, fID, fDegree, fMajor, fAddress, fGender);
        facultyData.add(facultyInfo);

        for (Faculty testClass : facultyData) {
            System.out.println(testClass);
        }
        break;
    case 3:
        // code to add course
        System.out.println("Enter course name ");
        String courseName = input.nextLine();

        System.out.println("Enter course ID ");
        int cID = input.nextInt();

        System.out.println("Enter number of credits ");
        int numOfCred = input.nextInt();

        System.out.println("Enter intstructor/faculty ID ");
        int instructorID = input.nextInt();

        System.out.println("Enter course year ");
        int year = input.nextInt();
        input.nextLine();

        System.out.println("Enter semester ");
        String semester = input.nextLine();

        System.out.println("Enter classroom size ");
        int size = input.nextInt();

        System.out.println("Enter course capacity ");
        int capacity = input.nextInt();

        Course courseInfo = new Course(courseName, cID, numOfCred, instructorID, year, semester, size, capacity);
        courseData.add(courseInfo);

        for (Course testClass : courseData) {
            System.out.println(testClass);
        }

        break;

    default:
        System.out.println("Invalid entry");
        break;
    }

}

I am trying to make an enrollment system. Right now I have made the program so that it prompts the user to choose if they want to add a student, faculty, or course. Once the user picks an option and fills out the questions asked, the program ends. How can I make it loop so that after the user answers the questions, it brings them back to the first prompt where they are given the three choices of what they want to do?

Body:
Put a loop around the entire switch, for example:

while(true){
  //entire switch statement here
}

I'd also break your code up a bit with methods. If code is like a recipe, methods are small parts of the process that always perform the same, though might have different inputs - for example, you can beat an egg, beat cream, stir soup, stir sauce, stir flour - methods are typically named with something that sounds like an action (a verb) so if you hired a new young chef, who'd never seen cream before but knew how to beat things, you could hand him your cream and your eggs and tell him to beat them.. that's the idea of a method, that you take a small part of code that always does the same thing, though the inputs and outputs change, and make it a method. Input.nextLine() is a method of scanner. It always reads from the console (when the console is attached to the scanner) and gives a line of text, whatever text was typed.

Here's an example from your code:

private Student getStudentFromInput(Scanner input){
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

      //  ... blah blah and so on right the way to the bit where you make the student
        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);

        return studentInfo;
}

That's a Method. It takes input parameters, does something with them, gives something back

You can now tidy up your switch statement to:

   case 1:

        Student studentInfo = getStudentFromInput(input);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }
        break;

"But it's not really any different to before" you mit say - no it's not, because your code only ever calls the method from one place. The good part is, you could call that method from another place, to read in a student, without have to repeat all the lines of code again. It also stops our main (which is also a method) ending up ten thousand lines long by the time we've extended our program to handle entire towns of kinds of people and organisations. Try to always follow a rule that a method shouldn't be more than a couple of screens long. If it is, it's an indication your code needs breaking up into more methods, smaller units of work per se


问:
nav bar won't display horizontally when fully expanded in the browser
I am trying to get my nav bar to display horizontally in a line at the top of my web page below my h1 tag. I tried all sorts of different methods to get it to line up horizontally but it won't change. My nav bar continues to display vertically centered. I want it to be a thin bar up at the top below the h1. As of right now, it displays with each li stacked on top of the other instead of side by side. Any help or ideas are appreciated.

#wrapper{
        background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {
        background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;
        }

main {
        margin-left: 180px;
        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 100%;
    }
li a {
   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}
nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }
 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid ;
    text-align: right;
    display:inline-block;
}
nav a{
        text-decoration: none;
        border: 1px solid;
        width: 100%
        }
nav a:link{color:cyan;}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<header>
<h1>Polar Bar</h1>
<nav>
<ul>
<li>Home</li>
<li>Menu</li>
<li>About Us</li>
<li>Contact</li>
<li>Social</li>
</ul>
</nav></code>```

答:
Make the li elements inline-block, and add box-sizing:border-box:

CSS: #wrapper {
  background-color: #FFFFFF;
  color: #000066;
  width: 700px;
  max-width: 1024px;
  margin-right: auto;
  margin-left: auto;
  padding-top: 0px;
}

h1 {
  background-color: darkcyan;
  color: #74ebd5;
  background-position: center;
  background-repeat: no-repeat;
  text-align: center;
  font-size: 3em;
  line-height: 80%;
  padding: 30px;
  text-shadow: #CCCCCC;
  margin-bottom: 0;
}

main {
  margin-left: 180px;
  padding-bottom: 100px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 10px;
  overflow: hidden;
  background-color: #333;
  width: 100%;
  box-sizing: border-box;
}

li {
  display: inline-block;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 20px;
  text-decoration: none;
  box-sizing: border-box;
}

nav {
  display: inline-block;
  width: 100%;
  font-weight: bold;
  background-color: grey;
}

nav ul {
  list-style: none;
  width: 100%;
  border: 1px solid;
  text-align: right;
  display: inline-block;
}

nav a {
  text-decoration: none;
  border: 1px solid;
  width: 100%;
}

nav a:link {
  color: cyan;
}

nav a:visited {
  color: #6699FF;
}

nav a:hover {
  color: gold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <header>
    <h1>Polar Bar</h1>
    <nav>
      <ul>
        <li>Home</li>
        <li>Menu</li>
        <li>About Us</li>
        <li>Contact</li>
        <li>Social</li>
      </ul>
    </nav></code>```

Body:
I am trying to get my nav bar to display horizontally in a line at the top of my web page below my h1 tag. I tried all sorts of different methods to get it to line up horizontally but it won't change. My nav bar continues to display vertically centered. I want it to be a thin bar up at the top below the h1. As of right now, it displays with each li stacked on top of the other instead of side by side. Any help or ideas are appreciated.

#wrapper{
        background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {
        background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;
        }

main {
        margin-left: 180px;
        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 100%;
    }
li a {
   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}
nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }
 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid ;
    text-align: right;
    display:inline-block;
}
nav a{
        text-decoration: none;
        border: 1px solid;
        width: 100%
        }
nav a:link{color:cyan;}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}

Polar Bar

Home

Menu

About Us

Contact

Social

Body:
Make the li elements inline-block, and add box-sizing:border-box:

CSS: #wrapper {
  background-color: #FFFFFF;
  color: #000066;
  width: 700px;
  max-width: 1024px;
  margin-right: auto;
  margin-left: auto;
  padding-top: 0px;
}

h1 {
  background-color: darkcyan;
  color: #74ebd5;
  background-position: center;
  background-repeat: no-repeat;
  text-align: center;
  font-size: 3em;
  line-height: 80%;
  padding: 30px;
  text-shadow: #CCCCCC;
  margin-bottom: 0;
}

main {
  margin-left: 180px;
  padding-bottom: 100px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 10px;
  overflow: hidden;
  background-color: #333;
  width: 100%;
  box-sizing: border-box;
}

li {
  display: inline-block;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 20px;
  text-decoration: none;
  box-sizing: border-box;
}

nav {
  display: inline-block;
  width: 100%;
  font-weight: bold;
  background-color: grey;
}

nav ul {
  list-style: none;
  width: 100%;
  border: 1px solid;
  text-align: right;
  display: inline-block;
}

nav a {
  text-decoration: none;
  border: 1px solid;
  width: 100%;
}

nav a:link {
  color: cyan;
}

nav a:visited {
  color: #6699FF;
}

nav a:hover {
  color: gold;
}

<div id="wrapper">
  <header>
    <h1>Polar Bar</h1>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="menu.html">Menu</a></li>
        <li><a href="aboutus.html">About Us</a></li>
        <li><a href="contact.html">Contact</a></li>
        <li><a href="social.html">Social</a></li>
      </ul>
    </nav>


问:
grid-size from environment variable in Spring Batch
I'm following partition pattern for Spring Batch. Currently I'm using a fixed grid-size of 10. Here is the master job configuration:

```<code><batch:step id="master">
      <batch:partition step="slave" partitioner="rangePartitioner">
         <batch:handler grid-size="10" task-executor="taskExecutor" />
      </batch:partition>
</batch:step>
</code>```

Is this possible to assign the grid-size from jvm arguments or spring application.properties file?

答:
Try changing your grid-size value to following and when starting application from command line, append --grid.size=10 in your command.

```<code><batch:step id="master">
      <batch:partition step="slave" partitioner="rangePartitioner">
         <batch:handler grid-size="${grid.size}" task-executor="taskExecutor" />
      </batch:partition>
</batch:step>
</code>```

Body:
I'm following partition pattern for Spring Batch. Currently I'm using a fixed grid-size of 10. Here is the master job configuration:

<batch:step id="master">
      <batch:partition step="slave" partitioner="rangePartitioner">
         <batch:handler grid-size="10" task-executor="taskExecutor" />
      </batch:partition>
</batch:step>

Is this possible to assign the grid-size from jvm arguments or spring application.properties file?

Body:
Try changing your grid-size value to following and when starting application from command line, append --grid.size=10 in your command.

<batch:step id="master">
      <batch:partition step="slave" partitioner="rangePartitioner">
         <batch:handler grid-size="${grid.size}" task-executor="taskExecutor" />
      </batch:partition>
</batch:step>


问:
Android: TextView: Remove spacing and padding on top and bottom
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

```<code>android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"
</code>```

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?

答: You might want to try aligning the bottom of the left text view with the bottom of the 2nd right text view.</p>

Body:
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?


问:
javascript find and replace just whole words in a textarea
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

```<code>XI
XXI
XXXI
</code>```

and I get

```<code>11
X11
XX11
</code>```

but I want

```<code>11
XXI
XXXI
</code>```

The code I'm using is:

```<code>function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}
</code>```

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

答:
What you need is add \\b to begin and end of the regular expression. It will match the whole word.

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b","gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="textArea" style="width: 400px; height: 100px"></textarea>
<br />
<button onClick="romanToArabic()">Convert</button></code>```

Body:
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

XI
XXI
XXXI

and I get

11
X11
XX11

but I want

11
XXI
XXXI

The code I'm using is:

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

Body:
What you need is add \\b to begin and end of the regular expression. It will match the whole word.

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp("\\b(" + Object.keys(mapObj).join("|") + ")\\b","gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}

<textarea id="textArea" style="width: 400px; height: 100px"></textarea>
<br />
<button onClick="romanToArabic()">Convert</button>


问:
How to change blogger JSON Feed URL onclick?
i am using blogger json feed data from say SITE1 , The code contains document.write(SITE1feedurl).

I am using it without problem.
But now i want to change url of json feed to document.write(SITE2feedurl) on click without refreshing page,
So i created function change(); so that on click it loads document.write(Site2feedurl) .

It works but problem is that the document.write replaces full page with content that we loaded from site2.
So I came to know that is the drawback of document.write , so replacements of document.write are InnerHTML and Jquery's $Div.append('') , Both works but shows ONLY FIRST ITEM from blog list.

Maybe that will work when we replace document.write with something similar and still display more than 1 post.
Tried many things , couldn't get it. Never used it before. Help.
Here is the code :

Code Demo is Live at : http://ytlmega.bitballoon.com/food/temp

Code goes as follows:

```<code><!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<button onclick="go();">Click to change src of json feed url</button>
<div class="idli" id="idli" style="background-color:yellow"> Please Notice that , After you click button : The new content replaces ENTIRE page (due to document.write)</div>

<hr/><hr/>

<script type="text/javascript" async>
var ListBlogLink = window.location.hostname;
var ListCount = 0;
var ChrCount = 140;
var TitleCount = 1000;
var ImageSize = 500;
//################ Function Start
function mbtlist(json) {
document.write('<div class="mbtlist">');
for (var i = 0; i < ListCount; i++)
{
//################### Variables Declared
var listing= ListImage = ListUrl = ListTitle = ListImage = ListContent = ListConten = ListAuthor = ListTag = ListDate = ListUpdate = ListComments = thumbUrl = TotalPosts = sk = ListMonth = Y = D = M = m = YY = DD = MM = mm = TT =  "";
//################### Category
if (json.feed.entry[i].category != null)
{
for (var k = 0; k < json.feed.entry[i].category.length; k++) {
    ListTag += json.feed.entry[i].category[k].term;
if(k < json.feed.entry[i].category.length-1)
{ ListTag += ", ";}
}
}
//################### URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
      if (json.feed.entry[i].link[j].rel == 'alternate') {
        break;
      }
    }
ListUrl= "'" + json.feed.entry[i].link[j].href + "'";
//################### Info
TotalPosts = json.feed.openSearch$totalResults.$t;
if (json.feed.entry[i].title!= null)
{
ListTitle= json.feed.entry[i].title.$t.substr(0, TitleCount);
}
if (json.feed.entry[i].thr$total)
{
ListComments= json.feed.entry[i].thr$total.$t;
}
ListAuthor= json.feed.entry[i].author[0].name.$t.split(" ");
ListAuthor=ListAuthor.slice(0, 1).join(" ");

//################### Content Check
ListConten = json.feed.entry[i].content.$t;
ListContent= ListConten.replace(/(<([^>]+)>)/ig,"").substring(0, ChrCount);
//################### Date Format
ListMonth= ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
ListDate= json.feed.entry[i].published.$t.substring(0,10);
                         Y = ListDate.substring(0, 4);
                        m = ListDate.substring(5, 7);
                         D = ListDate.substring(8, 10);
                         M = ListMonth[parseInt(m - 1)];
ListUpdate= json.feed.entry[i].updated.$t.substring(0, 16);
                         YY = ListUpdate.substring(0, 4);
                        mm = ListUpdate.substring(5, 7);
                         DD = ListUpdate.substring(8, 10);
                         TT = ListUpdate.substring(11, 16);
                         MM = ListMonth[parseInt(mm - 1)];
//################### Thumbnail Check
// YouTube scan
if (json.feed.entry[i].content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/) != null)
{
    var youtube_id = json.feed.entry[i].content.$t.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/).pop();

    if (youtube_id.length == 11) {
        var ListImage = "'//img.youtube.com/vi/"+youtube_id+"/0.jpg'";
        }
}
else if (json.feed.entry[i].media$thumbnail)
{
thumbUrl = json.feed.entry[i].media$thumbnail.url;
sk= thumbUrl.replace("/s72-c/","/s"+ImageSize+"/");
ListImage= "'" + sk.replace("?imgmax=800","") + "'";
}
else if (json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/) != null)
{
// Support For 3rd Party Images
ListImage =  json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
}
else
{
ListImage= "'../ext/404.png'";
}
//################### Printing List
var listing = "<div  style='padding:13px'><div  id='mains' class='card ' style='border-radius:9px'><div class='card-image' ><div   style='animation-delay:0.5s' class='animated bounceIn node"+[i]+"' ><a class='primary progressive replace' href="
+ ListImage+
  "> <img  style='margin-top:-1px;margin-right:-1px;' data-src="
  +ListImage+
  "  ></div></a></div><div class='card-content ' ><span style='cursor: pointer;font-size:42px;font-family:mont;float:right;padding:7px;color:#78d0fe;' class='add'>+</span> <span style='color:#78d0fe;border-radius:200px;padding:4px;cursor: pointer;font-size:42px;align:right;font-family:mont;float:right' class='minus'>-</span> <input style='padding:4px;border-radius:1.5px;background-color:#e9e9e9;color:#016aa3;width:30px;height:20px;' type=number class='qty' id='book-qty' value='1' disabled></input><div   class='add-to-cart' style='background-color:#ff6f00;border-radius:4px;height:30px;padding:5px;float:right;width:110px;color:white;margin-left:14px;margin-bottom:10px;cursor:pointer'  onclick='myAdded()' class='chip'>   <b  style='background-color:#ff6f00;color:#fff;font-family:mont'> • Add to cart</b></div><br/><span class='card-title activator grey-text text-darken-4'><a class='mbttitle' style='padding:0px;color:#212121;font-family:mont;align:left' ="
+ ListUrl+
"><p id='book-name' >"
+ ListTitle+
"</p>   </a></span><br/><hr class='style12' style='margin-bottom:5px'><div style='margin-bottom:0px;margin-top:0px;margin-left:0px;font-size:18px;'> <div style='background-color:#fff   ;color:#212121;height:18.8px;width:100%;font-family:mont;font-size:21.7px' class='chip'> <img width='120px' src='https://image.flaticon.com/icons/svg/592/592015.svg' ><p id='book-content'>"
+ListContent+
"</p></div></div></div></div></div></div>";
document.write(listing);
}
document.write("<div class='itotal'><span> <a href='"+ListBlogLink+"/search'>View all <font>"+TotalPosts+"</font> posts</a></span></div></div>");
}

var ListBlogLink = "http://viofd.blogspot.in/";
var ListCount = 1000;

document.write("<script src='"+ListBlogLink+"/feeds/posts/default/?alt=json-in-script&max-results=1000&callback=mbtlist'></"+"script>");

function go(){
document.write("<script src='"+ListBlogLink+"/feeds/posts/default/?alt=json-in-script&max-results=2&callback=mbtlist'></"+"script>");
}
</script>

</body>
</html>
</code>```

答:
After several tries, finally Jquery's append method seems to be most effective way to do that.
It was blogger json which was placed with document.write and thus only shows 1 post when any other method was used. It was pretty clear that document.write needs to be replaced.
But now placing jquery append at right place and inside [i++] loop, and clearing div before append works.

Here is the working code after solution :

```<code>//################### Printing List
var listing = "<div  style='padding:13px'><div  id='mains' class='card ' style='border-radius:9px'><div class='card-image' ><div   style='animation-delay:0.5s' class='animated bounceIn node"+[i]+"' ><a class='primary progressive replace' href="
+ ListImage+
  "> <img  style='margin-top:-1px;margin-right:-1px;' data-src="
  +ListImage+
  "  ></div></a></div><div class='card-content ' ><span style='cursor: pointer;font-size:42px;font-family:mont;float:right;padding:7px;color:#78d0fe;' class='add'>+</span> <span style='color:#78d0fe;border-radius:200px;padding:4px;cursor: pointer;font-size:42px;align:right;font-family:mont;float:right' class='minus'>-</span> <input style='padding:4px;border-radius:1.5px;background-color:#e9e9e9;color:#016aa3;width:30px;height:20px;' type=number class='qty' id='book-qty' value='1' disabled></input><div   class='add-to-cart' style='background-color:#ff6f00;border-radius:4px;height:30px;padding:5px;float:right;width:110px;color:white;margin-left:14px;margin-bottom:10px;cursor:pointer'  onclick='myAdded()' class='chip'>   <b  style='background-color:#ff6f00;color:#fff;font-family:mont'> • Add to cart</b></div><br/><span class='card-title activator grey-text text-darken-4'><a class='mbttitle' style='padding:0px;color:#212121;font-family:mont;align:left' ="
+ ListUrl+
"><p id='book-name' >"
+ ListTitle+
"</p>   </a></span><br/><hr class='style12' style='margin-bottom:5px'><div style='margin-bottom:0px;margin-top:0px;margin-left:0px;font-size:18px;'> <div style='background-color:#fff   ;color:#212121;height:18.8px;width:100%;font-family:mont;font-size:21.7px' class='chip'> <img width='120px' src='https://image.flaticon.com/icons/svg/592/592015.svg' ><p id='book-content'>"
+ListContent+
"</p></div></div></div></div></div></div>";
$(idli).append(listing);
}

}

var ListBlogLink = "http://viofd.blogspot.in/";
var ListCount = 1000;

</script>

<script>
function go1(){

$(idli).html('');
$(idli).append("<script src='"+ListBlogLink+"/feeds/posts/default/?alt=json-in-script&max-results=3&callback=mbtlist'></"+"script>");
}

</script>

<script>
function go2(){

$(idli).html('');
$(idli).append("<script src='"+ListBlogLink+"/feeds/posts/default/-/drinks?alt=json-in-script&max-results=3&callback=mbtlist'></"+"script>");
}

</script>
</code>```

Now, go1() function defines url from site1 and go2() defines site2 .. and so on..
Solved!

Body:
i am using blogger json feed data from say SITE1 , The code contains document.write(SITE1feedurl).

I am using it without problem.
But now i want to change url of json feed to document.write(SITE2feedurl) on click without refreshing page,
So i created function change(); so that on click it loads document.write(Site2feedurl) .

It works but problem is that the document.write replaces full page with content that we loaded from site2.
So I came to know that is the drawback of document.write , so replacements of document.write are InnerHTML and Jquery's $Div.append('') , Both works but shows ONLY FIRST ITEM from blog list.

Maybe that will work when we replace document.write with something similar and still display more than 1 post.
Tried many things , couldn't get it. Never used it before. Help.
Here is the code :

Code Demo is Live at : http://ytlmega.bitballoon.com/food/temp

Code goes as follows:

<!DOCTYPE html>

<button onclick="go();">Click to change src of json feed url</button>

 Please Notice that , After you click button : The new content replaces ENTIRE page (due to document.write)

Body:
After several tries, finally Jquery's append method seems to be most effective way to do that.
It was blogger json which was placed with document.write and thus only shows 1 post when any other method was used. It was pretty clear that document.write needs to be replaced.
But now placing jquery append at right place and inside [i++] loop, and clearing div before append works.

Here is the working code after solution :

//################### Printing List
var listing = "<div  style='padding:13px'><div  id='mains' class='card ' style='border-radius:9px'><div class='card-image' ><div   style='animation-delay:0.5s' class='animated bounceIn node"+[i]+"' ><a class='primary progressive replace' href="
+ ListImage+
  "> <img  style='margin-top:-1px;margin-right:-1px;' data-src="
  +ListImage+
  "  ></div></a></div><div class='card-content ' ><span style='cursor: pointer;font-size:42px;font-family:mont;float:right;padding:7px;color:#78d0fe;' class='add'>+</span> <span style='color:#78d0fe;border-radius:200px;padding:4px;cursor: pointer;font-size:42px;align:right;font-family:mont;float:right' class='minus'>-</span> <input style='padding:4px;border-radius:1.5px;background-color:#e9e9e9;color:#016aa3;width:30px;height:20px;' type=number class='qty' id='book-qty' value='1' disabled></input><div   class='add-to-cart' style='background-color:#ff6f00;border-radius:4px;height:30px;padding:5px;float:right;width:110px;color:white;margin-left:14px;margin-bottom:10px;cursor:pointer'  onclick='myAdded()' class='chip'>   <b  style='background-color:#ff6f00;color:#fff;font-family:mont'> &#8226; Add to cart</b></div><br/><span class='card-title activator grey-text text-darken-4'><a class='mbttitle' style='padding:0px;color:#212121;font-family:mont;align:left' ="
+ ListUrl+
"><p id='book-name' >"
+ ListTitle+
"</p>   </a></span><br/><hr class='style12' style='margin-bottom:5px'><div style='margin-bottom:0px;margin-top:0px;margin-left:0px;font-size:18px;'> <div style='background-color:#fff   ;color:#212121;height:18.8px;width:100%;font-family:mont;font-size:21.7px' class='chip'> <img width='120px' src='https://image.flaticon.com/icons/svg/592/592015.svg' ><p id='book-content'>"
+ListContent+
"</p></div></div></div></div></div></div>";
$(idli).append(listing);
}

}

var ListBlogLink = "http://viofd.blogspot.in/";
var ListCount = 1000;

</script>

<script>
function go1(){

$(idli).html('');
$(idli).append("<script src='"+ListBlogLink+"/feeds/posts/default/?alt=json-in-script&max-results=3&callback=mbtlist'></"+"script>");
}

</script>

<script>
function go2(){

$(idli).html('');
$(idli).append("<script src='"+ListBlogLink+"/feeds/posts/default/-/drinks?alt=json-in-script&max-results=3&callback=mbtlist'></"+"script>");
}

</script>

Now, go1() function defines url from site1 and go2() defines site2 .. and so on..
Solved!


问:
How to make browser request smaller range with 206 Partial Content
I am currently making a video streaming service where the video is transcoded in chunks of roughly 1MB each. The HTML5 player of Firefox, Chrome and IE all try their best to request partial content (by adding the Range header to their request). Unfortunately, most of the time this header looks like this:

```<code>Range:bytes=0-
</code>```

I don't want to return the full content, but only 1MB of the content, so I return this:

```<code>Content-Range:bytes 0-1048575/5074944
</code>```

Now Chrome accepts this completely and keeps requesting partial content until it has reached the total length. Firefox however makes only one request which contains the partial content and not the full. Firefox thinks it is the full content and thus not the full video is being played, only part of it. How would I get the same behavior in Firefox as I have in Chrome? I tried returning 416 Range not Satisfiable but both Chrome and Firefox seems to requesting after receiving this status code.

答:
The answer to the question 'How would I get the same behavior in Firefox as I have in Chrome?' is to upgrade to Firefox 57.0 (Quantum). This version of Firefox (in tests of my own server code, which does the same limiting of partial response size) is able to make requests for additional partial content as the video plays, in much the same way as Chrome and IE.

Having said that, if I seek backwards in the video, Firefox will play a portion of the content from the new position (presumably using the cached partial content for that position) but then fails to request (or use cached) partial content when the buffered content runs out - instead it jumps to the end.

It looks like the Firefox developers made a stab at fixing the issue of smaller-than-expected partial content, but have not got it quite right with respect to seeking and/or caching.

I would be interested to know where in the Firefox source was the original comment about "what to do", to find out what has actually been done and perhaps provide appropriate feedback to the Firefox developers.

Body:
I am currently making a video streaming service where the video is transcoded in chunks of roughly 1MB each. The HTML5 player of Firefox, Chrome and IE all try their best to request partial content (by adding the Range header to their request). Unfortunately, most of the time this header looks like this:

Range:bytes=0-

I don't want to return the full content, but only 1MB of the content, so I return this:

Content-Range:bytes 0-1048575/5074944

Now Chrome accepts this completely and keeps requesting partial content until it has reached the total length. Firefox however makes only one request which contains the partial content and not the full. Firefox thinks it is the full content and thus not the full video is being played, only part of it. How would I get the same behavior in Firefox as I have in Chrome? I tried returning 416 Range not Satisfiable but both Chrome and Firefox seems to requesting after receiving this status code.


问:
Gesture problem: UISwipeGestureRecognizer + UISlider
Got a gesture related problem. I implemented UISwipeGestureRecognizer to get swipe left and right events and that is working fine. However the problem I'm facing is that the UISlider's I have in the same view are not playing nice. The sliding motion of the sliders is being mistaken as a swipe left/right.

Any one experienced this problem before, got any ideas how to correct it?

Many thanks.

Here is the code contained within the view controller:

```<code> - (void)viewDidLoad {

            [super viewDidLoad];

                //Setup handling of LEFT and RIGHT swipes
             UISwipeGestureRecognizer *recognizer;

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];
        }

    -(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

      if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
       NSLog(@"Swipe Right");
       //Do stuff
      }

      if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
       NSLog(@"Swipe Left");
       //Do stuff
      }
    }
</code>```

答:
I ended up getting this working just before Lily responded above. Here is the code I used, but Lily's looks cleaner (haven't tested Lily's thou):</p>

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    BOOL AllowSwipes = YES;

        CGPoint point1 = [touch locationInView:_sliderLeft];
        CGPoint point2 = [touch locationInView:_sliderRight];

        //Left slider test
        if ([_sliderLeft hitTest:point1 withEvent:nil] != nil) {
            AllowSwipes = NO;
            NSLog(@"On Left Slider");
        }

        //Right slider test
        if ([_sliderRight hitTest:point2 withEvent:nil] != nil) {
            AllowSwipes = NO;
            NSLog(@"On Right Slider");
        }
    }
    return AllowSwipes;
}
</code>```

Body:
Got a gesture related problem. I implemented UISwipeGestureRecognizer to get swipe left and right events and that is working fine. However the problem I'm facing is that the UISlider's I have in the same view are not playing nice. The sliding motion of the sliders is being mistaken as a swipe left/right.

Any one experienced this problem before, got any ideas how to correct it?

Many thanks.

Here is the code contained within the view controller:

 - (void)viewDidLoad {

            [super viewDidLoad];

                //Setup handling of LEFT and RIGHT swipes
             UISwipeGestureRecognizer *recognizer;

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];

                recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
                [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
                [[self view] addGestureRecognizer:recognizer];
                [recognizer release];
        }

    -(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

      if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
       NSLog(@"Swipe Right");
       //Do stuff
      }

      if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
       NSLog(@"Swipe Left");
       //Do stuff
      }
    }

Body:
I ended up getting this working just before Lily responded above. Here is the code I used, but Lily's looks cleaner (haven't tested Lily's thou):

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    BOOL AllowSwipes = YES;

        CGPoint point1 = [touch locationInView:_sliderLeft];
        CGPoint point2 = [touch locationInView:_sliderRight];

        //Left slider test
        if ([_sliderLeft hitTest:point1 withEvent:nil] != nil) {
            AllowSwipes = NO;
            NSLog(@"On Left Slider");
        }

        //Right slider test
        if ([_sliderRight hitTest:point2 withEvent:nil] != nil) {
            AllowSwipes = NO;
            NSLog(@"On Right Slider");
        }
    }
    return AllowSwipes;
}


问:
Error in android studio project and in IDE as well
I am facing completely unaware about this error, means why this is being thrown?

```<code>Error:Could not find com.android.support:appcompat-v7:27.0.1.
Required by:
    accounts-android:app:unspecified
    accounts-android:app:unspecified > com.android.support:design:25.3.1

Please install the Android Support Repository from the Android SDK Manager.
</code>```

but this is not about to Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error) .

Please help me to resolve this issue.

答: I solve the problem by replacing compile 'com.facebook.android:facebook-android-sdk:[4,5)' by 'com.facebook.android:facebook-android-sdk:4.26.0'</p>

Body:
I am facing completely unaware about this error, means why this is being thrown?

Error:Could not find com.android.support:appcompat-v7:27.0.1.
Required by:
    accounts-android:app:unspecified
    accounts-android:app:unspecified > com.android.support:design:25.3.1

Please install the Android Support Repository from the Android SDK Manager.

but this is not about to Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error) .

Please help me to resolve this issue.


问:
How to compare two array and alert the result?
I have two simple arrays:

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.
</code>```

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

```<code>arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)
</code>```

I use $.each but it's only check the array. Not comparing them.

```<code>$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});
</code>```

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

答:
There various way to doing so the set of limited number of practice may you use.
Like

By $.map() function

By $.filter() function

By array compare with multiple for Loops

Code Examples :

```<code><script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var noElement =[];
// This Example contains the `$.map()` function to accomplish the task.
$.map(arr_must_exist, function(el){
  if($.inArray(el, arr_created) < 0)
  {
        noElement.push(el);
       return null;
  }
  else
  {
      return el;
  }
  return $.inArray(el, arr_created) < 0 ? null : el;
});
if(noElement.length <= 0)
{
console.log("Your choice is valid");
}
else
{
console.log("Your choice must contain "+noElement);
}

//This example contain the `$.filter()` check;

$checkarray = arr_must_exist.filter(e => arr_created.indexOf(e) < 0);

 if($checkarray.length == 0)
 {
    console.log("Your choice is valid");
 }
 else
 {
    console.log("Your choice must contain "+ $checkarray);
 }
</script>
</code>```

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

Body:
There various way to doing so the set of limited number of practice may you use.
Like

By $.map() function

By $.filter() function

By array compare with multiple for Loops

Code Examples :

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var noElement =[];
// This Example contains the `$.map()` function to accomplish the task.
$.map(arr_must_exist, function(el){
  if($.inArray(el, arr_created) < 0)
  {
        noElement.push(el);
       return null;
  }
  else
  {
      return el;
  }
  return $.inArray(el, arr_created) < 0 ? null : el;
});
if(noElement.length <= 0)
{
console.log("Your choice is valid");
}
else
{
console.log("Your choice must contain "+noElement);
}

//This example contain the `$.filter()` check;

$checkarray = arr_must_exist.filter(e => arr_created.indexOf(e) < 0);

 if($checkarray.length == 0)
 {
    console.log("Your choice is valid");
 }
 else
 {
    console.log("Your choice must contain "+ $checkarray);
 }
</script>