text:
Q: Node.js filtered LS - missing ) after argument list I'm completing the learnyounode workshop, and not sure what is wrong with my code. I ran it through jslint, it says:
Expected ')' to match '(' from line 6 and instead saw '{'.
Line 6 is blank. Can someone please point me in the right direction so that I can learn what I did wrong, correct it, and move on to the next exercise? Thanks.
var fs = require('fs');
var path = require('path');
var file = process.argv[2];
var ext = process.argv[3];
var filtered = [];

fs.readdir(file, callback(error, list) {
    if (error) console.error(error);
    else {
        for (i = 0; i < list.length; i++) {
            if (path.extname(list[i]) === ext) {
                filtered.push(list[i]);
                if (i === list.length - 1) {
                    console.log(filtered);
                }
            }
        }
    }
});

The condensed instructions are to read through a list of files in a directory and log the ones that have file extensions matching the one provided by the command line to the console.

A: You need to use function keyword:
fs.readdir(file, function(error, list) {
    if (error) console.error(error);
    else {
        for (i = 0; i < list.length; i++) {
            if (path.extname(list[i]) === ext) {
                filtered.push(list[i]);
                if (i === list.length - 1) {
                    console.log(filtered);
                }
            }
        }
    }
});

A: put function instead of callback
fs.readdir(file, function(error, list)) {


text:
Q: Eclipse IDE ERROR (Exception in thread "main" java.lang.NoClassDefFoundError: sun/misc/Unsafe) I am currently following a game engine tutorial by ThinMatrix, this is the video https://www.youtube.com/watch?v=VS8wlS9hF8E&t=97s, and I keep getting this error:
Exception in thread "main" java.lang.NoClassDefFoundError: sun/misc/Unsafe
    at lwjgl/org.lwjgl.MemoryUtilSun$AccessorUnsafe.getUnsafeInstance(MemoryUtilSun.java:74)
    at lwjgl/org.lwjgl.MemoryUtilSun$AccessorUnsafe.<init>(MemoryUtilSun.java:62)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at lwjgl/org.lwjgl.MemoryUtil.loadAccessor(MemoryUtil.java:375)
    at lwjgl/org.lwjgl.MemoryUtil.<clinit>(MemoryUtil.java:63)
    at lwjgl/org.lwjgl.opengl.WindowsDisplay.setTitle(WindowsDisplay.java:523)
    at lwjgl/org.lwjgl.opengl.Display.setTitle(Display.java:541)
    at lwjgl/org.lwjgl.opengl.Display.createWindow(Display.java:312)
    at lwjgl/org.lwjgl.opengl.Display.create(Display.java:848)
    at lwjgl/org.lwjgl.opengl.Display.create(Display.java:797)
    at GameEngine/renderEngine.DisplayManager.createDisplay(DisplayManager.java:20)
    at GameEngine/engineTester.MainGameLoop.main(MainGameLoop.java:10)
Caused by: java.lang.ClassNotFoundException: sun.misc.Unsafe
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    ... 18 more

I have tried using both Java JRE 14 and Java JRE 17, both of these give me the same error. I tried reinstalling both of the above motioned JREs.
Does anyone have a solution to this?

A: There is no good solution to this.
The correct solution is to find and use a version of lwjgl that doesn't use Unsafe.  (There may be one, but I couldn't figure it out from the release notes.)
The hack solution (for Java 17) is to use an --add-opens option to smash through the access control barriers that they have added to stop people using Unsafe.
However, as the comments on In Java 17 how do I avoid resorting to --add-opens? point out, this is at best a short term fix.
You shouldn't use Java 14.  It is end-of-life.
You could roll back to an earlier LTS version of Java (Java 8 or 11) but that stops you from using newer Java features, and they will eventually go end-of-life anyway.  So this is not a good solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: i want to add/pass the value to my radio button to database

        <form id = "login" action="#" method="POST" >
            <input type = "text" name = "Name" required placeholder="Name" class="input">

                    <?php
                        $sql = "SELECT * FROM cand ";
                            $result  = $con->query($sql);
                        if ($result->num_rows > 0) {
                            echo "

                            Number
                            Name
                            Photo
                            Position
                            Voters
                            Vote

";
                                while($row = $result->fetch_assoc()){
                                    echo "

                                    " . $row["ID"]."
                                    " . $row["cName"]. "
                                    " .""."
                                    " . $row["Position"]."
                                    " . $row["Vcount"   ]."
                                    ".'
                                    <input type="checkbox" id="vote" name="vote" value="vote">'."

";
                        }
                        echo "
";
                        }
                    ?>

            <button name = "login" type="submit">Vote</button>
        </form>

<?php

  if(isset($_POST['login'])){
    $vote = $_POST['vote'];
    $sql = "INSERT into cand (Vcount) VALUES ('$vote')";
    $con->query($sql);
    }

?>

Everytime i submit it doesn't add the value of radio button to database table called cand, column Vcount. It still displays 0 but it keeps adding a new blank row every time I submit the form.

A: You have not properly joined strings, you should do:
$sql = "INSERT into cand (Vcount) VALUES ('" . $vote . "')";


text:
Q: React Native Expo Bare WF stuck on splash screen in prod mode only (in store) My react native App is build on Expo. I started in Managed Workflow and decided to eject to the Bare WorkFlow for using Stripe-React-Native module that require that.
After ejecting, i have decided to use the EAS (Expo build and publish service).
I have launched eas build for Both ios and Android. And no errors where thrown on ios side. I have published the app, installed it and it worked like a charm for all my users.
Android part is less smooth. A lot of errors where throwns at build phase and i have modified build.grade and mainactivity a lot for succeeding in building. I managed to do so, build a bundle, and publish it on the Play Store. But the app install, launch and get stuck on Splash Screen.
I decided to build and apk instead and run it from Android Studio for debugging purpose with logcat.
I think that the most interesting part of logcat output is that :
2021-05-31 01:41:57.280 16931-16931/? E/studio.deploy: Could not get package user id: /system/bin/run-as: package not debuggable: com.satyamdorville.discover
2021-05-31 01:41:57.563 17402-17402/? E/rville.discove: Not starting debugger since process cannot load the jdwp agent.
2021-05-31 01:41:57.860 1816-1926/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2021-05-31 01:41:57.861 1816-2469/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2021-05-31 01:41:57.972 1779-17426/? E/ResolverController: No valid NAT64 prefix (101, <unspecified>/0)
2021-05-31 01:41:58.058 17402-17437/? E/unknown:ReactNative: ReactInstanceManager.createReactContext: mJSIModulePackage not null
2021-05-31 01:41:58.058 17402-17441/? E/ReactNativeJNI: logMarker CREATE_REACT_CONTEXT_END
2021-05-31 01:41:58.187 1795-2310/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
2021-05-31 01:41:58.187 1795-2310/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2021-05-31 01:41:58.245 17402-17437/? E/unknown:ReactNative: ReactInstanceManager.createReactContext: ReactFeatureFlags.useTurboModules == false
2021-05-31 01:41:58.295 17402-17441/? E/ReactNativeJNI: logMarker RUN_JS_BUNDLE_START
2021-05-31 01:41:58.641 17402-17402/? E/unknown:ReactNative: Unable to launch logbox because react was unable to create the root view
2021-05-31 01:41:59.190 1795-2310/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
2021-05-31 01:41:59.190 1795-2310/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2021-05-31 01:41:59.967 1779-17461/? E/ResolverController: No valid NAT64 prefix (101, <unspecified>/0)
2021-05-31 01:41:59.969 17402-17441/? E/ReactNativeJNI: logMarker RUN_JS_BUNDLE_END
2021-05-31 01:42:00.008 1779-17470/? E/ResolverController: No valid NAT64 prefix (101, <unspecified>/0)

I got a bit of that also :
E/NetRec: [1196] aqzc.c: Could not retrieve server token for package com.google.android.apps.gcs
    java.util.concurrent.ExecutionException: uhf: 29503:

Here is some code :
build gradle top level
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        RNNKotlinVersion = "1.4.21"
        buildToolsVersion = "30.0.0"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
    classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.21")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

build.gradle in /app
apply plugin: "com.android.application"
apply plugin: "kotlin-android"
apply plugin: "kotlin-android-extensions"
import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: false
]

apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
kotlinOptions {
    jvmTarget = "1.8"
}
    defaultConfig {
        applicationId 'com.satyamdorville.discover'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 15
        versionName "1.0.7"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }
    addUnimodulesDependencies()

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "./eas-build.gradle"

eas-build.gradle
// Build integration with EAS
apply plugin: "com.android.application"
apply plugin: "kotlin-android"
apply plugin: "kotlin-android-extensions"
import java.nio.file.Paths

android {
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
kotlinOptions {
    jvmTarget = "1.8"
}
defaultConfig {
        applicationId 'com.satyamdorville.discover'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 15
        versionName "1.0.7"
    }
  signingConfigs {
    release {
      // This is necessary to avoid needing the user to define a release signing config manually
      // If no release config is defined, and this is not present, build for assembleRelease will crash
    }
  }

  buildTypes {
    release {
      // This is necessary to avoid needing the user to define a release build type manually
    }
  }
}

def isEasBuildConfigured = false

