问:
“No 'Access-Control-Allow-Origin' header is present” error for some requests but not others
I have a VueJS app running on S3 that is served by a Flask-powered API running on AWS Elastic Beastalk.

The problem

When making some requests, I get the following:

```<code>Access to XMLHttpRequest at 'https://api.myflaskapi.net/blueprint/get_info?date=2019-01-01' from origin 'https://app.myvuejsapp.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

What I've done so far

In my __init__.py file, initialized by the app factory in Flask I have set CORS(app, support_credentials=True) as the example on this link. With that, I would hope that basically any request would have the CORS heading, so I wouldn't have any policy blocking my frontend requests.

The ideal scenario would be to only allow requests from https://app.myvuejsapp.net, so I tried using CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net']) but also without success.

I've also tried making one CORS instance for each of my blueprints with CORS(myblueprint) for each .py route file (I have one for each blueprint), also without success.

The strange thing is, I do have one function on Vue that runs when the app is mounted that works just fine. I can't see any difference between this and other functions that won't work.

Example of working function (returns true or false from the backend):

```<code>      checkDB() {
        const path = this.base_url + 'blueprint/check_db'
        axios.get(path, this.token)
          .then(checkupd => {
            this.isupdated = Boolean(checkupd.data);
            if (this.isupdated == true) {
              this.update_msg = "Database up to date."
              this.loading = false
              this.finished = true
            } else {
              this.update_msg = "WARNING: Check DB status."
            }
          })
          .catch(error => {
            console.log(error)
          })
      },
</code>```

Example of non-working function (returns a XLS from the backend):

```<code>      getSalesFrom(file) {
        const fs = require('fs')
        const FileDownload = require('js-file-download');
        const path = this.base_url + `blueprint/get_sales?date=${this.date}`
        axios.get(path, {
            headers:
              {
                "X-Access-Token": "mytoken",
                "Content-Type": "application/json"
              },
            responseType: 'blob'
          })
          .then(response => {
            const content = response.headers['content-type'];
            download(response.data, 'text.xlsx', content)
          })
          .catch(error => {
            console.log(error)
          })
        this.export_dialog = false
      }
</code>```

S3 CORS Configuration XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
    <AllowedHeader>Content-Length</AllowedHeader>
    <AllowedHeader>Access-Control-Allow-Origin</AllowedHeader>
    <AllowedHeader>X-Access-Token</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

Any ideas on what I might be doing wrong?
I've been reading for a while, but can't seem to find a solution for what it seems a pretty simple problem... Maybe I should mess with the S3 bucket permission configuration?

Thanks.

答:
Any time you run into a case where you’re seeing a “No 'Access-Control-Allow-Origin' header is present” message for some requests but not others, use the Network pane in browser devtools to check the HTTP status code of the response.

Almost always what you’re going to find is that the HTTP status code in those cases is a 4xx or 5xx error instead of the expected 200 OK success response.

The only reason you see the “No 'Access-Control-Allow-Origin' header is present” message is those cases is, the Access-Control-Allow-Origin header typically isn’t going to get added to 4xx and 5xx errors. Part of the reason is, in the 5xx case especially, the cause can be a server failure that occurs before the server ever gets around to running your application code. Along with that, most servers by default won’t add application-set response headers to 4xx and 5xx errors; instead by default they only add them to 2xx success responses.

So anyway, what you want to do is, look at the server logs on the server side (for the server you’re sending the request to) and see what messages the server is logging about the cause of whatever problem it is that makes the server end up sending that 4xx or 5xx error response.

Body:
I have a VueJS app running on S3 that is served by a Flask-powered API running on AWS Elastic Beastalk.

The problem

When making some requests, I get the following:

Access to XMLHttpRequest at 'https://api.myflaskapi.net/blueprint/get_info?date=2019-01-01' from origin 'https://app.myvuejsapp.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What I've done so far

In my __init__.py file, initialized by the app factory in Flask I have set CORS(app, support_credentials=True) as the example on this link. With that, I would hope that basically any request would have the CORS heading, so I wouldn't have any policy blocking my frontend requests.

The ideal scenario would be to only allow requests from https://app.myvuejsapp.net, so I tried using CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net']) but also without success.

I've also tried making one CORS instance for each of my blueprints with CORS(myblueprint) for each .py route file (I have one for each blueprint), also without success.

The strange thing is, I do have one function on Vue that runs when the app is mounted that works just fine. I can't see any difference between this and other functions that won't work.

Example of working function (returns true or false from the backend):

      checkDB() {
        const path = this.base_url + 'blueprint/check_db'
        axios.get(path, this.token)
          .then(checkupd => {
            this.isupdated = Boolean(checkupd.data);
            if (this.isupdated == true) {
              this.update_msg = "Database up to date."
              this.loading = false
              this.finished = true
            } else {
              this.update_msg = "WARNING: Check DB status."
            }
          })
          .catch(error => {
            console.log(error)
          })
      },

Example of non-working function (returns a XLS from the backend):

      getSalesFrom(file) {
        const fs = require('fs')
        const FileDownload = require('js-file-download');
        const path = this.base_url + `blueprint/get_sales?date=${this.date}`
        axios.get(path, {
            headers:
              {
                "X-Access-Token": "mytoken",
                "Content-Type": "application/json"
              },
            responseType: 'blob'
          })
          .then(response => {
            const content = response.headers['content-type'];
            download(response.data, 'text.xlsx', content)
          })
          .catch(error => {
            console.log(error)
          })
        this.export_dialog = false
      }

S3 CORS Configuration XML

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
    <AllowedHeader>Content-Length</AllowedHeader>
    <AllowedHeader>Access-Control-Allow-Origin</AllowedHeader>
    <AllowedHeader>X-Access-Token</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Any ideas on what I might be doing wrong?
I've been reading for a while, but can't seem to find a solution for what it seems a pretty simple problem... Maybe I should mess with the S3 bucket permission configuration?

Thanks.


来源: stackexchange

问:
ACI caching docker images after pull
Primarily I have a docker container with MSBuild tools installed and the Vsts agent. Building the docker container takes a fair amount of time because of the visual studio installer. (45 minutes on local machine)

In Azure DevOps I've created a pipeline that uses this image to start, build and deploy our applications. After finishing the build it should stop the container till next request.

I thought that using ACI would make my current local build server obsolete, because i find it a little bit stupid to have a full blown windows server to run docker on it with the containers also running a full blown windows server.
Either i missed something or running msbuild and the agent on the physical server defeats the purpose of the whole docker solution.

On the other side, removing this physical server and replace it by ACI should do the trick. Starting and stopping this container with Azure Cli can be handled by Azure Devops. The only issue here is that the container instance is stateless, which has a nasty side effect of pulling the image every time the instance is started which takes an half hour to complete. Keep the instance running is a no-go because of the costs.
If only the pulled image is cached and used on every restart, this would be the ultimate solution but sadly it's not.

Did i missed something in the preliminary investigation or did i made some wrong assumptions?

答:
No, you can have cache in Azure Devops, it has some of the base images cached already, you can query this API to find them out.

Azure Container Instances uses a caching mechanism to help speed
  container startup time for images built on common Windows base images,
  including nanoserver:1809, servercore:ltsc2019, and servercore:1809.
  Commonly used Linux images such as ubuntu:1604 and alpine:3.6 are also
  cached.

Reading:

https://learn.microsoft.com/bs-latn-ba/azure/container-instances/container-instances-faq#what-windows-base-os-images-are-supported

https://learn.microsoft.com/bs-latn-ba/azure/container-instances/container-instances-troubleshooting?view=azurermps-6.13.0#cached-images

ContentLicense: CC BY-SA 4.0

Title: ACI caching docker images after pull


问:
Could not find or load main class com.weekdays.claobj.Ann1
enter image description hereMy code is showing no compilation error but it fails while execution with below error:

```<code>C:\Program Files\Java\jdk-11.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.1\lib\idea_rt.jar=51590:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.1\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\ag186097\IdeaProjects\Prwatech\target\scala-2.11\classes;C:\Users\ag186097\.ivy2\cache\org.scala-lang\scala-library\jars\scala-library-2.11.8.jar com.weekdays.claobj.Ann1
**Error: Could not find or load main class com.weekdays.claobj.Ann1
Caused by: java.lang.ClassNotFoundException: com.weekdays.claobj.Ann1**
</code>```

I have tried setting the main folder as root folder still not getting executed

```<code>package com.weekdays.claobj

class Annon1Obj {

  var age:Int = 29

  def show():Unit = {

    println("this is the age of raju " + age)}

}

object Ann1{

