问:
How to return a boolean from a function in java? getting an error
```<code>public class Test {
    public boolean checkx(boolean x) {
        boolean status;
        if (x) {
            status = true;
        }
        return status;
    }
}
</code>```

Error: The local variable status may not have been initialized

I don't know what I was doing wrong, code looks alright to me.

答:
In the Java Language Speciication, it is written that:

A local variable (§14.4, §14.14) must be explicitly given a value
before it is used, by either initialization (§14.4) or assignment
(§15.26), in a way that can be verified using the rules for definite
assignment (§16 (Definite Assignment)).

So, you must have to initialize or assign a value to the local variable before using it.

In your particular example:

```<code>public boolean checkx(boolean x) {
    boolean status = false;
    if (x) {
        status = true;
    }
    return status;
}
</code>```

Body:
public class Test {
    public boolean checkx(boolean x) {
        boolean status;
        if (x) {
            status = true;
        }
        return status;
    }
}

Error: The local variable status may not have been initialized

I don't know what I was doing wrong, code looks alright to me.

Body:
In the Java Language Speciication, it is written that:

A local variable (§14.4, §14.14) must be explicitly given a value
before it is used, by either initialization (§14.4) or assignment
(§15.26), in a way that can be verified using the rules for definite
assignment (§16 (Definite Assignment)).

So, you must have to initialize or assign a value to the local variable before using it.

In your particular example:

public boolean checkx(boolean x) {
    boolean status = false;
    if (x) {
        status = true;
    }
    return status;
}


来源: stackexchange

问:
ITMS-90338: Non-public API usage - The app references non-public selectors in [App]
I am building a Xamarin.Forms app that is building properly and deploying to the Apple App Store but keeps getting rejected for the following reasons:

ITMS-90338: Non-public API usage - The app references non-public
selectors in [App].Mobile.iOS: accessibilityBrailleMapRenderRegion,
accessibilityBrailleMapRenderer, accessibilityColumnRange,
accessibilityRowRange, activePlayer, beginAuthorizationWithRequest:,
cancelAuthorizationWithRequest:, errorForCHIPErrorCode:,
errorToCHIPErrorCode:, playerId, serviceExtensionWillTerminate,
session:didReceiveData:fromPlayer:,
session:didReceiveMessage:withData:fromPlayer:,
session:player:didChangeConnectionState:, session:player:didSaveData:,
setAccessibilityBrailleMapRenderRegion:,
setAccessibilityBrailleMapRenderer:. If method names in your source
code match the private Apple APIs listed above, altering your method
names will help prevent this app from being flagged in future
submissions. In addition, note that one or more of the above APIs may
be located in a static library that was included with your app.

I coded the app on a PC in Visual Studio Community 2019 v16.9.1. And built and deployed the app via Appcenter.ms.

Packages that I am using are:

Microsoft.AppCenter.Analytics v4.5.0

Microsoft.AppCenter.Crashes v4.5.0

Xamarin.Essentials v1.7.1

Xamarin.Forms v5.0.0.2337

Target Framework: .NET Standard 2.0

Information that I have confirmed from other sources:

Build Configuration: Release

Linker Behavior: Link Framework SDKs Only

Additional mtouch arguments: --linkskip=[selectors]

Additional mtouch arguments: --linkplatform

I have found all of the non-public selectors in xamarin/xamarin-macios and xamarin/apple-api-docs but I have not been able to find out how to fix the errors.

Thanks

Edit: I was not able to fix the issue. Instead, I got a Mac VM and was able to publish the code that way.

答:
Try add --linksdkonly to the Additional mtouch arguments on the iOS Build settings page

Refer from:https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/linker?tabs=macos#link-sdk-assemblies-only

ContentLicense: CC BY-SA 4.0


问:
TypeScript + React: Trying to write a component that accepts two types of props but I end up only being able to access the common prop
I want to have a component Foo that accepts two types of props:

Foo({a: 'a'})

Foo({a: 'a', b: 'b', c:'c'})

where {a: 'a'} is required.

These should invalid

```<code>Foo({a: 'a', b: 'b'}) // ❌
Foo({a: 'a', c: 'c'}) // ❌
</code>```

Here is my attempt.

type BaseProps = {
  a: "a";
};

type VariantPrps = {
  b: "b";
  c: "c";
} & BaseProps;

function Foo(props: BaseProps): React.ReactNode;
function Foo(props: VariantPrps): React.ReactNode;

function Foo(props: BaseProps | VariantPrps) {
  // I can only access `props.a` inside
  return {props.a};
}

// usage
Foo({a: 'a'}) // ✅
Foo({a: 'a', b: 'b', c:'c'}) // ✅

Foo({a: 'a', b: 'b'}) // ❌
Foo({a: 'a', c: 'c'}) // ❌
```

it works to some extent but inside Foo I can only access a, not b and c. My intention is that inside that component I should be able to access b and c and check to see if they exist or not before using them. Is there a way to do that?

答:
Consider this example:

import React from 'react'

// credits goes to https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
    T extends any
    ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;

type StrictUnion<T> = StrictUnionHelper<T, T>

type BaseProps = {
    a: "a";
};

type VariantPrps = {
    b: "b";
    c: "c";
} & BaseProps;

function Foo(props: BaseProps): React.ReactNode;
function Foo(props: VariantPrps): React.ReactNode;

function Foo(props: StrictUnion<BaseProps | VariantPrps>) {
    props.a // "a"
    props.b // "b" | undefined
    props.c // "c" | undefined
    // I can only access `props.a` inside
    return {props.a};
}

// usage
Foo({ a: 'a' }) // ✅
Foo({ a: 'a', b: 'b', c: 'c' }) // ✅

Foo({ a: 'a', b: 'b' }) // ❌
Foo({ a: 'a', c: 'c' }) // ❌
```

Playground

You were allowed to use only a property because it is common property for both types.
See docs

Body:
I want to have a component Foo that accepts two types of props:

Foo({a: 'a'})

Foo({a: 'a', b: 'b', c:'c'})

where {a: 'a'} is required.

These should invalid

Foo({a: 'a', b: 'b'}) // ❌
Foo({a: 'a', c: 'c'}) // ❌

Here is my attempt.

type BaseProps = {
  a: "a";
};

type VariantPrps = {
  b: "b";
  c: "c";
} & BaseProps;

function Foo(props: BaseProps): React.ReactNode;
function Foo(props: VariantPrps): React.ReactNode;

function Foo(props: BaseProps | VariantPrps) {
  // I can only access `props.a` inside
  return {props.a};
}

// usage
Foo({a: 'a'}) // ✅
Foo({a: 'a', b: 'b', c:'c'}) // ✅

Foo({a: 'a', b: 'b'}) // ❌
Foo({a: 'a', c: 'c'}) // ❌

it works to some extent but inside Foo I can only access a, not b and c. My intention is that inside that component I should be able to access b and c and check to see if they exist or not before using them. Is there a way to do that?

Body:
Consider this example:

import React from 'react'

// credits goes to https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
    T extends any
    ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;

type StrictUnion<T> = StrictUnionHelper<T, T>

type BaseProps = {
    a: "a";
};

type VariantPrps = {
    b: "b";
    c: "c";
} & BaseProps;

function Foo(props: BaseProps): React.ReactNode;
function Foo(props: VariantPrps): React.ReactNode;

function Foo(props: StrictUnion<BaseProps | VariantPrps>) {
    props.a // "a"
    props.b // "b" | undefined
    props.c // "c" | undefined
    // I can only access `props.a` inside
    return <span>{props.a}</span>;
}

// usage
Foo({ a: 'a' }) // ✅
Foo({ a: 'a', b: 'b', c: 'c' }) // ✅

Foo({ a: 'a', b: 'b' }) // ❌
Foo({ a: 'a', c: 'c' }) // ❌

Playground

You were allowed to use only a property because it is common property for both types.
See docs


问:
problem while deploying react application to github
I created a todolist that is working properly in localhost.
Iam trying to deploy it on github, when I run '$ npm run deploy' in command propmt it showing error  p

Added homepage, predeploy, deploy properties to package.json

installed gh-pages --save-dev

Please help I am a beginner

This is the command prompt error.

```<code>

C:\Users\Syed\Desktop\project\todolist>npm run deploy

> todolist@0.1.0 predeploy C:\Users\Syed\Desktop\project\todolist
> npm run build

> todolist@0.1.0 build C:\Users\Syed\Desktop\project\todolist
> react-scripts build

Creating an optimized production build...
Compiled with warnings.

./src/App.js
  Line 2:8:    'logo' is defined but never used              no-unused-vars
  Line 52:20:  Expected to return a value in arrow function  array-callback-return

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

File sizes after gzip:

  55.54 KB  build\static\js\2.0512a152.chunk.js
  1.19 KB   build\static\js\main.1e3fd05a.chunk.js
  785 B     build\static\js\runtime-main.ce724f51.js
  657 B     build\static\css\main.362672fb.chunk.css

The project was built assuming it is hosted at /To-Do-List/.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

Find out more about deployment here:

  bit.ly/CRA-deploy

> todolist@0.1.0 deploy C:\Users\Syed\Desktop\project\todolist
> gh-pages -d build

fatal: A branch named 'gh-pages' already exists.

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! todolist@0.1.0 deploy: `gh-pages -d build`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the todolist@0.1.0 deploy script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Syed\AppData\Roaming\npm-cache\_logs\2020-07-02T01_49_57_997Z-debug.log

</code>```

