问:
Achieving simple tasks with vue (Laravel)
Ive recently started learning vue.js (Coming from angular 2+), Ive watched a few tutorials and it all seemed to go swimmingly.

As always after ive finished doing the tutorials, I create a little app for myself just to ensure I know what im doing. But I seem to be really stuggling with Vue.

So far the app is very simple. A user posts a story, The story has comments.... simple as that

I got to the point where I wanted the user to be able to edit there comment, But It seems I cannot work out how to do this. I would like it so that when the user clicks the edit button the comment changes to a textarea or an input of some kind.

At this point I have not used to vue in the project at all. All the pages are rendered with blade.

Im trying to get my head round how you are meant to use it? So I have the following questions

Are you meant to use multiple vue components, Loop in blade and create a  on each iteration?

```<code><div id="app">
    @foreach($comments as $comment)
        <comment {Stuff passed in}></comment>
    @endforeach
</div>
</code>```

Are you meant to have that one vue "app" that gets the data from the api and loop them within the vue component?

```<code>    const comments = new Vue({
        el: '#comments#'
    })
</code>```

As all the site is a multipage application (Dont want to go down the SPA route) and lets say I now have a products page, The product has a list of attributes (Pretty much the same as comments). Do I create another vue app?

```<code>const comments = new Vue({
    el: '#comments',
});

const productThings = new Vue({
    el: '#productThings'
})
</code>```

If I want to sections on a page controlled by vue (Lets say the comment section and another interactive section) Would this have to be 2 vue "apps" like in the above code example, One that is "comments" and one that is "somethingelse" or would the whole page have to be one big vue component.

```<code>// Comment loop, How ever this gets handled with vue
// Some other content
// Another place I need it to be interactive````
```

This seems very complicated just to acheive simple tasks, Also seems as if it would get out of control very quickly (I could only imagine coming back to this after 6 months and trying to work out what was going on).

You can see how confused I am with it all, The more I read the more confused I seem to get.

答:
Vue is used to create fully fledged SPA web applications but can only be used as a drop-in without build process for simpler use cases. Usually you would integrated Vue Router to create a multi-page experience, but you can also just define single components and mount them on an element. In your case, with the mixing of PHP and Vue, I would suggest going for the way without build process and drop-in components.

Vue is a JavaScript framework with static templates. So, you should not generate dynamic templates and then pass them to Vue, but rather define static templates and then pass only the data to Vue. You can e.g. fetch the data via Ajax in a JSON format and then process this data to e.g. render a list of comments.

If you go for using Vue as a drop-in without routing, you need to mount two separate Vue instances on their respective pages. You can of course reuse parts of these components. Keep in mind, that you cannot share data between these instances (one of the benefits of using a SPA). You could however share the data via LocalStorage/SessionStorage/IndexedDB.

One common way to access the data is via a REST API (via Ajax/fetch). You would provide the data in a proper format (usually JSON) behind a HTTP REST interface. Then, Vue fetches the data (see also axios for easy data fetching) and then uses it to build up the components. Another approach (less nice) is to just render the data with your server-side programming language and put it into a JavaScript variable, so, that you have access to the data on runtime.

Here is a basic example. Keep in mind that binding a value from a property is an anti-pattern and therefore I did not bind the comment text in a two-way manner. I have also hard-coded the comment data and do not fetch it from remote.

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('comment', {
  data () {
    return {
      commentAsInput: false
    };
  },
  props: {
    commentObject: {
      type: Object,
      required: true
    }
  },
  template: `

      {{ commentObject.text }}

    <textarea :value="commentObject.text" v-if="commentAsInput" />

`
});

Vue.component('comments', {
  data () {
    return {
      comments: [{ id: 124, text: 'fkgnsdklgnl' }, { id: 2135325, text: 'nlekng345gn' }]
    }
  },
  template: `

Comments

      <comment :comment-object="comment" />

`
});

new Vue({
  el: '#app',
  template: `<comments />`
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div></code>```

Body:
Ive recently started learning vue.js (Coming from angular 2+), Ive watched a few tutorials and it all seemed to go swimmingly.

As always after ive finished doing the tutorials, I create a little app for myself just to ensure I know what im doing. But I seem to be really stuggling with Vue.

So far the app is very simple. A user posts a story, The story has comments.... simple as that

I got to the point where I wanted the user to be able to edit there comment, But It seems I cannot work out how to do this. I would like it so that when the user clicks the edit button the comment changes to a textarea or an input of some kind.

At this point I have not used to vue in the project at all. All the pages are rendered with blade.

Im trying to get my head round how you are meant to use it? So I have the following questions

Are you meant to use multiple vue components, Loop in blade and create a  on each iteration?

    @foreach($comments as $comment)
        <comment {Stuff passed in}></comment>
    @endforeach

Are you meant to have that one vue "app" that gets the data from the api and loop them within the vue component?

    const comments = new Vue({
        el: '#comments#'
    })

As all the site is a multipage application (Dont want to go down the SPA route) and lets say I now have a products page, The product has a list of attributes (Pretty much the same as comments). Do I create another vue app?

const comments = new Vue({
    el: '#comments',
});

const productThings = new Vue({
    el: '#productThings'
})

If I want to sections on a page controlled by vue (Lets say the comment section and another interactive section) Would this have to be 2 vue "apps" like in the above code example, One that is "comments" and one that is "somethingelse" or would the whole page have to be one big vue component.

// Comment loop, How ever this gets handled with vue
// Some other content
// Another place I need it to be interactive````

This seems very complicated just to acheive simple tasks, Also seems as if it would get out of control very quickly (I could only imagine coming back to this after 6 months and trying to work out what was going on).

You can see how confused I am with it all, The more I read the more confused I seem to get.

Body:
Vue is used to create fully fledged SPA web applications but can only be used as a drop-in without build process for simpler use cases. Usually you would integrated Vue Router to create a multi-page experience, but you can also just define single components and mount them on an element. In your case, with the mixing of PHP and Vue, I would suggest going for the way without build process and drop-in components.

Vue is a JavaScript framework with static templates. So, you should not generate dynamic templates and then pass them to Vue, but rather define static templates and then pass only the data to Vue. You can e.g. fetch the data via Ajax in a JSON format and then process this data to e.g. render a list of comments.

If you go for using Vue as a drop-in without routing, you need to mount two separate Vue instances on their respective pages. You can of course reuse parts of these components. Keep in mind, that you cannot share data between these instances (one of the benefits of using a SPA). You could however share the data via LocalStorage/SessionStorage/IndexedDB.

One common way to access the data is via a REST API (via Ajax/fetch). You would provide the data in a proper format (usually JSON) behind a HTTP REST interface. Then, Vue fetches the data (see also axios for easy data fetching) and then uses it to build up the components. Another approach (less nice) is to just render the data with your server-side programming language and put it into a JavaScript variable, so, that you have access to the data on runtime.

Here is a basic example. Keep in mind that binding a value from a property is an anti-pattern and therefore I did not bind the comment text in a two-way manner. I have also hard-coded the comment data and do not fetch it from remote.

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('comment', {
  data () {
    return {
      commentAsInput: false
    };
  },
  props: {
    commentObject: {
      type: Object,
      required: true
    }
  },
  template: `<div>
    <a href="#" @click="commentAsInput = !commentAsInput" v-if="!commentAsInput">
      {{ commentObject.text }}
    </a>
    <textarea :value="commentObject.text" v-if="commentAsInput" />
  </div>`
});

Vue.component('comments', {
  data () {
    return {
      comments: [{ id: 124, text: 'fkgnsdklgnl' }, { id: 2135325, text: 'nlekng345gn' }]
    }
  },
  template: `<div>
    <h1>Comments</h1>
    <div v-for="comment in comments" :key="comment.id">
      <comment :comment-object="comment" />
    </div>
  </div>`
});

new Vue({
  el: '#app',
  template: `<comments />`
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>


来源: stackexchange

问:
get position of clicked item in recyclerView using dataBinding
thank you for reading my question,
I've Implemented onClick in recyclerView using dataBinding but I can send the object itself to click function but I need the item position is it possible to get item position in onClick?
here is how click is implemented in the recyclerView item:

```<code>    android:onClick="@{ (v) -> model.click(obj) }"
</code>```

答:
You can use adapterPosition in view holder to pass item position to ItemView and then you can pass itemPosition to android:onClick="@{ (v) -> model.click(obj, itemPosition) }"

```<code> class GeneralHolder<DataModel, ClickListner>(
        private val binding: ViewDataBinding,
        val listener: ClickListner
    ) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: DataModel) {
            binding.setVariable(BR.item, data)
            binding.setVariable(BR.presenter, listener)
            binding.setVariable(BR.itemPosition, adapterPosition)
            binding.executePendingBindings()
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
thank you for reading my question,
I've Implemented onClick in recyclerView using dataBinding but I can send the object itself to click function but I need the item position is it possible to get item position in onClick?
here is how click is implemented in the recyclerView item:

    android:onClick="@{ (v) -> model.click(obj) }"

Body:
You can use adapterPosition in view holder to pass item position to ItemView and then you can pass itemPosition to android:onClick="@{ (v) -> model.click(obj, itemPosition) }"

 class GeneralHolder<DataModel, ClickListner>(
        private val binding: ViewDataBinding,
        val listener: ClickListner
    ) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: DataModel) {
            binding.setVariable(BR.item, data)
            binding.setVariable(BR.presenter, listener)
            binding.setVariable(BR.itemPosition, adapterPosition)
            binding.executePendingBindings()
        }
    }


