问:
Output caching on PartialViews doesn't work
OutputCaching on the main controller actions seems to work fine but for PartialViews they don't seem to work as expected.

I added the attribute in one of the partialviews, debugged it. I continuously hit the breakpoint inside the method (which i think means output caching isn't working).  I tried providing parameters, cacheprofiles, enablingoutputcaching and fragments but same effect.  Is there something else that I am missing?

```<code>[ValidateInput(false)]
        [OutputCache(Duration = 60000, VaryByParam = "componentId;")]
        public PartialViewResult NewCategoryComboPartial(string componentId)
        {
            //ComponentId
            ViewData[ControllerEnums.GlobalViewDataProperty.ComponentId.ToString()] = componentId;

            //ViewModel
            ViewData[ControllerEnums.GlobalViewDataProperty.ProfileComponentCategories.ToString()] = GetComponentCategoriesList();

            return PartialView("~/Views/Compliance/Profile/Partials/NewCategoryCombo.ascx");
        }
</code>```

Is it because of an existing action filter?  ValidateInputAttribute?  My PartialView()?

Thanks in advance.

UPDATE:

Below is the code snippet from the main view on how the partialview is declared.

```<code>        <div id="compliance-navigation-control">
            <% Html.RenderPartial("~/Views/Shared/Compliance/ComplianceNavigationControl.ascx", Model.PandCRecord); %>
        </div>
</code>```

Below is the content of the partialview

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="atp.webnav.Web.Controllers" %>
<%@ Import Namespace="atp.webnav.Web.Utilities" %>

<% Html.DevExpress().ComboBox(x =>
        {
            x.Name = "categoryComboBox_" + ViewData[ControllerEnums.GlobalViewDataProperty.ComponentId.ToString()].ToString();
            x.Theme = "Glass";
            x.Width = Unit.Percentage(100);
            x.Properties.ValueType = typeof(string);
            x.Properties.TextField = "Name";
            x.Properties.ValueField = "Id";
            x.SelectedIndex = 0;
            x.Properties.DropDownStyle = DropDownStyle.DropDown;
            x.Properties.MaxLength = 30;
            x.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
            x.Properties.AllowUserInput = true;
            x.CallbackRouteValues = new {Controller = "Profile", Action = "NewCategoryComboPartial"};
            x.Properties.EnableCallbackMode = true;
            x.Properties.CallbackPageSize = 1000;
            x.Properties.ClientSideEvents.BeginCallback = "webnav.compliance.profile.categoryComboBox_OnBeginCallback";
            x.Properties.ClientSideEvents.SelectedIndexChanged = "webnav.compliance.profile.categoryComboBox_OnSelectedIndexChanged";
            x.Properties.ClientSideEvents.EndCallback = "webnav.compliance.profile.categoryComboBox_OnSelectedIndexChanged";
            x.Properties.ClientSideEvents.CallbackError = DevExpressGridViewHelper.HandleCallbackErrors;

            x.Properties.EnableSynchronizationOnPerformCallback = true;
        })
        .BindList(ViewData[ControllerEnums.GlobalViewDataProperty.ProfileComponentCategories.ToString()])
        .Render();
%>
</code>```

Essentially this combobox is a devexpress combobox that has autocomplete features.  It uses callbacks to the controller actions to get the data based on the value selected.  I am trying to see if I can cache the results of the callback.  Thanks.

答:
How are you calling it? Using Html.Partial or Html.Action (as a child action)?

Quoting from Donut Hole Caching in ASP.NET MVC

"the Html.RenderPartial method ignores any OutputCache directives on the view user control"
so use Html.Action/Html.RenderAction. As they say here Caching ChildActions using cache profiles won't work use parameters Duraction and optionally VaryByParam. Profile wont work.

Body:
OutputCaching on the main controller actions seems to work fine but for PartialViews they don't seem to work as expected.

I added the attribute in one of the partialviews, debugged it. I continuously hit the breakpoint inside the method (which i think means output caching isn't working).  I tried providing parameters, cacheprofiles, enablingoutputcaching and fragments but same effect.  Is there something else that I am missing?

[ValidateInput(false)]
        [OutputCache(Duration = 60000, VaryByParam = "componentId;")]
        public PartialViewResult NewCategoryComboPartial(string componentId)
        {
            //ComponentId
            ViewData[ControllerEnums.GlobalViewDataProperty.ComponentId.ToString()] = componentId;

            //ViewModel
            ViewData[ControllerEnums.GlobalViewDataProperty.ProfileComponentCategories.ToString()] = GetComponentCategoriesList();

            return PartialView("~/Views/Compliance/Profile/Partials/NewCategoryCombo.ascx");
        }

Is it because of an existing action filter?  ValidateInputAttribute?  My PartialView()?

Thanks in advance.

UPDATE:

Below is the code snippet from the main view on how the partialview is declared.

            <% Html.RenderPartial("~/Views/Shared/Compliance/ComplianceNavigationControl.ascx", Model.PandCRecord); %>

Below is the content of the partialview

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="atp.webnav.Web.Controllers" %>
<%@ Import Namespace="atp.webnav.Web.Utilities" %>

<% Html.DevExpress().ComboBox(x =>
        {
            x.Name = "categoryComboBox_" + ViewData[ControllerEnums.GlobalViewDataProperty.ComponentId.ToString()].ToString();
            x.Theme = "Glass";
            x.Width = Unit.Percentage(100);
            x.Properties.ValueType = typeof(string);
            x.Properties.TextField = "Name";
            x.Properties.ValueField = "Id";
            x.SelectedIndex = 0;
            x.Properties.DropDownStyle = DropDownStyle.DropDown;
            x.Properties.MaxLength = 30;
            x.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
            x.Properties.AllowUserInput = true;
            x.CallbackRouteValues = new {Controller = "Profile", Action = "NewCategoryComboPartial"};
            x.Properties.EnableCallbackMode = true;
            x.Properties.CallbackPageSize = 1000;
            x.Properties.ClientSideEvents.BeginCallback = "webnav.compliance.profile.categoryComboBox_OnBeginCallback";
            x.Properties.ClientSideEvents.SelectedIndexChanged = "webnav.compliance.profile.categoryComboBox_OnSelectedIndexChanged";
            x.Properties.ClientSideEvents.EndCallback = "webnav.compliance.profile.categoryComboBox_OnSelectedIndexChanged";
            x.Properties.ClientSideEvents.CallbackError = DevExpressGridViewHelper.HandleCallbackErrors;

            x.Properties.EnableSynchronizationOnPerformCallback = true;
        })
        .BindList(ViewData[ControllerEnums.GlobalViewDataProperty.ProfileComponentCategories.ToString()])
        .Render();
%>

Essentially this combobox is a devexpress combobox that has autocomplete features.  It uses callbacks to the controller actions to get the data based on the value selected.  I am trying to see if I can cache the results of the callback.  Thanks.


来源: stackexchange

问:
W/MediaPlayer: Couldn't open java.io.FileNotFoundException: No content provider:
I am trying to load a String url into mediaPlayer but getting following error

```<code>W/MediaPlayer: Couldn't open https://somewebsite.com/video.mp4: java.io.FileNotFoundException: No content provider:
</code>```

When I access the link via browser the video plays fine.

Following is my code.

In Swipe Adapter (It loads from a list, and when you swipe  it loads more)

```<code>void setVideoData(VideosListModel videosListModel) {

    vvVideo.setVideoPath(videosListModel.getVideo_url());
    vvVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            pbProgressBar.setVisibility(View.GONE);
            mp.start();

            float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
            float screenRatio = vvVideo.getWidth() / (float) vvVideo.getHeight();
            float scale = videoRatio / screenRatio;
            if (scale >= 1f) {
                vvVideo.setScaleX(scale);
            } else {
                vvVideo.setScaleY(1f / scale);
            }
        }
    });
    vvVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.start();
        }
    });
}
</code>```

Interestingly when I upload using API27 from a Real Phone it works, but when using API31 Redmi Note 10 Pro Max it does not work for the same video.  Even though there is error on API27 but it still plays.

答:
If you not add this in Manifest.xml

 and error may be in onPrepared

ContentLicense: CC BY-SA 4.0

Body:
I am trying to load a String url into mediaPlayer but getting following error

W/MediaPlayer: Couldn't open https://somewebsite.com/video.mp4: java.io.FileNotFoundException: No content provider:

When I access the link via browser the video plays fine.

Following is my code.

In Swipe Adapter (It loads from a list, and when you swipe  it loads more)

void setVideoData(VideosListModel videosListModel) {

    vvVideo.setVideoPath(videosListModel.getVideo_url());
    vvVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            pbProgressBar.setVisibility(View.GONE);
            mp.start();

            float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
            float screenRatio = vvVideo.getWidth() / (float) vvVideo.getHeight();
            float scale = videoRatio / screenRatio;
            if (scale >= 1f) {
                vvVideo.setScaleX(scale);
            } else {
                vvVideo.setScaleY(1f / scale);
            }
        }
    });
    vvVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.start();
        }
    });
}

Interestingly when I upload using API27 from a Real Phone it works, but when using API31 Redmi Note 10 Pro Max it does not work for the same video.  Even though there is error on API27 but it still plays.


问:
php echo from a start point to a end point
I have built a php site that takes code from a page using GET, and then echos it to the current page, but it exports text like this,

{ "selection13": [ { "name": "L" }, { "name": "100%\nA" } ], "selection7": [ { "name": "S" }, { "name": "100%\nA" } ], "selection8": [ { "name": "SS" }, { "name": "100%\nA" } ], "selection9": [ { "name": "SP" }, { "name": "100%\nA" } ], "selection10": [ { "name": "P" }, { "name": "100%\nA" } ], "selection11": [ { "name": "A" }, { "name": "100.00%\nA+" } ], "selection12": [ { "name": "H", "selection5": [ { "name": "T }, { "name": "100.00%\nA+" } ] }, { "name": "100.00%\nA+", "selection5": [ { "name": "T" }, { "name": "100.00%\nA+" } ] } ] }```
</div>
</div>
</p>
<p>I need to organizes it in to categorizes like, {L},{100%), here is the code I am currently using,</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
$params = http_build_query(array(
  "api_key" => "()",
  "format" => "json"
));