答:
Please check this quickstart guide
You will need to set up the GitHub pages homepage link on your GitHub repository settings page first.
Then check the source as well.
Then save. That should work.</p>

Body:
I created a todolist that is working properly in localhost.
Iam trying to deploy it on github, when I run '$ npm run deploy' in command propmt it showing error  p

Added homepage, predeploy, deploy properties to package.json

installed gh-pages --save-dev

Please help I am a beginner

This is the command prompt error.

C:\Users\Syed\Desktop\project\todolist>npm run deploy

> todolist@0.1.0 predeploy C:\Users\Syed\Desktop\project\todolist
> npm run build

> todolist@0.1.0 build C:\Users\Syed\Desktop\project\todolist
> react-scripts build

Creating an optimized production build...
Compiled with warnings.

./src/App.js
  Line 2:8:    'logo' is defined but never used              no-unused-vars
  Line 52:20:  Expected to return a value in arrow function  array-callback-return

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

File sizes after gzip:

  55.54 KB  build\static\js\2.0512a152.chunk.js
  1.19 KB   build\static\js\main.1e3fd05a.chunk.js
  785 B     build\static\js\runtime-main.ce724f51.js
  657 B     build\static\css\main.362672fb.chunk.css

The project was built assuming it is hosted at /To-Do-List/.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

Find out more about deployment here:

  bit.ly/CRA-deploy

> todolist@0.1.0 deploy C:\Users\Syed\Desktop\project\todolist
> gh-pages -d build

fatal: A branch named 'gh-pages' already exists.

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! todolist@0.1.0 deploy: `gh-pages -d build`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the todolist@0.1.0 deploy script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Syed\AppData\Roaming\npm-cache\_logs\2020-07-02T01_49_57_997Z-debug.log


问:
Finding out is user fully completed download or not in C#
I have created a class that downloads files from a web client and the completed method returns a message in the console of the downloaded yes or no. This works, but is it also possible to read out how big the file is before downloading, and if the download is interrupted and not completely downloaded to delete this file?

How can I add this detection? I was thinking to read out the size of each file via readallbytes to get the size but so far without success

This is my code so far

```<code>public class FileDownload
{
    private volatile bool _completed;

    public bool DownloadCompleted
    {
        get
        {
            return _completed;
        }
    }

    public async Task DownloadFile(string address, string location)
    {
        using (WebClient client = new WebClient())
        {
            Uri Uri = new Uri(address);
            _completed = false;
            client.Headers.Add("Authorization", await Header.getAuthorizationHeader());
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
            client.DownloadFileAsync(Uri, location);
        }
    }

    private void Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
            _completed = false;
        }
        else if (e.Error != null)
        {
            Console.WriteLine("Download error!");
            _completed = false;
        }
        else
        {
            Console.WriteLine("Download completed!");
            _completed = true;
        }
    }

    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
         (string)e.UserState,
         e.BytesReceived,
         e.TotalBytesToReceive,
         e.ProgressPercentage);
    }
}

// override DownloadFileAsync timeout to 10 second
public class WebClientWithTimeout : WebClient
{
    //10 secs default
    public int Timeout
    {
        get;
        set;
    } = 10000;

    //the above will not work for async requests :(
    //let's create a workaround by hiding the method
    //and creating our own version of DownloadStringTaskAsync
    public new async Task<string> DownloadStringTaskAsync(Uri address)
    {
        var t = base.DownloadStringTaskAsync(address);
        if (await Task.WhenAny(t, Task.Delay(Timeout)).ConfigureAwait(false) != t) //time out!
        {
            CancelAsync();
        }
        return await t.ConfigureAwait(false);
    }

    //for sync requests
    protected override WebRequest GetWebRequest(Uri uri)
    {
        var w = base.GetWebRequest(uri);
        w.Timeout = Timeout; //10 seconds timeout
        return w;
    }
</code>```

答:
Instead of having complicated logic, you could download it as another name and only rename it to the correct name after the download completed. If all your temporary files followed a pattern, you could delete those files when you start the program, since they obviously were left over from a prior run that failed.

You may also want to delete the temporary file if you find out the download failed (you already know, sice you are printing it to console).

Body:
I have created a class that downloads files from a web client and the completed method returns a message in the console of the downloaded yes or no. This works, but is it also possible to read out how big the file is before downloading, and if the download is interrupted and not completely downloaded to delete this file?

How can I add this detection? I was thinking to read out the size of each file via readallbytes to get the size but so far without success

This is my code so far

public class FileDownload
{
    private volatile bool _completed;

    public bool DownloadCompleted
    {
        get
        {
            return _completed;
        }
    }

    public async Task DownloadFile(string address, string location)
    {
        using (WebClient client = new WebClient())
        {
            Uri Uri = new Uri(address);
            _completed = false;
            client.Headers.Add("Authorization", await Header.getAuthorizationHeader());
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
            client.DownloadFileAsync(Uri, location);
        }
    }

    private void Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
            _completed = false;
        }
        else if (e.Error != null)
        {
            Console.WriteLine("Download error!");
            _completed = false;
        }
        else
        {
            Console.WriteLine("Download completed!");
            _completed = true;
        }
    }

    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
         (string)e.UserState,
         e.BytesReceived,
         e.TotalBytesToReceive,
         e.ProgressPercentage);
    }
}

// override DownloadFileAsync timeout to 10 second
public class WebClientWithTimeout : WebClient
{
    //10 secs default
    public int Timeout
    {
        get;
        set;
    } = 10000;

    //the above will not work for async requests :(
    //let's create a workaround by hiding the method
    //and creating our own version of DownloadStringTaskAsync
    public new async Task<string> DownloadStringTaskAsync(Uri address)
    {
        var t = base.DownloadStringTaskAsync(address);
        if (await Task.WhenAny(t, Task.Delay(Timeout)).ConfigureAwait(false) != t) //time out!
        {
            CancelAsync();
        }
        return await t.ConfigureAwait(false);
    }

    //for sync requests
    protected override WebRequest GetWebRequest(Uri uri)
    {
        var w = base.GetWebRequest(uri);
        w.Timeout = Timeout; //10 seconds timeout
        return w;
    }


问:
Multiple override-methods in inheritance each have multiple possible implementations
Let me introduce the following three classes: AbstractProcessor and these two child classes. The code below is not complex because there are only two child classes, but what if procedures1 and procedure2 both has many N candidate implementation? In such case, there are NxN child classes and a lot of duplication will be made by hand-coding. In the code below for example, each procedure can either be fast one or accurate one. So there are 2x2 possible child classes.

I would ask about technique/design pattern to reduce duplication. More precisely, is there any technique to reduce that NxN hand-coding to 2N hand-coding?

Noting that procedure1 and procedure2 both have to share the same var_ (in my case it is measurement value of physical world of robot) and the common function foo(), procedure1 and procudure2 can hardly be composed by a has-a relationship. Actually in my application, there are lot of var_ because the robot access to many type of sensors.

class AbstractProcessor
{
  virtual void procedure1() = 0;
  virtual void procedure2() = 0;

  Something foo(){ // ...
  }
  double var_;

  void run(){
    procedure1();
    procedure2();
  }
};

class FastProcessor : public AbstractProcessor
{
  void procedure1() override {// ... fast procedure ( use foo and var_ inside)
  }
  void procedure2() override {// ... fast procedure ( use foo and var_ inside)
  }
};

class AccurateProcessor : public AbstractProcessor
{
  void procedure1() override {// ... accurate procedure ( use foo and var_ inside)
  }
  void procedure2() override {// ... accurate procedure ( use foo and var_ inside)
  }
};
```

答:
Inheritance is not the solution to everything. Sometimes all the problems are gone once you don't use inheritance. There are many different ways to do what you want. One is to store the callables as members:

```<code>#include <functional>
#include <iostream>

struct Processor
{
  std::function<void(Processor*)> procedure1;
  std::function<void(Processor*)> procedure2;

  double var_ = 42.0;
  void foo() {
      std::cout << "hello foo\n";
  }