  def main(args: Array[String]): Unit = {

    var n = new Annon1Obj()

    n.show()

  }

}
</code>```

答:
https://www.scala-lang.org/download/

read the first step make sure you have JDK 8 installed.

if you have jdk 8 installed then you can go select jdk 8 as your project jdk.

file-> project structure -> there you will find a drop down where you will have the JDK you can change it.

Downgrade your jdk version to 8 it will work fine then.

Body:
enter image description hereMy code is showing no compilation error but it fails while execution with below error:

C:\Program Files\Java\jdk-11.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.1\lib\idea_rt.jar=51590:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.1\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\ag186097\IdeaProjects\Prwatech\target\scala-2.11\classes;C:\Users\ag186097\.ivy2\cache\org.scala-lang\scala-library\jars\scala-library-2.11.8.jar com.weekdays.claobj.Ann1
**Error: Could not find or load main class com.weekdays.claobj.Ann1
Caused by: java.lang.ClassNotFoundException: com.weekdays.claobj.Ann1**

I have tried setting the main folder as root folder still not getting executed

package com.weekdays.claobj

class Annon1Obj {

  var age:Int = 29

  def show():Unit = {

    println("this is the age of raju " + age)}

}

object Ann1{

  def main(args: Array[String]): Unit = {

    var n = new Annon1Obj()

    n.show()

  }

}


问:
Why do some ScriptResource.axd calls succeed and others fail?
We have a website that runs on ASP.NET 4.

I notice the website renders two ScriptResource.axd requests. On our QA environment the one request succeeds and the other request fails (with a 404 error). On all other environments both calls succeed.

The request urls are...

This one works:
http://qa.www.fin24.com/ScriptResource.axd?d=EXDGAyD7E-g0TI3ln2UV0Ito6mFPfvKoqGrtHwYwGdVJJOUwJ8gsPer-44iuksfoAzBnFSzXOLvF2P_wqjS6qmSsyI9GhZdZOUN3O0Z5p9JsE-pk_3BD4OQnX_Kud_dHKag4ecuNm9c042HsChtnGRiQU9rGs-ZiZBSlMUWBm6afRr20thS8CZ6ecsS-LuSV0&t=2610f696

This one returns a 404:
http://qa.www.fin24.com/ScriptResource.axd?d=PxoN2ObK88-8ae9bfqlj3V1AtnVv55YrZDDzgP3QS3cLonT7ilIgG1Ealrod7pi8hllo--dMwM5l9a_Gg8llygZZn50tZRKvfuDReuNGwaBszxD6QDss_qeT81nleD9XNVL7XI6RlZHHk2ktLrnLqcBNnZNBvUG2IYldG5UG-71Rj6CH9HYLfidCe6mJeX2M0&t=2610f696

Why would the second one fail?

I've read that these calls relate to different DLLs, so I'm guessing one DLL is not on the server? But I don't know which DLLs.

Am I on the right track? Any thoughts?

答:
This must have been a problem with ASP.NET. I deleted the website in IIS and re-created it.

Problem solved!

ContentLicense: CC BY-SA 3.0


问:
React native Linking.getInitialUrl on Android called always
I've a React-Native app with the following code (here App.js, the app entry point) that manages deep link on Android.

```<code>Linking.getInitialURL().then((deepLinkUrl) => {
  if (deepLinkUrl) {
    manageDeepLink(deepLinkUrl);
  } else {
    Navigation.startSingleScreenApp('rootScreen');
  }
});
</code>```

The problem here is that getInitialURL is called every time I launch my app, from both deep link or normally, and everytime it contains deepLinkUrl parameter empty.
I've registered in AndroidManifest my intent as follows:

```<code><application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:launchMode="singleTask"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize">
        <!-- deeplink -->
        <intent-filter android:label="@string/app_name">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</code>```

UPDATE
I'm using react-native navigation to register screens, if this can e useful.

答:
It seems it doesn't work if you register listener too soon in the app lifecycle (ex. directly in some .js file, so it's executed when app is loaded).

If you move it into componentDidMount() on the root component everything works fine.

```<code>    componentDidMount() {
        Linking.addEventListener('url', event => {
            console.warn('URL', event.url)
        })

        Linking.getInitialURL().then(url => {
            console.warn('INITIAL', url)
        })
    }
</code>```

Body:
I've a React-Native app with the following code (here App.js, the app entry point) that manages deep link on Android.

Linking.getInitialURL().then((deepLinkUrl) => {
  if (deepLinkUrl) {
    manageDeepLink(deepLinkUrl);
  } else {
    Navigation.startSingleScreenApp('rootScreen');
  }
});

The problem here is that getInitialURL is called every time I launch my app, from both deep link or normally, and everytime it contains deepLinkUrl parameter empty.
I've registered in AndroidManifest my intent as follows:

<application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:launchMode="singleTask"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize">

        <intent-filter android:label="@string/app_name">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

UPDATE
I'm using react-native navigation to register screens, if this can e useful.

Body:
It seems it doesn't work if you register listener too soon in the app lifecycle (ex. directly in some .js file, so it's executed when app is loaded).

If you move it into componentDidMount() on the root component everything works fine.

    componentDidMount() {
        Linking.addEventListener('url', event => {
            console.warn('URL', event.url)
        })

        Linking.getInitialURL().then(url => {
            console.warn('INITIAL', url)
        })
    }


问:
How can I return a struct if a condition is true and an int if the condition is false
First a simple example:

```<code>typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}
</code>```

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

答:
You can't have a function with a variable return type.

The common ways to handle the situation is to either:

1) use a numerical return value for error signalling and return the payload through a passed pointer

```<code> int algorithm(Order *ret, int a, int b){
        if(a == b) return -1;   //Error
        else return *ret=ord, 0;    //Returns the Order ord
    }
</code>```

2) or return a tagged struct (less common, in my experience, but it can generate slightly more optimal code if the payload is small); it it's tagged as successful, the rest of the struct is usable, otherwise it isn't

```<code> struct taggedOrder { Order order; _Bool is_ok; };
 struct taggedOrder algorithm(int a, int b){
    struct taggedOrder r = { ord, 1 };
    if(a == b) return r.is_ok=0, r;   //Error
    else return r;    //Returns the Order ord
  }
</code>```

Body:
First a simple example:

typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

Body:
You can't have a function with a variable return type.

The common ways to handle the situation is to either:

1) use a numerical return value for error signalling and return the payload through a passed pointer

 int algorithm(Order *ret, int a, int b){
        if(a == b) return -1;   //Error
        else return *ret=ord, 0;    //Returns the Order ord
    }

2) or return a tagged struct (less common, in my experience, but it can generate slightly more optimal code if the payload is small); it it's tagged as successful, the rest of the struct is usable, otherwise it isn't

 struct taggedOrder { Order order; _Bool is_ok; };
 struct taggedOrder algorithm(int a, int b){
    struct taggedOrder r = { ord, 1 };
    if(a == b) return r.is_ok=0, r;   //Error
    else return r;    //Returns the Order ord
  }


问:
MongoDB index construction in the background as the default behavior for all connections
We need to override the default value for background option in createIndex method of MongoDB, to true, so that if a developer forgets to pass the option, it runs in the background.

Is there any way to override this option at the driver, connection or any other levels?

Specifically for, but not only limited to, Java.

答:
Here is one solution for Spring data mongodb or mongodb-java-driver:

```<code>public static void insertIndex(MongoCollection<Document> collection) {
  //Create the json document describing your index
  Document textIndexes = new Document("dataset.metadata.description.text", "text");

  //set your index options
  IndexOptions io = new IndexOptions();
  io.name("my_index");
  io.background(true);

  //create your index for your collection
  collection.createIndex(textIndexes, io);
}
</code>```

Spring data mongodb @Indexed annotation also comes with various properties that allow you to control how the index is applied. See reference

```<code>@Indexed(background= true)
</code>```

Body:
Here is one solution for Spring data mongodb or mongodb-java-driver:

public static void insertIndex(MongoCollection<Document> collection) {
  //Create the json document describing your index
  Document textIndexes = new Document("dataset.metadata.description.text", "text");

  //set your index options
  IndexOptions io = new IndexOptions();
  io.name("my_index");
  io.background(true);

  //create your index for your collection
  collection.createIndex(textIndexes, io);
}

Spring data mongodb @Indexed annotation also comes with various properties that allow you to control how the index is applied. See reference

@Indexed(background= true)


问:
Process large csv file and limit goroutines
I'm trying to find the best efficient way to read a csv file (~1M row).
Each row contain a HTTP link to an image which I need to download.

This is my current code using worker pools:

```<code>func worker(queue chan []string, worknumber int, done, ks chan bool) {
    for true {
        select {
        case url := <-queue:
            fmt.Println("doing work!", url, "worknumber", worknumber)
            processData(url) // HTTP download
            done <- true
        case <-ks:
            fmt.Println("worker halted, number", worknumber)
            return
        }
    }
}