$result = file_get_contents(
    '(url)'.$params,
    false,
    stream_context_create(array(
        'http' => array(
            'method' => 'GET'
        )
    ))
);
echo gzdecode($result);
?></code>```

答:
Your script is outputting JSON but there appears to be a few issues with the data itself that need to be addressed first.

The next to the last "name": "T  is missing a closing quote.

Section 12 has an inconsistent organization compared to the other sections. Can a section be a child of another section or is this an error?

  "selection11": [
    {
      "name": "A"
    },
    {
      "name": "100.00%\nA+"
    }
  ],
  "selection12": [
    {
      "name": "H",
      "selection5": [
        {
          "name": "T"
        },
        {
          "name": "100.00%\nA+"
        }
      ]
    },
    {
      "name": "100.00%\nA+",
      "selection5": [
        {
          "name": "T"
        },
        {
          "name": "100.00%\nA+"
        }
      ]
    }
  ]
```
<p>These 2 issues need to be fixed in the JSON data you are retrieving first.</p>
<p>From there, the best way to reorganize this is to convert it to an array using json_decode.</p>
```$json = gzdecode($result);
$resultArray = json_decode($json);
```

I can't tell from your question exactly how you want to reorganize the data but use one or more of the builtin array functions to get the data in the structure you want. If you need to output it in JSON, use json_encode on the manipulated array to get the final data format. More specific help can be provided if you can be more clear on want output structure you are looking for and the format (does it need to be JSON or something else).

Body:
I have built a php site that takes code from a page using GET, and then echos it to the current page, but it exports text like this,