  void run(){
    procedure1(this);
    procedure2(this);
  }
};

int main() {
    Processor proc{
        [](auto p) { std::cout << p->var_ << "\n";},
        [](auto p) { p->foo(); }
    };
    proc.run();
}
</code>```

Instead of lambdas the parameters to the constructor could be free functions so they can be more easily be reused. Note that I hade to make everything public in the class, in your example everything is private (it cannot work like that).

As you are asking for a technique/design pattern, the term "composition over inheritance" fits best here I think. Dependency injection and other related design patterns might also help you to get into a different way of thinking about your design.

Body:
Inheritance is not the solution to everything. Sometimes all the problems are gone once you don't use inheritance. There are many different ways to do what you want. One is to store the callables as members:

#include <functional>
#include <iostream>

struct Processor
{
  std::function<void(Processor*)> procedure1;
  std::function<void(Processor*)> procedure2;

  double var_ = 42.0;
  void foo() {
      std::cout << "hello foo\n";
  }

  void run(){
    procedure1(this);
    procedure2(this);
  }
};

int main() {
    Processor proc{
        [](auto p) { std::cout << p->var_ << "\n";},
        [](auto p) { p->foo(); }
    };
    proc.run();
}

Instead of lambdas the parameters to the constructor could be free functions so they can be more easily be reused. Note that I hade to make everything public in the class, in your example everything is private (it cannot work like that).

As you are asking for a technique/design pattern, the term "composition over inheritance" fits best here I think. Dependency injection and other related design patterns might also help you to get into a different way of thinking about your design.


问:
Get active message count with the new Azure.messaging.servicebus
Is there any option to retrieve the Active Message Count of a queue using the new Azure.messaging.servicebus package?

With the old Microsoft.azure.servicebus you could use ManagementClient that exposes GetQueueRuntimeInfoAsync(String, CancellationToken)

```<code>var managementClient = new ManagementClient("queue connection string"));
var runtimeInfo = await managementClient.GetQueueRuntimeInfoAsync("queueName");

var messagesInQueueCount = runtimeInfo.MessageCountDetails.ActiveMessageCount;
</code>```

Is there a way to achieve something similar?
Thank you.

答: You can. The starting point would be a similar management client, ServiceBusManagementClient. It exposes methods to access entity runtime information such as GetQueueRuntimePropertiesAsync(), which returns QueueRuntimeProperties. The QueueRuntimeProperties object has all the info, including ActiveMessageCount.

Body:
Is there any option to retrieve the Active Message Count of a queue using the new Azure.messaging.servicebus package?

With the old Microsoft.azure.servicebus you could use ManagementClient that exposes GetQueueRuntimeInfoAsync(String, CancellationToken)

var managementClient = new ManagementClient("queue connection string"));
var runtimeInfo = await managementClient.GetQueueRuntimeInfoAsync("queueName");

var messagesInQueueCount = runtimeInfo.MessageCountDetails.ActiveMessageCount;

Is there a way to achieve something similar?
Thank you.


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答:
Do you mean setting up the enum itself?

I don't think that's possible. You cannot instantiate enums because they have a static nature. So I think that Spring IoC can't create enums as well.

On the other hand, if you need to set initialize something with a enum please check out the Spring IoC chapter. (search for enum) There's a simple example that you can use.

OwnerDisplayName: Olivier

ContentLicense: CC BY-SA 3.0

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

OwnerDisplayName: bruno conde

ContentLicense: CC BY-SA 2.5


问:
How to tell what packages you have used in R
I have a very long R script with many if statements and exception cases. As i've been going, if been importing and testing libraries as I've gone and haven't really documented them very well. The problem is that if I run this from a clean installation, i'm not sure which statements the script will run, and so which libraries will be needed.

My question is: Is there any R function to test which libraries are being used in a script?

EDIT: I have not used all of the libraries that have been installed so print(sessionInfo()) won't be useful  but and I just want to start the script with an install.packages function

答:
I'd trust the {renv} based solutions the most for identifying packages dependencies.

Though I wrote a package funspotr that contains similar functionality to the answers mentioning NCmisc::list.functions.in.file() and can be used for parsing the functions or packages in a file or files:

library(dplyr)

funspotr::spot_pkgs("https://gist.githubusercontent.com/brshallo/4b8c81bc1283a9c28876f38a7ad7c517/raw/b399b768e900a381d99f5120e44d119c7fb40ab9/source_rmd.R")
#> [1] "knitr"    "magrittr" "stringr"  "readr"    "purrr"    "glue"

funspotr::spot_funs("https://gist.githubusercontent.com/brshallo/4b8c81bc1283a9c28876f38a7ad7c517/raw/b399b768e900a381d99f5120e44d119c7fb40ab9/source_rmd.R") %>%
  select(-in_multiple_pkgs)
#> # A tibble: 13 x 2
#>    funs        pkgs
#>    <chr>       <chr>
#>  1 tempfile    base
#>  2 purl        knitr
#>  3 getOption   base
#>  4 options     base
#>  5 .Call       base
#>  6 source      base
#>  7 library     base
#>  8 read_file   readr
#>  9 map         purrr
#> 10 str_extract stringr
#> 11 glue        glue
#> 12 str_c       stringr
#> 13 write_file  readr
```


问:
How does Uber send new ride requests to drivers?
I was curious about what system design possibly Uber uses for sending new trips to Drivers.
The new trip requests keep popping up on the phone of Uber drivers. The things to consider would be :-

Are the requests sent by splitting by locality of the requests ?

Do they use a permanent open unidirectional socket connection ?

Or does the application keep querying the database ?

It would also be helpful if someone could give example of libraries which can achieve similar architecture using a nodejs server and android application frontend (current preferences).

答:
I used to be a software engineer at Uber. That was a long time ago, but I think I can answer your questions:

Ride requests from riders to drivers are sharded by the rider's city. The matching algorithm does not need to consider drivers in other parts of the world.

In the old days, the Uber driver and rider apps polled the server every 4 seconds or so. The server receives new GPS locations for the rider and driver and send back state updates. Nowadays, the Uber apps rely on persistent TCP connections--but polling is an important fallback when mobile networks are unreliable.

As far as I remember, the driver and rider apps don't have to continually query our on-disk databases every few seconds during a ride. That sort of information is generally cached in-memory until the ride is over.


问:
add help text for OneToOneField
I want to add a help_text to a field in my admin create for a model. I already tried what is suggested here.

models.py:

```<code>class Product(models.Model):
    name = ...
    ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, help_text = "from model, not visible ...")
</code>```

forms.py:

```<code>class ProductAdminForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        help_texts = {"name": "this is visible",
                      "ean": "this is not visible"}
</code>```

So I can add a helptext to a CharField but not to a OneToOneField. Why?

答:
This would be a bit of a workaround, but you can change how the field names show up in the admin by using verbose_name

```<code>    ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, verbose_name = "EAN - not visible")
</code>```

Title: add help text for OneToOneField

Body:
I want to add a help_text to a field in my admin create for a model. I already tried what is suggested here.

models.py:

class Product(models.Model):
    name = ...
    ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, help_text = "from model, not visible ...")

forms.py:

class ProductAdminForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        help_texts = {"name": "this is visible",
                      "ean": "this is not visible"}

So I can add a helptext to a CharField but not to a OneToOneField. Why?

Body:
This would be a bit of a workaround, but you can change how the field names show up in the admin by using verbose_name

    ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, verbose_name = "EAN - not visible")


问:
When using b-overlay in b-modal the modal body is not visible
I am using Vue Bootstrap and when I add b-overlay with no-wrap prop in b-modal the modal body is not visible even if the overlay is not active. Please see the example

https://codesandbox.io/s/friendly-worker-evcyd

I can use it without no-wrap prop but this way the modal footer and header are not overlaid

答: As mentioned here, you can add body-class="position-static" on b-modal and rounded prop enabled. This will make the entire b-modal covered with overlay.</p>


问:
Feature Whitening generates same image
I am looking at the feature whitening example shown here: How to implement ZCA Whitening? Python

I have implemented the code below but whenever I run it I get the same image in all 4 pictures and I am not sure why:

Code to read data (works fine)

```<code>import cv2
import matplotlib.pyplot as plt
from urllib.request import urlopen, Request
new_size = 50

urls = ['https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg',
        'https://dogtime.com/assets/uploads/2018/10/puppies-cover.jpg',
         'https://www.readersdigest.ca/wp-content/uploads/2013/03/6-facts-to-know-before-owning-a-puppy.jpg',
          'https://images.newscientist.com/wp-content/uploads/2021/06/03141753/03-june_puppies.jpg']

puppies = []
for url in urls:
    r = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    response = urlopen(r).read()
    arr = np.asarray(bytearray(response), dtype=np.uint8)
    puppies.append(cv2.imdecode(arr, 0)) # 'Load it as it is'

#item_pics = [cv2.imread( './pictures/picture_'+ str(x) + '.jpeg', 0) for x in range(1,5)]
puppies_scaled = [cv2.resize(x, [new_size,new_size], interpolation = cv2.INTER_AREA) for x in puppies]
puppies_vectors = [x.reshape(new_size * new_size) for x in puppies_scaled]
</code>```

Code to do the Whitening