问:
How to run external jar functions in spark-shell
I created a jar package from a project by this file-tree:

```<code>build.sbt
src/main
src/main/scala
src/main/scala/Tester.scala
src/main/scala/main.scala
</code>```

where Tester is a class by a function (name is print()) and main has an object to run that prints "Hi!" (from spark documention)
created a jar file by sbt successfully and worked well in spark-submit

now I wanna add it into spark-shell and use Tester class as a class to create objects and ...
I added the jar file into spark-default.conf but:

```<code>scala> val t = new Tester();
<console>:23: error: not found: type Tester
       val t = new Tester();
</code>```

答:
I tried two options and both worked for me.

spark-shell --jars <path of jar>

open spark-shell    -Type :help,you will get all the available help.
use below to add

:require /full_path_of_jar

ContentLicense: CC BY-SA 3.0

Body:
I created a jar package from a project by this file-tree:

build.sbt
src/main
src/main/scala
src/main/scala/Tester.scala
src/main/scala/main.scala

where Tester is a class by a function (name is print()) and main has an object to run that prints "Hi!" (from spark documention)
created a jar file by sbt successfully and worked well in spark-submit

now I wanna add it into spark-shell and use Tester class as a class to create objects and ...
I added the jar file into spark-default.conf but:

scala> val t = new Tester();
<console>:23: error: not found: type Tester
       val t = new Tester();


问:
Materialze Input bottom border-bottom color not changing on focus
I have the following html:

          <form class="col">
            <input type="text" class="input-field"></input>
            Email

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

          </form>

```

<p>and the following css:</p>

<pre class="lang-css prettyprint-override"><code>.input-field input[type=text]:focus {
  border-bottom: 1px solid #4ec632;
  box-shadow: 0 1px 0 0 #4ec632;
}
</code>```

The bottom outline of the input when focused is still the default blue-ish color instead of the green #4ec632. I've tried multiple solutions and referred to the materialize documentation, but nothing has seemed to work thus far. Any ideas on what I should try?

答:
To control the focus border-color the way that materialize does it:

1) Use the correct markup

```<code><div class="input-field">
  <input id="first_name2" type="text" class="validate">
  <label class="active" for="first_name2">First Name</label>
</div>
</code>```

This is an input/label pair nested inside div with a class of .input-field - the wrapper allows the label to move when focussed. (It is not supposed to be applied to the input itself as in your example). You are also missing a label (which may be deliberate).

2) Use the correct css override:

```<code>input[type=text]:not(.browser-default):focus {
     border-bottom: 1px solid firebrick !important;
     -webkit-box-shadow: 0 1px 0 0 firebrick !important;
     box-shadow: 0 1px 0 0 firebrick !important;
   }

 input[type=text]:not(.browser-default):focus:not([readonly])+label {
     color: firebrick;
 }
</code>```

Repalce firebrick with your desired colour.

Codepen.

Body:
I have the following html:

          <form class="col">
            <input type="text" class="input-field"></input>
            Email

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

          </form>

and the following css:

.input-field input[type=text]:focus {
  border-bottom: 1px solid #4ec632;
  box-shadow: 0 1px 0 0 #4ec632;
}

The bottom outline of the input when focused is still the default blue-ish color instead of the green #4ec632. I've tried multiple solutions and referred to the materialize documentation, but nothing has seemed to work thus far. Any ideas on what I should try?

Body:
To control the focus border-color the way that materialize does it:

1) Use the correct markup

<div class="input-field">
  <input id="first_name2" type="text" class="validate">
  <label class="active" for="first_name2">First Name</label>
</div>

This is an input/label pair nested inside div with a class of .input-field - the wrapper allows the label to move when focussed. (It is not supposed to be applied to the input itself as in your example). You are also missing a label (which may be deliberate).

2) Use the correct css override:

input[type=text]:not(.browser-default):focus {
     border-bottom: 1px solid firebrick !important;
     -webkit-box-shadow: 0 1px 0 0 firebrick !important;
     box-shadow: 0 1px 0 0 firebrick !important;
   }

 input[type=text]:not(.browser-default):focus:not([readonly])+label {
     color: firebrick;
 }

Repalce firebrick with your desired colour.

Codepen.


问:
psycopg2.extras.DictCursor not returning dict in postgres
Im using psycopg2 to access postgres database using the below query. In order to return a dictionary from the executed query, im using DictCursor in my cursor but still my output is a list and not a dictonary.

Here is the program and output below.

```<code>import psycopg2.extras

try:
    conn = psycopg2.connect("user='postgres' host='localhost' password='postgres'",
                            )
except:
    print "I am unable to connect to the database"

cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("""SELECT datname from pg_database""")

rows = cur.fetchall()
print "\nShow me the databases:\n"
print rows
</code>```

Output:-

```<code>[['template1'], ['template0'], ['postgres'], ['iip'], ['test'], ['test_postgres'], ['testdb']]
</code>```

答:
For those who came where because they really like the easy reference of the dictionary for column:value record representation, the answer by PRMoureu which notes that the DictRow has all the usual dictionary logic means that you can iterate over the DictRow with .items() and get the key:value pairs.

```<code>rows = cur.fetchall()
row_dict = [{k:v for k, v in record.items()} for record in rows]
</code>```

Will turn your list of DictRow records into a list of dict records.

Body:
Im using psycopg2 to access postgres database using the below query. In order to return a dictionary from the executed query, im using DictCursor in my cursor but still my output is a list and not a dictonary.

Here is the program and output below.

import psycopg2.extras

try:
    conn = psycopg2.connect("user='postgres' host='localhost' password='postgres'",
                            )
except:
    print "I am unable to connect to the database"

cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("""SELECT datname from pg_database""")

rows = cur.fetchall()
print "\nShow me the databases:\n"
print rows

Output:-

[['template1'], ['template0'], ['postgres'], ['iip'], ['test'], ['test_postgres'], ['testdb']]

Body:
For those who came where because they really like the easy reference of the dictionary for column:value record representation, the answer by PRMoureu which notes that the DictRow has all the usual dictionary logic means that you can iterate over the DictRow with .items() and get the key:value pairs.

rows = cur.fetchall()
row_dict = [{k:v for k, v in record.items()} for record in rows]

Will turn your list of DictRow records into a list of dict records.


问:
consuming from context provider returns element type is invalid
I have a component that queries a collection based on a user input collected from an input field. When the user inputs his value the app redirects to another page where I want to display my searchResults. I am trying to achieve this using Context. I have created my Context in the first component, but when I use the input field to type something and send it I get this error:

```<code>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `SearchResultsPage`.
</code>```

What am I missing here and how can I show searchResults in my SearchResults component?

here is my first component with the input field:

```<code>import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={this.state.searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export default Search;
</code>```

and here is my searchResults component:

```<code>import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import Search from '../Search/Search.jsx';
import SearchContext from '../../components/Search/Search.jsx';
let title = 'Search Results'

class SearchResultsPage extends Component {
    render() {
        return (
            <div>
                <CustomHeader
                    title={title}
                />

                <Search />
                <SearchContext.Consumer>
                    {value => value.postContent}
                </SearchContext.Consumer>
                <Footer />
            </div>
        )
    }
};

export default SearchResultsPage;

</code>```

答:
SearchContext is exported as a named export, so you need to import it accordingly:

```<code>import { SearchContext } from '../../components/Search/Search.jsx';
</code>```

Also, since Search and SearchContext are in the same file, you can combine their imports (assuming ../../components/Search and ../Search/ are the same):

```<code>import Search, { SearchContext } from '../Search/Search.jsx';
</code>```

Body:
I have a component that queries a collection based on a user input collected from an input field. When the user inputs his value the app redirects to another page where I want to display my searchResults. I am trying to achieve this using Context. I have created my Context in the first component, but when I use the input field to type something and send it I get this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `SearchResultsPage`.

What am I missing here and how can I show searchResults in my SearchResults component?

here is my first component with the input field:

import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={this.state.searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export default Search;

and here is my searchResults component:

import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import Search from '../Search/Search.jsx';
import SearchContext from '../../components/Search/Search.jsx';
let title = 'Search Results'

class SearchResultsPage extends Component {
    render() {
        return (

                <CustomHeader
                    title={title}
                />

                <Search />
                <SearchContext.Consumer>
                    {value => value.postContent}
                </SearchContext.Consumer>

        )
    }
};

export default SearchResultsPage;

Body:
SearchContext is exported as a named export, so you need to import it accordingly:

import { SearchContext } from '../../components/Search/Search.jsx';

Also, since Search and SearchContext are in the same file, you can combine their imports (assuming ../../components/Search and ../Search/ are the same):

import Search, { SearchContext } from '../Search/Search.jsx';


问:
Numpy dot product along specific axes
I have a 512x512 image array and I want to perform operations on 8x8 blocks. At the moment I have something like this:

```<code>output = np.zeros(512, 512)

for i in range(0, 512, 8):
    for j in rangerange(0, 512, 8):
        a = input[i:i+8, j:j+8]
        b = some_other_array[i:i+8, j:j+8]
        output[i:i+8, j:j+8] = np.dot(a, b)
</code>```

where a & b are 8x8 blocks derived from the original array. I would like to speed up this code by using vectorised operations. I have reshaped my inputs like this:

```<code>input = input.reshape(64, 8, 64, 8)
some_other_array = some_other_array.reshape(64, 8, 64, 8)
</code>```

How could I perform a dot product on only axes 1 & 3 to output an array of shape (64, 8, 64, 8)?

I have tried np.tensordot(input, some_other_array, axes=([0, 1], [2, 3])) which gives the correct output shape, but the values do not match the output from the loop above. I've also looked at np.einsum but I haven't come across a simple example with what I'm trying to achieve.

答:
They'll work if you reorder them a bit. If input and some_other_array are both shaped (64,8,64,8), then:

```<code>input = input.transpose(0,2,1,3)
some_other_array = some_other_array.transpose(0,2,1,3)
</code>```

This will reorder them to 64,64,8,8. At this point you can compute a matrix multiplication. Do note that you need matmul to compute the block products, and not dot, which will try to multiply the entire matrices.

```<code>output = input @ some_other_array
output = output.transpose(0,2,1,3)
output = output.reshape(512,512)
</code>```

Title: Numpy dot product along specific axes

Body:
I have a 512x512 image array and I want to perform operations on 8x8 blocks. At the moment I have something like this:

output = np.zeros(512, 512)

for i in range(0, 512, 8):
    for j in rangerange(0, 512, 8):
        a = input[i:i+8, j:j+8]
        b = some_other_array[i:i+8, j:j+8]
        output[i:i+8, j:j+8] = np.dot(a, b)

where a & b are 8x8 blocks derived from the original array. I would like to speed up this code by using vectorised operations. I have reshaped my inputs like this:

input = input.reshape(64, 8, 64, 8)
some_other_array = some_other_array.reshape(64, 8, 64, 8)

How could I perform a dot product on only axes 1 & 3 to output an array of shape (64, 8, 64, 8)?

I have tried np.tensordot(input, some_other_array, axes=([0, 1], [2, 3])) which gives the correct output shape, but the values do not match the output from the loop above. I've also looked at np.einsum but I haven't come across a simple example with what I'm trying to achieve.

Body:
They'll work if you reorder them a bit. If input and some_other_array are both shaped (64,8,64,8), then:

input = input.transpose(0,2,1,3)
some_other_array = some_other_array.transpose(0,2,1,3)

This will reorder them to 64,64,8,8. At this point you can compute a matrix multiplication. Do note that you need matmul to compute the block products, and not dot, which will try to multiply the entire matrices.

output = input @ some_other_array
output = output.transpose(0,2,1,3)
output = output.reshape(512,512)


问:
audio not send react-native-webrtc
In prepareWebrtc function at the end I have the following code:

```<code>MediaStreamTrack.getSources(sourceInfos => {
  var isFront = camera_front
  console.log(sourceInfos);
  let videoSourceId;
  for (const i = 0; i < sourceInfos.length; i++) {
    const sourceInfo = sourceInfos[i];
    if(sourceInfo.kind == "video" &&
       sourceInfo.facing == (isFront ? "front" : "back")) {
      videoSourceId = sourceInfo.id;
    }
  }
  console.log("videoSourceId:" + videoSourceId)
  getUserMedia({
    "audio": true,
    "video":false
  }, (stream) => {
    streamsDone(handleId, jsep, media, callbacks, stream)
  },
  // TODO: add error handling
  () => undefined
  );
});
</code>```

When "video" is true for android and when video is{optional: [{sourceId: videoSourceId}] } for ios, audio gets transmitted, however, then I have to ask for camera permissions which I don't want to do. When I do "video":false, audio can be received by my app; however, it doesn't get send.

答:
First check the permissions in androidmanifest.xml. Below permissions should be there.

```<code>    <uses-permission android:name="android.permission.MICROPHONE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</code>```

Next check the candidate data you are sending, it should contain
"sdpMid": "audio"

Now if the audio is still not there, it could be because of react-native-webrtc is playing audio on earphone to change it to speaker use  https://github.com/react-native-webrtc/react-native-incall-manager

Title: audio not send react-native-webrtc

Body:
In prepareWebrtc function at the end I have the following code:

MediaStreamTrack.getSources(sourceInfos => {
  var isFront = camera_front
  console.log(sourceInfos);
  let videoSourceId;
  for (const i = 0; i < sourceInfos.length; i++) {
    const sourceInfo = sourceInfos[i];
    if(sourceInfo.kind == "video" &&
       sourceInfo.facing == (isFront ? "front" : "back")) {
      videoSourceId = sourceInfo.id;
    }
  }
  console.log("videoSourceId:" + videoSourceId)
  getUserMedia({
    "audio": true,
    "video":false
  }, (stream) => {
    streamsDone(handleId, jsep, media, callbacks, stream)
  },
  // TODO: add error handling
  () => undefined
  );
});

When "video" is true for android and when video is{optional: [{sourceId: videoSourceId}] } for ios, audio gets transmitted, however, then I have to ask for camera permissions which I don't want to do. When I do "video":false, audio can be received by my app; however, it doesn't get send.

Body:
First check the permissions in androidmanifest.xml. Below permissions should be there.

    <uses-permission android:name="android.permission.MICROPHONE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

Next check the candidate data you are sending, it should contain
"sdpMid": "audio"

Now if the audio is still not there, it could be because of react-native-webrtc is playing audio on earphone to change it to speaker use  https://github.com/react-native-webrtc/react-native-incall-manager


问:
Is Nlog not archiving all files?
I'm logging one file per day, and I want to move the old ones to a subfolder every month. I'm feeling there is something off here.

These are my current settings. For testing purposes, I changed it to archive every minute:

<target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}"
            fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
            archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
            archiveDateFormat="yyyy-MM-dd"
            archiveNumbering="Date"
            archiveEvery="Minute"
      />
```

<p>Consider the actual date for this test: May 29th 2020.</p>

<ol>
<li>If I run my app now, the file <code>2020-05-29.log</code> will be created in the <code>LOG</code> folder.</li>
</ol>

```
    .
    ├── ...
    ├── LOG
    │   └── 2020-05-29.log
    └── ...

```

<ol start="2">
<li>If I run my app one minute later, the file above will be archived to the newly created subfolder <code>OLD_LOGS</code> and a new file will be created in the <code>LOG</code> folder.</li>
</ol>

```   .
   ├── ...
   ├── LOG
   │   ├── 2020-05-29.log
   │   ├── OLD_LOGS
   │      └── 2020-05-29.log
   └── ...
```

<ol start="3">
<li>If I change my clock to the next day (May 30th 2020) a new file will be created <code>2020-05-30.log</code></li>
</ol>

```   .
   ├── ...
   ├── LOG
   │   ├── 2020-05-29.log
   │   ├── 2020-05-30.log
   │   ├── OLD_LOGS
   │      └── 2020-05-29.log
   └── ...
```

<ol start="4">
<li>If I run my app one minute later, the <code>2020-05-30.log</code> file will be archived</li>
</ol>

```  .
  ├── ...
  ├── LOG
  │   ├── 2020-05-29.log
  │   ├── 2020-05-30.log
  │   ├── OLD_LOGS
  │      ├── 2020-05-29.log
  │      └── 2020-05-30.log
  └── ...
```

Shouldn't the LOG/2020-05-29.log file have been archived?

答:
There is a problem in your configuration for per minute archival.

NLog starts overriding the old file because your file format is yyyy-MM-DD.
The correct configuration for per minute achieving, add below code.

```<code>    <target name="kFile" xsi:type="File"
        layout="${longdate} ${logger} ${message}${exception:format=ToString}"
        fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
        archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
        archiveDateFormat="yyyy-MM-dd-mm"
        archiveNumbering="Date"
        archiveEvery="Minute"
  />
</code>```

Changed format to yyyy-MM-dd-mm.

This change created below files in my folder

```<code>  .
├── ...
├── LOG
│   ├── 2020-05-30.log
│   ├── OLD_LOGS
│      ├── 2020-05-30-01.log
│      └── 2020-05-30-02.log
└── ...
</code>```

I checked with the same configuration as yours
and the result was

So the NLog archiving feature does not work the way you want it to. It just places the last file of the month to the archive folder not all.

So, you have to configure NLog to archive files every day and set max file number to something like 365 to keep them for one year.
Apply below configuration:

```<code>    <target name="kFile" xsi:type="File"
        layout="${longdate} ${logger} ${message}${exception:format=ToString}"
        fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
        archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
        archiveDateFormat="yyyy-MM-dd"
        archiveNumbering="Date"
        archiveEvery="Day"
        maxArchiveFiles="365"
  />