func main() {
    start := time.Now()
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), "\n"))
    if *filename == "REQUIRED" {
        return
    }

    csvfile, err := os.Open(*filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    count, _ := lineCounter(csvfile)
    fmt.Printf("Total count: %d\n", count)
    csvfile.Seek(0, 0)

    defer csvfile.Close()

    //bar := pb.StartNew(count)
    bar := progressbar.NewOptions(count)
    bar.RenderBlank()

    reader := csv.NewReader(csvfile)

    //channel for terminating the workers
    killsignal := make(chan bool)

    //queue of jobs
    q := make(chan []string)
    // done channel takes the result of the job
    done := make(chan bool)

    numberOfWorkers := *numChannels
    for i := 0; i < numberOfWorkers; i++ {
        go worker(q, i, done, killsignal)
    }

    i := 0
    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Println(err)
            return
        }
        i++

        go func(r []string, i int) {
            q <- r
            bar.Add(1)
        }(record, i)
    }

    // a deadlock occurs if c >= numberOfJobs
    for c := 0; c < count; c++ {
        <-done
    }

    fmt.Println("finished")

    // cleaning workers
    close(killsignal)
    time.Sleep(2 * time.Second)

    fmt.Printf("\n%2fs", time.Since(start).Seconds())
}
</code>```

My issue here is that it opens a lot of goroutines, use all the memory and crash.

What would be the best way to limit it?

答:
You're creating a new goroutine for every line in the file. That's why. There's no reason to do that, if you already have the workers you need.

So in short, change this:

```<code>    go func(r []string, i int) {
        q <- r
        bar.Add(1)
    }(record, i)
</code>```

to this:

```<code>    q <- record
    bar.Add(1)
</code>```

Body:
I'm trying to find the best efficient way to read a csv file (~1M row).
Each row contain a HTTP link to an image which I need to download.

This is my current code using worker pools:

func worker(queue chan []string, worknumber int, done, ks chan bool) {
    for true {
        select {
        case url := <-queue:
            fmt.Println("doing work!", url, "worknumber", worknumber)
            processData(url) // HTTP download
            done <- true
        case <-ks:
            fmt.Println("worker halted, number", worknumber)
            return
        }
    }
}

func main() {
    start := time.Now()
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), "\n"))
    if *filename == "REQUIRED" {
        return
    }

    csvfile, err := os.Open(*filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    count, _ := lineCounter(csvfile)
    fmt.Printf("Total count: %d\n", count)
    csvfile.Seek(0, 0)

    defer csvfile.Close()

    //bar := pb.StartNew(count)
    bar := progressbar.NewOptions(count)
    bar.RenderBlank()

    reader := csv.NewReader(csvfile)

    //channel for terminating the workers
    killsignal := make(chan bool)

    //queue of jobs
    q := make(chan []string)
    // done channel takes the result of the job
    done := make(chan bool)

    numberOfWorkers := *numChannels
    for i := 0; i < numberOfWorkers; i++ {
        go worker(q, i, done, killsignal)
    }

    i := 0
    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Println(err)
            return
        }
        i++

        go func(r []string, i int) {
            q <- r
            bar.Add(1)
        }(record, i)
    }

    // a deadlock occurs if c >= numberOfJobs
    for c := 0; c < count; c++ {
        <-done
    }

    fmt.Println("finished")

    // cleaning workers
    close(killsignal)
    time.Sleep(2 * time.Second)

    fmt.Printf("\n%2fs", time.Since(start).Seconds())
}

My issue here is that it opens a lot of goroutines, use all the memory and crash.

What would be the best way to limit it?

Body:
You're creating a new goroutine for every line in the file. That's why. There's no reason to do that, if you already have the workers you need.

So in short, change this:

    go func(r []string, i int) {
        q <- r
        bar.Add(1)
    }(record, i)

to this:

    q <- record
    bar.Add(1)


问:
Python programs hangs randomly
I'm a newbie in python , so I was creating this project to create Sudoku using brute force method. To some extent I was successful but I am not able to figure out why sometimes the program hangs randomly while generating. Hope someone can pinpoint the issue.

I have tried debugging the code but still am not able to pinpoint what's causing the issue. The most close I have come to figuring something about the bug is that it is caused somewhere in the brute_generator() function.

A little Info on how the code is intended to work :-

The Sudoku is generated row by row by calling the brute_generator()function 9 times.

In the function brute_generator() the rows are generated using trial and error where a random number is picked up from possibilities list which is from number 1-9 and then it is treated as first number of row , now check_1() and check_2() function are called to check if the number has already been repeated in its column in previous rows if any and its 3x3 square as per the rules of Sudoku , if yes then the number is added to blacklist list and another number is chosen till the right number is obtained. When the right number is obtained it is appended to a temp_array while being removed from possibilities list so that it cannot be chosen again and counter is increased by 1 . This repeats till the row is generated  (i.e counter = 9) or no number from possibilities list can be placed in a given cell of row (i.e len(blacklist)==len(possibilities) , all possibilities are blacklisted) in which case the row being generated is scraped by returning all variables to their default values and a new row is generated . This happens until the perfect row is obtained which is then appended to sudoku_array()

def check_1(x , temp_array ,  sudoku_array) :  # Check for recurrence in the Block in which the cell exist
    flag_1 = True
    if len(temp_array) < 3 :
        j = 2
        l = 0
    elif len(temp_array) < 6 :
        j = 5
        l = 3
    else :
        j = 8
        l = 6
    i = len(sudoku_array)
    if len(sudoku_array) < 3 :
        o = 0
    elif len(sudoku_array) < 6 :
        o = 3
    else :
        o = 6
    for m in range(o,i) :
        for n in range(l,j+1) :
            if x == sudoku_array[m][n] :
                flag_1 = False
                break
        if x == sudoku_array[m][n] :
            break
    return flag_1

def check_2(x, counter, sudoku_array) :  # Check for the recurrence of number in its consequent column
    flag_2 = True
    for k in range(len(sudoku_array)) :
        if x == sudoku_array[k][counter] :
            flag_2 = False
            break
    return flag_2

def brute_generator(sudoku_array) : # The main sudoku Generating Algo.
    all_possibilities = [1,2,3,4,5,6,7,8,9]
    possibilities = all_possibilities.copy()
    blacklist = []
    counter = 0
    temp_array = []
    while counter != 9 :
        if len(blacklist) == len(possibilities) :
            all_possibilities = [1,2,3,4,5,6,7,8,9]
            possibilities = all_possibilities.copy()
            blacklist = []
            counter = 0
            temp_array = []
            continue
        x = random.choice(possibilities)
        if x not in blacklist :
            if len(sudoku_array) != 0 :
                if check_1(x, temp_array , sudoku_array) == False :
                    blacklist.append(x)
                    continue
                elif check_2(x, counter , sudoku_array) == False :
                    blacklist.append(x)
                    continue
            possibilities.remove(x)
            counter+=1
            temp_array.append(x)
            blacklist = []
    sudoku_array.append(temp_array)

sudoku_array = []   # This will be the generated sudoku
for i in range(9) :
    brute_generator(sudoku_array)
```

<p>The Traceback calls show the following after the program is stuck</p>

```Traceback (most recent call last):
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in <module>
    vspd.debug(filename, port_num, debug_id, debug_options, run_as)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 37, in debug
    run(address, filename, *args, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 64, in run_file
    run(argv, addr, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 125, in _run
    _pydevd.main()
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1099, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1106, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\groot\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 145, in <module>
    brute_generator(sudoku_array)
  File "C:\Users\groot\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 109, in brute_generator
    x = random.choice(possibilities)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\random.py", line 255, in choice
    def choice(self, seq):
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydevd_bundle\pydevd_trace_dispatch_regular.py", line 273, in __call__
    frame_cache_key = (frame.f_code.co_firstlineno, frame.f_code.co_name, frame.f_code.co_filename)
KeyboardInterrupt
```

答:
Hope someone can pinpoint the issue.

The issue is that for i in range(9) : brute_generator(sudoku_array) can create a partial sudoku_array which is impossible to complete, e. g. the five rows:

```<code>[1, 5, 7, 2, 3, 6, 8, 4, 9],
[9, 8, 2, 5, 4, 7, 6, 3, 1],
[4, 3, 6, 8, 1, 9, 7, 2, 5],
[5, 7, 9, 4, 2, 1, 3, 6, 8],
[6, 1, 3, 9, 5, 8, 2, 7, 4]
</code>```