```<code>#borrowed heavily from  https://stackoverflow.com/questions/31528800/how-to-implement-zca-whitening-python
def zca_whitening_matrix(X):
    """
    Function to compute ZCA whitening matrix (aka Mahalanobis whitening).
    INPUT:  X: [M x N] matrix.
        Rows: Variables
        Columns: Observations
    OUTPUT: ZCAMatrix: [M x M] matrix
    """
    # Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N
    sigma = np.cov(X, rowvar=True) # [M x M]
    # Singular Value Decomposition. X = U * np.diag(S) * V
    U,S,V = np.linalg.svd(sigma)
        # U: [M x M] eigenvectors of sigma.
        # S: [M x 1] eigenvalues of sigma.
        # V: [M x M] transpose of U
    # Whitening constant: prevents division by zero
    epsilon = 1e-25
    # ZCA Whitening matrix: U * Lambda * U'
    ZCAMatrix = np.dot(U, np.dot(np.diag(1.0/np.sqrt(S + epsilon)), U.T)) # [M x M]
    return ZCAMatrix
</code>```

Code to Whiten

```<code>combined_data = np.array(puppies_vectors).T
my_zca_transformer_image_stuff = zca_whitening_matrix(combined_data)
xZCAMatrix = np.dot(my_zca_transformer_image_stuff, combined_data)
reshaped_pics = [xZCAMatrix[:,i].reshape(new_size,new_size) for i in range(4)]
</code>```

Result (all pictures the same)

答:
Whitening is performed on zero-mean data. This means, that the matrices are computed on the zero-mean data and that they should also be applied on the zero-mean data. If you don't do that, you will essentially see the transformed mean vector W*mean_imagein all images. If that dominates in magnitude, the pictures all look identical due to rounding effects. However, they aren't if you compute the differences between your images.

In code, you can see all that with

combined_data = np.array(puppies_vectors).T
my_zca_transformer_image_stuff = zca_whitening_matrix(combined_data)
mean_image = np.mean(combined_data,axis=1)
without_mean = (combined_data-mean_image[:,None])
xZCAMatrix = np.dot(my_zca_transformer_image_stuff, without_mean)
reshaped_pics = [xZCAMatrix[:,i].reshape(new_size,new_size) for i in range(4)]
for i in reshaped_pics:
    plt.imshow(i, cmap='gray')
    plt.show() # Should look good now
## What you essential saw is this transformed mean image
i = np.dot(my_zca_transformer_image_stuff, mean_image).reshape(new_size,new_size)
plt.imshow(i, cmap='gray')
plt.show()
```

Title: Feature Whitening generates same image

Body:
I am looking at the feature whitening example shown here: How to implement ZCA Whitening? Python

I have implemented the code below but whenever I run it I get the same image in all 4 pictures and I am not sure why:

Code to read data (works fine)

import cv2
import matplotlib.pyplot as plt
from urllib.request import urlopen, Request
new_size = 50

urls = ['https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg',
        'https://dogtime.com/assets/uploads/2018/10/puppies-cover.jpg',
         'https://www.readersdigest.ca/wp-content/uploads/2013/03/6-facts-to-know-before-owning-a-puppy.jpg',
          'https://images.newscientist.com/wp-content/uploads/2021/06/03141753/03-june_puppies.jpg']

puppies = []
for url in urls:
    r = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    response = urlopen(r).read()
    arr = np.asarray(bytearray(response), dtype=np.uint8)
    puppies.append(cv2.imdecode(arr, 0)) # 'Load it as it is'

#item_pics = [cv2.imread( './pictures/picture_'+ str(x) + '.jpeg', 0) for x in range(1,5)]
puppies_scaled = [cv2.resize(x, [new_size,new_size], interpolation = cv2.INTER_AREA) for x in puppies]
puppies_vectors = [x.reshape(new_size * new_size) for x in puppies_scaled]

Code to do the Whitening

#borrowed heavily from  https://stackoverflow.com/questions/31528800/how-to-implement-zca-whitening-python
def zca_whitening_matrix(X):
    """
    Function to compute ZCA whitening matrix (aka Mahalanobis whitening).
    INPUT:  X: [M x N] matrix.
        Rows: Variables
        Columns: Observations
    OUTPUT: ZCAMatrix: [M x M] matrix
    """
    # Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N
    sigma = np.cov(X, rowvar=True) # [M x M]
    # Singular Value Decomposition. X = U * np.diag(S) * V
    U,S,V = np.linalg.svd(sigma)
        # U: [M x M] eigenvectors of sigma.
        # S: [M x 1] eigenvalues of sigma.
        # V: [M x M] transpose of U
    # Whitening constant: prevents division by zero
    epsilon = 1e-25
    # ZCA Whitening matrix: U * Lambda * U'
    ZCAMatrix = np.dot(U, np.dot(np.diag(1.0/np.sqrt(S + epsilon)), U.T)) # [M x M]
    return ZCAMatrix

Code to Whiten

combined_data = np.array(puppies_vectors).T
my_zca_transformer_image_stuff = zca_whitening_matrix(combined_data)
xZCAMatrix = np.dot(my_zca_transformer_image_stuff, combined_data)
reshaped_pics = [xZCAMatrix[:,i].reshape(new_size,new_size) for i in range(4)]

Result (all pictures the same)


问:
Chaining a new object instance in PHP
We have the following chaining:

```<code>$obj = new obj();
$obj->setname($params1)->setcolor($params2);
</code>```

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

```<code>$obj = new obj()->setname($params1)->setcolor($params2);
</code>```

答:
I use static functions of class for it.

```<code>
class a{
    static public function gets($args){
         return new self($args);
    }
    public function do_other(){

    }
}

a::gets()->do_other();
</code>```

Usually there are more then I static method to different usages

Title: Chaining a new object instance in PHP

Body:
We have the following chaining:

$obj = new obj();
$obj->setname($params1)->setcolor($params2);

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

$obj = new obj()->setname($params1)->setcolor($params2);

Body:
I use static functions of class for it.

class a{
    static public function gets($args){
         return new self($args);
    }
    public function do_other(){

    }
}

a::gets()->do_other();

Usually there are more then I static method to different usages


问:
Undefined symbols for architecture arm64: "_main", referenced from: implicit entry/start for main executable
```<code>Undefined symbols for architecture arm64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
dhanushn@ELON DS PROGRAM %
</code>```

can anybody pls help me to solve this problem?
my program was running well but suddenly now its not compiling

答: It may be that the content in the editor has not been saved</p>

Body:
Undefined symbols for architecture arm64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
dhanushn@ELON DS PROGRAM %

can anybody pls help me to solve this problem?
my program was running well but suddenly now its not compiling


问:
VS Code: How to move terminal to the left after Feb update
I would like to move the terminal/debug/ports panel to the left of the editor, side-by-side with the explorer. Previously, I just right-click the terminal and there is an option to do so. After the Feb update, it seems that I could only move it to the right side.

Does anyone know a solution to this?

Thanks!

答: Well, I found another way to do it:

Body: Well, I found another way to do it:


问:
brute force polynomial evaluation algorithm javascript
what is required is a brute force algorithm, and not some other!

I'm trying to implement the brute force method for a polynomial in javascript, but an error occurs, the answer is different from the other method above (horner method) - this method is checked and it gives the correct answer
but here is the second brut force- method that gives an excellent result, which is not correct.

What is the error in my code?

input :

_x = 6 _n = 5 polyEval = [2,3,5,-6,2]

output Horner method:

3386 // good. correct answer

output Bruforce method:

1496 // bad. incorrect answer

```<code>class Programm {

      constructor(x:number, n:number) {
           this._x = 4;
           this._n = 5;
           this.polyEval =  [2,3,5,-6,2] //this.RandomArray(this._n);
    }

      private _x:number;
      private _n:number;
      private polyEval:number[] = [];

</code>```

//working method

```<code>      private Horner(poly:number[], n:number, x:number){

        let time = performance.now();

        let result = poly[0];
        for (let i = 1; i < n; i++){
                result = result * x + poly[i];
        }
        time = performance.now() - time;
        console.log("Method: Horner |" ,`Result: ${result}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
      }

</code>```

// method with an error that I can't find

```<code>      private BruteForce(poly:number[], n:number, x:number){

        let time = performance.now();

        let p: number = 0;
        for(let i = n - 1; i >= 0; i--){
          let coefficient = 1;
          for(let j = 1; j <= i; j++){
            coefficient = coefficient * x;
          }
          p = p + poly[i] * coefficient;
        }
        time = performance.now() - time;
        console.log("Method: Brute Force |" ,`Result: ${p}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
      }

</code>```

// generate random array

```<code>      private RandomArray(n: number):number[]{
        let result:number[] = new Array(n);
        for (let i = 0; i < n; i++){
          if(Math.round(Math.random() * 1) > 0){
            result[i] = Math.floor(Math.random() * (10 - 1)) + 1;
          }else{
            result[i] = Math.floor(((Math.random() * (10 - 1)) + 1) * -1);
          }
        }
        return result;
      }

      public Main() {
        console.log(`n - array length: ${this._n} | x - coefficient: ${this._x}`);
        this.Horner(this.polyEval, this._n, this._x);
        this.BruteForce(this.polyEval, this._n, this._x);
      }
    }
    const random_N:number = Math.floor(Math.random() * (5 - 1)) + 3;
    const random_X:number = Math.floor(Math.random() * (5 - 1)) + 2;
    const poly = new Programm(random_N, random_X);
    poly.Main();
</code>```

答:
The Horner's scheme works like this:

```<code> // initially
 result = poly[0] == p_0;

 // iteration 1
 result = result * x + poly[1] == p_0 * x + p_1

 // iteration 2
 result = result * x + poly[2] == (p_0 * x + p_1) * x + p_2
   == p_0 * x^2 + p_1 * x + p_2
</code>```

Thus, the polynomial coefficients in the array poly are in order of highest to lowest. Then to replicate that in the brute force solution, one needs to apply the formula as

```<code> result = sum(poly[i] * pow(x, n-1-i))  ==

 result = sum(poly[n-1-i] * pow(x, i))

</code>```

Body:
what is required is a brute force algorithm, and not some other!

I'm trying to implement the brute force method for a polynomial in javascript, but an error occurs, the answer is different from the other method above (horner method) - this method is checked and it gives the correct answer
but here is the second brut force- method that gives an excellent result, which is not correct.

What is the error in my code?

input :

_x = 6 _n = 5 polyEval = [2,3,5,-6,2]

output Horner method:

3386 // good. correct answer

output Bruforce method:

1496 // bad. incorrect answer

class Programm {

      constructor(x:number, n:number) {
           this._x = 4;
           this._n = 5;
           this.polyEval =  [2,3,5,-6,2] //this.RandomArray(this._n);
    }

      private _x:number;
      private _n:number;
      private polyEval:number[] = [];

//working method

      private Horner(poly:number[], n:number, x:number){

        let time = performance.now();

        let result = poly[0];
        for (let i = 1; i < n; i++){
                result = result * x + poly[i];
        }
        time = performance.now() - time;
        console.log("Method: Horner |" ,`Result: ${result}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
      }