</code>```

This way you will get one file per day and the file will be transferred to the archive folder each day. The archive will keep the file for one year. You may want to review the max archive file though. Because it may increase the size of the folder based on how much you log.

Title: Is Nlog not archiving all files?

Body:
I'm logging one file per day, and I want to move the old ones to a subfolder every month. I'm feeling there is something off here.

These are my current settings. For testing purposes, I changed it to archive every minute:

<target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}"
            fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
            archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
            archiveDateFormat="yyyy-MM-dd"
            archiveNumbering="Date"
            archiveEvery="Minute"
      />

Consider the actual date for this test: May 29th 2020.

If I run my app now, the file 2020-05-29.log will be created in the LOG folder.

    .
    ├── ...
    ├── LOG
    │   └── 2020-05-29.log
    └── ...

If I run my app one minute later, the file above will be archived to the newly created subfolder OLD_LOGS and a new file will be created in the LOG folder.

   .
   ├── ...
   ├── LOG
   │   ├── 2020-05-29.log
   │   ├── OLD_LOGS
   │      └── 2020-05-29.log
   └── ...

If I change my clock to the next day (May 30th 2020) a new file will be created 2020-05-30.log

   .
   ├── ...
   ├── LOG
   │   ├── 2020-05-29.log
   │   ├── 2020-05-30.log
   │   ├── OLD_LOGS
   │      └── 2020-05-29.log
   └── ...

If I run my app one minute later, the 2020-05-30.log file will be archived

  .
  ├── ...
  ├── LOG
  │   ├── 2020-05-29.log
  │   ├── 2020-05-30.log
  │   ├── OLD_LOGS
  │      ├── 2020-05-29.log
  │      └── 2020-05-30.log
  └── ...

Shouldn't the LOG/2020-05-29.log file have been archived?

Body:
There is a problem in your configuration for per minute archival.

NLog starts overriding the old file because your file format is yyyy-MM-DD.
The correct configuration for per minute achieving, add below code.

    <target name="kFile" xsi:type="File"
        layout="${longdate} ${logger} ${message}${exception:format=ToString}"
        fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
        archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
        archiveDateFormat="yyyy-MM-dd-mm"
        archiveNumbering="Date"
        archiveEvery="Minute"
  />

Changed format to yyyy-MM-dd-mm.

This change created below files in my folder

  .
├── ...
├── LOG
│   ├── 2020-05-30.log
│   ├── OLD_LOGS
│      ├── 2020-05-30-01.log
│      └── 2020-05-30-02.log
└── ...

I checked with the same configuration as yours
and the result was

So the NLog archiving feature does not work the way you want it to. It just places the last file of the month to the archive folder not all.

So, you have to configure NLog to archive files every day and set max file number to something like 365 to keep them for one year.
Apply below configuration:

    <target name="kFile" xsi:type="File"
        layout="${longdate} ${logger} ${message}${exception:format=ToString}"
        fileName="${basedir}/LOG/${date:format=yyyy-MM-dd}.log"
        archiveFileName="${basedir}/LOG/OLD_LOGS/{#}.log"
        archiveDateFormat="yyyy-MM-dd"
        archiveNumbering="Date"
        archiveEvery="Day"
        maxArchiveFiles="365"
  />

This way you will get one file per day and the file will be transferred to the archive folder each day. The archive will keep the file for one year. You may want to review the max archive file though. Because it may increase the size of the folder based on how much you log.


问:
Is there a way to pass dependencies to JPA converters?
I have a custom converter that needs to use few dependencies.

Since converters are managed by JPA, I can't figure out a way of passing it dependencies from another component (like dependency injector). Is there such a way?

```<code>@Converter
public class CompressingJsonConverter implements AttributeConverter<CompressedJson, Byte[]> {

    private final Compressing compressing;
    private final ObjectMapper objectMapper;

    public CompressingJsonConverter() {
        // I would like to inject those dependencies instead
        compressing = new Compressing();
        objectMapper = new ObjectMapper();
    }
</code>```

答:
This depends on which world are your two objects living :

If both are created by CID then there should not have been any issues just using javax.inject would suffice.

If one is created by a different DI framework say GUICE then you need to write some glue code to connect them.

One such technique I used in one of my projects is to create a class like :

// create a new class
class Bridge { @Inject public static ObjectMapper objectMapper; }

// in GUICE module
requestStaticInjection(Bridge.class)

// in Convertor
class MyConvertor {

  private ObjectMapper objectMapper;

  public MyConvertor(){
    this.objectMapper = Bridge.objectMapper;
  }
}```

Body:
I have a custom converter that needs to use few dependencies.

Since converters are managed by JPA, I can't figure out a way of passing it dependencies from another component (like dependency injector). Is there such a way?

@Converter
public class CompressingJsonConverter implements AttributeConverter<CompressedJson, Byte[]> {

    private final Compressing compressing;
    private final ObjectMapper objectMapper;

    public CompressingJsonConverter() {
        // I would like to inject those dependencies instead
        compressing = new Compressing();
        objectMapper = new ObjectMapper();
    }


问:
Is there a Heap in java?
I am porting a C++ library to Java and I need a heap data structure. Is there a standard implementation or will I need to do it myself?</p>

答:
No as such there isn't but you can use Priority Queue as a Heap. Its officially told by Oracle to use Priority Queue as a Heap you can also refer to this link for further clarification.</p>

```<code>PriorityQueue<Integer> MinHeap = new PriorityQueue<>();

PriorityQueue<Integer> MaxHeap = new PriorityQueue<>(Comparator.reverseOrder());
</code>```

Title: Is there a Heap in java?

Body:
No as such there isn't but you can use Priority Queue as a Heap. Its officially told by Oracle to use Priority Queue as a Heap you can also refer to this link for further clarification.

PriorityQueue<Integer> MinHeap = new PriorityQueue<>();

PriorityQueue<Integer> MaxHeap = new PriorityQueue<>(Comparator.reverseOrder());


问:
Laravel Multiple Filters Table with Multiple Collections
I am trying to create a multiple filter function to filter my table. I have a model called Product and it has collections named categories, colors and sizes. I have the following in my view:

```<code>                <div class="col-6">
                    <div class="form-group mt-3">
                        <label>{{ __('Categories') }}</label>
                        <select class="form-control" id="select-categories">
                            <option value="0">All</option>
                            @foreach($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group mt-3">
                        <label>{{ __('Colors') }}</label>
                        <select class="form-control" id="select-colors">
                            <option value="0">All</option>
                            @foreach($colors as $color)
                            <option value="{{ $color->id }}">{{ $color->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group mt-3">
                        <label>{{ __('Sizes') }}</label>
                        <select class="form-control" id="select-sizes">
                            <option value="0">All</option>
                            @foreach($sizes as $size)
                            <option value="{{ $size->id }}">{{ $size->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
</code>```

And then I use JQuery to send a AJAX request to my controller with the current selected option values of all three dropdowns.

Example data:
Categories: All
Colors: Red
Sizes: Small

Now I wish to show the products with the color red and size small but the category doesn't matter.
I get the collections with the use of one to many relationships and link tables.

```<code>$product->categories
$product->colors
$product->sizes
</code>```

I am not sure how to approach this.

答:
You can do something similar to below:

```<code>public function index(ProductRequest $request)
{
   $query = Product::where($request->validated());

   return ProductResource::collection($query);
}
</code>```

and in your ProductRequest you can define filters that you want to allow

```<code>class ProductRequest extends FormRequest
{
   ...
   public function rules()
   {
      return [
         'categories' => 'exists:categories,id'
         ....
      ];
   }
</code>```

Body:
I am trying to create a multiple filter function to filter my table. I have a model called Product and it has collections named categories, colors and sizes. I have the following in my view:

                        {{ __('Categories') }}
                        <select class="form-control" id="select-categories">
                            <option value="0">All</option>
                            @foreach($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                            @endforeach
                        </select>

                        {{ __('Colors') }}
                        <select class="form-control" id="select-colors">
                            <option value="0">All</option>
                            @foreach($colors as $color)
                            <option value="{{ $color->id }}">{{ $color->name }}</option>
                            @endforeach
                        </select>

                        {{ __('Sizes') }}
                        <select class="form-control" id="select-sizes">
                            <option value="0">All</option>
                            @foreach($sizes as $size)
                            <option value="{{ $size->id }}">{{ $size->name }}</option>
                            @endforeach
                        </select>

And then I use JQuery to send a AJAX request to my controller with the current selected option values of all three dropdowns.

Example data:
Categories: All
Colors: Red
Sizes: Small

Now I wish to show the products with the color red and size small but the category doesn't matter.
I get the collections with the use of one to many relationships and link tables.

$product->categories
$product->colors
$product->sizes

I am not sure how to approach this.

Body:
You can do something similar to below:

public function index(ProductRequest $request)
{
   $query = Product::where($request->validated());

   return ProductResource::collection($query);
}

and in your ProductRequest you can define filters that you want to allow

class ProductRequest extends FormRequest
{
   ...
   public function rules()
   {
      return [
         'categories' => 'exists:categories,id'
         ....
      ];
   }


问:
How can I make the corners of my bottom sheet dialog rounded?
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

```<code> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ...
    <item name="shapeAppearanceLargeComponent">@style/CustomShapeAppearanceBottomSheetDialog</item>
</style>

<style name="CustomShapeAppearanceBottomSheetDialog" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">16dp</item>
    <item name="cornerSizeTopLeft">16dp</item>
</style>
</code>```

BottomNavMenuFragment:

```<code>public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}
</code>```

And this is how I'm showing the fragment:

```<code>BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());
</code>```

Nothing I seem to do works. Could someone point me in the right direction?

答:
Follow the below steps to attain top rounded corner bottomsheet:

Step 1: Create drawable rounded_top_corners.xml file inside drawable folder

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white"/>
    <corners android:topLeftRadius="8dp"
        android:topRightRadius="8dp"/>
</shape>
</code>```

Step 2: Create below styles in styles.xml

```<code> <style name="BottomSheetDialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/bottomSheetBackground</item>
    </style>

    <style name="bottomSheetBackground" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/rounded_top_corners</item>
    </style>
</code>```

Step 3: Add style in BottomNavMenuFragment class

```<code> @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialogStyle);
    }
</code>```

That's it, the style will be applied to bottomsheet.

Body:
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

BottomNavMenuFragment:

public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}

And this is how I'm showing the fragment:

BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());

Nothing I seem to do works. Could someone point me in the right direction?

Body:
Follow the below steps to attain top rounded corner bottomsheet:

Step 1: Create drawable rounded_top_corners.xml file inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white"/>
    <corners android:topLeftRadius="8dp"
        android:topRightRadius="8dp"/>
</shape>

Step 2: Create below styles in styles.xml

 <style name="BottomSheetDialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/bottomSheetBackground</item>
    </style>

    <style name="bottomSheetBackground" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/rounded_top_corners</item>
    </style>

Step 3: Add style in BottomNavMenuFragment class

 @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialogStyle);
    }

That's it, the style will be applied to bottomsheet.


问:
Google app script: upload a csv file from html service
I'm trying to upload a csv file from an html service in google sheets, and after some research I found some code which seemed to be working at the time:

html service call:

```<code>function importAnalysis() {
  var html = HtmlService.createHtmlOutputFromFile('Import')
      .setWidth(1524)
      .setHeight(800);
  SpreadsheetApp.getUi()
      .showModalDialog(html, 'Import d\'analyse');
}
</code>```

html template:

```<code><!DOCTYPE html>
  <html>
    <body>
      <form>
        <input type="file" name="analysisCsv" accept=".csv">
        <input type="button" onclick="google.script.run.processForm(this.parentNode);">
      </form>
    </body>
  </html>
</code>```

gs file (I commented further code to isolate the source of the problem):

```<code>function processForm(form) {
  let fileBlob=form.analysisCsv;
//  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Table_Analysis");
//  let lastRow = sheet.getLastRow();
//  let values = []
//  let rows = fileBlob.contents.split('\n');
//  for(let r=0; r<rows.length; ++r){
//    values.push( rows[r].split(';') );
//  }
//  for (var i = 0; i < values.length; i++) {
//    sheet.getRange(lastRow+i+1, 1, 1, values[i].length).setValues(new Array(values[i]));
//  }
}
</code>```

Problem is I get an error 400 on processForm function:
"Failed to load resource: the server responded with a status of 400 ()"

Do you know what's wrong with my code, or another way to upload csv content in my sheet?

答:
Here is my solution using client-side FileReader API:

code.gs:

function doSomething(csvstr) {
  Logger.log('doSomething', csvstr);

  const csvarr = Utilities.parseCsv(csvstr);

  return csvarr; // now an array !
}
```

<p><code>index.html</code>:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">