Now the function keeps searching for an appropriate sixth row which it never finds, and it never backtracks, which would mean throwing away previously generated rows to get out of the dead end.

Title: Python programs hangs randomly

Body:
I'm a newbie in python , so I was creating this project to create Sudoku using brute force method. To some extent I was successful but I am not able to figure out why sometimes the program hangs randomly while generating. Hope someone can pinpoint the issue.

I have tried debugging the code but still am not able to pinpoint what's causing the issue. The most close I have come to figuring something about the bug is that it is caused somewhere in the brute_generator() function.

A little Info on how the code is intended to work :-

The Sudoku is generated row by row by calling the brute_generator()function 9 times.

In the function brute_generator() the rows are generated using trial and error where a random number is picked up from possibilities list which is from number 1-9 and then it is treated as first number of row , now check_1() and check_2() function are called to check if the number has already been repeated in its column in previous rows if any and its 3x3 square as per the rules of Sudoku , if yes then the number is added to blacklist list and another number is chosen till the right number is obtained. When the right number is obtained it is appended to a temp_array while being removed from possibilities list so that it cannot be chosen again and counter is increased by 1 . This repeats till the row is generated  (i.e counter = 9) or no number from possibilities list can be placed in a given cell of row (i.e len(blacklist)==len(possibilities) , all possibilities are blacklisted) in which case the row being generated is scraped by returning all variables to their default values and a new row is generated . This happens until the perfect row is obtained which is then appended to sudoku_array()

def check_1(x , temp_array ,  sudoku_array) :  # Check for recurrence in the Block in which the cell exist
    flag_1 = True
    if len(temp_array) < 3 :
        j = 2
        l = 0
    elif len(temp_array) < 6 :
        j = 5
        l = 3
    else :
        j = 8
        l = 6
    i = len(sudoku_array)
    if len(sudoku_array) < 3 :
        o = 0
    elif len(sudoku_array) < 6 :
        o = 3
    else :
        o = 6
    for m in range(o,i) :
        for n in range(l,j+1) :
            if x == sudoku_array[m][n] :
                flag_1 = False
                break
        if x == sudoku_array[m][n] :
            break
    return flag_1

def check_2(x, counter, sudoku_array) :  # Check for the recurrence of number in its consequent column
    flag_2 = True
    for k in range(len(sudoku_array)) :
        if x == sudoku_array[k][counter] :
            flag_2 = False
            break
    return flag_2

def brute_generator(sudoku_array) : # The main sudoku Generating Algo.
    all_possibilities = [1,2,3,4,5,6,7,8,9]
    possibilities = all_possibilities.copy()
    blacklist = []
    counter = 0
    temp_array = []
    while counter != 9 :
        if len(blacklist) == len(possibilities) :
            all_possibilities = [1,2,3,4,5,6,7,8,9]
            possibilities = all_possibilities.copy()
            blacklist = []
            counter = 0
            temp_array = []
            continue
        x = random.choice(possibilities)
        if x not in blacklist :
            if len(sudoku_array) != 0 :
                if check_1(x, temp_array , sudoku_array) == False :
                    blacklist.append(x)
                    continue
                elif check_2(x, counter , sudoku_array) == False :
                    blacklist.append(x)
                    continue
            possibilities.remove(x)
            counter+=1
            temp_array.append(x)
            blacklist = []
    sudoku_array.append(temp_array)

sudoku_array = []   # This will be the generated sudoku
for i in range(9) :
    brute_generator(sudoku_array)

The Traceback calls show the following after the program is stuck