// method with an error that I can't find

      private BruteForce(poly:number[], n:number, x:number){

        let time = performance.now();

        let p: number = 0;
        for(let i = n - 1; i >= 0; i--){
          let coefficient = 1;
          for(let j = 1; j <= i; j++){
            coefficient = coefficient * x;
          }
          p = p + poly[i] * coefficient;
        }
        time = performance.now() - time;
        console.log("Method: Brute Force |" ,`Result: ${p}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
      }

// generate random array

      private RandomArray(n: number):number[]{
        let result:number[] = new Array(n);
        for (let i = 0; i < n; i++){
          if(Math.round(Math.random() * 1) > 0){
            result[i] = Math.floor(Math.random() * (10 - 1)) + 1;
          }else{
            result[i] = Math.floor(((Math.random() * (10 - 1)) + 1) * -1);
          }
        }
        return result;
      }

      public Main() {
        console.log(`n - array length: ${this._n} | x - coefficient: ${this._x}`);
        this.Horner(this.polyEval, this._n, this._x);
        this.BruteForce(this.polyEval, this._n, this._x);
      }
    }
    const random_N:number = Math.floor(Math.random() * (5 - 1)) + 3;
    const random_X:number = Math.floor(Math.random() * (5 - 1)) + 2;
    const poly = new Programm(random_N, random_X);
    poly.Main();

Body:
The Horner's scheme works like this:

 // initially
 result = poly[0] == p_0;

 // iteration 1
 result = result * x + poly[1] == p_0 * x + p_1

 // iteration 2
 result = result * x + poly[2] == (p_0 * x + p_1) * x + p_2
   == p_0 * x^2 + p_1 * x + p_2

Thus, the polynomial coefficients in the array poly are in order of highest to lowest. Then to replicate that in the brute force solution, one needs to apply the formula as

 result = sum(poly[i] * pow(x, n-1-i))  ==

 result = sum(poly[n-1-i] * pow(x, i))


问:
React debouncing problem with useCallback
Inside my React component, I have these:

```<code>const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");

function updateQuery () {
  const filters = [];
  if(vendor) {
    filters.push({
      label: `Vendor: ${vendor}`
    })
  }
  if(taggedWith) {
    filters.push({
      label: `Tagged with: ${taggedWith}`
    })
  }
  props.onUpdate(filters);
}

function debounce (func,delay){
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(()=>{
      func();
    },delay);
  };
};

const updateQueryWithDebounce = useCallback(debounce(updateQuery,300),[]);

useEffect(()=>{
  updateQueryWithDebounce();
},[taggedWith,vendor]);
</code>```

Debouncing works, but the problem is, the stateful variables inside updateQuery function stays the same, because of useCallback. If I pass those states to the dependency array of useCallback, the debouncing function gets redeclared at every render, thus, new function with its closure is created which leads to debouncing not working. How can I fix that ?

答:
You can use a ref to store the timer handle, so you can cancel the previous update when either state variable changes:

```<code>const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");
const updateRef = useRef(0);

useEffect(() => {
    updateRef.current = setTimeout(() => {
        updateRef.current = 0;
        const filters = [];
        if (vendor) {
            filters.push({
                label: `Vendor: ${vendor}`
            });
        }
        if (taggedWith) {
            filters.push({
                label: `Tagged with: ${taggedWith}`
            });
        }
        props.onUpdate(filters);
    }, 300);
    return () => { // Cleanup callback
        clearTmeout(updateRef.current);
        updateRef.current = 0;
    };
}, [taggedWith, vendor]);
</code>```

Some of that code can be isolated out the component entirely:

```<code>const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};
</code>```

Then the body of the component becomes:

```<code>const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");
const updateRef = useRef(0);

useEffect(() => {
    updateRef.current = setTimeout(() => {
        updateRef.current = 0;
        props.onUpdate(buildFilters(taggedWith, vendor));
    }, 300);
    return () => { // Cleanup callback
        clearTmeout(updateRef.current);
        updateRef.current = 0;
    };
}, [taggedWith, vendor]);
</code>```

Note: All of the above assumes that props.onUpdate is guaranteed to be a stable function (like the setters from useState are). If it isn't, things are more complicated, because you have to add it to the dependencies list and then handle the possibility that onUpdate has changed but taggedWith and vendor haven't.

You could probably even wrap that debouncing logic in a hook (and have the hook handle an unstable callback). Here's a fairly off-the-cuff example:

```<code>const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};
</code>```

Then the component code (using buildFilters) looks like this:

```<code>const [vendor, setVendor] = useState("");
const [taggedWith, setTaggedWith] = useState("");

useDebounce(
    () => {
        props.onUpdate(buildFilters(taggedWith, vendor));
    },
    300,
    [taggedWith, vendor]
);
</code>```

Live Example:

const { useState, useRef, useEffect } = React;

const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};

const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};

const Example = (props) => {
    const [vendor, setVendor] = useState("");
    const [taggedWith, setTaggedWith] = useState("");

    useDebounce(
        () => {
            props.onUpdate(buildFilters(taggedWith, vendor));
        },
        300,
        [taggedWith, vendor]
    );

    return

            <input type="text" value={vendor} onChange={
                ({target: {value}}) => { setVendor(value); }
            } />

            <input type="text" value={taggedWith} onChange={
                ({target: {value}}) => { setTaggedWith(value); }
            } />

;
};

const App = () => {
    const [filters, setFilters] = useState([]);

    return

        <Example onUpdate={setFilters} />

            Filters ({filters.length}):
            {!!filters.length &&

                    {filters.map(filter =>
{filter.label}
)}

            }

;
};

ReactDOM.render(<App />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script></code>```

I can't claim that hook is thoroughly tested, but it does seem to work even when the callback is unstable:

const { useState, useRef, useEffect } = React;

const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};

const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};

const Example = (props) => {
    const [vendor, setVendor] = useState("");
    const [taggedWith, setTaggedWith] = useState("");

    useDebounce(
        () => {
            console.log(`filter update ${vendor} ${taggedWith}`);
            props.onUpdate(buildFilters(taggedWith, vendor));
        },
        300,
        [taggedWith, vendor]
    );

    return

            <input type="text" value={vendor} onChange={
                ({target: {value}}) => { setVendor(value); }
            } />

            <input type="text" value={taggedWith} onChange={
                ({target: {value}}) => { setTaggedWith(value); }
            } />

;
};

const App = () => {
    const [counter, setCounter] = useState(0);
    const [filters, setFilters] = useState([]);
    const ref = useRef(null);
    if (!ref.current) {
        ref.current = {};
    }

    useEffect(() => {
        const timer = setInterval(() => setCounter(c => c + 1), 100);
        return () => {
            clearInterval(timer);
        };
    }, []);

    // An update callback that we intentionally recreate every render
    // to check that useDebounce handles using the **latest** function
    const onUpdate = ref.current.onUpdate = function onUpdate(filters) {
        if (onUpdate !== ref.current.onUpdate) {
            console.log("STALE FUNCTION CALLED");
        }
        setFilters(filters);
    };

    return

        Counter: {counter}
        <Example onUpdate={onUpdate} />

            Filters ({filters.length}):
            {!!filters.length &&

                    {filters.map(filter =>
{filter.label}
)}

            }

;
};