tasks.whenTaskAdded {
  def debug = gradle.startParameter.taskNames.any { it.toLowerCase().contains('debug') }

  if (debug) {
    return
  }

  // We only need to configure EAS build once
  if (isEasBuildConfigured) {
    return
  }

  isEasBuildConfigured = true;

  android.signingConfigs.release {
    def credentialsJson = rootProject.file("../credentials.json");

    if (credentialsJson.exists()) {
      if (storeFile && System.getenv("EAS_BUILD") != "true") {
        println("Path to release keystore file is already set, ignoring 'credentials.json'")
      } else {
        try {
          def credentials = new groovy.json.JsonSlurper().parse(credentialsJson)
          def keystorePath = Paths.get(credentials.android.keystore.keystorePath);
          def storeFilePath = keystorePath.isAbsolute()
            ? keystorePath
            : rootProject.file("..").toPath().resolve(keystorePath);

          storeFile storeFilePath.toFile()
          storePassword credentials.android.keystore.keystorePassword
          keyAlias credentials.android.keystore.keyAlias
          if (credentials.android.keystore.containsKey("keyPassword")) {
            keyPassword credentials.android.keystore.keyPassword
          } else {
            // key password is required by Gradle, but PKCS keystores don't have one
            // using the keystore password seems to satisfy the requirement
            keyPassword credentials.android.keystore.keystorePassword
          }
        } catch (Exception e) {
          println("An error occurred while parsing 'credentials.json': " + e.message)
        }
      }
    } else {
      if (storeFile == null) {
        println("Couldn't find a 'credentials.json' file, skipping release keystore configuration")
      }
    }
  }

  android.buildTypes.release {
    signingConfig android.signingConfigs.release
  }
}

My Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.satyamdorville.discover">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  <uses-permission android:name="android.permission.VIBRATE"/>
  <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.WAKE_LOCK"/>
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="true" android:theme="@style/AppTheme">
    <meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="https://exp.host/@satyamdorville/discover" />
    <meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="41.0.0" />
    <meta-data android:name="expo.modules.updates.ENABLED" android:value="true"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS" android:value="0"/>
    <meta-data android:name="expo.modules.updates.EXPO_RELEASE_CHANNEL" android:value="default" />

  <activity
    android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:screenOrientation="portrait">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="discover"/>
        <data android:scheme="com.satyamdorville.discover"/>
      </intent-filter>
      <intent-filter>
        <data android:scheme="discover"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT"/>
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
  </application>
</manifest>

And EAS config json
{
  "builds": {
    "android": {
      "release": {
        "workflow": "generic",
        "withoutCredentials": true,
        "gradleCommand": ":app:assembleDebug",
        "artifactPath": "android/app/build/outputs/apk/debug/app-debug.apk"
      }
    },
    "ios": {
      "release": {
        "workflow": "generic"
      }
    }
  }
}

Also my Main Application java
package com.satyamdorville.discover;

import android.app.Application;
import android.content.Context;
import android.net.Uri;

import com.facebook.react.PackageList;
import com.reactnativenavigation.NavigationApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.reactnativenavigation.react.NavigationReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.satyamdorville.discover.generated.BasePackageList;

import org.unimodules.adapters.react.ReactAdapterPackage;
import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.modules.constants.ConstantsPackage;
import expo.modules.permissions.PermissionsPackage;
import expo.modules.filesystem.FileSystemPackage;
import expo.modules.updates.UpdatesController;

import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;

public class MainApplication extends NavigationApplication {
  private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
    new BasePackageList().getPackageList()
  );

  private final ReactNativeHost mReactNativeHost = new NavigationReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      List<ReactPackage> packages = new PackageList(this).getPackages();
      packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
      return packages;
    }

    @Override
    protected String getJSMainModuleName() {
      return "Table Discover";
    }

    @Override
    protected JSIModulePackage getJSIModulePackage() {
      return new ReanimatedJSIModulePackage();
    }

    @Override
    protected @Nullable String getJSBundleFile() {
      if (BuildConfig.DEBUG) {
        return super.getJSBundleFile();
      } else {
        UpdatesController.initialize(this.getApplication().getApplicationContext());
        return UpdatesController.getInstance().getLaunchAssetFile();
      }
    }

    @Override
    protected @Nullable String getBundleAssetName() {
      if (BuildConfig.DEBUG) {
        return super.getBundleAssetName();
      } else {
        UpdatesController.initialize(this.getApplication().getApplicationContext());
        return UpdatesController.getInstance().getBundleAssetName();
      }
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);

    if (!BuildConfig.DEBUG) {
      UpdatesController.initialize(this);
    }

    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }

  /**
   * Loads Flipper in React Native templates. Call this in the onCreate method with something like
   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
   *
   * @param context
   * @param reactInstanceManager
   */
  private static void initializeFlipper(
      Context context, ReactInstanceManager reactInstanceManager) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.satyamdorville.discover.ReactNativeFlipper");
        aClass
            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class);
             aClass.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class).invoke(null, context,
            reactInstanceManager);
            } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

And my activity java
package com.satyamdorville.discover;
import android.content.res.Configuration;
import android.content.Intent;

import android.os.Bundle;

import com.reactnativenavigation.NavigationActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

import expo.modules.splashscreen.singletons.SplashScreen;
import expo.modules.splashscreen.SplashScreenImageResizeMode;

public class MainActivity extends NavigationActivity {

    // Added automatically by Expo Config
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Intent intent = new Intent("onConfigurationChanged");
        intent.putExtra("newConfig", newConfig);
        sendBroadcast(intent);
    }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    // SplashScreen.show(...) has to be called after super.onCreate(...)
    // Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually
    SplashScreen.show(this, SplashScreenImageResizeMode.CONTAIN, ReactRootView.class, false);
  }

protected String getMainComponentName() {
    return "Table Discover";
    }

    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}

Every bit of help and / or understanding is welcomed there as i fight with the current situation for several days....

A: I have deleted ios / android folders.
I have ran expo eject again.
I have deleted everywhere in my code react-native-navigation which was the source of the problem.
It works !


text:
Q: sam local start-api gives error while testing SAM application in local Hi i have a sam application which one lambda function and can be invoked from rest endpoint which is working as expected but when i try to test the sam application locally using sam local start-lambda or sam local start-api or sam local invoke  i get the error as  :
    self.connect()
  File "C:\Users\divyanayan.awasthi\AppData\Roaming\Python\Python37\site-packages\docker\transport\npipeconn.py", line 31, in connect
    sock.connect(self.npipe_path)
  File "C:\Users\divyanayan.awasthi\AppData\Roaming\Python\Python37\site-packages\docker\transport\npipesocket.py", line 22, in wrapped
    return f(self, *args, **kwargs)
  File "C:\Users\divyanayan.awasthi\AppData\Roaming\Python\Python37\site-packages\docker\transport\npipesocket.py", line 50, in connect
    win32pipe.WaitNamedPipe(address, self._timeout)
pywintypes.error: (2, 'WaitNamedPipe', 'The system cannot find the file specified.')

Sam version used
SAM CLI, version 0.7.0

Is this because i dont have a docker running in my local or some other configuration  is required .i have one .py class and template.yml file for SAM application.

A: Yes we need to install docker locally then sam local works as expected .if you are running sam local on windows then there might a problem to install docker installer as it needs Windows 10 Pro or enterpise version to install.
In case you dont have the above windows configuration  then install docker toolbox
https://docs.docker.com/toolbox/toolbox_install_windows/


text:
Q: Displaying ManyToManyField in Django Detail Generic View In my Django project I have two models - Program and Cycle - which are linkedin by a ManyToMany Relationship, so that one program can have many cycles and at the same time cycles can be part of many different programs.
From a Generic List View, the user can select one program and access the Detail View of that programs, where I am supposed to show all the cycles included in the selected program.
views.py
class AllProgramsView (generic.ListView):
    template_name = 'programs/index.html'
    context_object_name = 'programs_list'

    def get_queryset(self):
        return Program.objects.all()

class ProgramDetailView (generic.DetailView):
    model = Program
    template_name = 'programs/program.html'

in models.py
class Cycle(models.Model):
    cycle_name = models.CharField(max_length=150)
    cycle_description = models.CharField(max_length=250)
    steps = models.ManyToManyField(Step)

    def __str__(self):
        return self.cycle_name + "  --  " + self.cycle_description

class Program(models.Model):
    program_name = models.CharField(max_length=50)
    program_description = models.CharField(max_length=250)
    cycles = models.ManyToManyField(Cycle)
    is_favourite = models.BooleanField(default="False")

    def get_absolute_url(self):
        return reverse('programs:program', kwargs={'pk': self.pk})

    def __str__(self):
        return self.program_name

In the html template, program.html

    {% if cycle %}
          {% for cycle in program %}

{{ cycles.cycle_name }}

{{ cycles.cycle_description }}

           Modify it

        {% endfor %}
    {% else %}

No Cycles Found

    {% endif %}

The issue is that no cycles get displayed in the detail page, even though I have programs with cycles saved in the db so they should display.
Is there any error in the code?
Thank you very much in advance!

A: class ProgramDetailView (generic.DetailView):
    model = Program
    template_name = 'programs/program.html'
    context_object_name = 'sp'
    slug_field = 'id'

    def get_context_data(self, **kwargs):
        kwargs['cycles'] = self.get_object().cycles.all()
        return super(ProgramDetailView, self).get_context_data(**kwargs)

or

class ProgramDetailView (generic.DetailView):
    model = Program
    template_name = 'programs/program.html'
    context_object_name = 'sp'
    slug_field = 'id'

html

    {% if sp %}
       {% for cycle in sp.cycles.all %}

{{ cycles.cycle_name }}

{{ cycles.cycle_description }}

           Modify it

        {% endfor %}
    {% else %}

No Cycles Found

    {% endif %}