Traceback (most recent call last):
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in <module>
    vspd.debug(filename, port_num, debug_id, debug_options, run_as)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 37, in debug
    run(address, filename, *args, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 64, in run_file
    run(argv, addr, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 125, in _run
    _pydevd.main()
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1099, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1106, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\groot\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 145, in <module>
    brute_generator(sudoku_array)
  File "C:\Users\groot\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 109, in brute_generator
    x = random.choice(possibilities)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\random.py", line 255, in choice
    def choice(self, seq):
  File "c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydevd_bundle\pydevd_trace_dispatch_regular.py", line 273, in __call__
    frame_cache_key = (frame.f_code.co_firstlineno, frame.f_code.co_name, frame.f_code.co_filename)
KeyboardInterrupt

Body:
Hope someone can pinpoint the issue.

The issue is that for i in range(9) : brute_generator(sudoku_array) can create a partial sudoku_array which is impossible to complete, e. g. the five rows:

[1, 5, 7, 2, 3, 6, 8, 4, 9],
[9, 8, 2, 5, 4, 7, 6, 3, 1],
[4, 3, 6, 8, 1, 9, 7, 2, 5],
[5, 7, 9, 4, 2, 1, 3, 6, 8],
[6, 1, 3, 9, 5, 8, 2, 7, 4]

Now the function keeps searching for an appropriate sixth row which it never finds, and it never backtracks, which would mean throwing away previously generated rows to get out of the dead end.


问:
How to fix .default.ref is not a function?
I have an issue uploading an image for firebase storage.

This is my firebase config file

```<code>import firebase from 'firebase/app';
import 'firebase/storage'
import 'firebase/database';
import 'firebase/auth';

var firebaseConfig = {
    apiKey: 'apiKey',
    authDomain: 'authDomain',
    databaseURL: 'databaseURL',
    projectId: 'projectId',
    storageBucket: 'storageBucket',
    messagingSenderId: 'messagingSenderId',
    appId: 'appId'
};

const fire = firebase.initializeApp(firebaseConfig);

const storage = firebase.storage();

export {
    storage ,fire as default
}
</code>```

I import it as storage in my Component and use it as

```<code>storage.ref('images/' + this.state.imageUrl.name).put(this.state.imageUrl).on(
    'state_changed',
    (snapshot) => {},
    (error) => {
        console.log(error);
    },
    () => {
        storage.ref('images').child(this.state.imageUrl.name).getDownloadURL().then((url) => {
            console.log(url);
        });
    }
)
</code>```

But whenever I click a button it throws me this error

'TypeError: _config_config__WEBPACK_IMPORTED_MODULE_10__.default.ref is not a function'

答:
when writing export {storage ,fire as default}, it means you are exporting storage as a named export and fire as a default export, its equivalent as the following code

```<code>export const storage = firebase.storage();
export default firebase.initializeApp(firebaseConfig);
</code>```

To solve your problem you need to fix the imports in your component

```<code>import {storage, default as fire} from 'config';
</code>```

or

```<code>import {storage} from 'config';
import fire from 'config';
</code>```

Body:
I have an issue uploading an image for firebase storage.

This is my firebase config file

import firebase from 'firebase/app';
import 'firebase/storage'
import 'firebase/database';
import 'firebase/auth';

var firebaseConfig = {
    apiKey: 'apiKey',
    authDomain: 'authDomain',
    databaseURL: 'databaseURL',
    projectId: 'projectId',
    storageBucket: 'storageBucket',
    messagingSenderId: 'messagingSenderId',
    appId: 'appId'
};

const fire = firebase.initializeApp(firebaseConfig);

const storage = firebase.storage();

export {
    storage ,fire as default
}

I import it as storage in my Component and use it as

storage.ref('images/' + this.state.imageUrl.name).put(this.state.imageUrl).on(
    'state_changed',
    (snapshot) => {},
    (error) => {
        console.log(error);
    },
    () => {
        storage.ref('images').child(this.state.imageUrl.name).getDownloadURL().then((url) => {
            console.log(url);
        });
    }
)

But whenever I click a button it throws me this error

'TypeError: _config_config__WEBPACK_IMPORTED_MODULE_10__.default.ref is not a function'

Body:
when writing export {storage ,fire as default}, it means you are exporting storage as a named export and fire as a default export, its equivalent as the following code

export const storage = firebase.storage();
export default firebase.initializeApp(firebaseConfig);

To solve your problem you need to fix the imports in your component

import {storage, default as fire} from 'config';

or

import {storage} from 'config';
import fire from 'config';


问:
Action when an element from collection get scrolled by
I have an unknown number of section blocks.
I use the titles of these automaticaly generated sections to populate the "tabs" container who follow the scroll (using sticky position).

What I need, is when I pass by one of the title contained in the sections, the same title from the "tabs" bar get the class "selected"so I indicate where the user is.

But what I've tried so far is only working partialy.
Here's a working example:

let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    $(document).on('mousewheel DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            if(winscrollpos >= v && winscrollpos < v+100) {
                $('.deco-tab-title').eq(i).add('.selected').toggleClass('selected');
            }
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}</code>```

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

```

as you can see, the first title lose the class if you scroll to the end. But nothing else. And when you go back, the second title get the class. And overall, it doesn't work so well.

答:
You might want to use the scroll event, which also captures using the scroll bar.

Scrolling height depends on the user agent. You should compare
[offset of current tab] < winscrollpos < offset[next tab] instead of [offset of current tab] < winscrollpos < offset[current tab] + 100.

Here's a working demo:

let titles = [];

$.each($('section>h3'), function () {
    titles.push($(this).offset().top);
});

$(document).on('scroll', function (e) {
    // 50 for the tab title height
    let winscrollpos = $(window).scrollTop() + 50;
    let titleElements = $('.deco-tab-title');
    $.each(titles, function (i, v) {
        if (winscrollpos >= v && (i === titles.length - 1 || winscrollpos < titles[i + 1])) {
            titleElements.eq(i).addClass('selected');
        } else {
            titleElements.eq(i).removeClass('selected');
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}</code>```

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

```

Body:
I have an unknown number of section blocks.
I use the titles of these automaticaly generated sections to populate the "tabs" container who follow the scroll (using sticky position).

What I need, is when I pass by one of the title contained in the sections, the same title from the "tabs" bar get the class "selected"so I indicate where the user is.

But what I've tried so far is only working partialy.
Here's a working example:

let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    $(document).on('mousewheel DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            if(winscrollpos >= v && winscrollpos < v+100) {
                $('.deco-tab-title').eq(i).add('.selected').toggleClass('selected');
            }
        });
    });

.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

as you can see, the first title lose the class if you scroll to the end. But nothing else. And when you go back, the second title get the class. And overall, it doesn't work so well.

Body:
You might want to use the scroll event, which also captures using the scroll bar.

Scrolling height depends on the user agent. You should compare
[offset of current tab] < winscrollpos < offset[next tab] instead of [offset of current tab] < winscrollpos < offset[current tab] + 100.

Here's a working demo:

let titles = [];

$.each($('section>h3'), function () {
    titles.push($(this).offset().top);
});

$(document).on('scroll', function (e) {
    // 50 for the tab title height
    let winscrollpos = $(window).scrollTop() + 50;
    let titleElements = $('.deco-tab-title');
    $.each(titles, function (i, v) {
        if (winscrollpos >= v && (i === titles.length - 1 || winscrollpos < titles[i + 1])) {
            titleElements.eq(i).addClass('selected');
        } else {
            titleElements.eq(i).removeClass('selected');
        }
    });
});

.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='main'>
    <div class='filler'>

    </div>
    <div class='wrapper'>
    <div class='tabs'><h3 class='deco-tab-title selected'>title1</h3><h3 class='deco-tab-title'>title2</h3><h3 class='deco-tab-title'>title3</h3><h3 class='deco-tab-title'>title4</h3></div>
    <div class='core'>
    <section>
        <h3 class='deco-tab-title'>title1</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
        <h3 class='deco-tab-title'>title2</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
        <h3 class='deco-tab-title'>title3</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
        <h3 class='deco-tab-title'>title4</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    </div>
    </div>
</div>


问:
Edit request data before validation

Request data:

```<code>    [
        "invoice_data" => [
            ...
            "discount" => null,
        ],
        "product_credit" => [
            ...
            "discount" => null,
        ]
    ];
</code>```

What I am trying to do

I am trying to create an if statement to check if the

$request -> invoice_data['discount'] == null then set it to 0 ALSO

$request -> product_credit['discount'] == null then set it to 0

Before the validation process because the validation will fail.

What I have tried:

I have found a method in Laravel called prepareForValidation() and it use $this -> merge([...]) which is what I am looking for but problem is that I cannot access the discount in invoice_data and product_credit.

答:
```<code><?php

$data =
[
        "invoice_data" => [
            "discount" => null,
        ],
        "product_credit" => [
            "discount" => null,
        ]
    ];

$keyWhitelist = [
    'invoice_data',
    'product_credit'
];

foreach ($data as $key => $entry) {

    if(!in_array($key, $keyWhitelist)) {
        continue;
    }

    if(key_exists('discount',$entry)) {
        if ($entry['discount'] === null) {
            $data[$key]['discount'] = 0;
        }
    }
}

var_export($data);
</code>```

gives result:

```<code>array (
  'invoice_data' =>
  array (
    'discount' => 0,
  ),
  'product_credit' =>
  array (
    'discount' => 0,
  ),
)
</code>```

Title: Edit request data before validation

Body:
Request data:

    [
        "invoice_data" => [
            ...
            "discount" => null,
        ],
        "product_credit" => [
            ...
            "discount" => null,
        ]
    ];

What I am trying to do

I am trying to create an if statement to check if the

$request -> invoice_data['discount'] == null then set it to 0 ALSO

$request -> product_credit['discount'] == null then set it to 0

Before the validation process because the validation will fail.

What I have tried:

I have found a method in Laravel called prepareForValidation() and it use $this -> merge([...]) which is what I am looking for but problem is that I cannot access the discount in invoice_data and product_credit.

Body:
<?php

$data =
[
        "invoice_data" => [
            "discount" => null,
        ],
        "product_credit" => [
            "discount" => null,
        ]
    ];

$keyWhitelist = [
    'invoice_data',
    'product_credit'
];

foreach ($data as $key => $entry) {

    if(!in_array($key, $keyWhitelist)) {
        continue;
    }

    if(key_exists('discount',$entry)) {
        if ($entry['discount'] === null) {
            $data[$key]['discount'] = 0;
        }
    }
}

var_export($data);

gives result:

array (
  'invoice_data' =>
  array (
    'discount' => 0,
  ),
  'product_credit' =>
  array (
    'discount' => 0,
  ),
)


问:
Getting error while converting to PDF using HiQPdf in MVC
I am trying to use HiQPdf for converting my html code to PDF. but i am getting below error. Even though "HiQPdf.dep" and "HiQPdf.dll" are same location.

An exception of type 'System.Exception' occurred in HiQPdf.dll but was not handled in user code
Additional information: Error 0xD8. Check the HiQPdf.dep resource file can be found near the HiQPdf.dll assembly and the user has read and execute permissions for this file. Call SetDepFilePath() method if you placed the HiQPdf.dep in a different location

Below is the method:

```<code> // get the HTML code of this view
        string htmlToConvert = RenderViewAsString("GetHTMLView", null);

        // the base URL to resolve relative images and css
        String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
        String baseUrl =  thisPageUrl.Substring(0, thisPageUrl.Length - "tblWSRDetails/ConvertWSRReportToPdf".Length);

        // instantiate the HiQPdf HTML to PDF converter
        HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

        // hide the button in the created PDF
        htmlToPdfConverter.HiddenHtmlElements = new string[] { "#ConvertReportToPdf" };

       // render the HTML code as PDF in memory
        byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

        // send the PDF file to browser
        FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
        fileResult.FileDownloadName = "WSR.pdf";

        return fileResult;
</code>```

Please help on the issue.

Regards,
Anand

答: I solved this error granting write permission in App_Data, Bin and Content (where I save the pdf file) folders in my host provider.</p>

Body:
I am trying to use HiQPdf for converting my html code to PDF. but i am getting below error. Even though "HiQPdf.dep" and "HiQPdf.dll" are same location.

An exception of type 'System.Exception' occurred in HiQPdf.dll but was not handled in user code
Additional information: Error 0xD8. Check the HiQPdf.dep resource file can be found near the HiQPdf.dll assembly and the user has read and execute permissions for this file. Call SetDepFilePath() method if you placed the HiQPdf.dep in a different location

Below is the method:

 // get the HTML code of this view
        string htmlToConvert = RenderViewAsString("GetHTMLView", null);

        // the base URL to resolve relative images and css
        String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
        String baseUrl =  thisPageUrl.Substring(0, thisPageUrl.Length - "tblWSRDetails/ConvertWSRReportToPdf".Length);

        // instantiate the HiQPdf HTML to PDF converter
        HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

        // hide the button in the created PDF
        htmlToPdfConverter.HiddenHtmlElements = new string[] { "#ConvertReportToPdf" };

       // render the HTML code as PDF in memory
        byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

        // send the PDF file to browser
        FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
        fileResult.FileDownloadName = "WSR.pdf";

        return fileResult;

Please help on the issue.

Regards,
Anand


问:
How to cycling Arrays to display all the data of all the rows of a table?
I created an HTML page where the user is asked to fill a search form and click on the button "Search" in order to display results.

When the "Search" button is clicked, if the form field is not empty some data will be displayed after 2 seconds (I used the Javascript setTimeout() method to achieve that).

The data to display consist of several names, surnames, and addresses, and they do correspond to the three  of the three
 of the table named "Name", "Surname" and "Address".

In the js file, I created a new variable called myArray:

```<code>var myArray = [
  //first row
    [
      ["Mary", "Otto", "1204 Stoney Ridge"],
      ["Paula", "Red", "445 Mount Eden Road"],
      ["Jack", "Twist", "21 Greens Road RD 2"]
    ],

  //second row
    [
      ["Oliver", "Howick", "32 Wilson Street"],
      ["Jean", "Bros", "address 5"],
      ["Antoine", "Lavoisier", "address 6"]
    ],
  //third row
    [
      ["Benny", "Fair", "address 7"],
      ["Corinne", "Robespierre", "address 8"],
      ["Michael", "Mury", "address 9"]
    ]
  ];
</code>```

I want to cycle myArray in order to display all the series of "name, surname, address" without having to type them all. I'm trying to use the Javascript for loop method in order to do so:

```<code>    function validateNome(){
  console.log('function validateNome has been activated');
  if ($("#inlineFormInputNome").val()=="") {
      $("#errorLog").show();
  } else {
    $("#errorLog").hide();
    $("#cercaNome").prop("disabled", true);
    $("#tbody").empty();
    setTimeout(function (){
      //ID alert bootstrap
      //$("#tbody").empty().append('<tr><th scope="row">1</th><td>Maria</td><td>Ottone</td><td>Viale della Resistenza 1, 53100 Siena (SI)</td></tr>');
      // aggiungi un'array e mostra i dati dell'array

      var myArray = [
      //first row
        [
          ["Mary", "Otto", "1204 Stoney Ridge"],
          ["Paula", "Red", "445 Mount Eden Road"],
          ["Jack", "Twist", "21 Greens Road RD 2"]
        ],

      //second row
        [
          ["Oliver", "Howick", "32 Wilson Street"],
          ["Jean", "Bros", "address 5"],
          ["Antoine", "Lavoisier", "Via Flogisto 1"]
        ],
      //third row
        [
          ["Benny", "Fair", "address 7"],
          ["Corinne", "Robespierre", "address 8"],
          ["Michael", "Mury", "address 9"]
        ]
      ];

        for(var i=0; i<myArray.length; i++) {
          $("#tbody").append  ('<tr><th scope="row"> </th><td> myArray [0][0][0]</td> <td>myArray [0][0][1]</td><td> myArray [0][0][2] </td></tr>');
      }
      $("#tabella").show();
      $("#cercaNome").prop("disabled", false);
    } , 2000);
  }
}
</code>```

In other terms, what I did  is substituting the following line:

$("#tbody").append('
1	Mary	Otto	1204 Stoney Ridge
');

with the for loop function below:

```<code>for(var i=0; i<myArray.length; i++) {

      $("#tbody").append  (

    '<tr><th scope="row"> </th><td> myArray [0][0][0]</td> <td>myArray [0][0][1]</td><td> myArray [0][0][2] </td></tr>') ;
  }
</code>```

where myArray[0][0][0] do correspond to "Mary" , myArray[0][0][1] do correspond to "Otto" and myArray[0][0][2] do correspond to "1204 Stoney Ridge".

How to cycling Arrays to display all the 27 data  of the three different rows
 of a table when a button is being clicked?

答:
At the moment you're iterating over myArray using the local variable i. You need to use it to reference a row from your array.

```<code>myArray[i][0]
</code>```

Each row holds three additional arrays

```<code>myArray[i][0] myArray[i][1] myArray[i][2]
</code>```

These can be accessed using another nested for loop like

```<code>for (var i = 0; i < myArray.length; i++) {
  for (var j = 0; j < myArray[0][0].length; j++) {
    console.log(myArray[i][j]);
  }
}
</code>```

To ultimately construct a valid tr element you need to access myArray's elements. At the moment you put it directly inside the string as part of the string.
e.g. the correct way myString="the value "+myArray[0]+" the rest of my string"

```<code>for (var i = 0; i < myArray.length; i++) {
  for (var j = 0; j < myArray[0][0].length; j++) {
    $("#tbody").append("<tr><th scope='row'> </th><td>" + myArray[i][i][0] + "</td> <td>" + myArray[i][j][1] + "</td><td>" + myArray[i][i][2] + "</td></tr>");
  }
}
</code>```

Body:
I created an HTML page where the user is asked to fill a search form and click on the button "Search" in order to display results.

When the "Search" button is clicked, if the form field is not empty some data will be displayed after 2 seconds (I used the Javascript setTimeout() method to achieve that).

The data to display consist of several names, surnames, and addresses, and they do correspond to the three  of the three
 of the table named "Name", "Surname" and "Address".

In the js file, I created a new variable called myArray:

var myArray = [
  //first row
    [
      ["Mary", "Otto", "1204 Stoney Ridge"],
      ["Paula", "Red", "445 Mount Eden Road"],
      ["Jack", "Twist", "21 Greens Road RD 2"]
    ],

  //second row
    [
      ["Oliver", "Howick", "32 Wilson Street"],
      ["Jean", "Bros", "address 5"],
      ["Antoine", "Lavoisier", "address 6"]
    ],
  //third row
    [
      ["Benny", "Fair", "address 7"],
      ["Corinne", "Robespierre", "address 8"],
      ["Michael", "Mury", "address 9"]
    ]
  ];

I want to cycle myArray in order to display all the series of "name, surname, address" without having to type them all. I'm trying to use the Javascript for loop method in order to do so:

    function validateNome(){
  console.log('function validateNome has been activated');
  if ($("#inlineFormInputNome").val()=="") {
      $("#errorLog").show();
  } else {
    $("#errorLog").hide();
    $("#cercaNome").prop("disabled", true);
    $("#tbody").empty();
    setTimeout(function (){
      //ID alert bootstrap
      //$("#tbody").empty().append('
1	Maria	Ottone	Viale della Resistenza 1, 53100 Siena (SI)
');
      // aggiungi un'array e mostra i dati dell'array

      var myArray = [
      //first row
        [
          ["Mary", "Otto", "1204 Stoney Ridge"],
          ["Paula", "Red", "445 Mount Eden Road"],
          ["Jack", "Twist", "21 Greens Road RD 2"]
        ],

      //second row
        [
          ["Oliver", "Howick", "32 Wilson Street"],
          ["Jean", "Bros", "address 5"],
          ["Antoine", "Lavoisier", "Via Flogisto 1"]
        ],
      //third row
        [
          ["Benny", "Fair", "address 7"],
          ["Corinne", "Robespierre", "address 8"],
          ["Michael", "Mury", "address 9"]
        ]
      ];

        for(var i=0; i<myArray.length; i++) {
          $("#tbody").append  ('
 	 myArray [0][0][0]	 myArray [0][0][1]	 myArray [0][0][2]
');
      }
      $("#tabella").show();
      $("#cercaNome").prop("disabled", false);
    } , 2000);
  }
}

In other terms, what I did  is substituting the following line:

$("#tbody").append('
1	Mary	Otto	1204 Stoney Ridge
');

with the for loop function below:

for(var i=0; i<myArray.length; i++) {

      $("#tbody").append  (

    '
 	 myArray [0][0][0]	 myArray [0][0][1]	 myArray [0][0][2]
') ;
  }

where myArray[0][0][0] do correspond to "Mary" , myArray[0][0][1] do correspond to "Otto" and myArray[0][0][2] do correspond to "1204 Stoney Ridge".

How to cycling Arrays to display all the 27 data  of the three different rows
 of a table when a button is being clicked?

Body:
At the moment you're iterating over myArray using the local variable i. You need to use it to reference a row from your array.

myArray[i][0]

Each row holds three additional arrays

myArray[i][0] myArray[i][1] myArray[i][2]

These can be accessed using another nested for loop like

for (var i = 0; i < myArray.length; i++) {
  for (var j = 0; j < myArray[0][0].length; j++) {
    console.log(myArray[i][j]);
  }
}

To ultimately construct a valid tr element you need to access myArray's elements. At the moment you put it directly inside the string as part of the string.
e.g. the correct way myString="the value "+myArray[0]+" the rest of my string"

for (var i = 0; i < myArray.length; i++) {
  for (var j = 0; j < myArray[0][0].length; j++) {
    $("#tbody").append("<tr><th scope='row'> </th><td>" + myArray[i][i][0] + "</td> <td>" + myArray[i][j][1] + "</td><td>" + myArray[i][i][2] + "</td></tr>");
  }
}


问:
Unclassifiable statement error of Logical Type - Fortran
```<code>program test
logical :: check
check = 2 < 3 < 5
print *, check
end program test
</code>```

When trying to compile, it will give this error:

Error(s): source_file.f:5:0:

check = 2 < 3 < 5  1 Error: Unclassifiable statement at (1)

where is the problem?

you can test it online here: https://rextester.com/l/fortran_online_compiler

答:
If you want to check that 2 is less then 3 and 3 is less then 5 then you really need two comparisons and one Boolean operator</p>

```<code>check = (2 < 3) .and. (3 < 5)
</code>```

Body:
program test
logical :: check
check = 2 < 3 < 5
print *, check
end program test

When trying to compile, it will give this error:

Error(s): source_file.f:5:0:

check = 2 < 3 < 5  1 Error: Unclassifiable statement at (1)

where is the problem?

you can test it online here: https://rextester.com/l/fortran_online_compiler

Body:
If you want to check that 2 is less then 3 and 3 is less then 5 then you really need two comparisons and one Boolean operator

check = (2 < 3) .and. (3 < 5)


问:
How to get only the unique values out of a list of strings in C#?
Is there an easy way to get only the unique values out of a list of strings in C#?  My google-fu is failing me today.

(I know I can put them in another structure and pull them out again.  I'm looking for stupidly-easy, like Ruby's .uniq method.  C# has bloody well everything else, so I'm probably just using the wrong synonym.)

Specifically, this is coming from Linq, so if Linq had a built-in way to select only unique strings, that would be even cooler.

答:
```<code>List<string> strings = new string[] { "Hello", "Hello", "World" }.ToList();

strings = strings.Distinct().ToList();
</code>```

OwnerDisplayName: Ken

OwnerDisplayName: CQ

ContentLicense: CC BY-SA 2.5


问:
swift function returning nil (returning too early)
I had some code within a ViewDidLoad function that would set a class variable in the end of its' call stack. I have tried to refactor that code to become a separate function that would return the value instead of setting the class variable.

Due to my lack of swift knowledge, I am not sure what is wrong, it seems like my function returns too earl, as I can tell in the debugger that it jumps to return, before shareURL is set to publicUrl.absoluteString.

```<code>func getShareUrl() -> String? {
    var shareURL: String?
    if let extItem = extensionContext?.inputItems.first as? NSExtensionItem,
      let itemProvider = extItem.attachments?.first as? NSItemProvider,
      itemProvider.hasItemConformingToTypeIdentifier("public.url") {
      itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
        if let publicUrl = url as? URL {
          shareURL = publicUrl.absoluteString
        }
      }
    }
    return shareURL
  }
</code>```

I can also see in the debugger that the inner function is called later after the main function have returned.

How do I wait for the inner call to finish before returning? Or what is the correct swift approach.

答:
You need a completion as the method itemProvider.loadItem(forTypeIdentifier is asynchronous

```<code>func getShareUrl(completion:@escaping (String?) -> ()) {
    if let extItem = extensionContext?.inputItems.first as? NSExtensionItem,
        let itemProvider = extItem.attachments?.first as? NSItemProvider,
        itemProvider.hasItemConformingToTypeIdentifier("public.url") {
        itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
            if let publicUrl = url as? URL {
                completion(publicUrl.absoluteString)
            } else {
                completion(nil)
            }
        }
    }
}
</code>```

Body:
I had some code within a ViewDidLoad function that would set a class variable in the end of its' call stack. I have tried to refactor that code to become a separate function that would return the value instead of setting the class variable.

Due to my lack of swift knowledge, I am not sure what is wrong, it seems like my function returns too earl, as I can tell in the debugger that it jumps to return, before shareURL is set to publicUrl.absoluteString.

func getShareUrl() -> String? {
    var shareURL: String?
    if let extItem = extensionContext?.inputItems.first as? NSExtensionItem,
      let itemProvider = extItem.attachments?.first as? NSItemProvider,
      itemProvider.hasItemConformingToTypeIdentifier("public.url") {
      itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
        if let publicUrl = url as? URL {
          shareURL = publicUrl.absoluteString
        }
      }
    }
    return shareURL
  }

I can also see in the debugger that the inner function is called later after the main function have returned.

How do I wait for the inner call to finish before returning? Or what is the correct swift approach.

Body:
You need a completion as the method itemProvider.loadItem(forTypeIdentifier is asynchronous

func getShareUrl(completion:@escaping (String?) -> ()) {
    if let extItem = extensionContext?.inputItems.first as? NSExtensionItem,
        let itemProvider = extItem.attachments?.first as? NSItemProvider,
        itemProvider.hasItemConformingToTypeIdentifier("public.url") {
        itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
            if let publicUrl = url as? URL {
                completion(publicUrl.absoluteString)
            } else {
                completion(nil)
            }
        }
    }
}


答:
Variable return types do not exist in C.

You could do this:

```<code>Order algorithm(int a, int b, int *ok) {
  if(a == b)
     *ok = 0;
  else
     *ok = 1;
   return ord;    //Returns the Order ord
}
</code>```

or simpler:

```<code>Order algorithm(int a, int b, int *ok) {
  *ok = (a != b)
  return ord;    //Returns the Order ord
}
</code>```

and call it like this:

```<code>int ok;
someorder = algorithm(v1, v2, &ok);
if (ok)
  ... handle OK case
else
  ... handle not OK case
</code>```

or you could return a pointer to the order if it's OK and return NULL if it's not OK:

```<code>Order *algorithm(int a, int b) {
  if(a == b)
     return NULL;
  else
     return ⩝    //Returns the Order ord
}
</code>```

and call it like this:

```<code>Order *someorder;
...
someorder = algorithm(v1, v2);
if (someorder != NULL)
  ... handle OK case
else
  ... handle not OK case
</code>```

There are many possibilities to achieve this. See also the other answers.

Title: How can I return a struct if a condition is true and an int if the condition is false

Body:
First a simple example:

typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

Body:
Variable return types do not exist in C.

You could do this:

Order algorithm(int a, int b, int *ok) {
  if(a == b)
     *ok = 0;
  else
     *ok = 1;
   return ord;    //Returns the Order ord
}

or simpler:

Order algorithm(int a, int b, int *ok) {
  *ok = (a != b)
  return ord;    //Returns the Order ord
}

and call it like this:

int ok;
someorder = algorithm(v1, v2, &ok);
if (ok)
  ... handle OK case
else
  ... handle not OK case

or you could return a pointer to the order if it's OK and return NULL if it's not OK:

Order *algorithm(int a, int b) {
  if(a == b)
     return NULL;
  else
     return &ord;    //Returns the Order ord
}

and call it like this:

Order *someorder;
...
someorder = algorithm(v1, v2);
if (someorder != NULL)
  ... handle OK case
else
  ... handle not OK case

There are many possibilities to achieve this. See also the other answers.


问:
unable to import the module in react App getting : unexpected token import
Okay, I am pretty new to the react-node-express trio. But I will try my best to explain the issue. I have a library(module/library) that was made in by someone. I am trying to import some function from that module in to my react app as -

```<code>import {some_module} from 'some_library';
</code>```

Now, that module is a standalone project that exports this function, there in that project they have - import reference to some local file to which my import gives an error while loading that :

```<code>import * as Util from './util.js';
SyntaxError: Unexpected token import
</code>```

my package.json have following dependencies:

```<code>"dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.4.4",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/runtime": "^7.4.3",
    "@bbmx/utilities": "^1.4.0",
    "axios": "^0.18.0",
    "babel-preset-stage-0": "^6.24.1",
    "config": "^3.1.0",
    "cookie-parser": "^1.4.4",
    "express": "^4.16.3",
    "grunt": "^1.0.1",
    "grunt-artifactory-artifact": "^1.0.1",
    "grunt-contrib-copy": "^1.0.0",
    "load-grunt-tasks": "4.0.0",
    "lodash": "^4.17.11",
    "node-fetch": "^2.6.0",
    "react": "^16.8.6",
    "react-dom": "^16.5.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^5.0.0",
    "redux": "^3.7.2",
    "redux-thunk": "^2.3.0",
  },
  "devDependencies": {
    "@babel/cli": "^7.1.2",
    "@babel/core": "^7.1.2",
    "@babel/node": "^7.2.2",
    "@babel/plugin-proposal-object-rest-spread": "^7.4.4",
    "@babel/plugin-transform-runtime": "^7.4.3",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/register": "^7.4.4",
    "babel-loader": "^8.0.4",
    "babel-plugin-dynamic-import-node": "^2.2.0",
    "babel-polyfill": "^6.26.0",
    "css-loader": "^2.1.1",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.12.1",
    "enzyme-to-json": "^3.3.5",
    "file-loader": "^3.0.1",
    "jest": "^24.7.1",
    "less": "^3.9.0",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.6.0",
    "nodemon": "^1.18.11",
    "postcss-loader": "^3.0.0",
    "pre-commit": "^1.2.2",
    "script-loader": "0.7.2",
    "style-loader": "^0.23.1",
    "stylelint": "^10.0.1",
    "stylelint-config-standard": "^18.3.0",
    "webpack": "^4.31.0",
    "webpack-cli": "^3.1.2",
    "webpack-config-utils": "^2.3.1",
    "webpack-dev-middleware": "^3.6.2",
    "webpack-hot-middleware": "^2.24.3",
    "webpack-node-externals": "^1.7.2"
  }
</code>```

and have the .babelrc file with following config.

```<code>{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": ["@babel/plugin-transform-runtime","@babel/plugin-proposal-class-properties","@babel/plugin-syntax-dynamic-import"]
}
</code>```

with web-pack.config as :

```<code>const path = require('path');
const webpack = require('webpack');
const { getIfUtils } = require('webpack-config-utils');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { ifProduction } = getIfUtils(process.env.NODE_ENV || 'development');
const mode = process.env.NODE_ENV || 'development';
const pkg = require('./package.json');

module.exports = [
    {
        name: 'client',
        entry: {
            client: ['./client', 'webpack-hot-middleware/client'],
            bundle: './client/bundle.js'
        },
        output: {
            path: path.resolve(__dirname, `dist/client/${pkg.version}`),
            filename: '[name].js',
            publicPath: `/${pkg.version}`
        },
        devtool: ifProduction('nosources-source-map', 'source-map'),
        resolve: {
            modules: [path.resolve('./client'), path.resolve('./node_modules')]
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader'
                },
                {
                    test: /fp-clientlib-v3.js/,
                    use: ['script-loader']
                },
                {
                    test: /\.less$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        'css-loader',
                        'less-loader'
                    ]
                },
                {
                    test: /\.(ttf|eot|svg|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                    loader: 'file-loader?name=fonts/[name].[ext]'
                },
                {
                    test: /\.png/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/png&name=images/[name].[ext]'
                },
                {
                    test: /\.jpg/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/jpeg&name=images/[name].[ext]'
                },
                {
                    test: /\.gif/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/gif&name=images/[name].[ext]'
                },
                {
                    test: /\.ico/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/ico&name=images/[name].[ext]'
                }
            ]
        },
        mode,
        plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new MiniCssExtractPlugin()
        ]
    }
</code>```

Can someone help me out as why this might be happening?

答:
Node JS currently doesn't support ES6 imports. Enable ES6 imports in node js provides a solution to this issue. I have tired this and it worked for me.
Run the command:

```<code>npm install babel-register babel-preset-env --save-dev
</code>```

Now you need to create a new file(config.js) and add the following code to it.

```<code>require('babel-register')({
    presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
</code>```

Now you can write import statements without getting any errors.

Hope this helps.

You need to run the new file which you created with above code. In my case it was config.js. So i have to run:

```<code>node config.js
</code>```

OR

I found one easy solution to this issue.

Create .babelrc file in the root of your project.

Add following(and any other babel presets you need, can be added in this file):

```<code>{
    "presets": ["env"]
}
</code>```

Install babel-preset-env using command npm install babel-preset-env --save, and then install babel-cli using command npm install babel-cli -g --save

Now, go to the folder where your server or index file exists and run using: babel-node fileName.js

Or you can run using npm start by adding following code to your package.json file:

```<code>"scripts": {
    "start": "babel-node src/index.js"
}
</code>```

Body:
Okay, I am pretty new to the react-node-express trio. But I will try my best to explain the issue. I have a library(module/library) that was made in by someone. I am trying to import some function from that module in to my react app as -

import {some_module} from 'some_library';

Now, that module is a standalone project that exports this function, there in that project they have - import reference to some local file to which my import gives an error while loading that :

import * as Util from './util.js';
SyntaxError: Unexpected token import

my package.json have following dependencies:

"dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.4.4",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/runtime": "^7.4.3",
    "@bbmx/utilities": "^1.4.0",
    "axios": "^0.18.0",
    "babel-preset-stage-0": "^6.24.1",
    "config": "^3.1.0",
    "cookie-parser": "^1.4.4",
    "express": "^4.16.3",
    "grunt": "^1.0.1",
    "grunt-artifactory-artifact": "^1.0.1",
    "grunt-contrib-copy": "^1.0.0",
    "load-grunt-tasks": "4.0.0",
    "lodash": "^4.17.11",
    "node-fetch": "^2.6.0",
    "react": "^16.8.6",
    "react-dom": "^16.5.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^5.0.0",
    "redux": "^3.7.2",
    "redux-thunk": "^2.3.0",
  },
  "devDependencies": {
    "@babel/cli": "^7.1.2",
    "@babel/core": "^7.1.2",
    "@babel/node": "^7.2.2",
    "@babel/plugin-proposal-object-rest-spread": "^7.4.4",
    "@babel/plugin-transform-runtime": "^7.4.3",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/register": "^7.4.4",
    "babel-loader": "^8.0.4",
    "babel-plugin-dynamic-import-node": "^2.2.0",
    "babel-polyfill": "^6.26.0",
    "css-loader": "^2.1.1",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.12.1",
    "enzyme-to-json": "^3.3.5",
    "file-loader": "^3.0.1",
    "jest": "^24.7.1",
    "less": "^3.9.0",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.6.0",
    "nodemon": "^1.18.11",
    "postcss-loader": "^3.0.0",
    "pre-commit": "^1.2.2",
    "script-loader": "0.7.2",
    "style-loader": "^0.23.1",
    "stylelint": "^10.0.1",
    "stylelint-config-standard": "^18.3.0",
    "webpack": "^4.31.0",
    "webpack-cli": "^3.1.2",
    "webpack-config-utils": "^2.3.1",
    "webpack-dev-middleware": "^3.6.2",
    "webpack-hot-middleware": "^2.24.3",
    "webpack-node-externals": "^1.7.2"
  }

and have the .babelrc file with following config.

{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": ["@babel/plugin-transform-runtime","@babel/plugin-proposal-class-properties","@babel/plugin-syntax-dynamic-import"]
}

with web-pack.config as :

const path = require('path');
const webpack = require('webpack');
const { getIfUtils } = require('webpack-config-utils');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { ifProduction } = getIfUtils(process.env.NODE_ENV || 'development');
const mode = process.env.NODE_ENV || 'development';
const pkg = require('./package.json');

module.exports = [
    {
        name: 'client',
        entry: {
            client: ['./client', 'webpack-hot-middleware/client'],
            bundle: './client/bundle.js'
        },
        output: {
            path: path.resolve(__dirname, `dist/client/${pkg.version}`),
            filename: '[name].js',
            publicPath: `/${pkg.version}`
        },
        devtool: ifProduction('nosources-source-map', 'source-map'),
        resolve: {
            modules: [path.resolve('./client'), path.resolve('./node_modules')]
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader'
                },
                {
                    test: /fp-clientlib-v3.js/,
                    use: ['script-loader']
                },
                {
                    test: /\.less$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        'css-loader',
                        'less-loader'
                    ]
                },
                {
                    test: /\.(ttf|eot|svg|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                    loader: 'file-loader?name=fonts/[name].[ext]'
                },
                {
                    test: /\.png/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/png&name=images/[name].[ext]'
                },
                {
                    test: /\.jpg/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/jpeg&name=images/[name].[ext]'
                },
                {
                    test: /\.gif/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/gif&name=images/[name].[ext]'
                },
                {
                    test: /\.ico/,
                    loader:
                        'file-loader?limit=150000&mimetype=image/ico&name=images/[name].[ext]'
                }
            ]
        },
        mode,
        plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new MiniCssExtractPlugin()
        ]
    }

Can someone help me out as why this might be happening?

Body:
Node JS currently doesn't support ES6 imports. Enable ES6 imports in node js provides a solution to this issue. I have tired this and it worked for me.
Run the command:

npm install babel-register babel-preset-env --save-dev

Now you need to create a new file(config.js) and add the following code to it.

require('babel-register')({
    presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')

Now you can write import statements without getting any errors.

Hope this helps.

You need to run the new file which you created with above code. In my case it was config.js. So i have to run:

node config.js

OR

I found one easy solution to this issue.

Create .babelrc file in the root of your project.

Add following(and any other babel presets you need, can be added in this file):

{
    "presets": ["env"]
}

Install babel-preset-env using command npm install babel-preset-env --save, and then install babel-cli using command npm install babel-cli -g --save

Now, go to the folder where your server or index file exists and run using: babel-node fileName.js

Or you can run using npm start by adding following code to your package.json file:

"scripts": {
    "start": "babel-node src/index.js"
}