ReactDOM.render(<App />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script></code>```

Body:
Inside my React component, I have these:

const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");

function updateQuery () {
  const filters = [];
  if(vendor) {
    filters.push({
      label: `Vendor: ${vendor}`
    })
  }
  if(taggedWith) {
    filters.push({
      label: `Tagged with: ${taggedWith}`
    })
  }
  props.onUpdate(filters);
}

function debounce (func,delay){
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(()=>{
      func();
    },delay);
  };
};

const updateQueryWithDebounce = useCallback(debounce(updateQuery,300),[]);

useEffect(()=>{
  updateQueryWithDebounce();
},[taggedWith,vendor]);

Debouncing works, but the problem is, the stateful variables inside updateQuery function stays the same, because of useCallback. If I pass those states to the dependency array of useCallback, the debouncing function gets redeclared at every render, thus, new function with its closure is created which leads to debouncing not working. How can I fix that ?

Body:
You can use a ref to store the timer handle, so you can cancel the previous update when either state variable changes:

const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");
const updateRef = useRef(0);

useEffect(() => {
    updateRef.current = setTimeout(() => {
        updateRef.current = 0;
        const filters = [];
        if (vendor) {
            filters.push({
                label: `Vendor: ${vendor}`
            });
        }
        if (taggedWith) {
            filters.push({
                label: `Tagged with: ${taggedWith}`
            });
        }
        props.onUpdate(filters);
    }, 300);
    return () => { // Cleanup callback
        clearTmeout(updateRef.current);
        updateRef.current = 0;
    };
}, [taggedWith, vendor]);

Some of that code can be isolated out the component entirely:

const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};

Then the body of the component becomes:

const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");
const updateRef = useRef(0);

useEffect(() => {
    updateRef.current = setTimeout(() => {
        updateRef.current = 0;
        props.onUpdate(buildFilters(taggedWith, vendor));
    }, 300);
    return () => { // Cleanup callback
        clearTmeout(updateRef.current);
        updateRef.current = 0;
    };
}, [taggedWith, vendor]);

Note: All of the above assumes that props.onUpdate is guaranteed to be a stable function (like the setters from useState are). If it isn't, things are more complicated, because you have to add it to the dependencies list and then handle the possibility that onUpdate has changed but taggedWith and vendor haven't.

You could probably even wrap that debouncing logic in a hook (and have the hook handle an unstable callback). Here's a fairly off-the-cuff example:

const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};

Then the component code (using buildFilters) looks like this:

const [vendor, setVendor] = useState("");
const [taggedWith, setTaggedWith] = useState("");

useDebounce(
    () => {
        props.onUpdate(buildFilters(taggedWith, vendor));
    },
    300,
    [taggedWith, vendor]
);

Live Example:

const { useState, useRef, useEffect } = React;

const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};

const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};

const Example = (props) => {
    const [vendor, setVendor] = useState("");
    const [taggedWith, setTaggedWith] = useState("");

    useDebounce(
        () => {
            props.onUpdate(buildFilters(taggedWith, vendor));
        },
        300,
        [taggedWith, vendor]
    );

    return <div>
        <label>
            <input type="text" value={vendor} onChange={
                ({target: {value}}) => { setVendor(value); }
            } />
        </label>
        <label>
            <input type="text" value={taggedWith} onChange={
                ({target: {value}}) => { setTaggedWith(value); }
            } />
        </label>
    </div>;
};

const App = () => {
    const [filters, setFilters] = useState([]);

    return <div>
        <Example onUpdate={setFilters} />
        <div>
            Filters ({filters.length}):
            {!!filters.length &&
                <ul>
                    {filters.map(filter => <li key={filter.label}>{filter.label}</li>)}
                </ul>
            }
        </div>
    </div>;
};

ReactDOM.render(<App />, document.getElementById("root"));

<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

I can't claim that hook is thoroughly tested, but it does seem to work even when the callback is unstable:

const { useState, useRef, useEffect } = React;

const useDebounce = (fn, ms, deps) => {
    const ref = useRef(null);
    if (!ref.current) {
        // One-time init
        ref.current = {
            timer: 0,
        };
    }
    // Always remember the most recent `fn` on our ref object
    ref.current.fn = fn;

    useEffect(() => {
        ref.current.timer = setTimeout(() => {
            ref.current.timer = 0;
            // Always use the most recent `fn`, not necessarily
            // the one we had when scheduling the timer
            ref.current.fn.call(); // `call` so we don't pass our ref obj as `this`
        }, ms);
        return () => {
            clearTimeout(ref.current.timer);
            ref.current.timer = 0;
        };
    }, deps);
};

const buildFilters = (taggedWith, vendor) => {
    const filters = [];
    if (vendor) {
        filters.push({
            label: `Vendor: ${vendor}`
        });
    }
    if (taggedWith) {
        filters.push({
            label: `Tagged with: ${taggedWith}`
        });
    }
    return filters;
};

const Example = (props) => {
    const [vendor, setVendor] = useState("");
    const [taggedWith, setTaggedWith] = useState("");

    useDebounce(
        () => {
            console.log(`filter update ${vendor} ${taggedWith}`);
            props.onUpdate(buildFilters(taggedWith, vendor));
        },
        300,
        [taggedWith, vendor]
    );

    return <div>
        <label>
            <input type="text" value={vendor} onChange={
                ({target: {value}}) => { setVendor(value); }
            } />
        </label>
        <label>
            <input type="text" value={taggedWith} onChange={
                ({target: {value}}) => { setTaggedWith(value); }
            } />
        </label>
    </div>;
};

const App = () => {
    const [counter, setCounter] = useState(0);
    const [filters, setFilters] = useState([]);
    const ref = useRef(null);
    if (!ref.current) {
        ref.current = {};
    }

    useEffect(() => {
        const timer = setInterval(() => setCounter(c => c + 1), 100);
        return () => {
            clearInterval(timer);
        };
    }, []);

    // An update callback that we intentionally recreate every render
    // to check that useDebounce handles using the **latest** function
    const onUpdate = ref.current.onUpdate = function onUpdate(filters) {
        if (onUpdate !== ref.current.onUpdate) {
            console.log("STALE FUNCTION CALLED");
        }
        setFilters(filters);
    };

    return <div>
        Counter: {counter}
        <Example onUpdate={onUpdate} />
        <div>
            Filters ({filters.length}):
            {!!filters.length &&
                <ul>
                    {filters.map(filter => <li key={filter.label}>{filter.label}</li>)}
                </ul>
            }
        </div>
    </div>;
};

ReactDOM.render(<App />, document.getElementById("root"));

<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>


问:
How to return a boolean from a function in java? getting an error
```<code>public class Test {
    public boolean checkx(boolean x) {
        boolean status;
        if (x) {
            status = true;
        }
        return status;
    }
}
</code>```

Error: The local variable status may not have been initialized

I don't know what I was doing wrong, code looks alright to me.

答:
You're doing it way to complicated. You can check the status of a boolean by writing:

```<code>if(x == true)
        // Do Something
</code>```

or even simpler:

```<code>if(x)
        // Do Something
</code>```

Or you can write a function to get x from another class. In case the x is private:

```<code>public boolean getX() {
    return x;
}
</code>```

Body:
public class Test {
    public boolean checkx(boolean x) {
        boolean status;
        if (x) {
            status = true;
        }
        return status;
    }
}

Error: The local variable status may not have been initialized

I don't know what I was doing wrong, code looks alright to me.

Body:
You're doing it way to complicated. You can check the status of a boolean by writing:

if(x == true)
        // Do Something

or even simpler:

if(x)
        // Do Something

Or you can write a function to get x from another class. In case the x is private:

public boolean getX() {
    return x;
}


问:
How to split objects
How to split objects?
I want to split Object.
Such as one object per group or two object per group.</p>
```<code>obj1: {
    1: 1,
    2: 2,
    3: 3,
},
Split objects into groups(convert obj1 to obj2)
obj2: {
    0: {
            1: 1,
        },
    1: {
            2: 2,
        },
    },
    2: {
            3: 3,
        },
    },
}