  </head>
  <body>
    <input type="file">

    <script>
    const $input = document.querySelector('input')

    $input.onchange = function (e) {
      // File
      const file = e.target.files[0]

      //
      // FileReader
      //
      // see: https://web.dev/read-files/#read-content
      //

      const reader = new FileReader();

      reader.onerror = event => {
        console.error('error while reading CSV file', event)
        reader.abort()
      }

      reader.onload = event => {
        const content = event.target.result // result
        console.log(content)

        // https://developers.google.com/apps-script/guides/html/reference/run
        google.script.run
          .withFailureHandler(err => {
            console.error('oh noes', err)
          })
          .withSuccessHandler(val => {
            console.log('yay!', val)

            google.script.host.close() // https://developers.google.com/apps-script/guides/html/reference/host#close
          })
          .doSomething(content)
      }
      reader.readAsText(file);
    }
    </script>
  </body>
</html>
</code>```

Body:
I'm trying to upload a csv file from an html service in google sheets, and after some research I found some code which seemed to be working at the time:

html service call:

function importAnalysis() {
  var html = HtmlService.createHtmlOutputFromFile('Import')
      .setWidth(1524)
      .setHeight(800);
  SpreadsheetApp.getUi()
      .showModalDialog(html, 'Import d\'analyse');
}

html template:

<!DOCTYPE html>

      <form>
        <input type="file" name="analysisCsv" accept=".csv">
        <input type="button" onclick="google.script.run.processForm(this.parentNode);">
      </form>

gs file (I commented further code to isolate the source of the problem):

function processForm(form) {
  let fileBlob=form.analysisCsv;
//  sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Table_Analysis");
//  let lastRow = sheet.getLastRow();
//  let values = []
//  let rows = fileBlob.contents.split('\n');
//  for(let r=0; r<rows.length; ++r){
//    values.push( rows[r].split(';') );
//  }
//  for (var i = 0; i < values.length; i++) {
//    sheet.getRange(lastRow+i+1, 1, 1, values[i].length).setValues(new Array(values[i]));
//  }
}

Problem is I get an error 400 on processForm function:
"Failed to load resource: the server responded with a status of 400 ()"

Do you know what's wrong with my code, or another way to upload csv content in my sheet?

Body:
Here is my solution using client-side FileReader API:

code.gs:

function doSomething(csvstr) {
  Logger.log('doSomething', csvstr);

  const csvarr = Utilities.parseCsv(csvstr);

  return csvarr; // now an array !
}

index.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">

  </head>
  <body>
    <input type="file">

    <script>
    const $input = document.querySelector('input')

    $input.onchange = function (e) {
      // File
      const file = e.target.files[0]

      //
      // FileReader
      //
      // see: https://web.dev/read-files/#read-content
      //

      const reader = new FileReader();

      reader.onerror = event => {
        console.error('error while reading CSV file', event)
        reader.abort()
      }

      reader.onload = event => {
        const content = event.target.result // result
        console.log(content)

        // https://developers.google.com/apps-script/guides/html/reference/run
        google.script.run
          .withFailureHandler(err => {
            console.error('oh noes', err)
          })
          .withSuccessHandler(val => {
            console.log('yay!', val)

            google.script.host.close() // https://developers.google.com/apps-script/guides/html/reference/host#close
          })
          .doSomething(content)
      }
      reader.readAsText(file);
    }
    </script>
  </body>
</html>


问:
AWS Educate - Launch EC2 instance authorization issue
I am working on my school project and seeing permission issues using AWS Educate for students.

I am unable to launch EC2 instance (Spot instance). Read through the documentation about changing roles and policies to grant permission but it says my user is unauthorized to. Neither is it permitting to create a role - No permissions to change anything in IAM.

Also, since it's student access AWS doesn't provide support to raise a Case Request with them. I understand this is a redundant question but I tried the solutions provided but in vain due to student access limitations. To ask administrator to add permissions it just redirects me to documentation.

Help much appreciated!

答: I am under the impression that spot instances are not available through AWS Educate. You would need to use a regular account which is what you did apparently.</p>


问:
trying to create a div below a div css
I realize this is a a pretty basic question, and perhaps I'm taking advantage of you all while I should be sifting through some dense css books/materials. But I can't figure out why my code doesn't work.

I'm trying to create two divs on a page, one below the other and it seems like I should be able to give the lower and absolute position which is below the top div.

I've got to div box whose css layouts are all the same but they don't look anything like eachother. Why is it that the second one looks completely unlike the first, why can't I make a "copy" of the first and place it below the first?

Heres the code. the top is the desired scroller is the desired effect. http://jsfiddle.net/7YueC/

答:
Take out the IDs on the divs and/or add the class .same and then switch the #lasteventimg styles to .same.  Remove the #2 styles.

Fiddle: http://jsfiddle.net/7YueC/7/

Title: trying to create a div below a div css


问:
Error in SQL syntax when running SQL in Java but not in HeidiSQL
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

```<code>Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);
</code>```

I can't figure out why.

答:
You should have tried NamedParameterStatement with your query to facilitate setting of string parameters and avoid their duplication (using refactored query suggested in GMB's earlier answer):

```<code>String sql = "INSERT INTO billboards (Name, XML, CreatorName) VALUES (:name, :xml, :creator) "
             + "ON DUPLICATE KEY UPDATE SET XML = :xml";

NamedParameterStatement statement = new NamedParameterStatement(con, sql);
statement.setString("name", billboard.getName());
statement.setString("xml", EscapeString(billboard.getXml()));
statement.setString("creator", billboard.getCreatorName());

// Insert or update billboard
statement.execute(sql);
</code>```

Body:
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);

I can't figure out why.

Body:
You should have tried NamedParameterStatement with your query to facilitate setting of string parameters and avoid their duplication (using refactored query suggested in GMB's earlier answer):

String sql = "INSERT INTO billboards (Name, XML, CreatorName) VALUES (:name, :xml, :creator) "
             + "ON DUPLICATE KEY UPDATE SET XML = :xml";

NamedParameterStatement statement = new NamedParameterStatement(con, sql);
statement.setString("name", billboard.getName());
statement.setString("xml", EscapeString(billboard.getXml()));
statement.setString("creator", billboard.getCreatorName());

// Insert or update billboard
statement.execute(sql);


问:
Update Builder gives late response when multiple versions are there in Elasticsearch?
Project : Spring Boot

I'm updating my elasticsearch document using following way,

```<code>@Override
public Document update(DocumentDTO document) {
    try {
        Document doc = documentMapper.documentDTOToDocument(document);
        Optional<Document> fetchDocument = documentRepository.findById(document.getId());
        if (fetchDocument.isPresent()) {
            fetchDocument.get().setTag(doc.getTag());
            Document result = documentRepository.save(fetchDocument.get());
            final UpdateRequest updateRequest = new UpdateRequest(Constants.INDEX_NAME, Constants.INDEX_TYPE, document.getId().toString());
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
            updateRequest.doc(jsonBuilder().startObject().field("tag", doc.getTag()).endObject());
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            log.info("ES result : "+ updateResponse.status());
            return result;
        }
    } catch (Exception ex) {
        log.info(ex.getMessage());
    }
    return null;
}
</code>```

Using this my document updated successfully and version incremented but when version goes 20+.

It takes lot many time to retrieve data(around 14sec).

I'm still confused regarding process of versioning. How it works in update and delete scenario? At time of search it process all the data version and send latest one? Is it so?

答:
Elasticsearch internally uses Lucene which uses immutable segments to store the data. as these segments are immutable, every update on elasticsearch internally marks the old document delete(soft delete) and inserts a new document(with a new version).

The old document is later on cleanup during a background segment merging process.

A newly updated document should be available in 1 second(default refresh interval) but it can be disabled or change, so please check this setting in your index. I can see you are using wait_for param in your code, please remove this and you should be able to see the updated document fast if you have not changed the default refresh_interval.

Note:- Here both update and delete operation works similarly, the only difference is that in delete operation new document is not created, and the old document is marked soft delete and later on during segment merge deleted permanently.

Body:
Project : Spring Boot

I'm updating my elasticsearch document using following way,

@Override
public Document update(DocumentDTO document) {
    try {
        Document doc = documentMapper.documentDTOToDocument(document);
        Optional<Document> fetchDocument = documentRepository.findById(document.getId());
        if (fetchDocument.isPresent()) {
            fetchDocument.get().setTag(doc.getTag());
            Document result = documentRepository.save(fetchDocument.get());
            final UpdateRequest updateRequest = new UpdateRequest(Constants.INDEX_NAME, Constants.INDEX_TYPE, document.getId().toString());
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
            updateRequest.doc(jsonBuilder().startObject().field("tag", doc.getTag()).endObject());
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            log.info("ES result : "+ updateResponse.status());
            return result;
        }
    } catch (Exception ex) {
        log.info(ex.getMessage());
    }
    return null;
}

Using this my document updated successfully and version incremented but when version goes 20+.

It takes lot many time to retrieve data(around 14sec).

I'm still confused regarding process of versioning. How it works in update and delete scenario? At time of search it process all the data version and send latest one? Is it so?


问:
custom count measure runs forever MDX
So this question goes off the one here

I've been trying to do a similar count measure and I did the suggested solution but it's still running.... and it's been more than 30 minutes with no results, while without that it runs in under a minute. So am I missing something? Any guidance would help. Here is my query:

```<code>WITH
    MEMBER [Measures].[IteractionCount] AS
    NONEMPTY
    (
        FILTER
        (
            ([DimInteraction].[InteractionId].[ALL].Children,
            [Measures].[Impression Count]),
            [DimInteraction].[Interaction State].&[Enabled]
        )
    ).count

SELECT
(
    {[Measures].[IteractionCount],
    [Measures].[Impression Count]}
)
ON COLUMNS,
(

    ([DimCampaign].[CampaignId].[CampaignId].MEMBERS,
     [DimCampaign].[Campaign Name].[Campaign Name].MEMBERS,
     [DimCampaign].[Owner].[Owner].MEMBERS)
    ,[DimDate].[date].[date].MEMBERS
)
ON ROWS
FROM
(
    SELECT
    (
       {[DimDate].[date].&[2020-05-06T00:00:00] : [DimDate].[date].&[2020-05-27T00:00:00]}
    )
    ON COLUMNS
    FROM [Model]
)
WHERE
(
        {[DimCampaign].[EndDate].&[2020-05-27T00:00:00]:NULL},
        [DimCampaign].[Campaign State].&[Active],
        {[DimInteraction].[End Date].&[2020-05-27T00:00:00]:NULL}//,
        //[DimInteraction].[Interaction State].&[Enabled]
)
</code>```

I don't know if FILTER is affecting it in any way but I tried it with and without and it still runs forever. I do need it specifically filtered to [DimInteraction].[Interaction State].&[Enabled]. I have also tried to instead filter to that option in the WHERE clause but no luck

Any suggestions to optimize this would be greatly appreciated! thanks!

UPDATE:
I end up using this query to load data into a python dataframe. Here is my code for that. I used this script for connecting and loading the data. I had to make some edits to it though to use windows authentication.

```<code>ssas_api._load_assemblies() #this uses Windows Authentication
conn = ssas_api.set_conn_string(server='server name',db_name='db name')

df = ssas_api.get_DAX(connection_string=conn, dax_string=query))
</code>```

The dax_string parameter is what accepts the dax or mdx query to pull from the cube.

答:
Please try this optimization:

```<code>
WITH
    MEMBER [Measures].[IteractionCount] AS
    SUM
    (
        [DimInteraction].[InteractionId].[InteractionId].Members
         * [DimInteraction].[Interaction State].&[Enabled],
         IIF(
           IsEmpty([Measures].[Impression Count]),
           Null,
           1
         )
    )