text:
Q: unix/linux shell (command) script I'm making a command shell script name csbin. Here is my csbin file:
for (( i=1; i <= $#; ++i ))
do
    b+="\$$i "
done

echo my_program $b

If I run my shell script as given below:
./csbin hello everyone welcome here
Here is output what i get:
my_program $1 $2 $3 $4

But i want output must be look like:
my_program hello everyone welcome here

Actually I want to pass all argument (except command name csbin) to my_program. How can I do this? can anyone help me?


text:
Q: Java Web project Integration with Dropbox API I am facing  trouble in integrating my project with dropbox I use Dropbox For
upload file here I am able to upload the file by giving complete Path Of file. but I want to upload file by selecting or Brows from the system and upload to my dropbox Here my code is Like Static For Uploading the file by giving complete file path for upload now I want to upload file by selecting from disck here I use this code for selecting the file but i dont know how to pass this selected file as input for FileInputStream in my DbxUpload class

Select to Upload

Select file:

<form action="DbxUpload" method="Post" enctype="multipart/form-data">
<input type="file" name="file" size="70" />

<input type="submit" value="Upload File" />
Here my DbxUpload Class code that iam  using
import com.dropbox.core.*;
import java.io.*;

public class DbxUpload
{
 private static final String ACCESS_TOKEN = "XXXXXXXXXXXXXXX";

    public static void main(String args[]) throws DbxException, IOException {
        // Create Dropbox client
        DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial", "en_US");
        DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);

        // Get current account info
        FullAccount account = client.users().getCurrentAccount();
        System.out.println(account.getName().getDisplayName());

        // Get files and folder metadata from Dropbox root directory
        ListFolderResult result = client.files().listFolder("");
        while (true) {
            for (Metadata metadata : result.getEntries()) {
                System.out.println(metadata.getPathLower());
            }

            if (!result.getHasMore()) {
                break;
            }

            result = client.files().listFolderContinue(result.getCursor());
        }

        // Upload "test.txt" to Dropbox
        try (InputStream in = new FileInputStream("D:/RUNNING.txt")) {
            FileMetadata metadata = client.files().uploadBuilder("/RUNNING.txt")
                .uploadAndFinish(in);
        }
    }
}

Please Help me Thanks in Advance

A: Using web File browser, this is the entry point https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/web-file-browser/src/main/java/com/dropbox/core/examples/web_file_browser/Main.java where the user can start browse and upload a file to drop box api using Jetty application (uses Jetty server and servlet in the program to support file upload to drop box)
Ref :
https://github.com/dropbox/dropbox-sdk-java/tree/master/examples/web-file-browser/src/main/java/com/dropbox/core/examples/web_file_browser


text:
Q: How to populate a cell depending on which rows mention the row's first cell I have a table where the first cell names each row, e.g. Company A, Company B, .... I also have a column that we'll call Contracts With. When I now write Company B into this column in Company A's row, Company Bs cell in this column should be populated with Company A. So, basically, populate the other cell of this relationship

A: =IFERROR(INDEX($A$2:$A$8,MATCH(A2,$D$2:$D$8,0)),"not entered")

In this example the formula is in column C, copied down; data entry goes into column D.

A: Thank you to Alex for the answer!
However, to actually get what I want, i.e. populating a row's cell with values from other cells, concatenated with ", ", when they are mentioned (partial match) in these rows, you can use the following formula:
=TEXTJOIN(", "; TRUE; IF(ISNUMBER(SEARCH($A2; $B$2:$B$10)); $A$2:$A$10; ""))

Whereby column A has the values (e.g. company names) that should populate column B. ISNUMBER(SEARCH($A2; $B$2:$B$10)) ensures that partial matches also work, which can be replaced with $B$2:$B$10 = $A2 for an exact match.


text:
Q: What does the monopole/quadrupole moment of the Earth signify? I'm currently reading about orbits of near-Earth satellites and some terminology is getting thrown around that I'm not sure I understand what they actually mean:
The Earth's monopole moment and the Earth's quadrupole moment?
What are some easily understood explanations of the above terms?

A: Imagine having a mass distribution $\rho(x,y,z)$ around the origin O and we want to calculate the potential energy and force at a certain point P on the z-axis. The potential energy can easily expressed by the integral: $$U=-GM\int_{V}\frac{\rho(x,y,z)}{R}dv$$
However this intgral might be difficult to calculate and it's often easier to express the integrand by a series, this is called multipole expansion and can be done for both the gravitational force as the electrostatic force.
Because of the law of cosines, we express R in function of $\theta$, $r'$ and r: $R^2 = r^2 +r'^2 - 2rr'\cos(\theta)$, now we can simplify this integral by using this indentity and a Taylor series:
$$\frac{1}{R} = \frac{1}{r}\frac{1}{\sqrt{1+\alpha}} = \frac{1}{r}\left(1-\frac{1}{2}\alpha+\frac{3}{8}\alpha^2-...\right)$$
where $\alpha=\left(\frac{r'}{r}\right)^2-\frac{2r'}{r}\cos(\theta)$
The potential energy now becomes:
$$U=\frac{-GM}{r}\int_{V}\rho dv+\frac{-GM}{r^2}\int_{V}r'\cos(\theta)\rho dv+\frac{-GM}{r^3}\int_{V}r'^2\frac{3\cos^2(\theta)-1}{2}\rho dv +...$$
As you can see, in every term the the power of r becomes smaller and smaller.
Often we rewrite this expression as:
$$U=-GM\left(\frac{C_0}{r}+\frac{C_1}{r^2}+\frac{C^2}{r^3}...\right)$$
Where $C_0$ is the monopole moment, $C_1$ the dipole moment,$C_2$ the quadrupole moment and so on. These can be easily interpreted for wich I refer to @Hritik Narayan.

A: A monopole (gravitational) of a system is basically the amount of mass-energy the system has.
A dipole is a measure of how the mass is distributed away from some center.
The quadrupole moment describes how stretched out the mass distribution is along an axis. Quadrupole would be zero for a sphere, but non-zero for a rod, for instance. It is also non-zero for the Earth, because the Earth is an oblate spheroid.
The gravitational contribution from a quadrupole falls of faster than that of a monopole. (which is why the Earth's quadrupole moment is important for studying satellites and not really for studying the moon, owing to the $r^{-3}$ dependency of the contribution to the potential)
Quadrupoles and other higher order moments are important in GR because the change in their distribution can produce gravitational waves.

Example:
Let's consider two cases, in both the cases, the large bodies are of mass $M$ and the small one of mass $m$, and the small one is on the line of symmetry at a distance $r$.
Case 1: No quadrupole moment.
The force here is a simple: $$\frac{GMm}{r^2}$$.
Case 2: Non-zero quadrupole moment. (the larger spheres are separated by some distance $2R$.)
The force in this case is: $$\frac{2GMmr}{(r^2+R^2)^{3/2}}$$
This, for large $r$, can be approximated to (two term series expansion): $$F \sim \frac{2GMm}{r^2}-\frac{3GMmR^2}{r^4}$$
The weird term here is because of the quadrupole moment of the system. As you go further away ($r>>R$), the force, $F$ is more or less: $$F \sim \frac{2GMm}{r^2}$$
This is why the "quadrupole moment effect" falls off with distance.
Apologies for the obnoxious MS Paint diagrams.


text:
Q: How to scale an axis within multiplot The error msg:
multiplot> plot file1 u ($1/100):2 t "" w lp
           line 0: all points y value undefined!

is listed when the script (below) is executed. What am I doing wrong?
#!/bin/bash
cat > x.dat <<- "EOF"
100 1
200 2
300 3
EOF

cat | gnuplot <<- "EOF"
file1="x.dat"
set multiplot layout 2,1
stats file1 u 1:2 name "A"
set xrange [A_min_x:A_max_x]
plot file1 u 1:2 t""  w lp
plot file1 u ($1/100):2 t "" w lp
unset multiplot
EOF

A: Your command set xrange [A_min_x:A_max_x] set the xrange to [100:300].  But the second plot command divides x by 100, so all the points would have  x<100 and hence are out of range.  Try set xrange [0:A_max_x] instead.


text:
Q: How to pass a variable in Devise sign_up link How can I pass a variable to my sign_up controller using Devise? I want to add the user chosen plan to the database on registration.
Thanks

A: You can add this in your routes.rb
match 'register' => redirect('/users/sign_up?plan=pro')

OR
match 'register/:plan' => redirect('/users/sign_up/{%plan}')

And create the matching controllers.
Get more routes info from here: http://guides.rubyonrails.org/routing.html#redirection
Alternatively, this can also be used https://github.com/plataformatec/devise/wiki/How-To:-Customize-routes-to-user-registration-pages


text:
Q: How to import and write text in a for cycle I have the following code:
dat11=np.genfromtxt('errors11.txt')
dat12=np.genfromtxt('errors12.txt')
dat13=np.genfromtxt('errors13.txt')
dat22=np.genfromtxt('errors22.txt')
dat23=np.genfromtxt('errors23.txt')
dat33=np.genfromtxt('errors33.txt')

zip(dat11,dat12,dat13,dat22,dat23,dat33)
import csv
with open('Allerrors.txt', "w+") as output:
    writer = csv.writer(output, delimiter='\t')
    writer.writerows(zip(dat11,dat12,dat13,dat22,dat23,dat33))
quit

Where each of the 'errorsxy.txt' files consists in a column of numbers. With this program I created the 'Allerrors.txt' file, were all those columns are one next to the others. I need to do this same thing with a for cycle (or any other kind of loop) because I'll actually have much more files and I can't do it by hand. But I don't know how to write these various datxy with a cycle. I tried (for the first part of the code) with:
for x in range(1,Nbin+1):
    for y in range(1,Nbin+1):
        'dat'+str(x)+str(y)=np.genfromtxt('errors'+str(x)+str(y)+'.txt')

But of course I get the following error:
SyntaxError: can't assign to operator

I understand why I get this error, but I couldn't find any other way to write it. Also, I have no idea how to write the second part of the code.
I'm using Python 2.7
Anyone can help me?

A: Instead of making separate variables for each data file, you could append each read-in file to a list, then zip and print the list after the for loop has run.
errorfiles = []
for x in range(1,Nbin+1):
    for y in range(1,Nbin+1):
        dat=np.genfromtxt('errors'+str(x)+str(y)+'.txt')
        errorfiles.append(dat)


text:
Q: Make content fill the whole viewport https://gyazo.com/1440b13007c6e011ec46218ceecabb6a
As you can see by the screenshot, there is a white border around the main content of the page. Ive tried making everything 100% width etc. but nothing seems to work. The nav bar is just a ul and the bottom part is a container div with other child divs heald inside.

A: The <body> element has a default margin. You need to set it to zero:
body {
    margin: 0;
}

A: try adding css as below:
body, html {
margin: 0;
padding: 0;
}


text:
Q: How to check if a docker network with a given subnet/gateway exists? Is there a docker command that allows checking if there is a network already with a given IP? I need to create a new docker network and know its IP address.
In bash I could do something like:
docker network inspect $(docker network ls -q) | grep "address"

And check if it returns anything. But uses both the pipe | and the grep program, while I think there should be a simpler way of doing this using docker only commands.


text:
Q: Multiprocessing.Process in parallel I use this code: (from here)
import multiprocessing

def calc_square(numbers, result):

    for idx, n in enumerate(numbers):
        result[idx] = n*n

if __name__ == "__main__":
    numbers = [2,3,5]
    result = multiprocessing.Array('i',3)
    p = multiprocessing.Process(target=calc_square, args=(numbers, result))

    p.start()
    p.join()

    print(result[:])

How do I let this loop to run in parallel? For example, on 3 different processes.


text:
Q: Hardness of generating Gaussian distribution I would like to ask about the computational complexity of the problem of generating integers so that the obtained distribution is asymptotic to the Gaussian distribution. Any related reference is very appreciated.
More precisely, consider the following problem $\mathcal{P}$: generate $n$ integers between $-N$ and $N$ so that after scaling the interval to $[-1,1]$, one gets a distribution statistically close to Gaussian distribution, as $n, N$ tend to infinity. Is $\mathcal{P}$ NP-hard?


text:
Q: Returning an Array incorrectly, overwriting all with the last item I've seen some similar post but not the same issue I'm having. What I'm trying to do is calling a function that shows the name of the files numbered as
1- File1.txt,
2- File2.txt
..

This works as expected. The problem is that I need to return the path of those files in another Array. When I System.out.print(arrayRutasFicheros[j]) inside for, it shows all paths correctly. But when I try to access arrayRutasFicheros[j] from other functions. It just overwrites all the paths and just shows the last one.
public static String[] listarArchivos() throws IOException{

    File[] listadoDeFiles = documento.listFiles();
    File[] arrayFicheros = null;
    String[] arrayRutasFicheros = null;

    if(documento.exists() ) {

        for (int k=0; k< listadoDeFiles.length ;k++) {

            File ficheroRuta = listadoDeFiles[k];

            File fichero = new File(documento.getPath() + sep+ ficheroRuta.getName());

            if(fichero.isFile()==true) {

                arrayFicheros =new File[] {fichero};

                System.out.println( k + " - " + ficheroRuta.getName());

                for(int j= 0; j<arrayFicheros.length; j++) {

                    arrayRutasFicheros =  new String[] {arrayFicheros[j].getPath()};

                    //here it works and it display all the path
                    System.out.println(arrayRutasFicheros[j]);
                }

            }
        }
    }

    return arrayRutasFicheros;
}

public static muestraUnArchivo() throws IOException {

    String [] Fichero =listarArchivos();

    for(int k=0; k<Fichero.length; k++) {

    //here just the last one
    System.out.print(Fichero[k]);
    }
}

Expected:
-E:\Eclipse\Files\File1.txt
-E:\Eclipse\Files\File2.txt
-E:\Eclipse\Files\File3.txt

Output:
-E:\Eclipse\Files\File3.txt

A: Your array is recreated on every iteration of the loop, which is also on an array of length 1. You need a dynamic structure to store the string paths, because you don't know ahead of time how many there are. Also, you don't need to keep creating single element arrays; use a List<String>. Something like,
public static String[] listarArchivos() throws IOException {
    List<String> al = new ArrayList<>();
    if (documento.exists()) {
        File[] listadoDeFiles = documento.listFiles();
        for (File ficheroRuta : listadoDeFiles) {
            File fichero = new File(documento.getPath()
                    + sep + ficheroRuta.getName());
            if (fichero.isFile()) {
                al.add(fichero.getPath());
            }
        }
    }

    return al.toArray(new String[0]);
}

A: The following lines are not only unnecessary but also causing the issue which you are facing. The line, arrayRutasFicheros =  new String[] {arrayFicheros[j].getPath()}; is resetting arrayRutasFicheros for each value of k and therefore you will get only the value assigned to it at the the last value of k.
if(fichero.isFile()==true) {

    arrayFicheros =new File[] {fichero};

    System.out.println( k + " - " + ficheroRuta.getName());

    for(int j= 0; j<arrayFicheros.length; j++) {

        arrayRutasFicheros =  new String[] {arrayFicheros[j].getPath()};

        //here it works and it display all the path
        System.out.println(arrayRutasFicheros[j]);
    }

}

Replace the above lines with the following code:
if(fichero.isFile()) {
    arrayRutasFicheros[k] =  fichero.getPath();
}

A: Following line set the last value when the for ends the iteration.
I hope you will understand the logic.
arrayRutasFicheros =  new String[] {arrayFicheros[j].getPath()};

Please let me know if you have any confusion.
Happy coding.


text:
Q: Proving $Gal(K/\mathbb{Q})$ is $D_4$.
Let $a = \sqrt{2+i}$ and $K$ is the splitting field of minimal polynomial of $a$ over $\mathbb{Q}$. Prove that $Gal(K/\mathbb{Q})$ is $D_4$.

I find the minimal polynomial of $a$ is $p(x)=x^4-4x^2+5$ and its
 roots are $\sqrt{2+i},-\sqrt{2+i},\sqrt{2-i},-\sqrt{2-i}$. Let $b=\sqrt{2-i}$. So the splitting field of $p$ is $K=\mathbb{Q}(a,b)$. Also by rational root theorem, $p$ is irreducible over $\mathbb{Q}$. Thus $[\mathbb{Q}(a):\mathbb{Q}]=4$. Also $b\not\in\mathbb{Q}(a)$, and minimal polynomial of $b$ over $\mathbb{Q}(a)$ is $x^2-2+i$. Thus $[\mathbb{Q}(a,b):\mathbb{Q}]=[\mathbb{Q}(a,b):\mathbb{Q}(a)]\cdot[\mathbb{Q}(a):\mathbb{Q}]=2\cdot 4=8.$ Now since $K$ is the splitting field over $\mathbb{Q}$ of a separable polynomial, $K/\mathbb{Q}$ is Galois. Hence $|Gal(K/\mathbb{Q})|=8$. Hence the 8 automorphisms are $$a\to \begin{cases}a\\-a\\b\\-b\end{cases}\quad\text{and}\quad b \to \begin{cases}b\\-b\end{cases}.$$ From this how to conclude $Gal(K/\mathbb{Q})$ is isomorphic to $D_4$?
Thanks

A: This follows from Corollary $4.5$ in K. Conrad's notes. The minimal polynomial is $x^4-4x^2+5$, so its Galois group is $D_4$ of order $8$.

A: Find the minimal polynomial of $a$.
\begin{align*}
a &= \sqrt{2+i} \\
a^2 &= 2+i \\
a^2- 2 &= i \\
a^4 - 4a^2 +4&= -1 \\
\end{align*}
So $a$ satisfies the polynomial equation $f(x)=x^4-4x^2+5$.  You should check that this polynomial is irreducible, say, by applying Eisenstein's criterion to  $(x-1)^4-4(x-1)^2 +5 = x^4 - 4 x^3 + 2 x^2 + 4 x + 2
$.
By inspection $b=\sqrt{2-i}$ is another root of $f$.  $b$ does not belong to $\Bbb{Q}[\sqrt{2+i}]$, because if it did, $\sqrt{2+i}\cdot\sqrt{2-i}=\sqrt{5}$ would belong to $\Bbb{Q}[i]$ as $a^2$ and $b^2$ do which it does not.  So if we call $K$ the splitting field of $f$ we have $[K:\Bbb{Q}]=8$ since it's generated by $a=\sqrt{2+i}$ and $\sqrt{5}$.
For automorphisms of $K/\Bbb{Q}$ we have the obvious choice of complex conjugation, say $\tau: i \rightarrow -i$.  If we define $\sigma$ by
\begin{align*}
\sigma &: \sqrt{2+i} \rightarrow -\sqrt{2-i} \\
\sigma &: -\sqrt{2+i} \rightarrow \sqrt{2-i} \\
\sigma &: \sqrt{2-i} \rightarrow \sqrt{2+i} \\
\sigma &: -\sqrt{2-i} \rightarrow -\sqrt{2+i} \\
\end{align*}
$\sigma$ has order 4 and $\tau \sigma \tau = \sigma ^{-1}$, so the group generated by $\sigma$ and $\tau$ is isomorphic to $D_4$


text:
Q: How do I ensure that my Django singleton model exists on startup? I'm using a django third party app called django-solo to give me a SingletonModel that I can use for some global project settings, since I don't need multiple objects to represent these settings.
This works great, but on a fresh database, I need to go in and create an instance of this model, or it won't show up in Django Admin.
How can I make django automatically make sure that when django is starting up, when it connects to the database, it creates this?
I tried using the following code that I got here in my settings_app/apps.py, but it doesn't seem to fire at any point:
from django.db.backends.signals import connection_created

def init_my_app(sender, connection, **kwargs):
   from .models import MyGlobalSettings

   # This creates an instance of MyGlobalSettings if it doesn't exist
   MyGlobalSettings.get_solo()

   print("Instance of MyGlobalSettings created...")

class SettingsAppConfig(AppConfig):
    ...
    def ready(self):
        connection_created.connect(init_my_app, sender=self)

The instance isn't created, and I don't see my print statement in the logs. Am I doing something wrong?
The sample code has something about using post_migrate as well, but I don't need any special code to run after a migration, so I'm not sure that I need that.
Update:
My INSTALLED_APPS looks like this:
INSTALLED_APPS = [
    ...
    'settings_app.apps.SettingsAppConfig',
    'solo',  # This is for django-solo
]

Also note that the ready() method does run. If I add a print statement to it, I do see it in the logs. It's just my init_my_app() function that doesn't run.

A: I think it's likely that the database connection is initialised before your app's ready() method runs - so attaching to the signal at that point is too late.
You don't need to attach to the signal there anyway - just do the check directly in the ready() method:
def ready(self):
    from .models import MyGlobalSettings
    MyGlobalSettings.get_solo()

Note that there is potential to run into other issues here - e.g., you will get an error if migrations for the MyGlobalSettings model haven't yet been applied on the database (when running manage.py migrate for the first time, for example) - you will probably need to catch specific database exceptions and skip the creation of this object in such cases.


text:
Q: Kafka Consumer poll and reconnection We just started using Kafka for our project. We are using kafka_2.11-0.9.0.0. I have some queries related to KafkaConsumer.
1) I started Kafka Consumer before starting Zookeeper and Kafka server, but still my KafkaConsumer client was able to connect. I have following lines of code
    Consumer<String, String> consumer =  new KafkaConsumer<String,String>(props);
    consumer.subscribe(getConsumerRegisteredTopics());
    while (true) {
        ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
        for (ConsumerRecord<String, String> record : records){
           processRecord (record)
        }
   }

2) I read, Zookeeper keeps tracks of active Consumer by the use of poll(long timeout) method call. If i use Long.MAX_VALUE has timeout in poll(), how will zookeeper keeps track of my consumer. Could you please help me understand the behavior of KafkaConsumer poll call.
Thanks in advance.

A: 1) if you did'nt start zookeeper and kafka before starting your consumer it can't connect but will try to read metadata from kafka. my experience is that the KafkaConsumer 'poll' call will block undefinetly until it was able to connect and read metadata. in other words ... your consumer did'nt actually connected but is waiting for the kafka cluster to appear.
2) the poll timeout tells the consumer how long to wait until it can return any data. you have to make sure that after poll returns you invoke poll again soon enough for your consumer to stay active. The timeout given to the poll call is not related to the keepalive mechanism of the KafkaConsumer (this is controlled by the session.timeout.ms property of the consumer properties for your consumer).