{ "selection13": [ { "name": "L" }, { "name": "100%\nA" } ], "selection7": [ { "name": "S" }, { "name": "100%\nA" } ], "selection8": [ { "name": "SS" }, { "name": "100%\nA" } ], "selection9": [ { "name": "SP" }, { "name": "100%\nA" } ], "selection10": [ { "name": "P" }, { "name": "100%\nA" } ], "selection11": [ { "name": "A" }, { "name": "100.00%\nA+" } ], "selection12": [ { "name": "H", "selection5": [ { "name": "T }, { "name": "100.00%\nA+" } ] }, { "name": "100.00%\nA+", "selection5": [ { "name": "T" }, { "name": "100.00%\nA+" } ] } ] }

I need to organizes it in to categorizes like, {L},{100%), here is the code I am currently using,

<?php
$params = http_build_query(array(
  "api_key" => "()",
  "format" => "json"
));

$result = file_get_contents(
    '(url)'.$params,
    false,
    stream_context_create(array(
        'http' => array(
            'method' => 'GET'
        )
    ))
);
echo gzdecode($result);
?>

Body:
Your script is outputting JSON but there appears to be a few issues with the data itself that need to be addressed first.

The next to the last "name": "T  is missing a closing quote.

Section 12 has an inconsistent organization compared to the other sections. Can a section be a child of another section or is this an error?

  "selection11": [
    {
      "name": "A"
    },
    {
      "name": "100.00%\nA+"
    }
  ],
  "selection12": [
    {
      "name": "H",
      "selection5": [
        {
          "name": "T"
        },
        {
          "name": "100.00%\nA+"
        }
      ]
    },
    {
      "name": "100.00%\nA+",
      "selection5": [
        {
          "name": "T"
        },
        {
          "name": "100.00%\nA+"
        }
      ]
    }
  ]

These 2 issues need to be fixed in the JSON data you are retrieving first.

From there, the best way to reorganize this is to convert it to an array using json_decode.

$json = gzdecode($result);
$resultArray = json_decode($json);

I can't tell from your question exactly how you want to reorganize the data but use one or more of the builtin array functions to get the data in the structure you want. If you need to output it in JSON, use json_encode on the manipulated array to get the final data format. More specific help can be provided if you can be more clear on want output structure you are looking for and the format (does it need to be JSON or something else).


问:
How to copy element's innerhtml with attributes
I need some help about copying a element's innerHTMl text to another element with the attributes. Source element is a text that has html tags such as color and strong (for bold letters), the target element copies the source's elements innerHTML text as is with the html tags such as color and strong (for bold letters)  but it doesn't display the color and bold text (it simply display the plain text) but the source element has the text with the color and bold letters.

I'm using javascript.

Not sure how can I achieve this?

答:
So you can for example transfer all attributes from text1 to text2.

var $text1 = $("#text1");
var $text2 = $("#text2");

var attributes = $text1.prop("attributes");
// loop through text1 attributes and apply them on text2
$.each(attributes, function() {
    $text2.attr(this.name, this.value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 Hello
<br>
 World! </code>```

Body:
So you can for example transfer all attributes from text1 to text2.

var $text1 = $("#text1");
var $text2 = $("#text2");

var attributes = $text1.prop("attributes");
// loop through text1 attributes and apply them on text2
$.each(attributes, function() {
    $text2.attr(this.name, this.value);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<a style="color: red" id="text1"> Hello </a>
<br>
<a id="text2"> World! </a>


问:
RN Release build fails, but debug runs. Error:Execution failed for task ':app:compileReleaseJavaWithJavac'
I have a react-native app that runs perfectly well in debug, but fails on a release build.
Running node 16.3.2 inside Windows 11 with react-native 0.63.4

Any thoughts on what to try would be greatly appreciated.

The build error from gradlew assembleRelease is:

```<code>> Task :app:compileReleaseJavaWithJavac FAILED
C:\Projects\right-on-course-expo - ejectRelease-20220207\android\app\src\main\java\com\hordernit\rightoncourseapp\MainApplication.java:3: error: class, interface, or enum expected
package com.hordernit.rightoncourseapp;
^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
</code>```

The MainApplication.java referred to in the error is as follows:

```<code>import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
package com.hordernit.rightoncourseapp;

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

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.hordernit.rightoncourseapp.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.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 Application implements ReactApplication {
  private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
    new BasePackageList().getPackageList()
  );

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return DevLauncherController.getInstance().getUseDeveloperSupport();
    }

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

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

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

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

    @Override
    protected @Nullable String getBundleAssetName() {
      if (BuildConfig.DEBUG) {
        return super.getBundleAssetName();
      } else {
        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);
    }

    DevLauncherController.initialize(this, getReactNativeHost());
    if (BuildConfig.DEBUG) {
      DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.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.hordernit.rightoncourseapp.ReactNativeFlipper");
        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();
      }
    }
  }
}
</code>```

My /android/build.gradle file is as follows:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")

        // 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' }
    }
}
</code>```

and the android/app/build.gradle looks like:

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
]

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
    }

    defaultConfig {
        applicationId 'com.hordernit.rightoncourseapp'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0.0"
    }
    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'
        }
        release {
            storeFile file('roc-app.jks')
            storePassword 'snip'
            keyAlias 'snip'
            keyPassword 'snip'
        }
    }
    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.release
            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"
</code>```

答:
Try declaring the package separately above the imports like this:</p>
```<code>package com.hordernit.rightoncourseapp;

import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;