</code>```

答:
```<code>let obj1 = {
    1 : 1 ,
    2 : 2 ,
    3 : 3
}
let index = 0 ;
let obj2 = {}
for(let key in obj1 ) {
  let temp = {

  }
    temp[key] = obj1[key]
       let prev = obj2 ;
    obj2[index] = {
      ...temp
    }
     index++;
}
</code>```

Try this code .
I hope this solves your issue :)

Title: How to split objects

Body:
How to split objects?
I want to split Object.
Such as one object per group or two object per group.

obj1: {
    1: 1,
    2: 2,
    3: 3,
},
Split objects into groups(convert obj1 to obj2)
obj2: {
    0: {
            1: 1,
        },
    1: {
            2: 2,
        },
    },
    2: {
            3: 3,
        },
    },
}

Body:
let obj1 = {
    1 : 1 ,
    2 : 2 ,
    3 : 3
}
let index = 0 ;
let obj2 = {}
for(let key in obj1 ) {
  let temp = {

  }
    temp[key] = obj1[key]
       let prev = obj2 ;
    obj2[index] = {
      ...temp
    }
     index++;
}

Try this code .
I hope this solves your issue :)


问:
php - mysql avoid sql injections
I have many functions like

```<code>updateUser($id,$username,$email)
updateMusic($id, $music)
</code>```

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

```<code>$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);
</code>```

答:
ALWAYS use prepared statements

Do NOT use mysql driver, use mysqli or PDO

Title: php - mysql avoid sql injections

Body:
I have many functions like

updateUser($id,$username,$email)
updateMusic($id, $music)

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);


问:
How to check if data returned from ajax as json is empty object or not
I have set this script for checking if the email address exists in the DB or not:

```<code>function checkemail(){
            var e = document.getElementById("email").value;
            if(e != ""){
                document.getElementById("emailstatus").innerHTML = 'checking ...';
                $.ajax({
                    type:'get',
                    url:'{!! URL::to('checkEmailExists') !!}',
                    data:{'email':e},
                    success:function(data){
                        // console.log(data);

                        if(Object.keys(data).length === 0)
                        {
                            document.getElementById("emailstatus").style.color = "red";
                            document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
                        }else{
                            document.getElementById("emailstatus").style.color = "green";
                            document.getElementById("emailstatus").innerHTML = e + " is OK";
                        }
                    },
                    error:function(){

                    }
                });
            }
        }