text:
Q: Does supply voltage affects stepper motor driver heat dissipation? Below is a block diagram of a stepper motor controller with an external mosfet h-bridge that drives one of the stepper's coils. Let's say that the coil has 2ohm DC resistance and 3mh inductance, the motor is stationary, and the current through the coil is 2A (stabilized by the stepper controller).

*

*Does the average current from the source Vm depend on Vm's voltage (e.g. doubles when reducing Vm from 24V to 12V)?

*Does the power dissipation on the mosfets depend Vm's voltage (e.g. increased X4 when reducing Vm from 24V to 12V due to the fixed Ron of the mosfets )?

https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC5160_Datasheet_Rev1.10.pdf
EDIT: added A,B,C,D transistor references.

A: *

*Yes the supply current will be about double on 12V as compared to 24V.

*The average current through the pair of active MOSFETs is the coil current, which is fixed. The power dissipation moves from one MOSFET to the other as the supply voltage changes. For example, one might conduct for 10% of the time with 24V and the other conduct 90%, but that would change to 20% and 80% with a 12V supply. Current is only drawn from the supply in the shorter interval in this example, yielding an average coil voltage of 2.4V. There are also losses associated with the switching.
Edit: Imagine just one half-bridge driving one coil. I'll assume the other side of the coil is grounded (in reality it will conduct through the other half bridge).
The stepper coil is modeled as a resistor (2.4 ohms in this case) in series with an inductance (assumed to be large enough that the coil current does not change much during the PWM/chopping cycle).