import android.app.Application;
import android.content.Context;
import android.net.Uri;
//....
</code>```

Body:
I have a react-native app that runs perfectly well in debug, but fails on a release build.
Running node 16.3.2 inside Windows 11 with react-native 0.63.4

Any thoughts on what to try would be greatly appreciated.

The build error from gradlew assembleRelease is:

> Task :app:compileReleaseJavaWithJavac FAILED
C:\Projects\right-on-course-expo - ejectRelease-20220207\android\app\src\main\java\com\hordernit\rightoncourseapp\MainApplication.java:3: error: class, interface, or enum expected
package com.hordernit.rightoncourseapp;
^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

The MainApplication.java referred to in the error is as follows:

import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
package com.hordernit.rightoncourseapp;

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

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.hordernit.rightoncourseapp.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.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 Application implements ReactApplication {
  private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
    new BasePackageList().getPackageList()
  );

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return DevLauncherController.getInstance().getUseDeveloperSupport();
    }

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

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

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

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

    @Override
    protected @Nullable String getBundleAssetName() {
      if (BuildConfig.DEBUG) {
        return super.getBundleAssetName();
      } else {
        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);
    }

    DevLauncherController.initialize(this, getReactNativeHost());
    if (BuildConfig.DEBUG) {
      DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.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.hordernit.rightoncourseapp.ReactNativeFlipper");
        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();
      }
    }
  }
}

My /android/build.gradle file is as follows:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")

        // 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' }
    }
}

and the android/app/build.gradle looks like:

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
]

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
    }

    defaultConfig {
        applicationId 'com.hordernit.rightoncourseapp'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0.0"
    }
    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'
        }
        release {
            storeFile file('roc-app.jks')
            storePassword 'snip'
            keyAlias 'snip'
            keyPassword 'snip'
        }
    }
    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.release
            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"

Body:
Try declaring the package separately above the imports like this:

package com.hordernit.rightoncourseapp;

import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;

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


问:
ELB health check hitting wrong endpoint
My .NET Core Elastic beanstalk app is healthy but when i check the logs i see the following:

```<code>10.3.12.142 - - [06/Feb/2022:17:54:53 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.2.20"
10.3.11.145 - - [06/Feb/2022:17:54:57 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.1.114"
10.3.11.145 - - [06/Feb/2022:17:55:07 +0000] "GET /_system/health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [06/Feb/2022:17:55:07 +0000] "GET /_system/health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.11.145 - - [06/Feb/2022:17:55:07 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.1.114"
10.3.11.145 - - [06/Feb/2022:17:55:22 +0000] "GET /_system/health HTTP/1.1" 200 237 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [06/Feb/2022:17:55:22 +0000] "GET /_system/health HTTP/1.1" 200 237 "-" "ELB-HealthChecker/2.0" "-"
</code>```

/_system/health is the real health endpoint but i don't understand why ELB is hitting / instead of just /_system/health which ofcourse result in 404 which is expected from the app.

I have the following terraform config for health check and i don't use .ebextensions

```<code>setting {
    namespace = "aws:elasticbeanstalk:environment:process:default"
    name      = "HealthCheckPath"
    value     = "/_system/health"
  }

  setting {
    namespace = "aws:elasticbeanstalk:application"
    name      = "Application Healthcheck URL"
    value     = "/_system/health"
  }
</code>```

Edit 1

After i change the healthcheck path to /health(thanks @Marcin i notice that ELB-HealthChecker is still hitting /

```<code>10.3.11.145 - - [07/Feb/2022:08:35:08 +0000] "GET /health HTTP/1.1" 200 227 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [07/Feb/2022:08:35:08 +0000] "GET /health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [07/Feb/2022:08:35:13 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.2.20"
</code>```

答:
/_system/health is not supported. The valid paths are:

```<code>/ (HTTP GET to root path)

/health

HTTPS:443/

HTTPS:443/health
</code>```

Title: ELB health check hitting wrong endpoint

Body:
My .NET Core Elastic beanstalk app is healthy but when i check the logs i see the following:

10.3.12.142 - - [06/Feb/2022:17:54:53 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.2.20"
10.3.11.145 - - [06/Feb/2022:17:54:57 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.1.114"
10.3.11.145 - - [06/Feb/2022:17:55:07 +0000] "GET /_system/health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [06/Feb/2022:17:55:07 +0000] "GET /_system/health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.11.145 - - [06/Feb/2022:17:55:07 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.1.114"
10.3.11.145 - - [06/Feb/2022:17:55:22 +0000] "GET /_system/health HTTP/1.1" 200 237 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [06/Feb/2022:17:55:22 +0000] "GET /_system/health HTTP/1.1" 200 237 "-" "ELB-HealthChecker/2.0" "-"

/_system/health is the real health endpoint but i don't understand why ELB is hitting / instead of just /_system/health which ofcourse result in 404 which is expected from the app.

I have the following terraform config for health check and i don't use .ebextensions

setting {
    namespace = "aws:elasticbeanstalk:environment:process:default"
    name      = "HealthCheckPath"
    value     = "/_system/health"
  }

  setting {
    namespace = "aws:elasticbeanstalk:application"
    name      = "Application Healthcheck URL"
    value     = "/_system/health"
  }

Edit 1

After i change the healthcheck path to /health(thanks @Marcin i notice that ELB-HealthChecker is still hitting /

10.3.11.145 - - [07/Feb/2022:08:35:08 +0000] "GET /health HTTP/1.1" 200 227 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [07/Feb/2022:08:35:08 +0000] "GET /health HTTP/1.1" 200 232 "-" "ELB-HealthChecker/2.0" "-"
10.3.12.142 - - [07/Feb/2022:08:35:13 +0000] "GET / HTTP/1.1" 404 0 "-" "ELB-HealthChecker/2.0" "10.3.2.20"

Body:
/_system/health is not supported. The valid paths are:

/ (HTTP GET to root path)

/health

HTTPS:443/

HTTPS:443/health


问:
ModuleNotFoundError: No module named 'sktime.transformers'
I tried importing

```<code>from sktime.transformers.series_as_features.rocket import Rocket
</code>```

When I run this, I encounter this error ---

```<code>File "C:\Users\Success\AppData\Local\Temp/ipykernel_8440/2082396040.py", line 1, in <module>
runfile('C:/Users/Success/Desktop/untitled8.py', wdir='C:/Users/Success/Desktop')

File "C:\Users\Success\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_bundle\pydev_umd.py", line 167, in runfile
execfile(filename, namespace)
File "C:\Users\Success\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
exec(compile(contents + "\n", file, 'exec'), glob, loc)
File "C:/Users/Success/Desktop/untitled8.py", line 11, in <module>
from sktime.transformers.series_as_features.rocket import Rocket

ModuleNotFoundError: No module named 'sktime.transformers
</code>```

答:
I ran into a similar problem. They have moved the actual location of the module in the library. Trying this path should fix the issue you have:

from sktime.transformations.panel.rocket import Rocket

Body:
I tried importing

from sktime.transformers.series_as_features.rocket import Rocket

When I run this, I encounter this error ---

File "C:\Users\Success\AppData\Local\Temp/ipykernel_8440/2082396040.py", line 1, in <module>
runfile('C:/Users/Success/Desktop/untitled8.py', wdir='C:/Users/Success/Desktop')

File "C:\Users\Success\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_bundle\pydev_umd.py", line 167, in runfile
execfile(filename, namespace)
File "C:\Users\Success\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
exec(compile(contents + "\n", file, 'exec'), glob, loc)
File "C:/Users/Success/Desktop/untitled8.py", line 11, in <module>
from sktime.transformers.series_as_features.rocket import Rocket

ModuleNotFoundError: No module named 'sktime.transformers


问:
Know if iOS device has cellular data capabilities
I have a toggle in my app that's "download on WiFi only". However, that toggle is useless for iPod touch or WiFi-iPads.

Is there a way to know if the device has cellular data capabilities in code? Something that would work in the future would be great too (like if an iPod touch 5th gen with 3G comes out).

答:
3G by itself seems tough to find. You can find out whether a device can make calls using [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]]. You can check whether a device can get to the internet, period (and by which method that can currently happen) using Reachability code:

```<code>NetworkStatus currentStatus = [[Reachability reachabilityForInternetConnection]
                               currentReachabilityStatus];

if(currentStatus == kReachableViaWWAN) // 3G

else if(currentStatus == kReachableViaWifi) // ...wifi

else if(currentStatus == kNotReachable) // no connection currently possible
</code>```

..but aside from that, I don't think you can check for the existence of a 3G modem in the device.***** If it can't make a call, and doesn't currently have cell data turned on and wifi turned off, you won't be able to find out if it's 3G-capable.

An alternative way (not forward-compatible though, so you probably don't want to do this) is to compare the device's model with an exhaustive list, knowing which ones have 3G modems in them, as shown here.

***** As per bentech's answer, if you want to go digging around with device names (this may stop working with no advance warning if Apple decide to change the 3g interface name), call getifaddrs and check for the pdp_ip0 interface.

ContentLicense: CC BY-SA 3.0

Body:
3G by itself seems tough to find. You can find out whether a device can make calls using [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]]. You can check whether a device can get to the internet, period (and by which method that can currently happen) using Reachability code:

NetworkStatus currentStatus = [[Reachability reachabilityForInternetConnection]
                               currentReachabilityStatus];

if(currentStatus == kReachableViaWWAN) // 3G

else if(currentStatus == kReachableViaWifi) // ...wifi

else if(currentStatus == kNotReachable) // no connection currently possible

..but aside from that, I don't think you can check for the existence of a 3G modem in the device.***** If it can't make a call, and doesn't currently have cell data turned on and wifi turned off, you won't be able to find out if it's 3G-capable.

An alternative way (not forward-compatible though, so you probably don't want to do this) is to compare the device's model with an exhaustive list, knowing which ones have 3G modems in them, as shown here.

***** As per bentech's answer, if you want to go digging around with device names (this may stop working with no advance warning if Apple decide to change the 3g interface name), call getifaddrs and check for the pdp_ip0 interface.


问:
text box that goes to website when answer is correct
I need the user to type a word and if its the right keyword, I need it to change pages.

my code

```<code><form action="/yay.html">
    <label>what's 1+1</label><br>
    <input type="text"><br>
    <input type="submit" value="Submit">
</form>
</code>```

for example I want something a bit like this.

```<code><script>
function checkstuff() {
if text = "hello world"
}
</script>
//so a function checks if the text is equal to "hello world"

<form action="/yay.html">
    <input type="text">
    <input type="submit" value="Submit" onclick="checkstuff()">
    //submit input runs function
</form>
</code>```

答:
In the solution below, the user input is evaluated to enable/disable the disabled attribute of the submit button.

const submit = document.getElementById('submit');
let answer = document.getElementById('answer');
const target = 2;

function log(value, mode) {
  console.clear();

  if(mode)
    console.log(`Information: ${value}`);
  else
    console.log(`Input: ${value}`);
}

answer.addEventListener('input', function(event) {
  log(this.value, true);

  if(parseInt(this.value) == target) {
    submit.disabled = false;
  }
  else {
    submit.disabled = true;
  }
});

submit.addEventListener('click', function(event) {
  log("Button fired.", false);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="/yay.html">
    <label>what's 1+1</label><br>
    <input id="answer" type="text"><br>
    <input id="submit" type="submit" value="Submit" disabled>
</form></code>```

Body:
I need the user to type a word and if its the right keyword, I need it to change pages.

my code

<form action="/yay.html">
    what's 1+1

    <input type="text">

    <input type="submit" value="Submit">
</form>

for example I want something a bit like this.

//so a function checks if the text is equal to "hello world"

<form action="/yay.html">
    <input type="text">
    <input type="submit" value="Submit" onclick="checkstuff()">
    //submit input runs function
</form>

Body:
In the solution below, the user input is evaluated to enable/disable the disabled attribute of the submit button.

const submit = document.getElementById('submit');
let answer = document.getElementById('answer');
const target = 2;

function log(value, mode) {
  console.clear();

  if(mode)
    console.log(`Information: ${value}`);
  else
    console.log(`Input: ${value}`);
}

answer.addEventListener('input', function(event) {
  log(this.value, true);

  if(parseInt(this.value) == target) {
    submit.disabled = false;
  }
  else {
    submit.disabled = true;
  }
});

submit.addEventListener('click', function(event) {
  log("Button fired.", false);
});

<form action="/yay.html">
    <label>what's 1+1</label><br>
    <input id="answer" type="text"><br>
    <input id="submit" type="submit" value="Submit" disabled>
</form>


问:
How to download entire react component as pdf?
I have a resume component that I want to download as a pdf. I'm able to do that using html2canvas and jspdf.

```<code>const printDocument = () => {
const input = document.getElementById('resume-wrapper');
html2canvas(input)
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    console.log("clicked",typeof(imgData))
    const pdf = new jsPDF();
    pdf.addImage(imgData, 'JPEG', 10, 10);
    pdf.save("download.pdf");
  })
};
</code>```

But, I'm getting a small part of my resume component instead of the entire component. The pdf is smaller width and height wise. What can I do to get the entire component?

答:
Your problem is basic page control (PDF is a page XY language) so your new page needs to be defined well and the image needs to work XY within that.

Here is a small sample to show how the two (page and image) inter-relate.
Note the image is FORCED to the defined area, so units need to be calculated before application. If placement is not defined well you will cause stretching (here its desired for image 1 but not image 2) or in your case truncation.

```<code>// You'll need to make your image into a Data URL
// From https://contemporarycodes.com/dataUrl/Generator.en.html (minimal size)
var imgData1 = 'data:image/jpeg;base64,/9j/...too big for SO example thus use demodata...';

var imgData2 = 'data:image/png;base64,[encoded data, 15300 characters]'

// Set up page structure = landscape and metric units plus dimensions
var doc = new jsPDF("l", "mm", [297,210]);

// Build page 1
doc.setPage(1);
doc.setFont('helvetica', 'italic');
doc.setFontSize(30); //Font is Points not page units = approx. 10 mm total but 2 mm below baseline so set 8 mm down !
doc.text('I am a top left heading on page 1', 8.5, 8);

doc.addImage(imgData1, "JPG", 8.5, 10, 280, 190, "A Limousine Cat", "none", 0);
doc.addImage(imgData2, "PNG", 238.5, 150, 50, 50, "Hello World!", "none", 0);

doc.setFillColor(255, 255, 127); //Prepare colour of  rectangle
doc.rect(104.5, 114.5, 80, 10, 'F');
doc.text('I am text overlay', 105, 123); //Keeps previous font height and style

doc.setFont('helvetica', 'normal');
doc.setFontSize(30); //Font is Points not page units = approx. 10 mm total but 2 mm below baseline so set 8 mm down !
doc.text('I am a bottom right footing on page 1', 124, 207.5);

doc.save("download.pdf");

</code>```

Body:
I have a resume component that I want to download as a pdf. I'm able to do that using html2canvas and jspdf.

const printDocument = () => {
const input = document.getElementById('resume-wrapper');
html2canvas(input)
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    console.log("clicked",typeof(imgData))
    const pdf = new jsPDF();
    pdf.addImage(imgData, 'JPEG', 10, 10);
    pdf.save("download.pdf");
  })
};

But, I'm getting a small part of my resume component instead of the entire component. The pdf is smaller width and height wise. What can I do to get the entire component?

Body:
Your problem is basic page control (PDF is a page XY language) so your new page needs to be defined well and the image needs to work XY within that.

Here is a small sample to show how the two (page and image) inter-relate.
Note the image is FORCED to the defined area, so units need to be calculated before application. If placement is not defined well you will cause stretching (here its desired for image 1 but not image 2) or in your case truncation.

// You'll need to make your image into a Data URL
// From https://contemporarycodes.com/dataUrl/Generator.en.html (minimal size)
var imgData1 = 'data:image/jpeg;base64,/9j/...too big for SO example thus use demodata...';

var imgData2 = 'data:image/png;base64,[encoded data, 15300 characters]'

// Set up page structure = landscape and metric units plus dimensions
var doc = new jsPDF("l", "mm", [297,210]);

// Build page 1
doc.setPage(1);
doc.setFont('helvetica', 'italic');
doc.setFontSize(30); //Font is Points not page units = approx. 10 mm total but 2 mm below baseline so set 8 mm down !
doc.text('I am a top left heading on page 1', 8.5, 8);

doc.addImage(imgData1, "JPG", 8.5, 10, 280, 190, "A Limousine Cat", "none", 0);
doc.addImage(imgData2, "PNG", 238.5, 150, 50, 50, "Hello World!", "none", 0);

doc.setFillColor(255, 255, 127); //Prepare colour of  rectangle
doc.rect(104.5, 114.5, 80, 10, 'F');
doc.text('I am text overlay', 105, 123); //Keeps previous font height and style

doc.setFont('helvetica', 'normal');
doc.setFontSize(30); //Font is Points not page units = approx. 10 mm total but 2 mm below baseline so set 8 mm down !
doc.text('I am a bottom right footing on page 1', 124, 207.5);

doc.save("download.pdf");


问:
Hide/Show Form Elements Not Working on Android App
I'm trying to create an interactive form. Your selections determine the next questions that appear. I'm using jQuery Mobile and it is working fine on the PC using Dreamweaver but when I build to Android the java scripts aren't working. This seems like simple code so I'm not sure why it's not working on Android. Can someone tell me where I'm going wrong?

Here's the code:

Javascript:

```<code>function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
</code>```

HTML:

```<code><div id=SkillSet data-role="fieldcontain">
      <fieldset data-role="controlgroup" data-type="horizontal">
        <legend>Skill Set:</legend>
        <a onclick="toggle_visibility('AV');"><input type="checkbox" name="SkillSet" id="SkillSet_0" class="custom" value="" /></a>
        <label for="SkillSet_0">AV</label>
        <a onclick="toggle_visibility('IT');"><input type="checkbox" name="SkillSet" id="SkillSet_1" class="custom" value="" /></a>
        <label for="SkillSet_1">IT</label>
      </fieldset>
    </div>

   <div id="IT" style="display:none">
    <hr>

    Blah Blah Blah
</div>
</code>```

答:
This is an interesting one:

Android web DOES support display:none
And javascript
And jQuery mobile isn't being used

I think it might be because you have an anchor tag around your input. Try putting the onclick event on the checkbox or put something else in the anchor.

EDIT:
Or could it be that there are multiple elements with the same id? Ids are supposed to be unique...

Body:
I'm trying to create an interactive form. Your selections determine the next questions that appear. I'm using jQuery Mobile and it is working fine on the PC using Dreamweaver but when I build to Android the java scripts aren't working. This seems like simple code so I'm not sure why it's not working on Android. Can someone tell me where I'm going wrong?

Here's the code:

Javascript:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}