SELECT
(
    {[Measures].[IteractionCount],
    [Measures].[Impression Count]}
)
ON COLUMNS,
(

    ([DimCampaign].[CampaignId].[CampaignId].MEMBERS,
     [DimCampaign].[Campaign Name].[Campaign Name].MEMBERS,
     [DimCampaign].[Owner].[Owner].MEMBERS)
    ,[DimDate].[date].[date].MEMBERS
)
PROPERTIES MEMBER_CAPTION
ON ROWS
FROM
(
    SELECT
    (
       {[DimDate].[date].&[2020-05-06T00:00:00] : [DimDate].[date].&[2020-05-27T00:00:00]}
    )
    ON COLUMNS
    FROM [Model]
)
WHERE
(
        {[DimCampaign].[EndDate].&[2020-05-27T00:00:00]:NULL},
        [DimCampaign].[Campaign State].&[Active],
        {[DimInteraction].[End Date].&[2020-05-27T00:00:00]:NULL}//,
        //[DimInteraction].[Interaction State].&[Enabled]
)
CELL PROPERTIES VALUE

</code>```

If that doesn’t perform well the please describe the number of rows returned by your query when you comment out IteractionCount (sic) from the columns axis. And please describe how many unique InteractionId values you have.

Title: custom count measure runs forever MDX

Body:
So this question goes off the one here

I've been trying to do a similar count measure and I did the suggested solution but it's still running.... and it's been more than 30 minutes with no results, while without that it runs in under a minute. So am I missing something? Any guidance would help. Here is my query:

WITH
    MEMBER [Measures].[IteractionCount] AS
    NONEMPTY
    (
        FILTER
        (
            ([DimInteraction].[InteractionId].[ALL].Children,
            [Measures].[Impression Count]),
            [DimInteraction].[Interaction State].&[Enabled]
        )
    ).count

SELECT
(
    {[Measures].[IteractionCount],
    [Measures].[Impression Count]}
)
ON COLUMNS,
(

    ([DimCampaign].[CampaignId].[CampaignId].MEMBERS,
     [DimCampaign].[Campaign Name].[Campaign Name].MEMBERS,
     [DimCampaign].[Owner].[Owner].MEMBERS)
    ,[DimDate].[date].[date].MEMBERS
)
ON ROWS
FROM
(
    SELECT
    (
       {[DimDate].[date].&[2020-05-06T00:00:00] : [DimDate].[date].&[2020-05-27T00:00:00]}
    )
    ON COLUMNS
    FROM [Model]
)
WHERE
(
        {[DimCampaign].[EndDate].&[2020-05-27T00:00:00]:NULL},
        [DimCampaign].[Campaign State].&[Active],
        {[DimInteraction].[End Date].&[2020-05-27T00:00:00]:NULL}//,
        //[DimInteraction].[Interaction State].&[Enabled]
)

I don't know if FILTER is affecting it in any way but I tried it with and without and it still runs forever. I do need it specifically filtered to [DimInteraction].[Interaction State].&[Enabled]. I have also tried to instead filter to that option in the WHERE clause but no luck

Any suggestions to optimize this would be greatly appreciated! thanks!

UPDATE:
I end up using this query to load data into a python dataframe. Here is my code for that. I used this script for connecting and loading the data. I had to make some edits to it though to use windows authentication.

ssas_api._load_assemblies() #this uses Windows Authentication
conn = ssas_api.set_conn_string(server='server name',db_name='db name')

df = ssas_api.get_DAX(connection_string=conn, dax_string=query))

The dax_string parameter is what accepts the dax or mdx query to pull from the cube.

Body:
Please try this optimization:

WITH
    MEMBER [Measures].[IteractionCount] AS
    SUM
    (
        [DimInteraction].[InteractionId].[InteractionId].Members
         * [DimInteraction].[Interaction State].&[Enabled],
         IIF(
           IsEmpty([Measures].[Impression Count]),
           Null,
           1
         )
    )

SELECT
(
    {[Measures].[IteractionCount],
    [Measures].[Impression Count]}
)
ON COLUMNS,
(

    ([DimCampaign].[CampaignId].[CampaignId].MEMBERS,
     [DimCampaign].[Campaign Name].[Campaign Name].MEMBERS,
     [DimCampaign].[Owner].[Owner].MEMBERS)
    ,[DimDate].[date].[date].MEMBERS
)
PROPERTIES MEMBER_CAPTION
ON ROWS
FROM
(
    SELECT
    (
       {[DimDate].[date].&[2020-05-06T00:00:00] : [DimDate].[date].&[2020-05-27T00:00:00]}
    )
    ON COLUMNS
    FROM [Model]
)
WHERE
(
        {[DimCampaign].[EndDate].&[2020-05-27T00:00:00]:NULL},
        [DimCampaign].[Campaign State].&[Active],
        {[DimInteraction].[End Date].&[2020-05-27T00:00:00]:NULL}//,
        //[DimInteraction].[Interaction State].&[Enabled]
)
CELL PROPERTIES VALUE

If that doesn’t perform well the please describe the number of rows returned by your query when you comment out IteractionCount (sic) from the columns axis. And please describe how many unique InteractionId values you have.


问:
How to set different value instead of items's value in DropdownButton in flutter?
I want to achieve different values behind the scene, for example, if the user selects "United State of America" behind the scene I want a value "USA" only. How can I achieve this?

Here is my button:

```<code>DropdownButton<String>(
                        isExpanded: true,
                        underline: SizedBox(),
                        icon: SvgPicture.asset("assets/icons/dropdown.svg"),
                        value: dropdownValue,
                        items: [
                          'Nepal',
                          'India',
                          'United States',
                          'Denmark',
                          'UK',
                          'World Wide'
                        ].map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                        onChanged: (newValue) {
                          setState(() {
                            dropdownValue = newValue;
                          });
                        },
                      ),