simulate this circuit – Schematic created using CircuitLab
Let's say we set the coil current to 1A in this example, so the voltage across the coil resistance in steady state must be 2.4V. That means we need a 10% duty cycle from a 24V supply. So M1 conducts 1A for 10% of the time, and M2 conducts in reverse 1A for 90% of the time. The total conduction power dissipation of M1 and M2 is thus \$ 1A \cdot 1A
\cdot \text {Rds(on)}\$. If you lower V1 then M1 will conduct for more time (in order to maintain 1A) so its dissipation will go up, but M2 will conduct for less time so its dissipation will go down and the total stays constant.
Since there are two half bridges per coil and two coils (8 MOSFETs total) the total power dissipation of all 8 MOSFETs due to conduction is \$4\cdot I_C^2\cdot \text {Rds(on)}\$.

Returning to the total supply current and the half-bridge example above, the 24V supply sees 1A (24W) for 10% of the time, average 100mA or 2.4W. There are two coils in the stepper so that is doubled for the entire motor. If the supply is reduced to 12V the supply sees 1A (12W) for 20% of the time.
The advantage of a higher supply voltage is that during active stepping when the coil current is changing, the higher supply voltage is more quickly able to overcome the motor inductance and thus give you more torque at higher RPMs. For that, you would prefer a motor with a relatively low resistance and thus coil voltage relative to the supply voltage. Typical specs for a small (NEMA 23) motor:

Rated Current: 2.8A
Phase Resistance: 1.1 +/-15% ohm
Phase Inductance: 3.0+/-20% mH


text:
Q: Android: Open GL ES: Shape not rotating as expected I am trying to rotate a Triangle along Z axis from centre of triangle. But here i am getting triangle rotation from centre of an edge of triangle and not from its centre.
Renderer code:
@Override
public void onDrawFrame(GL10 gl) {

    float scratch[] = new float[16];

    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);

    int time = (int) (SystemClock.uptimeMillis() % 4000l);
    float angle = 0.090f * time;

    Matrix.setRotateM(mRotationMatrix, 0, angle, 0.0f, 0.0f, -1.0f);

    Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);
    triangle.draw(scratch);
}

A: The problem is more likely due to your vertices, which compose the triangle.
Solution 1: Before rotating the triangle, translate it so that its center aligns with the scene's center.
Solution 2: Provide vertices, that are around the center. For example:
glVertex(0,0,0);
glVertex(1,0,0);
glVertex(0,1,0); // will produce rotation around the first vertex

... so offset them with a half:
glVertex(0-0.5,0-0.5,0-0.5);
glVertex(1-0.5,0-0.5,0-0.5);
glVertex(0-0.5,1-0.5,0-0.5); // will produce rotation around the approximate center

Best way is to calculate the center and translate before rotation.
Good luck!


text:
Q: Perl while loop not behaving as expected I am using a while loop with a sleep inside to check when a an event has occured(i am launching a Virtual Machine, and then using the loop to wait and be sure that it is powered on and booted).
My loop is as follows:
my $vm_powerState = $vm_view->runtime->powerState->val;
my $vm_toolsStatus = $vm_view->guest->toolsStatus->val;
while (
    ($vm_powerState ne "poweredOn")
 && ($vm_toolsStatus ne "toolsOk")
) {
    debug($vmname);
    $vm_view = Vim::find_entity_view(
        view_type => 'VirtualMachine',
        filter => {"config.name" => $vmname }
    );
    debug ($vm_powerState . "\nbla\n" . $vm_toolsStatus);
    # $vm_toolsStatus = $vm_view->guest->toolsStatus->val
    if (my $ref = eval { $vm_view->can("guest")} )
    {
        print "OK\n";
        print $vm_view->guest->toolsStatus->val;
        $vm_toolsStatus = $vm_view->guest->toolsStatus->val;
    }
    $vm_powerState = $vm_view->runtime->powerState->val if (defined($vm_view));
    debug($vm_powerState . "\n\nbla222\n\n" . $vm_toolsStatus);
    debug("...");
    sleep(1);
}
debug ($vm_toolsStatus);
debug ("VM is ON");

In brief, i get the state of the VM(poweredOff and toolsNotRunning by default), and then loop until they both have good values(poweredOn and toolsOk). Should work, right?
Well, no. The first loop after powerState changes to poweredOn, the loop ends, even though toolsStatus is "toolsNotRunning".
Here's the main part of my output:
$VAR1 = \'VM TESTVM2is being turned on';
$VAR1 = \'Waiting for the VM to turn on and boot, it might take some time';
$VAR1 = \'TESTVM2';
$VAR1 = \'poweredOff
bla
toolsNotRunning';
OK
toolsNotRunning$VAR1 = \'poweredOn

bla222

toolsNotRunning';
$VAR1 = \'...';
$VAR1 = \'toolsNotRunning';
$VAR1 = \'VM is ON';