HTML:

      <fieldset data-role="controlgroup" data-type="horizontal">
        <legend>Skill Set:</legend>
        <input type="checkbox" name="SkillSet" id="SkillSet_0" class="custom" value="" />
        AV
        <input type="checkbox" name="SkillSet" id="SkillSet_1" class="custom" value="" />
        IT
      </fieldset>

    Blah Blah Blah


问:
Does Go have no real way to shrink a slice? Is that an issue?
I've been trying out Go for some time and this question keeps bugging me. Say I build up a somewhat large dataset in a slice (say, 10 million int64s).

```<code>package main

import (
    "math"
    "fmt"
)

func main() {
    var a []int64
    var i int64;
    upto := int64(math.Pow10(7))
    for i = 0; i < upto; i++ {
        a = append(a, i)
    }
    fmt.Println(cap(a))
}
</code>```

But then I decide I don't want most of them so I want to end up with a slice of just 10 of those. I've tried both slicing and delete techniques on Go's wiki but none of them seem to reduce the slice's capacity.

So that's my question: does Go has no real way of shrinking the capacity of a slice that would be similar to realloc()-ing with a smaller size argument than in your previous call on the same pointer in C? Is that an issue and how should one deal with it?

答:
There is a new feature called 3-index slice in Go 1.2, which means to get part of a slice in this way:

slice[a:b:c]
```
<p>In which the <code>len</code> for the returned slice whould be <code>b-a</code>, and the <code>cap</code> for the new slice would be <code>c-a</code>.</p>
<p>Tips: no copy is down in the whole process, it only returns a new slice which points to <code>&slice[a]</code> and has the len as <code>b-a</code> and cav as <code>c-a</code>.</p>
<p>And that's the only thing you have to do:</p>
```slice= slice[0:len(slice):len(slice)];
```

Then the cap of the slice would be changed to len(slice) - 0, which is the same as the len of it, and no copy is done.

Body:
I've been trying out Go for some time and this question keeps bugging me. Say I build up a somewhat large dataset in a slice (say, 10 million int64s).

package main

import (
    "math"
    "fmt"
)

func main() {
    var a []int64
    var i int64;
    upto := int64(math.Pow10(7))
    for i = 0; i < upto; i++ {
        a = append(a, i)
    }
    fmt.Println(cap(a))
}

But then I decide I don't want most of them so I want to end up with a slice of just 10 of those. I've tried both slicing and delete techniques on Go's wiki but none of them seem to reduce the slice's capacity.

So that's my question: does Go has no real way of shrinking the capacity of a slice that would be similar to realloc()-ing with a smaller size argument than in your previous call on the same pointer in C? Is that an issue and how should one deal with it?

Body:
There is a new feature called 3-index slice in Go 1.2, which means to get part of a slice in this way:

slice[a:b:c]

In which the len for the returned slice whould be b-a, and the cap for the new slice would be c-a.

Tips: no copy is down in the whole process, it only returns a new slice which points to &slice[a] and has the len as b-a and cav as c-a.

And that's the only thing you have to do:

slice= slice[0:len(slice):len(slice)];

Then the cap of the slice would be changed to len(slice) - 0, which is the same as the len of it, and no copy is done.


问:
Regular expression not returning everything on pattern in python
I'm using https://regexr.com/ for testing the regex pattern with the following,

but when I try to use the same pattern in python I got

how can I rewrite the python pattern so I can retrieve the "state of " as in the regexr site?

答:
Put the whole string you want to capture into parentheses. Note that with multiple capture groups, the result will be a list of tuples (the first element of the tuple will be the first capture group):

```<code>import re
re.findall(r'state.*.(ny|new york)', 'consumption state of ny ')
</code>```

['ny']

```<code>re.findall(r'(state.*.(ny|new york))', 'consumption state of ny ')
</code>```

[('state of ny', 'ny')]

Body:
Put the whole string you want to capture into parentheses. Note that with multiple capture groups, the result will be a list of tuples (the first element of the tuple will be the first capture group):

import re
re.findall(r'state.*.(ny|new york)', 'consumption state of ny ')

['ny']

re.findall(r'(state.*.(ny|new york))', 'consumption state of ny ')

[('state of ny', 'ny')]


问:
Alternate way to get Azure AD sign in logs in Python without using subprocess library and powershell.exe
As far as I can tell by looking at other posts, using the subprocess library in Python is the most popular way to execute PowerShell commands from within Python. For example:

```<code>data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId me@me.com \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)
</code>```

However, I'm ultimately trying to add this script to an automation account in Azure. Specifying the executable "powershell.exe" in the script won't work in an Azure automation account runbook (raises a "FileNotFound" error).

Is there some other way you can get the sign in log data from within Python that would be more amenable to using in an Azure automation account runbook? Can the Azure library be used to get sign in log data instead?

答:
I have tested in my environment

You can use MS Graph API query in your python script to get the Azure AD sign in logs of the users

You can use below python code:

```<code>import requests
import json