</code>```

答:
What you can do is create a CountryOption class with a key('USA' in your example) and a fullName ('United States' in your example).

You then create a list of dropdown items of CountryOption instead of String, so you can store the currently selected CountryOption and you have both the key and fullName properties available for later use.

I would also recommend loading your list of items only once, not on each rebuild.

```<code>import 'package:flutter/material.dart';

class CountriesButton extends StatefulWidget {
  const CountriesButton({Key key}) : super(key: key);

  @override
  _CountriesButtonState createState() => _CountriesButtonState();
}

class _CountriesButtonState extends State<CountriesButton> {
  List<DropdownMenuItem<CountryOption>> _countryItems;
  CountryOption _selectedCountry;

  @override
  void initState() {
    // Get all countries
    List<CountryOption> countries = CountryOption.allCountries;

    // Initialise your items only once
    _countryItems = countries.map<DropdownMenuItem<CountryOption>>(
      (CountryOption countryOption) {
        return DropdownMenuItem<CountryOption>(
          value: countryOption,
          child: Text(countryOption.fullName),
        );
      },
    ).toList();

    // Initialiste your dropdown with the first country in the list
    // (might be different in your specific scenario)
    _selectedCountry = countries[0];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton<CountryOption>(
        isExpanded: true,
        underline: SizedBox(),
        icon: SvgPicture.asset("assets/icons/dropdown.svg"),
        value: _selectedCountry,
        items: _countryItems,
        onChanged: (newValue) {
          setState(() {
            _selectedCountry = newValue;
          });
        },
      ),
    );
  }
}

class CountryOption {
  final String key;
  final String fullName;

  CountryOption(this.key, this.fullName);

  static List<CountryOption> get allCountries => [
        CountryOption('nepal', 'Nepal'),
        CountryOption('india', 'India'),
        CountryOption('USA', 'United States'),
        CountryOption('denmark', 'Denmark'),
        CountryOption('uk', 'UK'),
        CountryOption('world', 'World Wide'),
      ];
}
</code>```

Let me know if something is not clear or if you have any questions.

Body:
I want to achieve different values behind the scene, for example, if the user selects "United State of America" behind the scene I want a value "USA" only. How can I achieve this?

Here is my button:

DropdownButton<String>(
                        isExpanded: true,
                        underline: SizedBox(),
                        icon: SvgPicture.asset("assets/icons/dropdown.svg"),
                        value: dropdownValue,
                        items: [
                          'Nepal',
                          'India',
                          'United States',
                          'Denmark',
                          'UK',
                          'World Wide'
                        ].map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                        onChanged: (newValue) {
                          setState(() {
                            dropdownValue = newValue;
                          });
                        },
                      ),

Body:
What you can do is create a CountryOption class with a key('USA' in your example) and a fullName ('United States' in your example).

You then create a list of dropdown items of CountryOption instead of String, so you can store the currently selected CountryOption and you have both the key and fullName properties available for later use.

I would also recommend loading your list of items only once, not on each rebuild.

import 'package:flutter/material.dart';

class CountriesButton extends StatefulWidget {
  const CountriesButton({Key key}) : super(key: key);

  @override
  _CountriesButtonState createState() => _CountriesButtonState();
}

class _CountriesButtonState extends State<CountriesButton> {
  List<DropdownMenuItem<CountryOption>> _countryItems;
  CountryOption _selectedCountry;

  @override
  void initState() {
    // Get all countries
    List<CountryOption> countries = CountryOption.allCountries;

    // Initialise your items only once
    _countryItems = countries.map<DropdownMenuItem<CountryOption>>(
      (CountryOption countryOption) {
        return DropdownMenuItem<CountryOption>(
          value: countryOption,
          child: Text(countryOption.fullName),
        );
      },
    ).toList();

    // Initialiste your dropdown with the first country in the list
    // (might be different in your specific scenario)
    _selectedCountry = countries[0];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton<CountryOption>(
        isExpanded: true,
        underline: SizedBox(),
        icon: SvgPicture.asset("assets/icons/dropdown.svg"),
        value: _selectedCountry,
        items: _countryItems,
        onChanged: (newValue) {
          setState(() {
            _selectedCountry = newValue;
          });
        },
      ),
    );
  }
}

class CountryOption {
  final String key;
  final String fullName;

  CountryOption(this.key, this.fullName);

  static List<CountryOption> get allCountries => [
        CountryOption('nepal', 'Nepal'),
        CountryOption('india', 'India'),
        CountryOption('USA', 'United States'),
        CountryOption('denmark', 'Denmark'),
        CountryOption('uk', 'UK'),
        CountryOption('world', 'World Wide'),
      ];
}

Let me know if something is not clear or if you have any questions.


问:
right to left direction not working properly on urdu font
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <span class='r2l'>خدا کرے کے میری عرض پاک پے اترے</span>
  <span class='r2l'>وہ فصل گل جسے </span>
  <span class='r2l'>اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو</span>
  <span class='r2l'>یہاں جو سبزہ اگے ہمیشہ سبز رہے</span>
  <span class='r2l'>اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا</span>
  <span class='r2l'> اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</span>
</body>

</html></code>```

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

答:
rtl doesn't work on  tags. More information here: Using  to add a direction (dir = "rtl")

Change  and  to
 and

Body:
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}

  خدا کرے کے میری عرض پاک پے اترے
  وہ فصل گل جسے
  اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو
  یہاں جو سبزہ اگے ہمیشہ سبز رہے
  اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا
   اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

Body:
rtl doesn't work on <span> tags. More information here: Using <span> to add a direction (dir = "rtl")

Change <span> and </span> to <p> and </p>


问:
Show array with variable in Symfony
In my symfony project, I pass from the Controller a variable called 'button'.

In this case 'button' has the value 'content' but this is not always.

I need it to display the content of phrase.content in the '.html.twig' file but I can't.

index.html.twig:

button = 'content'

```<code>{% for frase in frases %}

    <tr>
        <th scope="row">{{ frase.id }}</th>
        <td>{{ frase. ~ button }}</td>
    </tr>

{% endfor %}
</code>```

I have tried like this but it gives me the following error:

```<code>Expected name or number. (500 Internal Server Error)
</code>```

----EDIT----

If I put frase.content directly it does, but if I put frase[button], it gives an error

```<code>Impossible to access a key" content"on an object of class" App \ Entity \ Frase"
that does not implement ArrayAccess interface.
</code>```

答:
I believe this twig's check could solve your problem:

```<code>{% if foo.bar is defined %}
</code>```

See doc: https://twig.symfony.com/doc/2.x/tests/defined.html

Also If you want to access object's property you can use twig function

```<code>attribute
</code>```

Link https://twig.symfony.com/doc/2.x/functions/attribute.html

So in your case it would be something like:

```<code>{{ attribute(frase, button) ?? '' }}
</code>```

Also you can additionally check if 'button' variable is defined

Title: Show array with variable in Symfony

Body:
In my symfony project, I pass from the Controller a variable called 'button'.

In this case 'button' has the value 'content' but this is not always.

I need it to display the content of phrase.content in the '.html.twig' file but I can't.

index.html.twig:

button = 'content'

{% for frase in frases %}

        {{ frase.id }}
        {{ frase. ~ button }}

{% endfor %}

I have tried like this but it gives me the following error:

Expected name or number. (500 Internal Server Error)

----EDIT----

If I put frase.content directly it does, but if I put frase[button], it gives an error

Impossible to access a key" content"on an object of class" App \ Entity \ Frase"
that does not implement ArrayAccess interface.

Body:
I believe this twig's check could solve your problem:

{% if foo.bar is defined %}

See doc: https://twig.symfony.com/doc/2.x/tests/defined.html

Also If you want to access object's property you can use twig function

attribute

Link https://twig.symfony.com/doc/2.x/functions/attribute.html

So in your case it would be something like:

{{ attribute(frase, button) ?? '' }}

Also you can additionally check if 'button' variable is defined


问:
WEP (Shared Key Authentication), how is the 136 byte challenge response formed?
I am playing around with WEP(Shared key authentication) challenge/response mechanism at the moment and I hope someone could help me out.

The AP sends a challenge text to the STA. The challenge text is 128 bytes

The STA encrypts the challenge and sends it back to the AP. This is 136 bytes (data) in wireshark.

My Question:

Can someone tell me the make-up of the 136 byte data challenge response and why it is this size.

Why is it not Enc([challengetext (128)] + [icv(4)]) = 132 bytes?

Thanks.

答:
I'm not an expert and I'm using personal experience to confirm the answer to the question. Feel free to edit eventual wrong terms.

TL;DR

Encrypted frame send by the STA contains:

802.11 parameters (24 bytes)

WEP parameters (clear IV + key index) (4 bytes)

management headers (encrypted) (8 bytes)

data (encrypted) (128 bytes)

ICV (encrypted) (4 bytes)

Total is 168 bytes, total of encrypted data without ICV is 136 bytes.

The encrypted data shown by Wireshark and Cie is 8 bytes longer than clear text challenge because it also carries the management headers (encrypted but predictable).

What does the AP send?

Clear text challenge frame sent by the AP is 160 bytes long, and the encrypted challenge response frame is 168 bytes long. That is not the question, but let's make things clear.