As you can see, the program exits right after the value of powerState is poweredOn, even though the second condition of the while loop is clearly not met.
Why would that happen???

A: ($vm_powerState ne "poweredOn") && ($vm_toolsStatus ne "toolsOk")
FALSE && TRUE
FALSE

You should have used || instead of &&.
!(A && B) is equivalent to (!A || !B)
A better way to write this loop would be:
until ($vm_powerState eq "poweredOn" && $vm_toolsStatus eq "toolsOk") {
  ...
}

A: You want to loop until
$vm_powerState eq "poweredOn" && $vm_toolsStatus eq "toolsOk"

Which means you want to loop while
!( $vm_powerState eq "poweredOn" && $vm_toolsStatus eq "toolsOk" )

Equivalent:
!( $vm_powerState eq "poweredOn" ) || !( $vm_toolsStatus eq "toolsOk" )

Equivalent:
$vm_powerState ne "poweredOn" || $vm_toolsStatus ne "toolsOk"

In other words, you want to loop as long as either has the wrong value, but you are looping as long as both have the wrong value.


text:
Q: Artificial Intelligence Batch File I have been trying to work on making a batch script i modified to output to a file the inputs and outputs, read the script and you will understand, but i have been unable to get it to read the file, i can get it to create it and write to it, but reading it is not working. Thanks if anyone can provide any insite. PS, it is supposed to output to a file called IO_DATA, and yes i know it has no file extension, but i do that purposely, and no thats not the issue, it still reads and rights as a text document.
@ECHO OFF
setlocal

COLOR 0a
title I/O System
cls
ECHO ** I/O System Initialized **
ECHO ****************************

if not exist IO_DATA echo ----------------------------------------
if not exist IO_DATA echo IO_DATA FILE NOT FOUND! CREATING NEW...
if not exist IO_DATA echo ----------------------------------------
if not exist IO_DATA echo.>IO_DATA

:begin
ECHO INPUT:
set INPUT=OUTPUT
SET /P INPUT=
set INPUT=%INPUT:?=%
call :%INPUT: =% 2>NUL
if %errorlevel% equ 0 goto begin

echo UNDEFINED INPUT "%INPUT%"
ECHO DEFINE

set /P OUTPUT=
echo :%INPUT: =% >> IO_DATA
echo echo OUTPUT: %OUTPUT% >> IO_DATA
echo exit /B 0 >> IO_DATA
echo REM ---------- >> IO_DATA
echo OUTPUT DEFINED FOR "%INPUT%" Successfully ( OUTPUT Defined = "%OUTPUT%" )
goto begin

A:
and no thats not the issue

yes, it is.
Analyzing the structure of that batchfile, it's designed to add new labels to itself (last code block), which can be called next time.
Adding that labels to another file doesn't make sense, because you can't call them from there.
Instead of writing to IO_DATA it should append to itself "%~dpnx0"


text:
Q: Image quality decrease when retrieving from SQL Server using ASP.NET I'm using ASP.NET to build a webpage which allow user to upload images. I use the following code to convert image to image byte:
FileUpload img = (FileUpload)fileUploadLocationPic;
Byte[] imgByte = null;
string strFileExtension = Path.GetExtension(img.PostedFile.FileName.ToString());

// Create a FILE
HttpPostedFile File = fileUploadLocationPic.PostedFile;

// Create byte array
imgByte = new Byte[File.ContentLength];

// force control to load data
File.InputStream.Read(imgByte, 0, File.ContentLength);

Then I save imgByte into SQL Server. But when I retrieve image byte from SQL Server, I can see that the image quality has decreased. Can anyone tell me how to solve this problem? Thanks in advance.
EDIT:
The way I show image is using ashx handler:
        SqlConnection connection = new SqlConnection(connectionString);
        string sql = "SELECT [ChargingBoxLocationImage] FROM [Parking Lot] WHERE [ID] = @PLID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@PLID", PLID);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }

And then in aspx, use
imageChargingLocation.ImageUrl = "~/Editor/ShowImage.ashx?PLID=" + strPLID;

It will be obvious to see the difference if you zoom in.

A: The code you have posted is fine since you are copying the bytes directly from the image.  What does your code look like that reads the data and sends it to the client?
As long as you don't load the bytes into a Bitmap and then call Bitmap.Save, your code will not decrease the image quality.


text:
Q: the given path's format is not supported in vb.net I use ESC/P or Epson Standard Code for Printers which aims to make bold. But I found there was an error "the given path's format is not supported". Is there a best solution?
Thanks
the given path's format is not supported
Dim ESC As String = "\u001B"
Dim BoldOn As String = (ESC + ("E" + "\u0001"))
Dim BoldOff As String = (ESC + ("E" + "\0"))
 Public Shared Function SendFileToPrinter(ByVal szPrinterName As String, ByVal szFileName As String) As Boolean
        ' Open the file.
        Using fs As New FileStream(szFileName, FileMode.Open)
            ' Create a BinaryReader on the file.
            Dim br As New BinaryReader(fs)

            ' Dim an array of bytes big enough to hold the file's contents.
            Dim bytes(fs.Length - 1) As Byte
            Dim bSuccess As Boolean = False
            ' Your unmanaged pointer.
            Dim pUnmanagedBytes As New IntPtr(0)
            Dim nLength As Integer

            nLength = Convert.ToInt32(fs.Length)
            ' Read the contents of the file into the array.
            bytes = br.ReadBytes(nLength)
            ' Allocate some unmanaged memory for those bytes.
            pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength)
            ' Copy the managed byte array into the unmanaged array.
            Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength)
            ' Send the unmanaged bytes to the printer.
            bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength)
            ' Free the unmanaged memory that you allocated earlier.
            Marshal.FreeCoTaskMem(pUnmanagedBytes)
            Return bSuccess
        End Using
    End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim printer As String = "Generic / Text Only"
        For i As Integer = 1 To 1
            SendFileToPrinter(printer, (BoldOn + ("C:\vDos\#LPT1.asc" + BoldOff)))
'SendFileToPrinter(printer, "C:\vDos\#LPT1.asc") if I use this code then the error does not appear
        Next i

    End Sub

A: Your are passing the result of (BoldOn + ("C:\vDos\#LPT1.asc" + BoldOff)) to the szFileName parameter of your method but the one and only place that parameter is being used is here:
Using fs As New FileStream(szFileName, FileMode.Open)

The prefix and suffix you're adding are creating a value that is not a valid file path as far as the FileStream constructor is concerned, hence the exception. You need to pass a valid file path to that constructor.
It appears that that prefix and suffix are supposed to be passed to the printer somehow, but you're not doing that. My guess would be that you need to add that prefix and suffix to the actual data from the file, not the file path, e.g.
Dim BoldOn As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\u0001"))
Dim BoldOff As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\0"))

Dim fileContents = File.ReadAllBytes(filePath)
Dim dataToPrint = BoldOn.Concat(fileContents).Concat(BoldOff).ToArray()

It appears that I need spell it out in detail, so here's your original code modified to incorporate what I explained above:
Private Shared ESC As String = "\u001B"
Private Shared BoldOn As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\u0001"))
Private Shared BoldOff As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\0"))

Public Shared Function SendFileToPrinter(printerName As String, filePath As String) As Boolean
    Dim bytes = BoldOn.Concat(File.ReadAllBytes(filePath)).Concat(BoldOff).ToArray()
    Dim byteCount = bytes.Length
    Dim unmanagedBytesPointer = Marshal.AllocCoTaskMem(byteCount)

    Marshal.Copy(bytes, 0, unmanagedBytesPointer, byteCount)

    Dim success = SendBytesToPrinter(printerName, unmanagedBytesPointer, byteCount)

    Marshal.FreeCoTaskMem(unmanagedBytesPointer)

    Return success
End Function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim printer = "Generic / Text Only"

    SendFileToPrinter(printer, "C:\vDos\#LPT1.asc")
End Sub

Note that it is just an educated guess that you need to combine those printer commands with the file contents. It's up to you to confirm that and, if it's not the case, find out what is required.


text:
Q: Is Z3 a Simple and Solvable groups? The group $C_3$ is cyclic of order $3$, and is simple. I've learned both that all abelian groups are solvable and that no simple group is solvable, which is a contradiction. What is the truth of the matter?

A: Non-abelian simple groups are not solvable. This is because simple groups don't have proper normal subgroups so the chain of normal subgroups is always trivial $\{e\}<G$. Hence if $G/\{e\}\simeq G$ is nonabelian then $G$ is not solvable.
Every abelian group is solvable on the other hand, becuase the same chain $\{e\}< G$ provides the answer.
In particular the cyclic group $C_n$ is always solvable even for prime $n$ (for which it is additionaly simple).
All in all: the only solvable and simple groups are $C_p$ for prime $p$.

A: All non-abealian simple groups are not solvable, but the abealian simple groups are solvable.
Proof: Since $G$ is simple, the only possible subnormal chain goes $\{1\}<G$. For $G$ to be normal, we need $G/\{1\}$ to be abealian. But $G/\{1\}=G$ so this is true precisely when $G$ is abelian.

A: There is something else that is good to know here. The following two statements are equivalent (and this is in fact easy to prove).
A non-abelian simple group has even order.
A group of odd order is solvable.
However, the proof of one of the statements, being an old conjecture of William Burnside, is highly non-trivial and is the famous Theorem of Feit and Thompson (1963). At the time it required a paper of $2^8-1$ pages, see http://projecteuclid.org/euclid.pjm/1103053941. It was the culmination of a long spell of research in finite group theory and group representation theory. Almost 50 years later, in September 2012, a fully formal proof, checked with the Coq proof assistant, was announced by Georges Gonthier and fellow researchers at Microsoft Research and INRIA.


