问:
Gatsby Build fails on Netlify by works locally. Ffmpeg dependency issue
I'm trying to deploy my site on Netlify, and the gatsby build command works perfectly fine on my system. But when I run in on Netlify, I run into the issue shown below.

Unhandled rejection: cannot find ffprobe seems to be the issue. I think it's because I have ffmpeg installed on my system (macOS) but there is no installation procedure during the build process in Netlify. Can somebody please guide me as to what I can do to fix this?

```<code>1:19:18 AM: info bootstrap finished - 5.299 s
1:19:18 AM:
1:19:22 AM: error UNHANDLED REJECTION Cannot find ffprobe
1:19:23 AM:
1:19:23 AM:   Error: Cannot find ffprobe
1:19:23 AM:
1:19:23 AM:   - ffprobe.js:145
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/ffprobe.js:145:31
1:19:23 AM:
1:19:23 AM:   - capabilities.js:194
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:194:9
1:19:23 AM:
1:19:23 AM:   - async.js:52
1:19:23 AM:     [repo]/[async]/lib/async.js:52:16
1:19:23 AM:
1:19:23 AM:   - async.js:1209
1:19:23 AM:     [repo]/[async]/lib/async.js:1209:30
1:19:23 AM:
1:19:23 AM:   - capabilities.js:186
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:186:13
1:19:23 AM:
1:19:23 AM:   - capabilities.js:123
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:123:9
1:19:23 AM:
1:19:23 AM:   - async.js:52
1:19:23 AM:     [repo]/[async]/lib/async.js:52:16
1:19:23 AM:
1:19:23 AM:   - async.js:1209
1:19:23 AM:     [repo]/[async]/lib/async.js:1209:30
1:19:23 AM:
1:19:23 AM:   - capabilities.js:116
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:116:11
1:19:23 AM:
1:19:23 AM:   - utils.js:223
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/utils.js:223:16
1:19:23 AM:
1:19:23 AM:   - which.js:68 F
1:19:23 AM:     [repo]/[which]/which.js:68:16
1:19:23 AM:
1:19:23 AM:   - which.js:80 E
1:19:23 AM:     [repo]/[which]/which.js:80:29
1:19:23 AM:
1:19:23 AM:   - which.js:89
1:19:23 AM:     [repo]/[which]/which.js:89:16
1:19:23 AM:
1:19:23 AM:   - index.js:42
1:19:23 AM:     [repo]/[isexe]/index.js:42:5
1:19:23 AM:
1:19:23 AM:   - mode.js:8
1:19:23 AM:     [repo]/[isexe]/mode.js:8:5
1:19:23 AM:
1:19:23 AM:
1:19:23 AM: not finished run queries - 4.168s
1:19:23 AM: not finished Generating image thumbnails - 4.111s
1:19:23 AM: (sharp:1520): GLib-CRITICAL **: 16:19:23.397: g_hash_table_lookup: assertion 'hash_table != NULL' failed
1:19:23 AM: (sharp:1520): GLib-CRITICAL **: 16:19:23.438: g_hash_table_lookup: assertion 'hash_table != NULL' failed
1:19:23 AM: Skipping functions preparation step: no functions directory set
1:19:23 AM: Caching artifacts
1:19:23 AM: Started saving node modules
1:19:23 AM: Finished saving node modules
1:19:23 AM: Started saving pip cache
1:19:23 AM: Finished saving pip cache
1:19:23 AM: Started saving emacs cask dependencies
1:19:23 AM: Finished saving emacs cask dependencies
1:19:23 AM: Started saving maven dependencies
1:19:23 AM: Finished saving maven dependencies
1:19:23 AM: Started saving boot dependencies
1:19:23 AM: Finished saving boot dependencies
1:19:23 AM: Started saving go dependencies
1:19:23 AM: Finished saving go dependencies
1:19:27 AM: Error running command: Build script returned non-zero exit code: 1
1:19:27 AM: Failing build: Failed to build site
1:19:27 AM: failed during stage 'building site': Build script returned non-zero exit code: 1
1:19:27 AM: Finished processing build request in 1m15.231125909s
</code>```

My gatsby-config.js file is as follows:

```<code>module.exports = {
  siteMetadata: {
    title: "#######",
    author: "#######"
  },
  plugins: [
    "gatsby-plugin-sass",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images`
      }
    },
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    "gatsby-transformer-ffmpeg",
    "gatsby-plugin-ffmpeg"
  ]
}

</code>```

答:
Netlify's build image runs Ubuntu, so you can probably install ffmpeg with the following command:

apt-get install ffmpeg
```

<p>You can prepend this script to your Netlify build command, i.e</p>

```apt-get install ffmpeg && npm run build
```

or stick it as a new script in your package.json.

Instruction on building latest version of ffmpeg on Ubuntu: https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu

Body:
I'm trying to deploy my site on Netlify, and the gatsby build command works perfectly fine on my system. But when I run in on Netlify, I run into the issue shown below.

Unhandled rejection: cannot find ffprobe seems to be the issue. I think it's because I have ffmpeg installed on my system (macOS) but there is no installation procedure during the build process in Netlify. Can somebody please guide me as to what I can do to fix this?

1:19:18 AM: info bootstrap finished - 5.299 s
1:19:18 AM:
1:19:22 AM: error UNHANDLED REJECTION Cannot find ffprobe
1:19:23 AM:
1:19:23 AM:   Error: Cannot find ffprobe
1:19:23 AM:
1:19:23 AM:   - ffprobe.js:145
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/ffprobe.js:145:31
1:19:23 AM:
1:19:23 AM:   - capabilities.js:194
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:194:9
1:19:23 AM:
1:19:23 AM:   - async.js:52
1:19:23 AM:     [repo]/[async]/lib/async.js:52:16
1:19:23 AM:
1:19:23 AM:   - async.js:1209
1:19:23 AM:     [repo]/[async]/lib/async.js:1209:30
1:19:23 AM:
1:19:23 AM:   - capabilities.js:186
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:186:13
1:19:23 AM:
1:19:23 AM:   - capabilities.js:123
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:123:9
1:19:23 AM:
1:19:23 AM:   - async.js:52
1:19:23 AM:     [repo]/[async]/lib/async.js:52:16
1:19:23 AM:
1:19:23 AM:   - async.js:1209
1:19:23 AM:     [repo]/[async]/lib/async.js:1209:30
1:19:23 AM:
1:19:23 AM:   - capabilities.js:116
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/capabilities.js:116:11
1:19:23 AM:
1:19:23 AM:   - utils.js:223
1:19:23 AM:     [repo]/[fluent-ffmpeg]/lib/utils.js:223:16
1:19:23 AM:
1:19:23 AM:   - which.js:68 F
1:19:23 AM:     [repo]/[which]/which.js:68:16
1:19:23 AM:
1:19:23 AM:   - which.js:80 E
1:19:23 AM:     [repo]/[which]/which.js:80:29
1:19:23 AM:
1:19:23 AM:   - which.js:89
1:19:23 AM:     [repo]/[which]/which.js:89:16
1:19:23 AM:
1:19:23 AM:   - index.js:42
1:19:23 AM:     [repo]/[isexe]/index.js:42:5
1:19:23 AM:
1:19:23 AM:   - mode.js:8
1:19:23 AM:     [repo]/[isexe]/mode.js:8:5
1:19:23 AM:
1:19:23 AM:
1:19:23 AM: not finished run queries - 4.168s
1:19:23 AM: not finished Generating image thumbnails - 4.111s
1:19:23 AM: (sharp:1520): GLib-CRITICAL **: 16:19:23.397: g_hash_table_lookup: assertion 'hash_table != NULL' failed
1:19:23 AM: (sharp:1520): GLib-CRITICAL **: 16:19:23.438: g_hash_table_lookup: assertion 'hash_table != NULL' failed
1:19:23 AM: Skipping functions preparation step: no functions directory set
1:19:23 AM: Caching artifacts
1:19:23 AM: Started saving node modules
1:19:23 AM: Finished saving node modules
1:19:23 AM: Started saving pip cache
1:19:23 AM: Finished saving pip cache
1:19:23 AM: Started saving emacs cask dependencies
1:19:23 AM: Finished saving emacs cask dependencies
1:19:23 AM: Started saving maven dependencies
1:19:23 AM: Finished saving maven dependencies
1:19:23 AM: Started saving boot dependencies
1:19:23 AM: Finished saving boot dependencies
1:19:23 AM: Started saving go dependencies
1:19:23 AM: Finished saving go dependencies
1:19:27 AM: Error running command: Build script returned non-zero exit code: 1
1:19:27 AM: Failing build: Failed to build site
1:19:27 AM: failed during stage 'building site': Build script returned non-zero exit code: 1
1:19:27 AM: Finished processing build request in 1m15.231125909s

My gatsby-config.js file is as follows:

module.exports = {
  siteMetadata: {
    title: "#######",
    author: "#######"
  },
  plugins: [
    "gatsby-plugin-sass",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images`
      }
    },
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    "gatsby-transformer-ffmpeg",
    "gatsby-plugin-ffmpeg"
  ]
}

Body:
Netlify's build image runs Ubuntu, so you can probably install ffmpeg with the following command:

apt-get install ffmpeg

You can prepend this script to your Netlify build command, i.e

apt-get install ffmpeg && npm run build

or stick it as a new script in your package.json.

Instruction on building latest version of ffmpeg on Ubuntu: https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu


来源: stackexchange

问:
projmanr data load in R
I need to work with this library in R (projmanr), but I cannot get how to put the data in the right format. For replication, I am using the dataframe which can be replicated but I need to get this data from CSV.

My dataframe is

```<code>    pred1=list( c(),c(1),c(1),c(2) ,c(3),c(3), c(4,5),  c(6,7) )

    data=data.frame(

      id=c(1,2,3,4,5,6,7,8),
      name=c("T1","T2","T3","T4","T5","T6","T7","T8"),
         duration=c(3, 4, 2, 5, 1, 2, 4, 3),
         pred=cbind(pred1)
    )

 > data
 id name duration pred1
 1  1   T1        3  NULL
 2  2   T2        4     1
 3  3   T3        2     1
 4  4   T4        5     2
 5  5   T5        1     3
 6  6   T6        2     3
 7  7   T7        4  4, 5
 8  8   T8        3  6, 7
</code>```

and when I call

```<code> critical_path(data)
</code>```

R returns

```<code>Error in walk_ahead(all_tasks, new_ids, start_date) :
Invalid predeccessor id. Using a predeccessor id for a task that does not exist.
</code>```

I guess it is because of the NULL value in the dataframe.

ContentLicense: CC BY-SA 4.0

Title: projmanr data load in R

Body:
I need to work with this library in R (projmanr), but I cannot get how to put the data in the right format. For replication, I am using the dataframe which can be replicated but I need to get this data from CSV.

My dataframe is

    pred1=list( c(),c(1),c(1),c(2) ,c(3),c(3), c(4,5),  c(6,7) )

    data=data.frame(

      id=c(1,2,3,4,5,6,7,8),
      name=c("T1","T2","T3","T4","T5","T6","T7","T8"),
         duration=c(3, 4, 2, 5, 1, 2, 4, 3),
         pred=cbind(pred1)
    )

 > data
 id name duration pred1
 1  1   T1        3  NULL
 2  2   T2        4     1
 3  3   T3        2     1
 4  4   T4        5     2
 5  5   T5        1     3
 6  6   T6        2     3
 7  7   T7        4  4, 5
 8  8   T8        3  6, 7

and when I call

 critical_path(data)

R returns

Error in walk_ahead(all_tasks, new_ids, start_date) :
Invalid predeccessor id. Using a predeccessor id for a task that does not exist.

I guess it is because of the NULL value in the dataframe.

Body:
I can see that converting pred1 to a vector of characters (instead of list of vectors) should solve the problem, as follows:

pred1 = list(c(), c(1), c(1), c(2), c(3), c(3), c(4,5), c(6,7) )
pred1 = sapply(pred1, paste0, collapse=",")

# Or
pred1 = c("", "1", "1", "2", "3", "3", "4,5 ", "6,7")

data = data.frame(

  id=c(1,2,3,4,5,6,7,8),
  name=c("T1","T2","T3","T4","T5","T6","T7","T8"),
     duration=c(3, 4, 2, 5, 1, 2, 4, 3),
     pred=cbind(pred1)
)

> data
#   id name duration pred
# 1  1   T1        3
# 2  2   T2        4    1
# 3  3   T3        2    1
# 4  4   T4        5    2
# 5  5   T5        1    3
# 6  6   T6        2    3
# 7  7   T7        4  4,5
# 8  8   T8        3  6,7

Now calling:

critical_path(data)

gives the following output:

# $critical_path
# [1] "1" "2" "4" "7" "8"
#
# $results
# id name start_date   end_date duration is_critical pred_id
# 1  1   T1 2020-02-17 2020-02-20        3        TRUE
# 2  2   T2 2020-02-20 2020-02-24        4        TRUE     1
# 3  3   T3 2020-02-20 2020-02-22        2       FALSE     1
# 4  4   T4 2020-02-24 2020-02-29        5        TRUE     2
# 5  5   T5 2020-02-22 2020-02-23        1       FALSE     3
# 6  6   T6 2020-02-22 2020-02-24        2       FALSE     3
# 7  7   T7 2020-02-29 2020-03-04        4        TRUE   4 5
# 8  8   T8 2020-03-04 2020-03-07        3        TRUE   6 7
#
# $total_duration
# [1] 19
#
# $end_date
# [1] "2020-03-07"
#
# $network
# IGRAPH a1f826c DN-- 8 9 --
# + attr: name (v/c)
# + edges from a1f826c (vertex names):
# [1] 1->2 1->3 2->4 3->5 3->6 4->7 5->7 6->8 7->8


问:
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why .
here is my javascript function  below if any one require my html code a can also provide

HTML Snippet

```<code><div class="row">
  <div class="col lg-3"></div>
  <div class="col lg-6 text-center">
     <div id="1">shahmir</div> </div>
     <div class="col lg-3"></div>
  </div>
</div>
</code>```

```

答:
You are shadowing the outer x variable by declaring a parameter to your function with the same name.

Inside the function x refers to the parameter, not the global variable.

You also have a function declaration with no body:

```<code>function add();
</code>```

If you mean to call the add function, you just do: add().

Take the x parameter out of the function declaration. Also, your condition will never be true. Since you initialise x to 1, and increment it before testing it, it will always be at least 2.

This is probably what you are trying to do (it's hard to tell, but at least this will do something):

```<code><script>
    var x=0;
    function add(){
        var a=document.getElementById("input").value;
        x++;
        if(x==1)document.getElementById("1").innerHTML=a;
    }
    add();
</script>
</code>```

Body:
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why .
here is my javascript function  below if any one require my html code a can also provide

HTML Snippet

shahmir

Body:
You are shadowing the outer x variable by declaring a parameter to your function with the same name.

Inside the function x refers to the parameter, not the global variable.

You also have a function declaration with no body:

function add();

If you mean to call the add function, you just do: add().

Take the x parameter out of the function declaration. Also, your condition will never be true. Since you initialise x to 1, and increment it before testing it, it will always be at least 2.

This is probably what you are trying to do (it's hard to tell, but at least this will do something):

<script>
    var x=0;
    function add(){
        var a=document.getElementById("input").value;
        x++;
        if(x==1)document.getElementById("1").innerHTML=a;
    }
    add();
</script>


问:
ScrollView in Fragment does not scroll when the soft keyboard shows up
I have a Fragment and there is a ScrollView in that Fragment.

```<code><ScrollView
    android:id="@+id/scroll_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/appbar">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.tatar.mobile.widget.CardSelectionView
            android:id="@+id/card_selection_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:accountRightTextView1="@string/available"
            app:accountTitleTextView="@string/from"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/line_text_view"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="8dp"
            android:background="@color/gray.light"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/card_selection_view" />

        <Spinner
            android:id="@+id/type_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/line_text_view" />

        <Spinner
            android:id="@+id/company_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/type_spinner" />

        <LinearLayout
            android:id="@+id/dynamic_form_container"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/company_spinner" />

        <Spinner
            android:id="@+id/installment_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            android:visibility="invisible"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/dynamic_form_container" />

        <Button
            android:id="@+id/continue_button"
            style="@style/action_button"
            android:layout_marginTop="16dp"
            android:text="@string/continue_button_text"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/installment_spinner" />

    </android.support.constraint.ConstraintLayout>

</ScrollView>
</code>```

The LinearLayout with the id of dynamic_form_container in that ScrollView contains form input fields which will are populated via a web service call and there might be up to 6-7 input fields depending on the parameters sent to web service. So, height of the form is kind of high and that is where the problem starts. When I try to enter something to an input field, soft keyboard shows up and some of the other input fields stay under the soft keyboard and scrolling is not possible.

I tried to put this to manifest for the Activity of that Fragment but it did not help.

```<code>android:windowSoftInputMode="adjustResize|stateHidden"
</code>```

I want to be able to scroll when the soft keyboard shows up. How can I fix that issue ?

Any help would be appreciated

答:
I have found solution for this problem here, include this class in your project.
And add this following line in onCreate of activity that contains fragment.

new KeyboardUtil(this,findViewById(R.id.fragment));

Body:
I have a Fragment and there is a ScrollView in that Fragment.

<ScrollView
    android:id="@+id/scroll_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/appbar">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.tatar.mobile.widget.CardSelectionView
            android:id="@+id/card_selection_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:accountRightTextView1="@string/available"
            app:accountTitleTextView="@string/from"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/line_text_view"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="8dp"
            android:background="@color/gray.light"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/card_selection_view" />

        <Spinner
            android:id="@+id/type_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/line_text_view" />

        <Spinner
            android:id="@+id/company_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/type_spinner" />

        <LinearLayout
            android:id="@+id/dynamic_form_container"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/company_spinner" />

        <Spinner
            android:id="@+id/installment_spinner"
            style="@style/spinner"
            android:layout_marginTop="8dp"
            android:visibility="invisible"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/dynamic_form_container" />

        <Button
            android:id="@+id/continue_button"
            style="@style/action_button"
            android:layout_marginTop="16dp"
            android:text="@string/continue_button_text"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/installment_spinner" />

    </android.support.constraint.ConstraintLayout>

</ScrollView>

The LinearLayout with the id of dynamic_form_container in that ScrollView contains form input fields which will are populated via a web service call and there might be up to 6-7 input fields depending on the parameters sent to web service. So, height of the form is kind of high and that is where the problem starts. When I try to enter something to an input field, soft keyboard shows up and some of the other input fields stay under the soft keyboard and scrolling is not possible.

I tried to put this to manifest for the Activity of that Fragment but it did not help.

android:windowSoftInputMode="adjustResize|stateHidden"

I want to be able to scroll when the soft keyboard shows up. How can I fix that issue ?

Any help would be appreciated


问:
Count events in range on a vector via iteration in R
I have a vector that contains sample numbers of event markers. They are only listed when there is an event found, not at every sample. I would like to obtain an output of the number of events found every second. Sampling rate is known (15hz).

I figured out how to do it with a for loop, but it is working a bit on the slow side. I am struggling to figure out a more efficient way to perform this calculation (with mapply or something like that maybe?). Does anybody have any suggestions?

Here is a sample of what I am doing:

```<code>vec <- c(9,20,23,48,50,51)
fs <- 15
start_idx <- seq(from=1,to=46,by=15)
end_idx <- seq(from=15,to=60,by=15)
counter <- vector()
for (i in 1:length(start_idx)) {
  counter[i] <- length(which(vec >= start_idx[i] & vec <= end_idx[i]))
}
</code>```

The results of counter should be:

```<code>> counter
[1] 1 2 0 3
</code>```

Any help is much appreciated!

答:
For a tidyverse approach, you can map inside mutate:

```<code>library(tidyverse)

ranges <- tibble(start_idx, end_idx)

ranges %>%
  mutate(ct = map2_int(start_idx, end_idx, ~sum(.x <= vec & .y >= vec)))

  start_idx end_idx    ct
      <dbl>   <dbl> <int>
1         1      15     1
2        16      30     2
3        31      45     0
4        46      60     3
</code>```

Body:
I have a vector that contains sample numbers of event markers. They are only listed when there is an event found, not at every sample. I would like to obtain an output of the number of events found every second. Sampling rate is known (15hz).

I figured out how to do it with a for loop, but it is working a bit on the slow side. I am struggling to figure out a more efficient way to perform this calculation (with mapply or something like that maybe?). Does anybody have any suggestions?

Here is a sample of what I am doing:

vec <- c(9,20,23,48,50,51)
fs <- 15
start_idx <- seq(from=1,to=46,by=15)
end_idx <- seq(from=15,to=60,by=15)
counter <- vector()
for (i in 1:length(start_idx)) {
  counter[i] <- length(which(vec >= start_idx[i] & vec <= end_idx[i]))
}

The results of counter should be:

> counter
[1] 1 2 0 3

Any help is much appreciated!

Body:
For a tidyverse approach, you can map inside mutate:

library(tidyverse)

ranges <- tibble(start_idx, end_idx)

ranges %>%
  mutate(ct = map2_int(start_idx, end_idx, ~sum(.x <= vec & .y >= vec)))

  start_idx end_idx    ct
      <dbl>   <dbl> <int>
1         1      15     1
2        16      30     2
3        31      45     0
4        46      60     3


问:
Node and NPM Running script and Ctrl-C triggers SIGINT twice
I've come across a problem on one of my Nodejs apps running with npm start (which just does node app.js).

My app contains a sigint handler as follows:

```<code>process.on('SIGINT', () => {
    db.disconnect().then({
        process.exit(0);
    }).catch(e => process.exit(1));
});
</code>```

With corresponding logs. After some testing on other files, I've noticed that Ctrl-C when on an npm process triggers SIGINT twice if the first one takes too long to exit. (try adding a timeout on a sample app).

For now I've added a counter to check if the call is performed more than once, but I'm not sure that's "the way to go" concerning this issue. I'm guessing that a SIGINT on an npm process is expected to quit in a certain timeframe, which is why npm passes it on one more time (always only twice).

Has anyone come across this problem and found a viable solution?

Thanks!

答:
You might want to run your command's directly via node, rather than via npm start. NPM can be a cause for wierd trapping of signals, see https://lisk.io/blog/tutorial/why-we-stopped-using-npm-start-child-processes.

Your SIGINT handler can get called multiple times, you should write your code to protect against that.

Also if you are running parent/child processes, see https://github.com/jtlapp/node-cleanup

When you hit Ctrl-C, you send a SIGINT signal to each process in the
  current process group. A process group is set of processes that are
  all supposed to end together as a group instead of persisting
  independently. However, some programs, such as Emacs, intercept and
  repurpose SIGINT so that it does not end the process. In such cases,
  SIGINT should not end any processes of the group.

Additionally, calling process.exit is not necessary most of the time, see https://nodejs.org/api/process.html#process_process_exit_code

Instead set process.exitCode, remove your signal handlers and then re-raise the signal via process.kill(process.pid, signal)

Body:
I've come across a problem on one of my Nodejs apps running with npm start (which just does node app.js).

My app contains a sigint handler as follows:

process.on('SIGINT', () => {
    db.disconnect().then({
        process.exit(0);
    }).catch(e => process.exit(1));
});

With corresponding logs. After some testing on other files, I've noticed that Ctrl-C when on an npm process triggers SIGINT twice if the first one takes too long to exit. (try adding a timeout on a sample app).

For now I've added a counter to check if the call is performed more than once, but I'm not sure that's "the way to go" concerning this issue. I'm guessing that a SIGINT on an npm process is expected to quit in a certain timeframe, which is why npm passes it on one more time (always only twice).

Has anyone come across this problem and found a viable solution?

Thanks!


问:
iOS Keyboard - Capitalise 'done' button
I am using 'UIKeyboardTypeDefault' keyboard type for my UITextfields.

The done button for the keyboard appears in lowercase as 'done'.
Is there anyway to make this a capitalised as 'Done' ?

答:
You can try using the POD - > IQKeyboardManagerSwift
LINK -->

pod 'IQKeyboardManagerSwift', :git =>
    'https://github.com/hackiftekhar/IQKeyboardManager.git'

This is very useful pod for handling stuff for keyboard

Title: iOS Keyboard - Capitalise 'done' button


问:
Swift 3.0 : Convert server UTC time to local time and vice-versa
I want to convert server UTC time to local time and vice-versa.
Here is my code..

```<code>var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time

if isTimeFromServer {

    let index = timeString.index(timeString.startIndex, offsetBy: 5)
    let twelve = timeString.substring(to: index)

    var dateString:String!

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm"
    let date12 = dateFormatter.date(from: twelve)!

    dateFormatter.dateFormat = "h:mm a"
    let date22 = dateFormatter.string(from: date12)

    //print(date22)
    dateString = date22
    //print("dateString=\(dateString)")

    time = dateString.components(separatedBy: " ")[0]
    period = dateString.components(separatedBy: " ")[1]

}
else {
    time = timeString.components(separatedBy: " ")[0]
    period = timeString.components(separatedBy: " ")[1]
}

var hour = Int(time.components(separatedBy: ":")[0])

hour = period == "AM" ? hour : hour! + 12
let minute = Int(time.components(separatedBy: ":")[1])
let calender = NSCalendar.current
var datecomponent = DateComponents()
datecomponent.calendar = calender
datecomponent.hour = hour
datecomponent.minute = minute

if !isTimeFromServer {
    // local to UTC
    datecomponent.timeZone = TimeZone.current
}
else {
    datecomponent.timeZone = TimeZone(abbreviation: "UTC")
}

let date = datecomponent.date
let dateFormatter = DateFormatter()

if !isTimeFromServer {
    dateFormatter.dateFormat = "H:mm"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.string(from: date!)
}
else {
    //UTC to local
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.string(from: date!)
}
</code>```

I get the local time

o/p: "12:52 PM"

But actual local time and output time difference is 23 minutes.

答:
You can use in swift 4/5

```<code>  var myDate:String = "2020-02-18 14:30:57"
    var convertedLocalTime:String = ""

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"

    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    if let dt = dateFormatter.date(from: myDate) {
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
        convertedLocalTime = dateFormatter.string(from: dt)
    } else {
        print("There was an error decoding the string")
    }

    print("convertedLocalTime--",convertedLocalTime)
</code>```

Body:
I want to convert server UTC time to local time and vice-versa.
Here is my code..

var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time

if isTimeFromServer {

    let index = timeString.index(timeString.startIndex, offsetBy: 5)
    let twelve = timeString.substring(to: index)

    var dateString:String!

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm"
    let date12 = dateFormatter.date(from: twelve)!

    dateFormatter.dateFormat = "h:mm a"
    let date22 = dateFormatter.string(from: date12)

    //print(date22)
    dateString = date22
    //print("dateString=\(dateString)")

    time = dateString.components(separatedBy: " ")[0]
    period = dateString.components(separatedBy: " ")[1]

}
else {
    time = timeString.components(separatedBy: " ")[0]
    period = timeString.components(separatedBy: " ")[1]
}

var hour = Int(time.components(separatedBy: ":")[0])

hour = period == "AM" ? hour : hour! + 12
let minute = Int(time.components(separatedBy: ":")[1])
let calender = NSCalendar.current
var datecomponent = DateComponents()
datecomponent.calendar = calender
datecomponent.hour = hour
datecomponent.minute = minute

if !isTimeFromServer {
    // local to UTC
    datecomponent.timeZone = TimeZone.current
}
else {
    datecomponent.timeZone = TimeZone(abbreviation: "UTC")
}

let date = datecomponent.date
let dateFormatter = DateFormatter()

if !isTimeFromServer {
    dateFormatter.dateFormat = "H:mm"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.string(from: date!)
}
else {
    //UTC to local
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.string(from: date!)
}

I get the local time

o/p: "12:52 PM"

But actual local time and output time difference is 23 minutes.

Body:
You can use in swift 4/5

  var myDate:String = "2020-02-18 14:30:57"
    var convertedLocalTime:String = ""

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"

    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    if let dt = dateFormatter.date(from: myDate) {
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
        convertedLocalTime = dateFormatter.string(from: dt)
    } else {
        print("There was an error decoding the string")
    }

    print("convertedLocalTime--",convertedLocalTime)


问:
Django utf-8 urls
I have a Django app that works fine on localhost.even for utf-8 URL path.but when I use it in production it gives me an error:

```<code>2019-09-01 14:32:09.558237 [ERROR] [12257] wsgiAppHandler pApp->start_response() return NULL.
Traceback (most recent call last):
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 139, in call
set_script_prefix(get_script_name(environ))
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 179, in get_script_name
script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') or get_bytes_from_wsgi(environ, 'REDIRECT_URL', '')
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 204, in get_bytes_from_wsgi
return value.encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 1-6: ordinal not in range(256)
</code>```

this error occurs when i try a url like

http://meduallameh.ir/صفحه

the only answer I got was that problem with the webserver. I deployed it on a shared host and I asked them and they told me that web server supports utf-8. now I need some help to fix this problem.

答:
At one point, I had UTF-8 characters in the URL working for me, and somehow, I noticed that it broke when I migrated from Python 2 to Python 3 (along the way, I also switched from Apache + mod_wsgi to Apache proxying to Gunicorn).

Based on the answer the OP provided, I reluctantly resorted to subclassing the default WSGIHandler and WSGIRequest.

Gist: https://gist.github.com/jontsai/afd5f5d9399ac2b0d770a73983d61690#file-django_wsgi_utf8_handler-py-L66-L69

While not ideal, this solution can be deployed to multiple servers/environments.

I'll be looking to try to file a patch with the Django project.

Title: Django utf-8 urls

Body:
I have a Django app that works fine on localhost.even for utf-8 URL path.but when I use it in production it gives me an error:

2019-09-01 14:32:09.558237 [ERROR] [12257] wsgiAppHandler pApp->start_response() return NULL.
Traceback (most recent call last):
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 139, in call
set_script_prefix(get_script_name(environ))
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 179, in get_script_name
script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') or get_bytes_from_wsgi(environ, 'REDIRECT_URL', '')
File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 204, in get_bytes_from_wsgi
return value.encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 1-6: ordinal not in range(256)

this error occurs when i try a url like

http://meduallameh.ir/صفحه

the only answer I got was that problem with the webserver. I deployed it on a shared host and I asked them and they told me that web server supports utf-8. now I need some help to fix this problem.


问:
List of Tuples to store on pyspark dataframe
I have few hundreds text files that I am reading as list of tuples below.

```<code>file_1= [(),(),(),(),()...]
file_2= [(),(),(),(),()...]
.
.
.
file_n= [(),(),(),(),()...]
</code>```

Now I want to add these into pyspark dataframe something like below

```<code>+------+------------------------+
|file_1 |     [(),(),(),(),()...]|
|file_2 |     [(),(),(),(),()...]|
 .
 .
 .
|file_n |     [(),(),(),(),()...]|
+------+------------------------+
</code>```

How can i achieve this or if there is even  a better way to do this.

答:
if the content of your text file is like this
    file_1= [(),(),(),(),()...]

And, if you are using spark 2 Then you can use csv to convert it into data frame:

```<code>df = spark.read.csv("file path", sep = " = ")
</code>```

Body:
I have few hundreds text files that I am reading as list of tuples below.

file_1= [(),(),(),(),()...]
file_2= [(),(),(),(),()...]
.
.
.
file_n= [(),(),(),(),()...]

Now I want to add these into pyspark dataframe something like below

+------+------------------------+
|file_1 |     [(),(),(),(),()...]|
|file_2 |     [(),(),(),(),()...]|
 .
 .
 .
|file_n |     [(),(),(),(),()...]|
+------+------------------------+

How can i achieve this or if there is even  a better way to do this.

Body:
if the content of your text file is like this
    file_1= [(),(),(),(),()...]

And, if you are using spark 2 Then you can use csv to convert it into data frame:

df = spark.read.csv("file path", sep = " = ")


问:
I want a way to hide the cursor from EditText
How to make the cursor automatically disappear from EditText when not writing ?

I want something easy to understand. I am not a much programming expert

```<code><android.support.design.widget.TextInputEditText
                                android:id="@+id/name1"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="8dp"
                                android:ems="8"
                                android:fontFamily="@font/bahij_janna"
                                android:hint="@string/team_2"
                                android:lines="1"
                                android:textColor="?attr/textColor"
                                android:inputType="textCapWords"
                                />
</code>```

See an example of the problem via the link

答:
android:textCursorDrawable="@null"

you can set the cursor as null for hide the cursor till the click event occured.
the cursor will shows up when you click the edittext to start typing.

cursor will always help us to copy and paste the text.

Body:
How to make the cursor automatically disappear from EditText when not writing ?

I want something easy to understand. I am not a much programming expert

<android.support.design.widget.TextInputEditText
                                android:id="@+id/name1"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="8dp"
                                android:ems="8"
                                android:fontFamily="@font/bahij_janna"
                                android:hint="@string/team_2"
                                android:lines="1"
                                android:textColor="?attr/textColor"
                                android:inputType="textCapWords"
                                />

See an example of the problem via the link


问:
How to parse Json from URL and display in Collection View in Xcode
Here is a sample of my Api code that I am trying to parse

```<code>     {"@iot.nextLink" : "Google.com","value" : [ {
    "phenomenonTime" : "2020-02-12T01:38:17.622Z",
    "resultTime" : "2020-02-12T01:38:17.622Z",
    "result" : 1009.3,
    "Datastream@1" : "Yahoo.com",
    "FeatureOfInterest@2" : "bing.com",
    "@iot.id" : 4093015,
    "@iot.selfLink" : "youtube.com"},

    {"phenomenonTime" : "2020-02-12T01:23:11.397Z",
    "resultTime" : "2020-02-12T01:23:11.397Z",
    "result" : 1009.7,
    "Datastream@1" : "walmart.com",
    "FeatureOfInterest@2" : "bestbuy.com",
    "@iot.id" : 4092867,
    "@iot.selfLink" : "gmail.com"}, ...]}
</code>```

I have created structures to parse the Json

```<code>struct Initial: Decodable {
let value : [Blue]}

struct Blue: Decodable {
let phenomenonTime : String
let result : Double}
</code>```

I only want to display the PhenomenonTime value and the result value. Next, I did

```<code>      var url1 = ""

      override func viewDidLoad() {
      let url = URL(string: url1)
      URLSession.shared.dataTask(with: url!) { (data, response, error) in
        guard let data = data else { return }
                do {
             let initial = try? JSONDecoder().decode(Initial.self, from: data)
                    print(initial?.value)

             }catch {
            print("Error")
        }

    }.resume()
}
</code>```

Here is my code of me parsing the JSON. I can print the values

```<code>Optional([GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:38:17.622Z", result: 1009.3),
GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:23:11.397Z", result: 1009.7),...])
</code>```

But, it doesn't allow me when I try to do

```<code>print(initial?.value.result)
</code>```

An error comes up saying "Value of type '[Blue]' has no member 'result'". So, I don't know how to fix this issue of how to print just values or just phenomenonTime so I can put just put values in the collection view or just put phenomenonTime in another collection view. Also, I didn't know how to parse the Json so the collection view can see the array of just phenomenonTime.

```<code>extension ViewController:UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = pressureView.dequeueReusableCell(withReuseIdentifier: "check", for: indexPath) as? PressureCollectionViewCell

    cell?.number.text=String(indexPath.row)
    return cell!
}
</code>```

Currently, I made it so it will just present a different number in each cell but I don't know how to get all the values into one array and all the phenomenonTime into one array and present them into the collectionview. When I try to refer to make the cell text display the values

```<code>        cell?.number.text=initial?.value[indexPath.row]
</code>```

It says:

"Use of unresolved identifier 'initial'"

So, what to do to fix it?

答:
So, set your viewcontroller like:

```<code>class ViewController: UIViewController {

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = .lightGray
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    var url1 = "your_url"
    private var cellId: String = "12312"
    private var phenomenonTimeArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.collectionView)
        NSLayoutConstraint.activate([
            self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        self.collectionView.register(PressureCollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
        self.getDataFromServer()
    }

    func getDataFromServer() {
        let url = URL(string: url1)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            guard let data = data else { return }
            do {
                let initial = try? JSONDecoder().decode(Initial.self, from: data)
                if let value = initial?.value {
                    self.phenomenonTimeArray = value.map { (blue) -> String in
                        return blue.phenomenonTime
                    }
                    self.collectionView.reloadData()
                }
            } catch {
                print("Error")
            }
        }.resume()
    }
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.phenomenonTimeArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as! PressureCollectionViewCell
        cell.item = phenomenonTimeArray[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: collectionView.frame.width, height: 30)
    }
}
</code>```

And your cell(design your cell as per requirement):

```<code>class PressureCollectionViewCell: UICollectionViewCell {

    var item: String? {
        didSet {
            self.label.text = item
        }
    }

    private lazy var label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    private func setupViews() {
        self.addSubview(self.label)
        NSLayoutConstraint.activate([
            self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            self.label.topAnchor.constraint(equalTo: self.topAnchor),
            self.label.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
    }
}
</code>```

Body:
Here is a sample of my Api code that I am trying to parse

     {"@iot.nextLink" : "Google.com","value" : [ {
    "phenomenonTime" : "2020-02-12T01:38:17.622Z",
    "resultTime" : "2020-02-12T01:38:17.622Z",
    "result" : 1009.3,
    "Datastream@1" : "Yahoo.com",
    "FeatureOfInterest@2" : "bing.com",
    "@iot.id" : 4093015,
    "@iot.selfLink" : "youtube.com"},

    {"phenomenonTime" : "2020-02-12T01:23:11.397Z",
    "resultTime" : "2020-02-12T01:23:11.397Z",
    "result" : 1009.7,
    "Datastream@1" : "walmart.com",
    "FeatureOfInterest@2" : "bestbuy.com",
    "@iot.id" : 4092867,
    "@iot.selfLink" : "gmail.com"}, ...]}

I have created structures to parse the Json

struct Initial: Decodable {
let value : [Blue]}

struct Blue: Decodable {
let phenomenonTime : String
let result : Double}

I only want to display the PhenomenonTime value and the result value. Next, I did

      var url1 = ""

      override func viewDidLoad() {
      let url = URL(string: url1)
      URLSession.shared.dataTask(with: url!) { (data, response, error) in
        guard let data = data else { return }
                do {
             let initial = try? JSONDecoder().decode(Initial.self, from: data)
                    print(initial?.value)

             }catch {
            print("Error")
        }

    }.resume()
}

Here is my code of me parsing the JSON. I can print the values

Optional([GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:38:17.622Z", result: 1009.3),
GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:23:11.397Z", result: 1009.7),...])

But, it doesn't allow me when I try to do

print(initial?.value.result)

An error comes up saying "Value of type '[Blue]' has no member 'result'". So, I don't know how to fix this issue of how to print just values or just phenomenonTime so I can put just put values in the collection view or just put phenomenonTime in another collection view. Also, I didn't know how to parse the Json so the collection view can see the array of just phenomenonTime.

extension ViewController:UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = pressureView.dequeueReusableCell(withReuseIdentifier: "check", for: indexPath) as? PressureCollectionViewCell

    cell?.number.text=String(indexPath.row)
    return cell!
}

Currently, I made it so it will just present a different number in each cell but I don't know how to get all the values into one array and all the phenomenonTime into one array and present them into the collectionview. When I try to refer to make the cell text display the values

        cell?.number.text=initial?.value[indexPath.row]

It says:

"Use of unresolved identifier 'initial'"

So, what to do to fix it?

Body:
So, set your viewcontroller like:

class ViewController: UIViewController {

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = .lightGray
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    var url1 = "your_url"
    private var cellId: String = "12312"
    private var phenomenonTimeArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.collectionView)
        NSLayoutConstraint.activate([
            self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        self.collectionView.register(PressureCollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
        self.getDataFromServer()
    }

    func getDataFromServer() {
        let url = URL(string: url1)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            guard let data = data else { return }
            do {
                let initial = try? JSONDecoder().decode(Initial.self, from: data)
                if let value = initial?.value {
                    self.phenomenonTimeArray = value.map { (blue) -> String in
                        return blue.phenomenonTime
                    }
                    self.collectionView.reloadData()
                }
            } catch {
                print("Error")
            }
        }.resume()
    }
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.phenomenonTimeArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as! PressureCollectionViewCell
        cell.item = phenomenonTimeArray[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: collectionView.frame.width, height: 30)
    }
}

And your cell(design your cell as per requirement):

class PressureCollectionViewCell: UICollectionViewCell {

    var item: String? {
        didSet {
            self.label.text = item
        }
    }

    private lazy var label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    private func setupViews() {
        self.addSubview(self.label)
        NSLayoutConstraint.activate([
            self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            self.label.topAnchor.constraint(equalTo: self.topAnchor),
            self.label.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
    }
}


问:
How to display all values from a json api into a single dropdown list using React JS?
I have a page written in React JS that consist of a dropdown list. The values in the dropdown-list are populated from a json file that has over a 100 clients.
The dropdown-list in my page presents the user with the clients, but the issue am encountering is: it displays the clients in individual dropdown-lists and my goal is to get all client into a one /single dropdown-list.

this is just one of the 100 arrays in the json file:

```<code>[
    {
        "id": 777,
        "abc_programid": "777777-1111-2222-333-444444",
        "clientName": "client one - AB"
    }
]
</code>```

The code:

```<code>import React, { Component } from 'react';
class Acl extends Component {

   constructor(){
       super();
       this.state = {
           data: [],
       };
   } //end constructor

    componentDidMount() {
        fetch('http://myClientapi/api/', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': 'Bearer abc.123.456'
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

    render() {
    console.log(this.state.data);
    return (
    <div>
        <div className="container">
            <form>
            <h2>Memeber Selection:</h2>
            <div>
                {
                    this.state.data.map(item =>(
                        <div>
                            <select className="custom-select" id="clientName">>
                            <option key={item.clientName}>{item.clientName}</option>
                            </select>
                        </div>
                    ))
                }
            </div>
            <div>
            <button type="submit" className="btn btn-primary">Submit</button>
            </div>
            </form>
        </div>
    </div>
        );
      }
}

export default Acl
</code>```

...my problem: My page is displaying 100 drop-downs and each one has an individual client; My goal: to get all clients into one single dropdown. Could I get some help with this please?

答:
                    <Form>
                            <FormGroup>
                              <Input
                              type="select"
                              onChange = {this.changeCarmodel}
                              value={this.state.changeCar}
                              >
                              {calculatorData.map((caldata, index) =>
                                <option key={index}> {caldata.name} </option>
                              )}
                              </Input>
                            </FormGroup>
                          </Form>```

Body:
I have a page written in React JS that consist of a dropdown list. The values in the dropdown-list are populated from a json file that has over a 100 clients.
The dropdown-list in my page presents the user with the clients, but the issue am encountering is: it displays the clients in individual dropdown-lists and my goal is to get all client into a one /single dropdown-list.

this is just one of the 100 arrays in the json file:

[
    {
        "id": 777,
        "abc_programid": "777777-1111-2222-333-444444",
        "clientName": "client one - AB"
    }
]

The code:

import React, { Component } from 'react';
class Acl extends Component {

   constructor(){
       super();
       this.state = {
           data: [],
       };
   } //end constructor

    componentDidMount() {
        fetch('http://myClientapi/api/', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': 'Bearer abc.123.456'
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

    render() {
    console.log(this.state.data);
    return (

            <form>

Memeber Selection:

                {
                    this.state.data.map(item =>(

                            <select className="custom-select" id="clientName">>
                            <option key={item.clientName}>{item.clientName}</option>
                            </select>

                    ))
                }

            <button type="submit" className="btn btn-primary">Submit</button>

            </form>

        );
      }
}

export default Acl

...my problem: My page is displaying 100 drop-downs and each one has an individual client; My goal: to get all clients into one single dropdown. Could I get some help with this please?


问:
program to handle Heterogeneous Lists in Scala;
I have to find out the maximum/minimum from this list:

```<code> val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
</code>```

From some stack over flow example ,i can see below solution:

```<code>val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten
</code>```

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark

答:
Let's go through your code in more detail:

```<code>sacla> val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
data: List[Any] = List(List(1, 2), List(3, 4, 91, 9, 10), 11, 211, 456, 345)
</code>```

The type of data is a List[Any] because the list is not one specific type. The compiler tries to infer the type, but since Int and List[Int] aren't compatible, it resolves to Any.

```<code>scala> data.collect{case i:Int => List(i); case l @ a :: b => l}
res0 List[List[Any]] = List(List(1, 2), List(3, 4, 91, 9, 10), List(11), List(211), List(456), List(345))
</code>```

This second part, tries to consolidate the entries to be a List of Lists. It matches an Int and wraps it in a List.

However, you see the type here is still List[List[Any]].

Now the last part, the .flatten

```<code>scala> res0.flatten
res1: List[Any] = List(1, 2, 3, 4, 91, 9, 10, 11, 211, 456, 345)
</code>```

This takes you from a List[List[Any] to List[Any].

Now the key part here is that if you try to call .max or .min on this list, it won't work. Since there is no such Ordering for Any.

```<code><console>:13: error: No implicit Ordering defined for Any.
</code>```

The fix will be to force the this type in the original collect call.

```<code>scala> data.collect{case i:Int => List(i); case l : List[Int] => l}
res6: List[List[Int]] = List(List(1, 2), List(3, 4, 91, 9, 10), List(11), List(211), List(456), List(345))

scala> .flatten
res7: List[Int] = List(1, 2, 3, 4, 91, 9, 10, 11, 211, 456, 345)

scala> .max
res8: Int = 456

scala> res7.min
res9: Int = 1

</code>```

Body:
I have to find out the maximum/minimum from this list:

 val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)

From some stack over flow example ,i can see below solution:

val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark

Body:
Let's go through your code in more detail:

sacla> val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
data: List[Any] = List(List(1, 2), List(3, 4, 91, 9, 10), 11, 211, 456, 345)

The type of data is a List[Any] because the list is not one specific type. The compiler tries to infer the type, but since Int and List[Int] aren't compatible, it resolves to Any.

scala> data.collect{case i:Int => List(i); case l @ a :: b => l}
res0 List[List[Any]] = List(List(1, 2), List(3, 4, 91, 9, 10), List(11), List(211), List(456), List(345))

This second part, tries to consolidate the entries to be a List of Lists. It matches an Int and wraps it in a List.

However, you see the type here is still List[List[Any]].

Now the last part, the .flatten

scala> res0.flatten
res1: List[Any] = List(1, 2, 3, 4, 91, 9, 10, 11, 211, 456, 345)

This takes you from a List[List[Any] to List[Any].

Now the key part here is that if you try to call .max or .min on this list, it won't work. Since there is no such Ordering for Any.

<console>:13: error: No implicit Ordering defined for Any.

The fix will be to force the this type in the original collect call.

scala> data.collect{case i:Int => List(i); case l : List[Int] => l}
res6: List[List[Int]] = List(List(1, 2), List(3, 4, 91, 9, 10), List(11), List(211), List(456), List(345))

scala> .flatten
res7: List[Int] = List(1, 2, 3, 4, 91, 9, 10, 11, 211, 456, 345)

scala> .max
res8: Int = 456

scala> res7.min
res9: Int = 1


问:
How to take data from aspx page to stored procedure?
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

```<code>USE [PC_Rewrite]
</code>```

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

```<code>-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END
</code>```

END

Any help would be appreciated.

答:
set  @query = 'select Resume.ResumeID,Resume.Name,Resume.DepartmentID,Department.DepartmentName,
        Resume.CurrentCompany ,Resume.CurrentLocation ,Resume.Phone,Resume.Email,
        Resume.KeySkills,Resume.TotalExpYears,Resume.TotalExpMonths,Resume.CandidateTextResume,Resume.ResumeStatus,
        Resume.IsActive from [Resume] inner join [Department]  on [Resume].DepartmentID=[Department].DepartmentID  where [Resume].IsActive =1 '

```<code>if(@DepartmentName != '')
begin
        select  @query = @query + ' And [Department].DepartmentName like ''%'  + @DepartmentName + '%'''
end

if(@TotalExpYears != '')
begin
        select  @query = @query + ' And TotalExpYears like ''%'  + @TotalExpYears + '%'''
end

if(@TotalExpMonths != '')
begin
        select  @query = @query + ' And TotalExpMonths like ''%'  + @TotalExpMonths + '%'''
end

if(@KeySkills != '')
begin
        select  @query = @query + ' And KeySkills like ''%'  + @KeySkills + '%'''
end

if(@CurrentLocation != '')
begin
        select  @query = @query + ' And CurrentLocation like ''%'  + @CurrentLocation + '%'''
end

if(@CandidateTextResume != '')
begin
        select  @query = @query + ' And CandidateTextResume like ''%'  + @CandidateTextResume + '%'''
end

if(@CurrentCompany != '')
begin
        select  @query = @query + ' And CurrentCompany like ''%'  + @CurrentCompany + '%'''
end
if(@ResumeStatus != '')
begin
    select  @query = @query + ' And ResumeStatus like ''%'  + @ResumeStatus + '%'''
end
</code>```

==============
@strId as varchar(100)//strId is comma seperated ids
'select * FROM tblSchool where intSchoolId IN ('+ @strId +')'

=================
Now is it fine?

ContentLicense: CC BY-SA 3.0

Body:
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

USE [PC_Rewrite]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END

END

Any help would be appreciated.

Body:
set  @query = 'select Resume.ResumeID,Resume.Name,Resume.DepartmentID,Department.DepartmentName,
        Resume.CurrentCompany ,Resume.CurrentLocation ,Resume.Phone,Resume.Email,
        Resume.KeySkills,Resume.TotalExpYears,Resume.TotalExpMonths,Resume.CandidateTextResume,Resume.ResumeStatus,
        Resume.IsActive from [Resume] inner join [Department]  on [Resume].DepartmentID=[Department].DepartmentID  where [Resume].IsActive =1 '

if(@DepartmentName != '')
begin
        select  @query = @query + ' And [Department].DepartmentName like ''%'  + @DepartmentName + '%'''
end

if(@TotalExpYears != '')
begin
        select  @query = @query + ' And TotalExpYears like ''%'  + @TotalExpYears + '%'''
end

if(@TotalExpMonths != '')
begin
        select  @query = @query + ' And TotalExpMonths like ''%'  + @TotalExpMonths + '%'''
end

if(@KeySkills != '')
begin
        select  @query = @query + ' And KeySkills like ''%'  + @KeySkills + '%'''
end

if(@CurrentLocation != '')
begin
        select  @query = @query + ' And CurrentLocation like ''%'  + @CurrentLocation + '%'''
end

if(@CandidateTextResume != '')
begin
        select  @query = @query + ' And CandidateTextResume like ''%'  + @CandidateTextResume + '%'''
end

if(@CurrentCompany != '')
begin
        select  @query = @query + ' And CurrentCompany like ''%'  + @CurrentCompany + '%'''
end
if(@ResumeStatus != '')
begin
    select  @query = @query + ' And ResumeStatus like ''%'  + @ResumeStatus + '%'''
end

==============
@strId as varchar(100)//strId is comma seperated ids
'select * FROM tblSchool where intSchoolId IN ('+ @strId +')'

=================
Now is it fine?


问:
How do I check if a value from an entry is in a list?
I'm trying to make a Pokemon Damage Calculator/Battle Simulator in python. Being moderately experienced in the language, I know most of the jibe, however, I can't seem to figure out how to retrieve an entry (the users choice of Pokemon) and check if it's in a list. I will be using this function for a chunk of the script and I'm not sure how to code it.

I've tried a if statement combined with .get but, when I try that, the error TypeError: 'set' object is not callable appears.

Heres my code to show my situation:

```<code>from tkinter import *

Pokemon = {"Bulbasaur", "Ivysaur", "Venusaur", "Charmander",
"Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise",
"Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill",
"Pidgey", "Pidgeotto", "Pidgeot"}

def begin():
    global battle
    if pokemon1.get() in Pokemon and pokemon2.get() in Pokemon():
      battle = Tk()
      battle.title("Battle")

root = Tk()
root.title("Select Pokemon")
root.geometry("600x400")

Label(root, text="Pokemon 1").pack()
pokemon1 = Entry(root)
pokemon1.pack()

Label(root, text="Pokemon 2").pack()
pokemon2 = Entry(root)
pokemon2.pack()

Button(root, text="Begin!", command=begin).pack()

root.mainloop()
</code>```

Its a bit chunky, but it's not much (I cut down on the size of the list). If I could get an answer that helps me fix this error I would appreciate it. Thanks!

答:
Like this

```<code>test = "Bulbasaur"
if test in Pokemon:
    print("Found")
</code>```

This is the simplest way to find something in a list/set

Body:
I'm trying to make a Pokemon Damage Calculator/Battle Simulator in python. Being moderately experienced in the language, I know most of the jibe, however, I can't seem to figure out how to retrieve an entry (the users choice of Pokemon) and check if it's in a list. I will be using this function for a chunk of the script and I'm not sure how to code it.

I've tried a if statement combined with .get but, when I try that, the error TypeError: 'set' object is not callable appears.

Heres my code to show my situation:

from tkinter import *

Pokemon = {"Bulbasaur", "Ivysaur", "Venusaur", "Charmander",
"Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise",
"Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill",
"Pidgey", "Pidgeotto", "Pidgeot"}

def begin():
    global battle
    if pokemon1.get() in Pokemon and pokemon2.get() in Pokemon():
      battle = Tk()
      battle.title("Battle")

root = Tk()
root.title("Select Pokemon")
root.geometry("600x400")

Label(root, text="Pokemon 1").pack()
pokemon1 = Entry(root)
pokemon1.pack()

Label(root, text="Pokemon 2").pack()
pokemon2 = Entry(root)
pokemon2.pack()

Button(root, text="Begin!", command=begin).pack()

root.mainloop()

Its a bit chunky, but it's not much (I cut down on the size of the list). If I could get an answer that helps me fix this error I would appreciate it. Thanks!

Body:
Like this

test = "Bulbasaur"
if test in Pokemon:
    print("Found")

This is the simplest way to find something in a list/set


问:
TypeError: in props.onStartGame(selectedNumber) , 'props.onStartGame' is undefined
I am following this module on Alex Macmillian's Udemy COurse on react native:

In the 65th module, I am getting this error :

error screenshot

```<code>import React, { useState } from "react";

import {
    View,
    StyleSheet,
    Text,
    TouchableWithoutFeedback,
    Keyboard,
    Dimensions,
    Alert,
    TouchableOpacity,
} from "react-native";

import Card from '../components/Card'
import Colors from '../constants/Colors'
import Input from '../components/Input'
import CircleShape from '../components/CircleShape'
import HeartShape from '../components/HeartShape'
import CrossShape from '../components/CrossShape'

const StartGameScreen = props => {

    const [enteredValue, setEnteredValue] = useState('')
    const [selectedNumber, setSelectedNumber] = useState()
    const [confirmed, setConfirmed] = useState(false);

    //validates the non valid inputs in the inputText
    const changeTextHandler = inputText => {
        //replaces any character other than 0-9 with a blank
        setEnteredValue(inputText.replace(/[^0-9]/g, ''))
    }

    const resetInputHandler = () => {
        setEnteredValue('');
        Keyboard.dismiss()
        setConfirmed(false)
    }

    const confirmInputHandler = () => {

        const chosenNumber = parseInt(enteredValue);

        if (isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) {
            Alert.alert('Invalid String!', "Enter a number between 0 and 99",
                [{ text: "Okay", style: "default", onPress: resetInputHandler },
                { text: 'Cancel', style: 'destructive', onPress: resetInputHandler }])
            return;
        }

        setConfirmed(true);
        setSelectedNumber(chosenNumber)
        setEnteredValue('')
        Keyboard.dismiss()
    }

    let confirmedOutput;

    if (confirmed) {
        // confirmedOutput = <Text> You Chose : {selectedNumber} </Text>
        confirmedOutput = (
            <Card style={styles.circleShapeView}>
                <Text style={styles.selectedNumber}>{selectedNumber}</Text>
                <TouchableOpacity
                    activeOpacity={0.26}
                    style={styles.TriangleShapeView}
                    onPress={() => props.onStartGame(selectedNumber)}>
                </TouchableOpacity>
            </Card>
        )
    }

    return (
        <TouchableWithoutFeedback onPress={() => {
            Keyboard.dismiss()
        }}>
            <View style={styles.screen}>
                <Card style={styles.gameArea}>
                    <Input
                        style={styles.textInput}
                        keyboardType="numeric"
                        maxLength={2}
                        onChangeText={changeTextHandler}
                        value={enteredValue}
                        placeholder='0'
                        placeholderTextColor="#000" />
                    {/* <View style={styles.buttonContainer}>
                        <View style={styles.button}>
                            <Button
                                onPress={resetInputHandler}
                                title="Reset"
                                color="#fff" />
                        </View>
                        <View style={styles.button}>
                            <Button
                                title="Confirm"
                                color="#fff"
                                onPress={confirmInputHandler} />
                        </View>
                    </View> */}

                    <View style={styles.buttonContainer}>
                        <TouchableOpacity style={styles.heartButton} onPress={resetInputHandler}>
                            <CircleShape style={styles.circle}>
                                <HeartShape style={styles.heart}>

                                </HeartShape>
                            </CircleShape>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.crossButton} onPress={confirmInputHandler}>
                            <CircleShape style={styles.circle}>
                                <CrossShape style={styles.cross}></CrossShape>
                            </CircleShape>
                        </TouchableOpacity>
                    </View>
                </Card>
                {confirmedOutput}

            </View>
        </TouchableWithoutFeedback>
    );
}

export default StartGameScreen;

</code>```

The App.js file -->

```<code>import React, { useState } from 'react';
import { StyleSheet, View } from 'react-native';

import Header from './components/Header'
import StartGameScreen from './screens/StartGameScreen'
import GameScreen from './screens/GameScreen';

export default function App() {

  const [userNumber, setUserNumber] = useState();

  const startGameHandler = selectedNumber => {
    setUserNumber(selectedNumber);
  }

  let screen = <StartGameScreen onStartGame={startGameHandler} />;

  if (userNumber) {
    screen = <GameScreen userChoice={userNumber}/>
  }

  return (
    <View style={styles.screen}>
      <Header title="Guessie"></Header>
      <StartGameScreen></StartGameScreen>
    </View>
  );

}

const styles = StyleSheet.create({
  screen: {
    flex:1
  },
});
</code>```

How do i fix this error?

Type Error: props.onStartGame is not a function. (IN 'props.onStartGame(selectedNUmber)','props.onStartGame' is undefined)

答:
You need to pass screen variable instead of <StartGameScreen></StartGameScreen> ,

if first approach doesn't work trying passing the onStartGame={startGameHandler} like this in your code
<StartGameScreen onStartGame={startGameHandler} >
</StartGameScreen>

Body:
I am following this module on Alex Macmillian's Udemy COurse on react native:

In the 65th module, I am getting this error :

error screenshot

import React, { useState } from "react";

import {
    View,
    StyleSheet,
    Text,
    TouchableWithoutFeedback,
    Keyboard,
    Dimensions,
    Alert,
    TouchableOpacity,
} from "react-native";

import Card from '../components/Card'
import Colors from '../constants/Colors'
import Input from '../components/Input'
import CircleShape from '../components/CircleShape'
import HeartShape from '../components/HeartShape'
import CrossShape from '../components/CrossShape'

const StartGameScreen = props => {

    const [enteredValue, setEnteredValue] = useState('')
    const [selectedNumber, setSelectedNumber] = useState()
    const [confirmed, setConfirmed] = useState(false);

    //validates the non valid inputs in the inputText
    const changeTextHandler = inputText => {
        //replaces any character other than 0-9 with a blank
        setEnteredValue(inputText.replace(/[^0-9]/g, ''))
    }

    const resetInputHandler = () => {
        setEnteredValue('');
        Keyboard.dismiss()
        setConfirmed(false)
    }

    const confirmInputHandler = () => {

        const chosenNumber = parseInt(enteredValue);

        if (isNaN(chosenNumber) || chosenNumber <= 0 || chosenNumber > 99) {
            Alert.alert('Invalid String!', "Enter a number between 0 and 99",
                [{ text: "Okay", style: "default", onPress: resetInputHandler },
                { text: 'Cancel', style: 'destructive', onPress: resetInputHandler }])
            return;
        }

        setConfirmed(true);
        setSelectedNumber(chosenNumber)
        setEnteredValue('')
        Keyboard.dismiss()
    }

    let confirmedOutput;

    if (confirmed) {
        // confirmedOutput = <Text> You Chose : {selectedNumber} </Text>
        confirmedOutput = (
            <Card style={styles.circleShapeView}>
                <Text style={styles.selectedNumber}>{selectedNumber}</Text>
                <TouchableOpacity
                    activeOpacity={0.26}
                    style={styles.TriangleShapeView}
                    onPress={() => props.onStartGame(selectedNumber)}>
                </TouchableOpacity>
            </Card>
        )
    }

    return (
        <TouchableWithoutFeedback onPress={() => {
            Keyboard.dismiss()
        }}>
            <View style={styles.screen}>
                <Card style={styles.gameArea}>
                    <Input
                        style={styles.textInput}
                        keyboardType="numeric"
                        maxLength={2}
                        onChangeText={changeTextHandler}
                        value={enteredValue}
                        placeholder='0'
                        placeholderTextColor="#000" />
                    {/* <View style={styles.buttonContainer}>
                        <View style={styles.button}>
                            <Button
                                onPress={resetInputHandler}
                                title="Reset"
                                color="#fff" />
                        </View>
                        <View style={styles.button}>
                            <Button
                                title="Confirm"
                                color="#fff"
                                onPress={confirmInputHandler} />
                        </View>
                    </View> */}

                    <View style={styles.buttonContainer}>
                        <TouchableOpacity style={styles.heartButton} onPress={resetInputHandler}>
                            <CircleShape style={styles.circle}>
                                <HeartShape style={styles.heart}>

                                </HeartShape>
                            </CircleShape>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.crossButton} onPress={confirmInputHandler}>
                            <CircleShape style={styles.circle}>
                                <CrossShape style={styles.cross}></CrossShape>
                            </CircleShape>
                        </TouchableOpacity>
                    </View>
                </Card>
                {confirmedOutput}

            </View>
        </TouchableWithoutFeedback>
    );
}

export default StartGameScreen;

The App.js file -->

import React, { useState } from 'react';
import { StyleSheet, View } from 'react-native';

import Header from './components/Header'
import StartGameScreen from './screens/StartGameScreen'
import GameScreen from './screens/GameScreen';

export default function App() {

  const [userNumber, setUserNumber] = useState();

  const startGameHandler = selectedNumber => {
    setUserNumber(selectedNumber);
  }

  let screen = <StartGameScreen onStartGame={startGameHandler} />;

  if (userNumber) {
    screen = <GameScreen userChoice={userNumber}/>
  }

  return (
    <View style={styles.screen}>

      <StartGameScreen></StartGameScreen>
    </View>
  );

}

const styles = StyleSheet.create({
  screen: {
    flex:1
  },
});

How do i fix this error?

Type Error: props.onStartGame is not a function. (IN 'props.onStartGame(selectedNUmber)','props.onStartGame' is undefined)

Body:
You need to pass screen variable instead of <StartGameScreen></StartGameScreen> ,

if first approach doesn't work trying passing the onStartGame={startGameHandler} like this in your code <Header title="Guessie"></Header>
<StartGameScreen onStartGame={startGameHandler} >
</StartGameScreen>


问:
How to transfer values between classes on iPhone?
I want to send a string from one class to the other:

1) In class1, I add a property to hold the string:

```<code>@property (nonatomic, retain) NSString *str; </code>```

2) and a method to send back a string:

```<code>
-(NSString *)sendBackStr:(NSString *)strURL
{
    NSString *str = [[NSString alloc] stringWithString:strURL];
    return str;
}
</code>```

3) In class2, I add a property to hold the received string:

```<code>@property (nonatomic, retain) NSString *returnStr; </code>```

4) and the following code:

```<code>Class1 *c1 = [[Class1 alloc] init];
returnStr = [c1 sendBackStr:@"URL"];</code>```

But the program stops at returnStr = [c1 sendBackStr:@"URL"]; Any ideas about what's wrong with it?

答:
stringWithString: is a message that needs to be sent to the NSString class, not an instance of your class (returned via alloc).

The correct code should be:

```<code>-(NSString *)sendBackStr:(NSString *)strURL
{
    return [NSString stringWithString:strURL];
}
</code>```

You might want to familarize yourself more about the idioms around allocation, retention, and autoreleasing of pointers. If you wanted to alloc this string for some reason and return it from the sendBackStr: message, then you would probably want this code:

```<code>-(NSString *)sendBackStr:(NSString *)strURL
{
    return [[[NSString alloc] initWithString:strURL] autorelease];
}
</code>```

OwnerDisplayName: iphony

ContentLicense: CC BY-SA 2.5

Body:
I want to send a string from one class to the other:

1) In class1, I add a property to hold the string:

@property (nonatomic, retain) NSString *str;

2) and a method to send back a string:

-(NSString *)sendBackStr:(NSString *)strURL
{
    NSString *str = [[NSString alloc] stringWithString:strURL];
    return str;
}

3) In class2, I add a property to hold the received string:

@property (nonatomic, retain) NSString *returnStr;

4) and the following code:

Class1 *c1 = [[Class1 alloc] init];
returnStr = [c1 sendBackStr:@"URL"];

But the program stops at returnStr = [c1 sendBackStr:@"URL"]; Any ideas about what's wrong with it?

Body:
stringWithString: is a message that needs to be sent to the NSString class, not an instance of your class (returned via alloc).

The correct code should be:

-(NSString *)sendBackStr:(NSString *)strURL
{
    return [NSString stringWithString:strURL];
}

You might want to familarize yourself more about the idioms around allocation, retention, and autoreleasing of pointers. If you wanted to alloc this string for some reason and return it from the sendBackStr: message, then you would probably want this code:

-(NSString *)sendBackStr:(NSString *)strURL
{
    return [[[NSString alloc] initWithString:strURL] autorelease];
}

OwnerDisplayName: Bill Heyman


问:
iPhone : How do I add existing project in "git local repository"?
I have existing project and I want to add it in "git local repository".

How can I do that ?

答:
Open the Terminal and go to your project directory – the one with *.xcodeproj.

Type git init . to initialize a Git repository there.

Now you don't want all the files under source control, so Git allows you to ignore some of them by including them in a file .gitignore. You can check this to find out

Open the project and your task is done. However it would be better to head to the Organizer Window and do a commit of all the files.

Now your project is backed by a git repository.


问:
What is the main advantage of using SFSafariViewController?
I am not getting proper understanding of what is the main adavantage of using SFSafariViewController, if we are using [[UIApplication sharedApplication] openUrl: strUrl];

What are the difference between both?

答: In case of [UIApplication openURL:], Safari is launched and your app is no longer in foreground and, generally, is not guaranteed to be running. In contrast, SFSafariViewController is a part of your app and you retain some control over it as a UIViewController or with SFSafariViewControllerDelegate methods. Which one to use depends on what you want to achieve. There is also WKWebView which gives you more control over the content and navigation but lacks some features of Safari such as content blocking.</p>


问:
jQuery UI Dialog strips Form Attributes and Non-form Elements
Got an issue I'm not sure how to solve with jQuery. I've been using the jQuery UI library to make a popup with a form on it.

However the jQuery code that controls the submission of the form can't find the form because of what looks like jQuery UI Dialog is removing all the attributes from the actual form upon dialog creation.

Here is a simplified version of the popup:

And turning it into a dialog box with jQuery is done as follows:

$("#dialog").dialog({
  autoOpen: false,
  show: {
    effect: "fade",
    duration: 250
  },
  hide: {
    effect: "fade",
    duration: 250
  },

  draggable: false,
  resizable: false,
  width: calculatedSize,
  dialogClass: 'fixed-dialog',
  closeOnEscape: true,
  modal: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dialog" class="about-dialog">
  <div class="dialog-bg-container">
    <div class="header-row">
      <button id="close-button" class="dialog-close">X</button>
    </div>

    <form id="popup-form" action="api/email.php">
      <input id="popup-email" class="email-input spacing-3" type="email" placeholder="Your email here" required><input id="popup-submit" class="submit-button spacing-3" type="submit" value="Sign me up!">

      <div id="popup-form-alert" class="spacing-1"></div>
    </form>
  </div>
</div></code>```

Upon inspecting the code with Chrome's tools, I can see that the "id" and "action" attributes of the form
are removed, as well as the div with the id of "popup-form-alert". If I comment out the jQuery UI code above, my form is left in-tact with no issues.

One thing to keep in mind is that I do not want to use a standard jQuery UI Dialog Form as shown on their docs (https://jqueryui.com/dialog/#modal-form) as I need to have a custom submit button placed where I want it to be.

Does anyone have any suggestions on how to stop jQuery stripping my form?

Many thanks!

答:
After more investigation, I discovered that a duplicate dialog form was the cause of the issue. Upon commenting out the duplicate, the jQuery UI Dialog would preserve my form attributes.

I'm still unsure as to why jQuery UI decides to strip the tags and would be interested in an explanation of this if anyone is able to!

Body:
Got an issue I'm not sure how to solve with jQuery. I've been using the jQuery UI library to make a popup with a form on it.

However the jQuery code that controls the submission of the form can't find the form because of what looks like jQuery UI Dialog is removing all the attributes from the actual form upon dialog creation.

Here is a simplified version of the popup:

And turning it into a dialog box with jQuery is done as follows:

$("#dialog").dialog({
  autoOpen: false,
  show: {
    effect: "fade",
    duration: 250
  },
  hide: {
    effect: "fade",
    duration: 250
  },

  draggable: false,
  resizable: false,
  width: calculatedSize,
  dialogClass: 'fixed-dialog',
  closeOnEscape: true,
  modal: true
});

      <button id="close-button" class="dialog-close">X</button>

    <form id="popup-form" action="api/email.php">
      <input id="popup-email" class="email-input spacing-3" type="email" placeholder="Your email here" required><input id="popup-submit" class="submit-button spacing-3" type="submit" value="Sign me up!">

    </form>

Upon inspecting the code with Chrome's tools, I can see that the "id" and "action" attributes of the form
are removed, as well as the div with the id of "popup-form-alert". If I comment out the jQuery UI code above, my form is left in-tact with no issues.

One thing to keep in mind is that I do not want to use a standard jQuery UI Dialog Form as shown on their docs (https://jqueryui.com/dialog/#modal-form) as I need to have a custom submit button placed where I want it to be.

Does anyone have any suggestions on how to stop jQuery stripping my form?

Many thanks!


问:
(Collapsing)Toolbar title resets its position after Snackbar appearance
I have a layout with CollapsingToolbarLayout and CoordinatorLayout as root element.
Whenever a Snackbar is shown in the activity the title of the toolbar resets its position to the default expanded title position of the CollapsingToolbar even if the toolbar is not (fully) expanded.

The second picture shows that the title is fixed no matter if the toolbar expands or not.

The result is the same when I call snackbar.show() in activity or fragment.

My layout structure looks like this:

```<code><CoordinatorLayout>
<AppBarLayout>
    <CollapsingToolbarLayout>
        <Toolbar />
        <TabLayout />
    </CollapsingToolbarLayout>
</AppBarLayout>
<ViewPager />
<FloatingActionButton />
</code>```

I use the latest dependencies for appcompat and design library (v24.2.1).
I hope that's enough information and somebody has an idea how to solve the issue :P

EDIT:
Also in the template when you start a new project and choose Scrolling activity the same problem appears when snackbar.show()is called. So it's a library issue.

答:
```<code>// Try This (Kotlin) :
    val collapsingToolbar = findViewById<CollapsingToolbarLayout>(R.id.collapsing_toolbar)
            collapsingToolbar.title = " "
            val appBarLayout = findViewById<AppBarLayout>(R.id.appbar)
            appBarLayout.setExpanded(true)
            appBarLayout.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
                var isShow = false
                var scrollRange = -1
                @SuppressLint("DefaultLocale")
                override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
                    if (scrollRange == -1) {
                        scrollRange = appBarLayout.totalScrollRange
                    }
                    if (scrollRange + verticalOffset == 0) {
                        collapsingToolbar.title = "YOUR_TITLE"
                        isShow = true
                    } else if (isShow) {
                        collapsingToolbar.title = " "
                        isShow = false
                    }
                }
            })
</code>```

Body:
I have a layout with CollapsingToolbarLayout and CoordinatorLayout as root element.
Whenever a Snackbar is shown in the activity the title of the toolbar resets its position to the default expanded title position of the CollapsingToolbar even if the toolbar is not (fully) expanded.

The second picture shows that the title is fixed no matter if the toolbar expands or not.

The result is the same when I call snackbar.show() in activity or fragment.

My layout structure looks like this:

<CoordinatorLayout>
<AppBarLayout>
    <CollapsingToolbarLayout>
        <Toolbar />
        <TabLayout />
    </CollapsingToolbarLayout>
</AppBarLayout>
<ViewPager />
<FloatingActionButton />

I use the latest dependencies for appcompat and design library (v24.2.1).
I hope that's enough information and somebody has an idea how to solve the issue :P

EDIT:
Also in the template when you start a new project and choose Scrolling activity the same problem appears when snackbar.show()is called. So it's a library issue.