In the clear text AP messages, the management headers are also clear text:

Authentication algorithm (2 bytes)

Authentication SEQ (2 bytes)

status code (2 bytes)

tag number (1 byte)

tag length (1 byte)

(challenge) ('tag length' bytes)

The management header are 8 bytes long.

What does the STA send?

In the STA encrypted message, everything over 802.11 layer is considered as "data" as this is encrypted gibberish. Before this data, you can find (part of the 802.11 layer) the WEP parameters: IV (3 bytes) and key index (1 bytes). This is clear text. You also have the ICV, the very last 4 bytes of the frame. Those are 8 bytes that appear in all WEP encrypted frames.

The "data" section contains the encrypted challenge and the encrypted management headers (that's what answers your question).

Your question

If you have 8 more bytes in the WEP frame that actually seem to compensate the 8 bytes management headers, then why your encrypted challenge data is 8 bytes longer?

This is not because of IV or ICV, as we saw before, as they are not part of the challenge data. Those 8 bytes are actually from the management headers, that are encrypted within the "data" section. The frame containing the encrypted challenge is also a management frame, but you can't see the headers as they are encrypted. Those are your 8 mysterious bytes (see simplified frame skeletons below)

I will finish on the fact that those shared key authentications permit you to do offline dictionnary or bruteforce attacks on WEP authentication captures without any IV (except the one used to encrypt the challenge of course). The fact that the first 8 encrypted bytes are management headers makes them predictable (it's always the same). So in a bruteforce implementation, you can just RC4 the first 4 or 8 bytes of the frame, instead of the whole 136 bytes, which leads to way better performance on huge dictionnary/full bruteforce attacks.

Authentication frames skeleton

Management frame with cleartext challenge

```<code>--------------------------------------------------------------
(ieee 802.11 headers) -> 24 bytes
--------------------------------------------------------------
---------------- 8 bytes management headers ------------------

ieee 802.11 Wireless Management:

[0][1] == Authentication algo (int16) == 0x0100 (Shared Key)
[2][3] == Authentication SEQ  (int16) == 0x0002
[4][5] == Status code         (int16) == 0x0000 (Successful)
[6]    == Tag Number          (int8)  == 0x10   (Challenge text)
[7]    == Tag length          (int8)  == 0x80   (128 bytes long challenge)
--------------------------------------------------------------
---------------------- 128 bytes data ------------------------

[0:128]== Challenge text
--------------------------------------------------------------

24 + 8 + 128 = 160 bytes frame
</code>```

Encrypted frame with predictable encrypted management headers

```<code>--------------------------------------------------------------
(ieee 802.11 headers) -> 24 bytes
--------------------------------------------------------------
------------------ 4 bytes WEP parameters --------------------

[0][1][2] == IV (3 bytes, clear text)
[3]       == key index (int8) (should be 0)
--------------------------------------------------------------
---------------- 8 bytes management headers ------------------

From here, everything is encrypted

[0][1] == Authentication algo (int16) == 0x0100 (Shared Key)
[2][3] == Authentication SEQ  (int16) == 0x0003 (incremented since last frame)
[4][5] == Status code         (int16) == 0x0000 (Successful)
[6]    == Tag Number          (int8)  == 0x10   (Challenge text)
[7]    == Tag length          (int8)  == 0x80   (128 bytes long challenge)
--------------------------------------------------------------
---------------------- 128 bytes data ------------------------

[0:128]== Encrypted data challenge
--------------------------------------------------------------
---------------------- 4 bytes ICV ---------------------------

[0:4]  == WEP ICV
--------------------------------------------------------------

24 + 4 + 8 + 128 + 4 = 168 bytes frame
8  + 128 = 136 bytes "data" (as wireshark interprets it)
</code>```

The only thing that changes from the previous one in the management headers of the encrypted frame is the SEQ number.

Body:
I'm not an expert and I'm using personal experience to confirm the answer to the question. Feel free to edit eventual wrong terms.

TL;DR

Encrypted frame send by the STA contains:

802.11 parameters (24 bytes)

WEP parameters (clear IV + key index) (4 bytes)

management headers (encrypted) (8 bytes)

data (encrypted) (128 bytes)

ICV (encrypted) (4 bytes)

Total is 168 bytes, total of encrypted data without ICV is 136 bytes.

The encrypted data shown by Wireshark and Cie is 8 bytes longer than clear text challenge because it also carries the management headers (encrypted but predictable).

What does the AP send?

Clear text challenge frame sent by the AP is 160 bytes long, and the encrypted challenge response frame is 168 bytes long. That is not the question, but let's make things clear.

In the clear text AP messages, the management headers are also clear text:

Authentication algorithm (2 bytes)

Authentication SEQ (2 bytes)

status code (2 bytes)

tag number (1 byte)

tag length (1 byte)

(challenge) ('tag length' bytes)

The management header are 8 bytes long.

What does the STA send?

In the STA encrypted message, everything over 802.11 layer is considered as "data" as this is encrypted gibberish. Before this data, you can find (part of the 802.11 layer) the WEP parameters: IV (3 bytes) and key index (1 bytes). This is clear text. You also have the ICV, the very last 4 bytes of the frame. Those are 8 bytes that appear in all WEP encrypted frames.

The "data" section contains the encrypted challenge and the encrypted management headers (that's what answers your question).

Your question

If you have 8 more bytes in the WEP frame that actually seem to compensate the 8 bytes management headers, then why your encrypted challenge data is 8 bytes longer?

This is not because of IV or ICV, as we saw before, as they are not part of the challenge data. Those 8 bytes are actually from the management headers, that are encrypted within the "data" section. The frame containing the encrypted challenge is also a management frame, but you can't see the headers as they are encrypted. Those are your 8 mysterious bytes (see simplified frame skeletons below)

I will finish on the fact that those shared key authentications permit you to do offline dictionnary or bruteforce attacks on WEP authentication captures without any IV (except the one used to encrypt the challenge of course). The fact that the first 8 encrypted bytes are management headers makes them predictable (it's always the same). So in a bruteforce implementation, you can just RC4 the first 4 or 8 bytes of the frame, instead of the whole 136 bytes, which leads to way better performance on huge dictionnary/full bruteforce attacks.

Authentication frames skeleton

Management frame with cleartext challenge

--------------------------------------------------------------
(ieee 802.11 headers) -> 24 bytes
--------------------------------------------------------------
---------------- 8 bytes management headers ------------------

ieee 802.11 Wireless Management:

[0][1] == Authentication algo (int16) == 0x0100 (Shared Key)
[2][3] == Authentication SEQ  (int16) == 0x0002
[4][5] == Status code         (int16) == 0x0000 (Successful)
[6]    == Tag Number          (int8)  == 0x10   (Challenge text)
[7]    == Tag length          (int8)  == 0x80   (128 bytes long challenge)
--------------------------------------------------------------
---------------------- 128 bytes data ------------------------

[0:128]== Challenge text
--------------------------------------------------------------

24 + 8 + 128 = 160 bytes frame

Encrypted frame with predictable encrypted management headers

--------------------------------------------------------------
(ieee 802.11 headers) -> 24 bytes
--------------------------------------------------------------
------------------ 4 bytes WEP parameters --------------------

[0][1][2] == IV (3 bytes, clear text)
[3]       == key index (int8) (should be 0)
--------------------------------------------------------------
---------------- 8 bytes management headers ------------------

From here, everything is encrypted

[0][1] == Authentication algo (int16) == 0x0100 (Shared Key)
[2][3] == Authentication SEQ  (int16) == 0x0003 (incremented since last frame)
[4][5] == Status code         (int16) == 0x0000 (Successful)
[6]    == Tag Number          (int8)  == 0x10   (Challenge text)
[7]    == Tag length          (int8)  == 0x80   (128 bytes long challenge)
--------------------------------------------------------------
---------------------- 128 bytes data ------------------------

[0:128]== Encrypted data challenge
--------------------------------------------------------------
---------------------- 4 bytes ICV ---------------------------

[0:4]  == WEP ICV
--------------------------------------------------------------

24 + 4 + 8 + 128 + 4 = 168 bytes frame
8  + 128 = 136 bytes "data" (as wireshark interprets it)

The only thing that changes from the previous one in the management headers of the encrypted frame is the SEQ number.


问:
Why are elements of my array being over written?
I have written a simple function in Python which aims to find, if from two elements a and b, one can be obtained from another by swapping at most one pair of elements in one of the arrays.

This is my function:

```<code>def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = b
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                test = 1
    return(test==1)
</code>```

The issue is that upon inspecting b, it has changed even though I don't actually perform any calculations on b - what's going on!!??

答:
I would got with Sadap's code, but if you want to copy, use :</p>

```<code>import copy
def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = copy.deepcopy(b)
            b2[i] = copy.deepcopy(b[j])
            b2[j] = copy.deepcopy(b[i])
            if a == b2:
                test = 1
    if test == 1:
        return True
    else:
        return False
</code>```

Body:
I have written a simple function in Python which aims to find, if from two elements a and b, one can be obtained from another by swapping at most one pair of elements in one of the arrays.

This is my function:

def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = b
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                test = 1
    return(test==1)

The issue is that upon inspecting b, it has changed even though I don't actually perform any calculations on b - what's going on!!??

Body:
I would got with Sadap's code, but if you want to copy, use :

import copy
def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = copy.deepcopy(b)
            b2[i] = copy.deepcopy(b[j])
            b2[j] = copy.deepcopy(b[i])
            if a == b2:
                test = 1
    if test == 1:
        return True
    else:
        return False