text:
Q: Find the duplicate element from an integer Last week I attended interview. They asked a question for finding a duplicate element in integer value.I know program using array but they asked to me without array. Please help me for finding duplicate element in integer without array.
Question:
Find the duplicate element from an integer display the element without the duplicate number. Like I/P:43456 O/P:4356. Condition: no array should be used
Coding:
void printRepeating(int arr[], int size) {
    int i;
    printf("The repeating elements are: \n");
    for (i = 0; i < size; i++) {
        if (arr[abs(arr[i])] >= 0)
            arr[abs(arr[i])] = -arr[abs(arr[i])]; elseprintf(" %d ", abs(arr[i]));
    }
}
int main() {
    int arr[] = { 1, 2, 3, 1, 3, 6, 6 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    getchar();
    return 0;
}

A: I actually understood the question to mean that an integer, not an array of integers, should be given as input:

They asked a question for finding a duplicate element in integer value.

Here is a solution that treats this problem. In my original solution the main function was recursive. This function seemed to work, but I had misunderstood that the problem requires that the duplicate digits be taken from the lower order digits first. My recursive solution removed the higher order digits first. This meant that for the sample input provided, 43456 evaluated to 3456 instead of the desired 4356.
I have redesigned the remove_dups() function to satisfy this requirement. It is no longer recursive. The function builds a new number by consuming the input number, taking the highest order digit and combining it with the highest order digit of remaining digits, after removing duplicates.
There are three helper functions used. The remove_digits() function is used to remove all occurrences of a digit from a number. The get_place() and remove_place() functions are used to get a digit in a given place, where a place is represented by 1, 10, 100,..., and to remove a digit from a given place, respectively.
Here is an example of how the get_place() function works:
get_place(1234, 100) --> (1234 % (10 * 100) - 1234 % 100) / 100
                     --> (1234 % 1000 - 1234 % 100) / 100
                     --> (234 - 34) / 100
                     --> 200 / 100
                     --> 2

And an example of how the remove_place() function works:
remove_place(1234, 100) --> (1234 / (10 * 100)) * 100 + 1234 % 100
                        --> (1234 / 1000) * 100 + 34
                        --> 1 * 100 + 34
                        --> 100 + 34
                        --> 134

Update
The code that I originally posted did not handle negative numbers. This is because when I initially tested with negative numbers, the results were incorrect. In this broken version I used long values in the functions, except for the plc parameters, which were unsigned long. I wrongly assumed that this problem had to do with the modulus operator, and just changed everything to unsigned. It seemed that it would be simple enough to convert a desired negative number to a positive one, and then multiply the result by -1. Here are the function prototypes for the original, broken code:
long get_place(long num, unsigned long plc);
long remove_place(long num, unsigned long plc);
long remove_digits(long num, long d);
long remove_dups(long num);

But further consideration has revealed that the original problem was that an unsigned long value can not be converted to a long value, since there are unsigned long values that are not representable as long values. This was leading to some garbage results in the get_place() and remove_place() functions. Changing everything to unsigned long resolved this problem, at the cost of excluding negative input values. But, with a better understanding of the problem, I changed all of the function parameters and return values to type long. This resolves the issue, and allows negative input values to be processed correctly.
Here is the code:
#include <stdio.h>

long get_place(long num, long plc);
long remove_place(long num, long plc);
long remove_digits(long num, long d);
long remove_dups(long num);

int main(void)
{
    long number;

    printf("Enter a number (q to quit): ");
    while (scanf("%ld", &number) == 1) {
        printf("%ld\n", remove_dups(number));
        printf("Enter a number (q to quit): ");
    }

    return 0;
}

/* return digit at plc = 1, 10, 100, ... */
long get_place(long num, long plc)
{
    return (num % ( 10 * plc) - num % plc) / plc;
}

/* remove digit at plc = 1, 10, 100, ..., and return result */
long remove_place(long num, long plc)
{
    return (num / (10 * plc)) * plc + num % plc;
}

/* remove all occurrences of d in num and return result */
long remove_digits(long num, long d)
{
    long place = 1;
    while (num / place) {
        if (get_place(num, place) == d)
            num = remove_place(num, place);
        else
            place *= 10;
    }

    return num;
}

long remove_dups(long num)
{
    long result, next_digit;
    long last_place = 1;

    result = 0;
    while (num) {
        for(last_place = 1; (num / (10 * last_place)); last_place *= 10)
            continue;

        next_digit = get_place(num, last_place);
        result = result * 10 + next_digit;
        num = remove_digits((num % last_place), next_digit);
    }
    return result;
}

Here is some sample output:
Enter a number (q to quit): -43456
-4356
Enter a number (q to quit): 43456
4356
Enter a number (q to quit): -12321
-123
Enter a number (q to quit): 299792458
297458
Enter a number (q to quit): 0
0
Enter a number (q to quit): 1
1
Enter a number (q to quit): -1
-1
Enter a number (q to quit): q

A: This is a rough sketch:
For each integer in the input, traverse the input towards the beginning, and compare each integer to the current one. If there is a match, move on to the next input integer. If you reach the beginning, it isn't a duplicate, so print it.
void printRepeating(const int arr[], size_t size) {
    const int* begin = arr;
    const int* end = arr + size;
    if ( begin == end ) return;
    // First element cannot be a duplicate, so always print it
    std::cout << *begin;
    // Traverse input array
    const int* curr = begin;
    while ( ++curr < end ) {
        // Traverse back to find a duplicate
        const int* curr_rev = curr - 1;
        for ( ; curr_rev >= begin && *curr != *curr_rev; --curr_rev );
        if ( curr_rev < begin )
            // Reached the beginning, so it cannot be a duplicate
            std::cout << " " << *curr;
    }
}

And while I'm not sure, whether constructing a pointer to the element just before an array is undefined behavior, here is a slight variation, that traverses the input from front to back to find a duplicate. This is just the main loop - everything else like above:
    // Traverse input array
    const int* curr = begin;
    while ( ++curr < end ) {
        // Traverse again to find a duplicate
        const int* cmp = begin;
        for ( ; cmp < curr && *cmp != *curr; ++cmp );
        if ( cmp == curr )
            // Reached current integer, so it cannot be a duplicate
            std::cout << " " << *curr;
    }

Given this program:
int main() {
    const int arr[]{ 1, 2, 3, 1, 3, 6, 6 };
    printRepeating( arr, std::end( arr ) - std::begin( arr ) );
}

produces the following output:

1 2 3 6

A: For your example

I/P:43456 O/P:4356

one way to think about this is that a digit is output only if it isn't also present in the more-significant part of the number. So we go through each digit from least- to most-significant. If the digit (lastdig(num)) is present in the more-significant part of the number (butlastdig(num)), we discard it, otherwise we keep it.
#include <stdbool.h>
#include <stdio.h>

inline unsigned lastdig(unsigned n) { return n%10; }
inline unsigned butlastdig(unsigned n) { return n/10; }
inline bool is_single_digit(unsigned n) { return n<10; }

bool is_in(unsigned digit, unsigned num)
{
    if (is_single_digit(num))
        return digit==num;
    else
        return (digit==lastdig(num)) || is_in(digit, butlastdig(num));
}

unsigned unique(unsigned num)
{
    unsigned last, butlast;

    if (is_single_digit(num))
        return num;
    last=lastdig(num);
    butlast=unique(butlastdig(num));

    if (is_in(last, butlast))
        return butlast;
    else
        return butlast*10 + last;
}

main(int argc, char **argv)
{
    int i=atoi(argv[1]);
    if (i < 0)
        printf("nonnegative numbers only\n");
    else
        printf("%u %u\n", i, unique(i));
}


text:
Q: Как при клике на кнопку вызвать функцию нужного объекта в Unity? В игре есть юниты, которые создаются из префаба. У каждого юнита есть оружие. Всего три типа оружия. Если дружественный юнит бьет врага с таким же типом оружия, то открывается экран с тремя кнопками для выбора другого типа оружия (принцип, как в Камень, ножницы, бумага).
Проблема в том, чтобы при нажатии кнопки заменить оружие именно для выбранного юнита. Как мне передать объект, для которого это должно срабатывать?


text:
Q: ActCtx + manifest + comhost + .NET 6.0: does it work, does anyone has a working example? My goal is to expose a .NET 6.0 library to COM, in order to use it from VBA in MS Access. And to use the manifest approach rather than using the registry.
Got article "Exposing .NET Core components to COM" working, using their "COM server sample" example code.
This example however requires that a manifest file is present in the folder containing the executable. When using the COM object from MS Access we do not want to place the manifest file and other files in the MS installation folders.
The suggested solution is to create an Microsoft.Windows.ActCtx object and let that object create my COM object, using the Manifest property of the ActCtx object to specify the manifest file.
This is the part that continues to fail. actCtx.CreateObject("") gives an Invalid Cast exception, even without assignment of the result to a variable, hence it is an internal issue. No additional details, no information in the event log. Tried this in C# and from VBA.
I have a few questions:

*

*Is ActCtx the way to specify the manifest path, or is there a better way to do this from VBA in MS Office?

*The example uses a COM host, which seems to be some COM class / object factory, which in turn helps creating my COM object. As opposed to .NET Framework this COM host seems to be introduced for .NET Core; .NET 6.0 in my case. Is the COM host required? Is the simpler direct instantiation possible?

Does anyone has answers to these questions, tips, or even better: a working example?

A: Some progress but I am still not happy. Abandoned the ActCtx approach for a while and tried to create the COM server object of the sample directly in MS Access VBA. Added a reference to the com host, say COMServer.comhost.dll, as opposed to the implementation COMServer.dll. Created the object, simply with New. Error: class not registered. Performed a regsvr32 COMServer.comhost.dll and the sample works.
Although the sample works there are now again registry entries: the guid of the server class has been added to the registry. Regfree COM not achieved.
This is despite COMServer.comhost.dll looking promising. A tlb type library built separately and embedded in the .dll is seen by VBA: intellisense works and the object browser works. The manifest seems to be correctly embedded in the .dll too, and takes precedence over the manifest on disk.
The question remains how to avoid the regsvr32 step and make the solution working by just adding the reference to COMServer.comhost.dll, in MS Access VBA.


text:
Q: How to append a fom's inputs to an jquery Ajax Post's existing data parameter list I'm using the latest jquery datatables 1.10  plugin
In my ajax call I have the following by standard to pass the data to my asp.net  mvc controller
"ajax": {
            "type": "POST",
            "url": '/myUrl/MyMethod/',
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) { return data = JSON.stringify(data); }
        },