url = 'https://graph.microsoft.com/v1.0/auditLogs/signIns'
token = "access_token"

headers = {
 'Authorization': 'Bearer {}'.format(token)
}

user_response_data = json.loads(requests.get(url, headers=headers).text)
print(user_response_data)
</code>```

Reference: Querying Microsoft Graph API with Python | by Ephraim Mwai | Towards Data Science

Body:
As far as I can tell by looking at other posts, using the subprocess library in Python is the most popular way to execute PowerShell commands from within Python. For example:

data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId me@me.com \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)

However, I'm ultimately trying to add this script to an automation account in Azure. Specifying the executable "powershell.exe" in the script won't work in an Azure automation account runbook (raises a "FileNotFound" error).

Is there some other way you can get the sign in log data from within Python that would be more amenable to using in an Azure automation account runbook? Can the Azure library be used to get sign in log data instead?

Body:
I have tested in my environment

You can use MS Graph API query in your python script to get the Azure AD sign in logs of the users

You can use below python code:

import requests
import json

url = 'https://graph.microsoft.com/v1.0/auditLogs/signIns'
token = "access_token"

headers = {
 'Authorization': 'Bearer {}'.format(token)
}

user_response_data = json.loads(requests.get(url, headers=headers).text)
print(user_response_data)

Reference: Querying Microsoft Graph API with Python | by Ephraim Mwai | Towards Data Science


问:
MVC in command line java
I am trying to get MVC in my command line project.

As of now (no MVC, obviously) I have:

MainClass (fake name obviously), a fret using the Menu few times it creates a System object

Menu (used by the Main to present options)

System, it has a Model as an attribute, created with a file or keyboard input, it uses the data from Model to perform a simple operation .calculate(valueA,valueB) where valueA and valueB are selected using the Menu from an areay of attributes of the Model

Model (kind of) is the container of the data I have.

Can someone please suggest me a proper structure for the classes?

Thanks a lot,
Luke

答:
I'm really surprised by the negative reactions to this question, as it's a rather interesting one. I expect it's because most people assume that MVC only has any meaning in a web environment, but MVC is completely applicable to a CLI program too. It just presents a different view medium. In fact, I'd consider it the superlative MVC design that was able to plug in either a CLI, GUI, or web "view" without any change to the controller and model pieces.

All that MVC says is that, given an application, you abstract as much as possible the view portion--the presentation of the app, what users see and interact with--from the real, internal logic of the app. The way you do that is to create controllers that "glue" the view and whatever controls exist in it to the logic on the back end. Put simply, controllers translate user input into method calls and translate return values back into stuff useful to the user. The model part of the pattern is somewhat debated. Some say that each, separate piece of object graph that's sent to the view for displaying is a "model". Others maintain that the entire stateful object graph that lives in the back end is the "model", and controllers form something of a looking glass that let the view pick out, inspect, and modify specific pieces of the model. The question is really whether there are many models constantly flowing back and forth or one, large model that needs to be exposed in a way the user can comprehend.

To get to MVC in a CLI--or any type of app--have a part of the code that's clearly defined as the view/presentation. It should never, ever have anything even resembling business logic in it. Your controller(s) should be objects that know how to respond to user inputs and can send things back for viewing, though without any assumptions about how those things will be displayed or exactly what form inputs will take. The model, one way or the other, is basically the actual data or "stuff" that the user cares about, and it should be oblivious of either the view that's showing it or the controller that's... um... controlling it.

Title: MVC in command line java


问:
Does Java stream().sorted or list.sort() not increases time complexity?
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

```<code>List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());
</code>```

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?

答:
The very first impotent thing that you have to understand about any kind of algorithm is that just talking about algorithms will not significantly change your knowledge in this area.

You have to study and practice them, implementing algorithms step by step.

If want to improve your understanding of sorting algorithms you need to start with the very basic like bubble sort and insertion sort (descriptions and pseudocode could've found in Wikipedia is quite enough to grasp the idea and start coding). When you'll have a firm understanding of the basics that you ready to go with merge sort and quicksort.

Here is a small insight on what is happening inside the so-called dual-pivot quicksort provided by JDK.

In fact, it's a very advanced compound algorithm which apart from the conventional quicksort entails merge sort, heap sort, and parallel computing in case of a massive data set.

Only when you know all proc and cons of the essential algorithms (like why there are different portition schemes out there, why quicksort is preferred over merge sort meanwhile in the worse case time complexity of the merge sort seems better, etc) it make sense to speculate about the optimizations that are going the dual-pivot quicksort.

For now short answer with regards to the performance of the build-in quicksort:

guarantees n*log(n) on any data

Now about Streams and sorting.

Sorting is always happening inside the array in place. If the source of data is backed by the array an ArrayList or CopyOnWriteArrayList, then its underlying array will get sorted.

Otherwise, for instance, if you are dialing with a LinkedList, a new array will be allocated in memory and all the data from the list will be copied to this array and then get sorted.

And when you are dialing with a stream it'll not affect the source of data. The whole data from the source requires to be loaded into memory to be sorted. And then you most likely will store it in a brand collection.

Conclusion:

if you need to change a source of data - use the sort() method with the list directly;

if your task doesn't require sorting all the initial data (or you simply want to preserve the initial state of the source) - then Stream API will give a hand with filtering and sorting.

Body:
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?


问:
DynamoDB Table Design Suggestion
Need guidance to design a DynamoDB table.

Below is my sample data.

FinanceType
ModelName
ModelCode
ModelYear
MoreAttributes ...

Lease
Avalon
TA1
2021
.....

Lease
Camry
TC1
2021
.....

Lease
Sienna
TS1
2021
.....

Loan
Avalon
TA1
2021
.....

Loan
Camry
TC1
2021
.....

Loan
Sienna
TS1
2021
.....

Lease
Avalon
TA1
2020
.....

Lease
Camry
TC1
2020
.....

Lease
Sienna
TS1
2020
.....

Loan
Avalon
TA1
2020
.....

Loan
Camry
TC1
2020
.....

Loan
Sienna
TS1
2020
.....

A Combination of FinanceType + ModelCode + ModelYear makes a record unique.

Access pattern would be to find MoreAttributes for a given FinanceType, ModelCode & ModelYear.

How do I design my table to have the right partition key and a sort key such that the data is evenly distributed and there are no hot partitions?

答:
I think a composite key if the form of:

```<code>FinanceType#ModelCode#ModelYear
</code>```

would be enough. If you want you can make ModelName as a sort key.

Title: DynamoDB Table Design Suggestion

Body:
I think a composite key if the form of:

FinanceType#ModelCode#ModelYear

would be enough. If you want you can make ModelName as a sort key.


问:
How to import images to google colab to use in my model
I created a model in google Collaboratory using the cifar10 dataset and I used it to predict images and their labels. This worked perfectly and I was very happy with the result. I then wanted to predict my own images because this is what I would be using this for. I want to upload images into google colab which I'm currently doing by mounting my drive. I then want to take that folder of images and turn it into an array of shape (number of images, 32,32,3) I am currently reshaping them and using keras.preprocessing.image.dataGenerator and then using .flow_from_directory to get the images. It seems to work when I put it into the model but I want to see the images using matplotlib.imshow. When I try this, it throws an error that it could not broadcast input array of shape (8,32,32,3) to array size (8). Why is it trying to reshape the array. Sorry I'm pretty new to all this. Here's my code. It is very messy and there are lots of dumb things that I tried.</p>
```<code>import tensorflow as tf
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
from keras.preprocessing.image import load_img
from keras.preprocessing.image import ImageDataGenerator