</code>```

So the code works fine but the only problem is comes from this condition checking which always returns TRUE:

```<code>if(Object.keys(data).length === 0)
</code>```

Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):

```<code>{}
</code>```

Otherwise, it will return this obj:

```<code>{
    "id": 1,
    "name": "Myname",
    "email": "myemail@yahoo.com",
    "email_verified_at": null,
    "created_at": "2022-02-09T05:49:27.000000Z",
    "updated_at": "2022-02-09T05:49:27.000000Z"
}
</code>```

So I need to properly check if the returned object is empty or not.

But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.

So how to properly check if the returned object is empty or not?

答:
You can check for a specific property, if it's not there then it will be undefined, meaning you didn't get a success response.

Combine undefined with || to get a "value if not set", gives:

```<code>success:function(data) {
    var success = (data.id || 0) > 0;
</code>```

You could just check for if (data.id == undefined) but there are a number of caveats when comparing with undefined

Body:
I have set this script for checking if the email address exists in the DB or not:

function checkemail(){
            var e = document.getElementById("email").value;
            if(e != ""){
                document.getElementById("emailstatus").innerHTML = 'checking ...';
                $.ajax({
                    type:'get',
                    url:'{!! URL::to('checkEmailExists') !!}',
                    data:{'email':e},
                    success:function(data){
                        // console.log(data);

                        if(Object.keys(data).length === 0)
                        {
                            document.getElementById("emailstatus").style.color = "red";
                            document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
                        }else{
                            document.getElementById("emailstatus").style.color = "green";
                            document.getElementById("emailstatus").innerHTML = e + " is OK";
                        }
                    },
                    error:function(){

                    }
                });
            }
        }

So the code works fine but the only problem is comes from this condition checking which always returns TRUE:

if(Object.keys(data).length === 0)

Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):

{}

Otherwise, it will return this obj:

{
    "id": 1,
    "name": "Myname",
    "email": "myemail@yahoo.com",
    "email_verified_at": null,
    "created_at": "2022-02-09T05:49:27.000000Z",
    "updated_at": "2022-02-09T05:49:27.000000Z"
}

So I need to properly check if the returned object is empty or not.

But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.

So how to properly check if the returned object is empty or not?

Body:
You can check for a specific property, if it's not there then it will be undefined, meaning you didn't get a success response.

Combine undefined with || to get a "value if not set", gives:

success:function(data) {
    var success = (data.id || 0) > 0;

You could just check for if (data.id == undefined) but there are a number of caveats when comparing with undefined


问:
How to determine if a web page is jquery-enabled?
What is the best way to determine if a webpage is jquery enabled? Using jquery itself if that's the best way to determine it.</p>

答:
I would like to use typeof operator.

if (typeof jQuery !== 'undefined') {
    // jQuery IS loaded
}
```


问:
How to calculate the difference between 2 rotations in SceneKit / ARKit
I have a node in ARKit for which I've registered its rotation at some point.
Later on, I'm registering the node's current rotation once again and I need to know the difference between those two.

I need this in the simdRotation format because I'll need to inject it to the simdPivot to then turn my node accordingly.  So I need the angle and the vector of axis of rotation.  (So I will turn this simdRotation into a rotation matrix and along with the translation, feed it to the simdPivot - this I know how to do).

I've been trying so many different things and I can't find how to calculate this difference nor do I find any documentation or site explaining how to accomplish this.

I tried maybe using the simdEulerAngles or the simdOrientation.
I found a method to convert the eulerAngles into an orientation quaternion.  But from here I don't know how to convert it back to the rotation format.

I need to do this in 2 places in my code.  In one place I'll need the difference of rotation in all 3 directions and in the 2nd place I'll just need the difference of rotation around the y-axis.

So what's the correct way to find the difference between 2 rotations?
I feel like it must be much simpler than how it currently looks to me.
Maybe I can convert both to rotation matrices and from here there's a clear formula?

Any help would be much appreciated!
Thanks.

答:
So I ultimately figured this out.
I turn each rotation into a rotation matrix - in my case I use a simd_float4x4 because I later combine it with a translation (as 4th column) into a transform matrix.
I do something like this:

```<code>let newRotationInTransformMatrix = simd_float4x4(SCNMatrix4MakeRotation(currentRotation!.w, currentRotation!.x, currentRotation!.y, currentRotation!.z))
</code>```

(If anyone knows how to create such a matrix directly in the simd world, please comment.  I didn't know so I first created it in the SCN notation and then converted to the sims format).

I do the same with the other rotation.
Then to find the difference between the two, I multiply one matrix by the transpose of the other:

```<code>let pivotRotationMatrix = lastMazeRotationInTransformMatirx * newRotationInTransformMatrix.transpose
</code>```

This worked for me.  I hope it can help others as well!

Body:
So I ultimately figured this out.
I turn each rotation into a rotation matrix - in my case I use a simd_float4x4 because I later combine it with a translation (as 4th column) into a transform matrix.
I do something like this:

let newRotationInTransformMatrix = simd_float4x4(SCNMatrix4MakeRotation(currentRotation!.w, currentRotation!.x, currentRotation!.y, currentRotation!.z))

(If anyone knows how to create such a matrix directly in the simd world, please comment.  I didn't know so I first created it in the SCN notation and then converted to the sims format).

I do the same with the other rotation.
Then to find the difference between the two, I multiply one matrix by the transpose of the other:

let pivotRotationMatrix = lastMazeRotationInTransformMatirx * newRotationInTransformMatrix.transpose

This worked for me.  I hope it can help others as well!


问:
Check for internet connection with Swift
When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

```<code>import Foundation
import SystemConfiguration

public class Reachability {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

    var flags: SCNetworkReachabilityFlags = 0

    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
        return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false
}

}
</code>```

The errors with the code:

If it is unreadable, error 1 says:

'Int' is not convertible to 'SCNetworkReachabilityFlags'

Error 2 & 3:

Could not find an overload for 'init' that accepts the supplied arguments

答:
There is no real way to do this, even APIs that do this will try to connect to a particular service and tell you if it succeed after previously failing, the best approach is to just try to connect to your service and handle the error appropriately, if you want some service that will notify you when you become connected, all that will happens is that it periodically calls to a fixed service until it gets a response and then let you know that it succeed, what if the problem is not the internet itself but the specific service you are trying to connect to.

The best approach to this is to design in you connection methods of handling this itself, you can trigger a retry in some given amount of time depending on your error, maybe the number of failures, you can return an error which you can use to display an error message giving the user a possibility to try again, maybe a combination of the try a few time, then return and error.

Another problem similar to this is sending messages you already have sent but haven't gotten a response to, again its best to just write your app to handle this, ignoring request until the one its waiting for has returned, cancelling waiting request if the request is different, etc

Theses things can be written in pretty generic ways so they can be used in many different aspects of your app or even different projects.

Body:
When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
import SystemConfiguration

public class Reachability {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

    var flags: SCNetworkReachabilityFlags = 0

    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
        return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false
}

}

The errors with the code:

If it is unreadable, error 1 says:

'Int' is not convertible to 'SCNetworkReachabilityFlags'

Error 2 & 3:

Could not find an overload for 'init' that accepts the supplied arguments


问:
How to solve Error inflating class in Android?
I have a custom view that extends the constraint layout as follows :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textViewMyTitle"
        style="@style/LabelLowLevel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="My Title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonEditMy"
        style="@style/InlineButtonTransparent"
        android:layout_width="wrap_content"
        android:text="@string/edit"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

    <Button
        android:id="@+id/buttonPlayMy"
        style="@style/InlineButtonHot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play"
        app:layout_constraintStart_toEndOf="@+id/buttonEditMy"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The view has some attributes :

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCard">
        <attr name="Mytitle" format="string"/>
        <attr name="Mydescription" format="string"/>
        <attr name="Myid" format="string"/>
    </declare-styleable>
</resources>
</code>```

And then the corresponding Java class :

```<code>public class MyCard extends ConstraintLayout {
    public MyCard(@NonNull Context context) {
        super(context);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public String Description;
    public String Topic;
    public String MyId;

    private void init(Context ctx, AttributeSet attrs) {
        TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

        Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
        Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
        MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

        LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.Mycard, this, true); // <<<<<< the error is raised here

        CustomAttr.recycle();

    }
}
</code>```

When running the code, I'm getting the error :

```<code>java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.colman.myapp/com.colman.myapp.Activity20_PersonalSpace}:
android.view.InflateException: Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Error inflating class com.colman.myapp.Libraries.views.MyCard
</code>```

Does anyone know how to solve that please ?

Tthanks.
Cheers

答:
try to change

inflater.inflate(R.layout.Mycard, this, true);

to

inflater.inflate(R.layout.Mycard, this, false);

Body:
I have a custom view that extends the constraint layout as follows :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textViewMyTitle"
        style="@style/LabelLowLevel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="My Title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonEditMy"
        style="@style/InlineButtonTransparent"
        android:layout_width="wrap_content"
        android:text="@string/edit"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

    <Button
        android:id="@+id/buttonPlayMy"
        style="@style/InlineButtonHot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play"
        app:layout_constraintStart_toEndOf="@+id/buttonEditMy"
        app:layout_constraintTop_toBottomOf="@+id/textViewMyTitle" />

</androidx.constraintlayout.widget.ConstraintLayout>

The view has some attributes :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCard">
        <attr name="Mytitle" format="string"/>
        <attr name="Mydescription" format="string"/>
        <attr name="Myid" format="string"/>
    </declare-styleable>
</resources>

And then the corresponding Java class :

public class MyCard extends ConstraintLayout {
    public MyCard(@NonNull Context context) {
        super(context);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public MyCard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public String Description;
    public String Topic;
    public String MyId;

    private void init(Context ctx, AttributeSet attrs) {
        TypedArray CustomAttr = ctx.obtainStyledAttributes(attrs, R.styleable.MyCard);

        Description = CustomAttr.getString(R.styleable.MyCard_Mydescription);
        Topic = CustomAttr.getString(R.styleable.MyCard_Mytitle);
        MyId = CustomAttr.getString(R.styleable.MyCard_Myid);

        LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.Mycard, this, true); // <<<<<< the error is raised here

        CustomAttr.recycle();

    }
}

When running the code, I'm getting the error :

java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.colman.myapp/com.colman.myapp.Activity20_PersonalSpace}:
android.view.InflateException: Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Binary XML file line #49 in com.colman.myapp:layout/activity_activity20_personal_space:
Error inflating class com.colman.myapp.Libraries.views.MyCard

Does anyone know how to solve that please ?

Tthanks.
Cheers


问:
How do I make it so that I can edit my vue to do list to add items?
Ok, so, I am new to Vue and I am trying to make a simple to do list. I have managed to display it and stuff but I am having trouble with the code to add items to the list. When I click the button to add the task, it adds a bullet point but it doesn’t show the text given. For example, in the input box, I will type the name of a task but when I click the button, what I wrote doesn’t show up, just the bullet point.

I have tried putting the newTask part in other places but the same problem happens. I know this is probably a pretty silly question and the solution is probably pretty obvious but please help as fast as you can, I need to do this for school.

Here is my HTML:

```<code><body>
  <div id="app">
    <!-- Vue App HTML Code -->
    <h1>To Do List</h1>
    <div id="app">
  <ul>
    <li v-for="x in tasks">
      {{ x.text }}
    </li>
  </ul>
</div>
    <div id="newTask">
      <input type="text" value="taskName" placeholder="Task Name" v-model="newTask"></input>
      <button v-on:click="tasks.push(newTask)">Add Task</button>
    </div>
</body>
</code>```

And my JavaScript/ Vue:

```<code>myObject = new Vue({
    el: '#app',
    data: {
        tasks: [
            { text: '1' },
            { text: '2' },
            { text: '3' },
        ],
        newTask: ''
    },
})
</code>```

I would really appreciate any other Vue tips (relevant or not) because it is my first week learning it and anything would be really useful.

答:
You can achieve this by pushing the newTask in the existing tasks array.

Working Demo :

var vm = new Vue({
  el: '#app',
  data: {
    tasks: [
      { text: '1' },
      { text: '2' },
      { text: '3' },
    ],
    newTask: ''
  },
  methods: {
    addTask() {
        this.tasks.push({ text: this.newTask })
      this.newTask = '';
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h1>To Do List</h1>
  <ul>
    <li v-for="x in tasks">
      {{ x.text }}
    </li>
  </ul>
  <input type="text" placeholder="Task Name" v-model="newTask"/>
  <button v-on:click="addTask">Add Task</button>
</div></code>```

Body:
Ok, so, I am new to Vue and I am trying to make a simple to do list. I have managed to display it and stuff but I am having trouble with the code to add items to the list. When I click the button to add the task, it adds a bullet point but it doesn’t show the text given. For example, in the input box, I will type the name of a task but when I click the button, what I wrote doesn’t show up, just the bullet point.

I have tried putting the newTask part in other places but the same problem happens. I know this is probably a pretty silly question and the solution is probably pretty obvious but please help as fast as you can, I need to do this for school.

Here is my HTML:

To Do List

      {{ x.text }}

      <input type="text" value="taskName" placeholder="Task Name" v-model="newTask"></input>
      <button v-on:click="tasks.push(newTask)">Add Task</button>

And my JavaScript/ Vue:

myObject = new Vue({
    el: '#app',
    data: {
        tasks: [
            { text: '1' },
            { text: '2' },
            { text: '3' },
        ],
        newTask: ''
    },
})

I would really appreciate any other Vue tips (relevant or not) because it is my first week learning it and anything would be really useful.

Body:
You can achieve this by pushing the newTask in the existing tasks array.

Working Demo :

var vm = new Vue({
  el: '#app',
  data: {
    tasks: [
      { text: '1' },
      { text: '2' },
      { text: '3' },
    ],
    newTask: ''
  },
  methods: {
    addTask() {
        this.tasks.push({ text: this.newTask })
      this.newTask = '';
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h1>To Do List</h1>
  <ul>
    <li v-for="x in tasks">
      {{ x.text }}
    </li>
  </ul>
  <input type="text" placeholder="Task Name" v-model="newTask"/>
  <button v-on:click="addTask">Add Task</button>
</div>


问:
React native async storage returning previous value
I'm using react-native-async-storage for saving API headers and user information received from API

```<code>const storeUserInfo = async (userInfo: any, headers: any) => {
  console.log(
    'Info Received in Local Storage Function',
    userInfo,
    'Headers Received in Local Storage Function',
    headers,
  );

  try {
    const user = JSON.stringify(userInfo);
    const userheaders = JSON.stringify(headers);
    await AsyncStorage.setItem('user', user);
    await AsyncStorage.setItem('headers', userheaders);
  } catch (e) {
    console.log('Error while storing user info', e);
  }
};
</code>```

when i try to get headers from async-storage, it gave old stored headers rather than returning latest.

// Getting headers like this..

```<code>const headers = await AsyncStorage.getItem('headers');
console.log('Headers received in get Profile Action', headers);
</code>```

but it returning old headers..

答:
Don't know why but React native async storage is not running next line after the setItem line

```<code>await AsyncStorage.setItem('user', user);
await AsyncStorage.setItem('headers', userheaders);
</code>```

setItem for a user is running but setItem for a header is not running and that's why it was returning old value

Body:
I'm using react-native-async-storage for saving API headers and user information received from API

const storeUserInfo = async (userInfo: any, headers: any) => {
  console.log(
    'Info Received in Local Storage Function',
    userInfo,
    'Headers Received in Local Storage Function',
    headers,
  );

  try {
    const user = JSON.stringify(userInfo);
    const userheaders = JSON.stringify(headers);
    await AsyncStorage.setItem('user', user);
    await AsyncStorage.setItem('headers', userheaders);
  } catch (e) {
    console.log('Error while storing user info', e);
  }
};

when i try to get headers from async-storage, it gave old stored headers rather than returning latest.

// Getting headers like this..

const headers = await AsyncStorage.getItem('headers');
console.log('Headers received in get Profile Action', headers);

but it returning old headers..

Body:
Don't know why but React native async storage is not running next line after the setItem line

await AsyncStorage.setItem('user', user);
await AsyncStorage.setItem('headers', userheaders);

setItem for a user is running but setItem for a header is not running and that's why it was returning old value