I also have a form on my page with various input elements. The id of the form is form1
what I want to do is append all this form's elements with values to the data parameters of my ajax call so my server can pick it up.
I don't want to lose the current data that is being passed by datatables. I want to append the form input elements to this JSON data.
As a workaround currently I pass it the form1 input elements's values individually in the url but this is far from ideal as you can see.
"ajax": {
            "type": "POST",
            "url": '/myUrl/MyMethod/?myselect='+$('#myselect').val(),
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) { return data = JSON.stringify(data); }
        },

Question:
How do I modify the line:
"data": function (data) { return data = JSON.stringify(data); }

to append #form1 inputs without explicitly specifying one input at a time.

A: You can use the handy .serializeArray function.
So for the jquery code:
var form_data = $("#form1").serializeArray();

//I'm just assuming here that 'table_data' is an existing array with index/values in it from your datatables

 $.each(form_date,function(index,value){
     table_data[value['name']] = value['value']
 })

 //And now both sets of data are merged and you can just pass table_data to your ajax call


text:
Q: How do I get a dummy database to test my Rails 3.2 engine using minitest? I'm working on an existing Rails 3.2 site and have been tasked with adding tests to one of the engines using Minitest.  My underlying issue here is that there are no rake tasks available beyond rake test.  Running anything in this engine's directory will result in the error:
rake aborted!
Don't know how to build task '[insert task here]'
Therefore, I have no access to db:create, db:test:prepare, etc.  I've manually created the test database and one of the tables.  However, for all my tests, I now receive the following error:
SQLite3::SQLException: no such table ... even though the table is in the database and there are fixtures available.  How do I get a working dummy database?


text:
Q: Specifying "folder" option does not upload image to folder in Cloudinary I'm having some difficulty getting uploads to the correct folder. If I specify:
cloudinary.uploader.upload(filePath, {
  folder: 'test-directory'
});

I'm following the Node integration guide at: http://cloudinary.com/documentation/image_upload_api_reference#upload
I created the "test-directory" ahead of time. The image uploads successfully, but always goes to the root of my media library.
I have "auto create folders" enabled in my account settings.
Here's a sample upload response from Cloudinary:
{
  public_id: 'we1yjvlpxc1qtuf1oaqe',
  version: 1503236713,
  signature: '37edbc2b19ea72b75298acce8075f9e8ddb12d09',
  width: 675,
  height: 37,
  format: 'jpg',
  resource_type: 'image',
  created_at: '2017-08-20T13:45:13Z',
  tags: [],
  bytes: 602,
  type: 'upload',
  etag: 'b5522ae652340881b213c46c035d0aed',
  url: 'http://res.cloudinary.com/alsoicode/image/upload/v1503236713/we1yjvlpxc1qtuf1oaqe.jpg',
  secure_url: 'https://res.cloudinary.com/alsoicode/image/upload/v1503236713/we1yjvlpxc1qtuf1oaqe.jpg',
  original_filename: 'test_r6_c1'
}

I have also tried adding the folder name to the public_id option, but that hasn't worked either.
What am I doing wrong?

A: Add the v2 to have the upload parameters' order as (file, options, callback) -
cloudinary.v2.uploader.upload(filePath, {
 folder: 'test-directory',
 use_filename: true
});

Without it the order is (file, callback, options) -
cloudinary.uploader.upload(filePath,function(res){console.log(res);},{
 folder: 'test-directory',
 use_filename: true
})

A: *

*upload parameters' order as (file, options, callback) *
cloudinary.uploader.upload(
          file,
          {
              folder: 'directory',
              use_filename: true
          },
          function (error, result) {
              if (result.url) {
                  resolve({ url: result.url })
              } else {
                  reject({ message: "image upload fail", error })
              }
          },

      );

A: cloudinary upload function expects three parameters,
cloudinary.uploader.upload(path,options,callback)
if you didn't declare the three parameters this way, cloudinary will understand your folder path as callback not an option, thus it won't understand the path nor the folder that you are pointing at.


text:
Q: Getting Time out Error while executing hadoop jar ./hadoop-examples-1.0.3.jar pi 2 5 When I am trying hadoop jar ./hadoop-examples-1.0.3.jar pi 2 5.It shows following error.
hduser@ubuntu:/usr/local/hadoop-1.0.3$ hadoop jar ./hadoop-examples-1.0.3.jar pi 2 5
Warning: $HADOOP_HOME is deprecated.

Number of Maps  = 2
Samples per Map = 5
Wrote input for Map #0
Wrote input for Map #1
Starting Job
14/12/07 09:47:33 INFO ipc.Client: Retrying connect to server: 172.16.76.1/172.16.76.1:9002. Already tried 0 time(s).
14/12/07 09:47:54 INFO ipc.Client: Retrying connect to server: 172.16.76.1/172.16.76.1:9002. Already tried 1 time(s).
^C^Chduser@ubuntu:/usr/local/hadoop-1.0.3$

hduser@ubuntu:~/data/dfs$ jps
7176 DataNode
7484 JobTracker
6960 NameNode
7704 TaskTracker
7400 SecondaryNameNode
7766 Jps
hduser@ubuntu:~/data/dfs$ cd /usr/local/hadoop-1.0.3/

As you can see that all the processes are running.But when I go to log I found the below error;

ERROR org.apache.hadoop.hdfs.server.namenode.FSNamesystem: FSNamesystem initialization failed.
org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /home/hduser/data/dfs/namenode is in an inconsistent state: storage directory does not exist or is not accessible.

I checked my .xml files configuration.Which is as follows;

mapre-site.xml

<property>
  <name>mapred.job.tracker</name>
  <value>172.16.76.1:9002</value>
</property>

core-site.xml

 <property>
   <name>fs.default.name</name>
   <value>hdfs://localhost:9001</value>
 </property>

hdfs-site.xml
<property>
   <name>dfs.name.dir</name>
   <value>/home/hduser/data/dfs/namenode</value>
</property>

<property>
   <name>dfs.data.dir</name>
   <value>/home/hduser/data/dfs/datanode</value>
</property>

<property>
  <name>dfs.replication</name>
  <value>1</value>
</property>

I tried formatting the namenode and starting again.But nothing happened.
I changed my directory owner permission to 755 and tried again but still the issue did not
resolve the issue.
I exhausted all the The suggestions given on this blog bur it did not help.
I though all the possible solution and tried so may times to solve it but still am not able to do
that.The same issue is coming again and again.
Here is the detailed error msg:
2014-12-07 06:25:05,376 INFO org.apache.hadoop.hdfs.server.common.Storage: Storage directory

/home/hduser/data/dfs/namenode does not exist.
2014-12-07 06:25:05,377 ERROR org.apache.hadoop.hdfs.server.namenode.FSNamesystem: FSNamesystem initialization failed.
org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /home/hduser/data/dfs/namenode is in an inconsistent state: storage directory does not exist or is not accessible.
        at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:303)
        at org.apache.hadoop.hdfs.server.namenode.FSDirectory.loadFSImage(FSDirectory.java:100)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.initialize(FSNamesystem.java:388)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.<init>(FSNamesystem.java:362)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:276)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:496)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1279)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1288)
2014-12-07 06:25:05,399 ERROR org.apache.hadoop.hdfs.server.namenode.NameNode: org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /home/hduser/data/dfs/namenode is in an inconsistent state: storage directory does not exist or is not accessible.
        at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:303)
        at org.apache.hadoop.hdfs.server.namenode.FSDirectory.loadFSImage(FSDirectory.java:100)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.initialize(FSNamesystem.java:388)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.<init>(FSNamesystem.java:362)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:276)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:496)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1279)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1288)
2014-12-07 06:25:05,407 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: SHUTDOWN_MSG:

A: Can you try delete the namenode storage directory /home/hduser/data/dfs/namenode and then format the namenode ?


text:
Q: My Spring Database (H2) is not Persisting This is my config file
@Configuration
@ComponentScan
public class Config {

@Bean
public DataSource datasource() {
    return new EmbeddedDatabaseBuilder().setName("MyDB").setType(EmbeddedDatabaseType.H2).addScript("schema.sql").build();
}

@Bean
public JdbcOperations jdbcTemplate(DataSource ds) {
    return new JdbcTemplate(ds);
}
}

After I run the program, I can not find the "MyDB" database.
I know it is an in-memory database. How to make it embedded so that when I close the program the data on the database persist and I can find "MyDB" on the project folder.

A: @Bean
public DataSource h2DataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

driver: org.h2.Driver
url: jdbc:h2:file:${java.io.tmpdir}/database/db_name;AUTO_SERVER=TRUE
username: user
password: pass