from keras.preprocessing.image import DirectoryIterator
from google.colab import files

test=ImageDataGenerator(rescale=1./255)
test_ims=DirectoryIterator('/content/drive/MyDrive/test/',test,target_size=(32,32),batch_size=32,class_mode='sparse')
test_set=test.flow_from_directory('/content/drive/MyDrive/test/',target_size=(32,32),batch_size=32,class_mode='sparse')
#print(test_set[0])
print(test_ims)

#imarray=np.array([img_to_array(img)])

!ls saved_model
modelll=tf.keras.models.load_model('/content/saved_model/mymode3')

#history=modelll(test_set)
#print(history)
#print(np.argmax(history[0]))
probability_model1 = tf.keras.Sequential([modelll,
                                         tf.keras.layers.Softmax()])
prediction1=probability_model1.predict(test_set)
#print(prediction1)

#print('10')
history1=np.argmax(prediction1[6])
print(test_set.__getitem__(0))
plt.imshow(test_set.__getitem__(0))
#print(history1)
#print(test_set)

#print(cifclassnems[history[0]])
#print('the rock')```
But yeah I just want to import images and run them through the model. The model is named modelll(don't ask). Anything is helpful! Thank you!
</code>```

答:
Try to iterate over array of images to show in matplotlib like this</p>
```<code># plot test_set images
 n_samples = 3
 for i in range(n_samples):
    pyplot.subplot(2, n_samples, 1 + i)
    pyplot.axis('off')
    pyplot.imshow(test_set[i].astype('uint8'))
 pyplot.show()
</code>```

Body:
I created a model in google Collaboratory using the cifar10 dataset and I used it to predict images and their labels. This worked perfectly and I was very happy with the result. I then wanted to predict my own images because this is what I would be using this for. I want to upload images into google colab which I'm currently doing by mounting my drive. I then want to take that folder of images and turn it into an array of shape (number of images, 32,32,3) I am currently reshaping them and using keras.preprocessing.image.dataGenerator and then using .flow_from_directory to get the images. It seems to work when I put it into the model but I want to see the images using matplotlib.imshow. When I try this, it throws an error that it could not broadcast input array of shape (8,32,32,3) to array size (8). Why is it trying to reshape the array. Sorry I'm pretty new to all this. Here's my code. It is very messy and there are lots of dumb things that I tried.

import tensorflow as tf
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
from keras.preprocessing.image import load_img
from keras.preprocessing.image import ImageDataGenerator

from keras.preprocessing.image import DirectoryIterator
from google.colab import files

test=ImageDataGenerator(rescale=1./255)
test_ims=DirectoryIterator('/content/drive/MyDrive/test/',test,target_size=(32,32),batch_size=32,class_mode='sparse')
test_set=test.flow_from_directory('/content/drive/MyDrive/test/',target_size=(32,32),batch_size=32,class_mode='sparse')
#print(test_set[0])
print(test_ims)

#imarray=np.array([img_to_array(img)])

!ls saved_model
modelll=tf.keras.models.load_model('/content/saved_model/mymode3')

#history=modelll(test_set)
#print(history)
#print(np.argmax(history[0]))
probability_model1 = tf.keras.Sequential([modelll,
                                         tf.keras.layers.Softmax()])
prediction1=probability_model1.predict(test_set)
#print(prediction1)

#print('10')
history1=np.argmax(prediction1[6])
print(test_set.__getitem__(0))
plt.imshow(test_set.__getitem__(0))
#print(history1)
#print(test_set)

#print(cifclassnems[history[0]])
#print('the rock')```
But yeah I just want to import images and run them through the model. The model is named modelll(don't ask). Anything is helpful! Thank you!

Body:
Try to iterate over array of images to show in matplotlib like this

# plot test_set images
 n_samples = 3
 for i in range(n_samples):
    pyplot.subplot(2, n_samples, 1 + i)
    pyplot.axis('off')
    pyplot.imshow(test_set[i].astype('uint8'))
 pyplot.show()


问:
ASP.NET MVC - Approach for global error handling?
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

```<code>public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}
</code>```

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

```<code><%= Html.RenderAllMessages %>
</code>```

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.

答:
If all you're going to do is redirect the user to another page, then you can use any ActionMethod to do so and just redirect to it.

If you want a global error, such as a 500 or 403 or some other error, then the MVC 3 default template creates an _Error.cshtml page for you and registers the error handler in the global.asax.

If you want to catch specific errors, then you can register additional handlers in the same place and  tell the system which Error page to use for that error.

Body:
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

<%= Html.RenderAllMessages %>

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.