问:
How can I separate variable and set the key to true for swift?
I want to separate the string in var into different vars and set key to true. For example

var x = [English , Chinese , Maths] => "English":true "Chinese":true
  "Maths":true

and push to firebase in order to get a data structure like:

name:anon subject:{"English":true
           "Chinese":true
           "Maths":true}

What should I do ?

答:
You can use

```<code>var x = ["English", "Chinese", "Maths"]

var subject: [String: Bool] = [:]
x.forEach { string in
  subject[string] = true
}
</code>```

or

```<code>var subjectList = ["English", "Chinese", "Maths"]

var subject: [String: Bool] = [:]
subjectList.forEach {
  subject[$0] = true
}
</code>```

Body:
You can use

var x = ["English", "Chinese", "Maths"]

var subject: [String: Bool] = [:]
x.forEach { string in
  subject[string] = true
}

or

var subjectList = ["English", "Chinese", "Maths"]

var subject: [String: Bool] = [:]
subjectList.forEach {
  subject[$0] = true
}


来源: stackexchange

问:
How to pass an array from an api as props to another component
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

```<code>     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}><i className="fa fa-search"></i></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}
</code>```

--------------------------------SearchedUser Component------------------------

```<code>    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(
    <div>
    </div>
     )
    }
    }
export default SearchedUser;
</code>```

答:
Use componentWillReceiveProps to update the state</p>

```<code>            import React from 'react'
            class SearchedUser extends React.Component {
                constructor(props) {
                    super(props);
                    this.state = {
                        Name:[]
                    }
                }

            /** When the SearchedUser component does anything with the new props,
            * componentWillReceiveProps is called, with the next props as the argument */

            componentWillReceiveProps(nextProps) {

                /** Update  state**/
                if (nextProps.UserName !== this.props.UserName) {
                    this.setState({
                        Name: nextProps.UserName
                    });
                }

            }

                render() {
                    console.log(this.state.Name);
                    return ( <
                        div >
                        <
                        /div>
                    )
                }
            }
            export default SearchedUser;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}

--------------------------------SearchedUser Component------------------------

    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

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

     )
    }
    }
export default SearchedUser;

Body:
Use componentWillReceiveProps to update the state

            import React from 'react'
            class SearchedUser extends React.Component {
                constructor(props) {
                    super(props);
                    this.state = {
                        Name:[]
                    }
                }

            /** When the SearchedUser component does anything with the new props,
            * componentWillReceiveProps is called, with the next props as the argument */

            componentWillReceiveProps(nextProps) {

                /** Update  state**/
                if (nextProps.UserName !== this.props.UserName) {
                    this.setState({
                        Name: nextProps.UserName
                    });
                }

            }

                render() {
                    console.log(this.state.Name);
                    return ( <
                        div >
                        <
                        /div>
                    )
                }
            }
            export default SearchedUser;


问:
Dynamically Creating Pages On Button Click
I am using Ionic 4 to create an app. So far, I have a floating action button, when you click it you can add a new item to a list (starts empty) that is displayed on screen. Each item has name and a button.

I want it so that whenever a button is pressed on the item, it goes to a page for that specific item.

I do not have the faintest idea how to do this so, this leaves me with a few questions:

1) Should I have one page premade and dynamically change the contents of it based on item button clicked OR whenever item is created, dynamically create a page unique to that item?

2) Based on the last question, what is the best way to accomplish it?

答:
TLDR; Answers
Question 1: Dynamically change the contents of the page based on the item buttons
Question 2: I just answered it in question 1.

Explanation:
You need to first understand how a new page gets created at its simplest form; it adds more code to the application that defines the new page.

Now, try asking yourself, should you on-the-fly add more code to your already built/published application or should you just build one page that dynamically loads different information based on the data/parameters provided to that page? Which one seems more feasible and why?


问:
Can I safely use observeForever in my repository?
I follow the architecture pattern laid out in Android Room with a View - Kotlin. My app displays N stacks and every of those stacks can be displayed with a closed cover or an open cover. The number of stacks can change at run time. The information about whether or not the cover is closed is not permanent and I have to react in the UI when it changes. I therefore thought about making it a LiveData object.

```<code>class ContentRepository(private  val contentDao: ContentDao) {
    val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
    val showCover = HashMap<Int, LiveData<Boolean>>()

    init {
        allStacks.observeForever { stacks ->
            stacks.filter { !showCover.containsKey(it.number) }
                .map { showCover.put(
                    it.number,
                    MutableLiveData<Boolean>(false)) }
        }
    }
}
</code>```

Given that I don't have access to a LifeCycleOwner from within the repository, can I use observeForever here, or will it result in data leaks?

答:
If the Repository is meant to have the same life cycle as the application and only one instance of it is created it should be fine. If not, you will end up leaking the repositories.

You should consider using the map extension function of LiveData to map the content into a new LiveData without the need of observing it, and instead of exposing a Map<Int, LiveData<Boolean>> exposing a LiveData<Map<Int, Boolean>> I don't know if this solution will work for your usecase. But if you can find a way to use the map function instead of observing forever it will make your code more robust.

Body:
I follow the architecture pattern laid out in Android Room with a View - Kotlin. My app displays N stacks and every of those stacks can be displayed with a closed cover or an open cover. The number of stacks can change at run time. The information about whether or not the cover is closed is not permanent and I have to react in the UI when it changes. I therefore thought about making it a LiveData object.

class ContentRepository(private  val contentDao: ContentDao) {
    val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
    val showCover = HashMap<Int, LiveData<Boolean>>()

    init {
        allStacks.observeForever { stacks ->
            stacks.filter { !showCover.containsKey(it.number) }
                .map { showCover.put(
                    it.number,
                    MutableLiveData<Boolean>(false)) }
        }
    }
}

Given that I don't have access to a LifeCycleOwner from within the repository, can I use observeForever here, or will it result in data leaks?


问:
Jquery Datatable Buttons Not Showing Up On React js
I initialized Jquery Datatables in my react app and it works perfectly fine, except that the buttons aren't showing up.
Here's my code:

I tried this at first and it works but it doesn't display the buttons.

```<code>import $ from 'jquery';
import JSZip from 'jszip';
window.JSZip = JSZip;

import 'datatables.net-bs4';
import 'datatables.net-responsive';
import 'datatables.net-buttons-bs4';
import 'datatables.net-buttons/js/buttons.colVis';
import 'datatables.net-buttons/js/buttons.html5';
import 'datatables.net-buttons/js/buttons.flash';
import 'datatables.net-buttons/js/buttons.print';
</code>```

Next, I tried the code below as well, the error it throws didn't allow my react app to render. It complained about this Uncaught TypeError: Cannot set property '$' of undefined
    at DataTable

```<code>import $ from 'jquery';
const JSZip = require('jszip');
window.JSZip = JSZip;

require('datatables.net')();
require('datatables.net-responsive')();
require('datatables.net-buttons')();
require('datatables.net-buttons/js/buttons.colVis')();
require('datatables.net-buttons/js/buttons.html5')();
require('datatables.net-buttons/js/buttons.print')();
</code>```

Finally, how I initialize my datatable:

```<code>var table = $('#dynamic_table').DataTable({
          'lengthChange': false,
          'buttons': [ 'copy', 'excel', 'pdf', 'colvis' ],
});
table.buttons().container().appendTo( '#dynamic_table_wrapper .col-md-6:eq(0)' );
</code>```

I came across a similar question Datatables button through React App, but it didn't solve my problem.
Without the buttons to export into excel the whole purpose of my using this plugin is defeated. Can I get a little help?

答:
```<code>import $ from 'jquery';
import JSZip from 'jszip';
window.JSZip = JSZip;

import 'datatables.net-bs4';
import 'datatables.net-responsive';
import 'datatables.net-buttons-bs4';
import 'datatables.net-buttons/js/buttons.colVis';
import 'datatables.net-buttons/js/buttons.html5';
import 'datatables.net-buttons/js/buttons.flash';
import 'datatables.net-buttons/js/buttons.print';
</code>```

After importing all my dependencies, it was as simple as adding

```<code>"dom": 'Bfrtip'
</code>```

to my datatable initialization.

```<code>$("#dynamic_table").DataTable({
  "lengthChange": true,
  "dom": 'Bfrtip',
  "buttons": [
    'copyHtml5',
    'excelHtml5',
    'csvHtml5',
    'pdfHtml5'
  ]
});
</code>```

I got rid of this line

```<code>table.buttons().container().appendTo( '#dynamic_table_wrapper .col-md-6:eq(0)' );
</code>```

Body:
I initialized Jquery Datatables in my react app and it works perfectly fine, except that the buttons aren't showing up.
Here's my code:

I tried this at first and it works but it doesn't display the buttons.

import $ from 'jquery';
import JSZip from 'jszip';
window.JSZip = JSZip;

import 'datatables.net-bs4';
import 'datatables.net-responsive';
import 'datatables.net-buttons-bs4';
import 'datatables.net-buttons/js/buttons.colVis';
import 'datatables.net-buttons/js/buttons.html5';
import 'datatables.net-buttons/js/buttons.flash';
import 'datatables.net-buttons/js/buttons.print';

Next, I tried the code below as well, the error it throws didn't allow my react app to render. It complained about this Uncaught TypeError: Cannot set property '$' of undefined
    at DataTable

import $ from 'jquery';
const JSZip = require('jszip');
window.JSZip = JSZip;

require('datatables.net')();
require('datatables.net-responsive')();
require('datatables.net-buttons')();
require('datatables.net-buttons/js/buttons.colVis')();
require('datatables.net-buttons/js/buttons.html5')();
require('datatables.net-buttons/js/buttons.print')();

Finally, how I initialize my datatable:

var table = $('#dynamic_table').DataTable({
          'lengthChange': false,
          'buttons': [ 'copy', 'excel', 'pdf', 'colvis' ],
});
table.buttons().container().appendTo( '#dynamic_table_wrapper .col-md-6:eq(0)' );

I came across a similar question Datatables button through React App, but it didn't solve my problem.
Without the buttons to export into excel the whole purpose of my using this plugin is defeated. Can I get a little help?

Body:
import $ from 'jquery';
import JSZip from 'jszip';
window.JSZip = JSZip;

import 'datatables.net-bs4';
import 'datatables.net-responsive';
import 'datatables.net-buttons-bs4';
import 'datatables.net-buttons/js/buttons.colVis';
import 'datatables.net-buttons/js/buttons.html5';
import 'datatables.net-buttons/js/buttons.flash';
import 'datatables.net-buttons/js/buttons.print';

After importing all my dependencies, it was as simple as adding

"dom": 'Bfrtip'

to my datatable initialization.

$("#dynamic_table").DataTable({
  "lengthChange": true,
  "dom": 'Bfrtip',
  "buttons": [
    'copyHtml5',
    'excelHtml5',
    'csvHtml5',
    'pdfHtml5'
  ]
});

I got rid of this line

table.buttons().container().appendTo( '#dynamic_table_wrapper .col-md-6:eq(0)' );


问:
Is there a way to get Facebook public page past events using graph API?
I want to get past events for a public facebook page (of an organization that i am working for) to integrate with their wordpress website (which i am working on)

What is the solution here?

I cannot seem to be able to use any plugins or even the facebook graph API to be able to accomplish this. (checked the graph api explorer, and it returns no data)

on the documentation it says that the events is a restricted edge
 but still they have :

GET /v3.3/{page-id}/events HTTP/1.1
Host: graph.facebook.com

Does this not work?

Even if I use facebook's ugly page plugin, i cannot get page PAST events.

答:
https://developers.facebook.com/docs/graph-api/reference/page/events:

This is a restricted edge. You cannot request access at this time.

There is currently no way for normal 3rd-party apps to get page events at all.


问:
Allocating more memory to an existing Global memory array
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

```<code>//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}
</code>```

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...

答:
Your psuedocode does not "add memory to a previously allocated array" at all. The standard C way of increasing the size of an existing allocation is via the realloc() function, and there is no CUDA equivalent of realloc() at the time of writing.

When you do

```<code>cudaMalloc(d_A....)

// something

cudaMalloc(d_A....)
</code>```

all you are doing is creating a new memory allocation and assigning it to d_A. The previous memory allocation still exists, but now you have lost the pointer value of the previous memory and have no way of accessing it. Based on this and your previous question on almost the same subject, might I suggest you spend a bit of time revising memory and pointer concepts in C before you try CUDA, because unless you have a very clear understanding of these fundamentals, you will find the distributed memory nature of CUDA to be very confusing,

ContentLicense: CC BY-SA 3.0

Body:
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...

Body:
Your psuedocode does not "add memory to a previously allocated array" at all. The standard C way of increasing the size of an existing allocation is via the realloc() function, and there is no CUDA equivalent of realloc() at the time of writing.

When you do

cudaMalloc(d_A....)

// something

cudaMalloc(d_A....)

all you are doing is creating a new memory allocation and assigning it to d_A. The previous memory allocation still exists, but now you have lost the pointer value of the previous memory and have no way of accessing it. Based on this and your previous question on almost the same subject, might I suggest you spend a bit of time revising memory and pointer concepts in C before you try CUDA, because unless you have a very clear understanding of these fundamentals, you will find the distributed memory nature of CUDA to be very confusing,


问:
Order by several columns
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

```<code>id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128
</code>```

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;
```

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

答:
Your Query is true

```<code>SELECT * FROM results ORDER BY last_updated, popularity;
</code>```

It will be sorted by last_updated Ascending, If you have duplicated values of last_updated column it will be sorted by popularity

Just see this answer and you will understand me
SQL multiple column ordering

Title: Order by several columns

Body:
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

Body:
Your Query is true

SELECT * FROM results ORDER BY last_updated, popularity;

It will be sorted by last_updated Ascending, If you have duplicated values of last_updated column it will be sorted by popularity

Just see this answer and you will understand me
SQL multiple column ordering


问:
How to access ref of a component through a function in React Native?
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

```<code>render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}
</code>```

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

```<code>myFunction = (ref) => {
  ref.setState({ myState: myValue })
}
</code>```

Then, I want to call that function for those separate components separately like this. (In the screen file)

```<code>this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)
</code>```

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

```<code>this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })
</code>```

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

答:
Inside your component,  in the componentDidMount function please add

```<code>componentDidMount() {
    this.props.refs(this)
}

setState(key, value){
    this.setState({[key]:value})
}
</code>```

and please change the ref param to refs

```<code><MyComponent refs={component => this.myComponent1 = component} />

myFunction = (ref) => {
    ref.setState('myState', 'myValue')
}
</code>```

Body:
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

Then, I want to call that function for those separate components separately like this. (In the screen file)

this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })

The state myState is in the component while I want to access it through the myFunction() in my screen file.

Can you please help me to solve this problem?

Body:
Inside your component,  in the componentDidMount function please add

componentDidMount() {
    this.props.refs(this)
}

setState(key, value){
    this.setState({[key]:value})
}

and please change the ref param to refs

<MyComponent refs={component => this.myComponent1 = component} />

myFunction = (ref) => {
    ref.setState('myState', 'myValue')
}


问:
QSplitter() doesn't treat a QScrollArea() and QFrame() equally

1. Problem explained

I'm experimenting with Qt's QSplitter() widget. I've built a very simple sample project in PyQt5 showing a QSplitter() encapsulating a QScrollArea() on the left and a QFrame() on the right:

I've given both the QScrollArea() and QFrame() equal stretch factors, but the QSplitter() doesn't treat them equally. The QScrollArea() always gets most space. I have no idea why.

 Minimal, Reproducible Example

Simply copy-paste the code below in a .py script and run it. I've got Python 3.7 with PyQt5 running on a Windows 10 machine.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class Scroller(QScrollArea):
    '''
    The Scroller(), will be first widget in the Splitter().

    '''
    def __init__(self):
        super().__init__()
        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setStyleSheet("""
            QScrollArea {
                background-color:#fce94f;
                border-color:#c4a000;
                padding: 0px 0px 0px 0px;
                margin: 0px 0px 0px 0px;
            }
        """)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # 1. FRAME
        self.__frm = QFrame()
        self.__frm.setStyleSheet("QFrame { background: #ff25292d; border: none; }")
        self.__frm.setMinimumHeight(100)

        # 2. LAYOUT
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)

        # 3. SELF
        self.setWidget(self.__frm)
        self.setWidgetResizable(True)
        return

class Frame(QFrame):
    '''
    The Frame(), will be second widget in the Splitter()

    '''
    def __init__(self):
        super().__init__()
        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        # 1. FRAME
        self.setStyleSheet("""
            QFrame {
                background-color:#fcaf3e;
                border-color:#ce5c00;
                padding: 0px 0px 0px 0px;
                margin: 0px 0px 0px 0px;
            }
        """)
        self.__lyt = QVBoxLayout()
        self.__lyt.setAlignment(Qt.AlignTop)
        self.__lyt.setSpacing(0)
        self.__lyt.setContentsMargins(10, 10, 10, 10)
        self.setLayout(self.__lyt)
        return

class Splitter(QSplitter):
    '''
    The Splitter().

    '''
    def __init__(self, widg1, widg2):
        super().__init__()
        self.setOrientation(Qt.Horizontal)
        self.addWidget(widg1)
        self.addWidget(widg2)
        self.setStretchFactor(0, 5)
        self.setStretchFactor(1, 5)
        return

    def createHandle(self):
        return QSplitterHandle(self.orientation(), self)

class CustomMainWindow(QMainWindow):
    '''
    CustomMainWindow(), a QMainWindow() to start the whole setup.

    '''
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 600, 300)
        self.setWindowTitle("QSPLITTER TEST")

        # 1. OUTER FRAME
        self.__frm = QFrame()
        self.__frm.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.__frm.setStyleSheet("""
            QFrame {
                background-color: #eeeeec;
                border-color: #2e3436;
            }
        """)
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.show()

        # 2. WIDGETS TO BE PUT IN SPLITTER
        self.__widg1 = Scroller()
        self.__widg2 = Frame()

        # 3. SPLITTER
        self.__splitter = Splitter(self.__widg1, self.__widg2)
        self.__lyt.addWidget(self.__splitter)
        return

if __name__== '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())
```

答:
QSplitter not only takes the stretch factor as a reference, it also takes into account the sizeHint(). If the following is added:

# ...
# 3. SPLITTER
self.__splitter = Splitter(self.__widg1, self.__widg2)
self.__lyt.addWidget(self.__splitter)
print(self.__widg1.sizeHint(), self.__widg2.sizeHint())
return
```

<p>You get the following:</p>

```PyQt5.QtCore.QSize(38, 22) PyQt5.QtCore.QSize(20, 20)
```

<p>Where we see that the QScrollArea has a greater width in the sizeHint() than the QFrame, and that explains why the observed behavior.</p>

<p>The solution is to establish the same width of sizeHint(), that is, not depend on what it contains.</p>

<pre class="lang-py prettyprint-override"><code>class Scroller(QScrollArea):
    # ...

    def sizeHint(self):
        s = super().sizeHint()
        s.setWidth(20) # same width
        return s

class Frame(QFrame):
    # ...

    def sizeHint(self):
        s = super().sizeHint()
        s.setWidth(20) # same width
        return s
# ...
</code>```

Output:

Body:
QSplitter not only takes the stretch factor as a reference, it also takes into account the sizeHint(). If the following is added:

# ...
# 3. SPLITTER
self.__splitter = Splitter(self.__widg1, self.__widg2)
self.__lyt.addWidget(self.__splitter)
print(self.__widg1.sizeHint(), self.__widg2.sizeHint())
return

You get the following:

PyQt5.QtCore.QSize(38, 22) PyQt5.QtCore.QSize(20, 20)

Where we see that the QScrollArea has a greater width in the sizeHint() than the QFrame, and that explains why the observed behavior.

The solution is to establish the same width of sizeHint(), that is, not depend on what it contains.

class Scroller(QScrollArea):
    # ...

    def sizeHint(self):
        s = super().sizeHint()
        s.setWidth(20) # same width
        return s

class Frame(QFrame):
    # ...

    def sizeHint(self):
        s = super().sizeHint()
        s.setWidth(20) # same width
        return s
# ...

Output:


问:
Fixed aspect ratio View
How would I go implementing a fixed aspect ratio View? I'd like to have items with 1:1 aspect ratio in a GridView. I think it's better to subclass the children than the GridView?

EDIT: I assume this needs to be done programmatically, that's no problem. Also, I don't want to limit the size, only the aspect ratio.

答:
The ExoPlayer from Google comes with an AspectRatioFrameLayout that you use like this:

```<code><com.google.android.exoplayer2.ui.AspectRatioFrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">
    <!-- https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.html#RESIZE_MODE_FIXED_WIDTH -->

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.exoplayer2.ui.AspectRatioFrameLayout>
</code>```

Then you must set the aspect ratio programmatically:

```<code>aspectRatioFrameLayout.setAspectRatio(16f/9f)
</code>```

Note that you can also set the resize mode programmatically with setResizeMode.

Since you are obviously not going to grab the whole ExoPlayer library for this single class, you can simply copy-paste the file from GitHub to your project (it's open source):

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/java/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.java

Don't forget to grab the attribute resize_mode too:

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/res/values/attrs.xml#L18-L25

```<code><attr name="resize_mode" format="enum">
  <enum name="fit" value="0"/>
  <enum name="fixed_width" value="1"/>
  <enum name="fixed_height" value="2"/>
  <enum name="fill" value="3"/>
  <enum name="zoom" value="4"/>
</attr>
</code>```

Title: Fixed aspect ratio View

Body:
The ExoPlayer from Google comes with an AspectRatioFrameLayout that you use like this:

<com.google.android.exoplayer2.ui.AspectRatioFrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">
    <!-- https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.html#RESIZE_MODE_FIXED_WIDTH -->

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.exoplayer2.ui.AspectRatioFrameLayout>

Then you must set the aspect ratio programmatically:

aspectRatioFrameLayout.setAspectRatio(16f/9f)

Note that you can also set the resize mode programmatically with setResizeMode.

Since you are obviously not going to grab the whole ExoPlayer library for this single class, you can simply copy-paste the file from GitHub to your project (it's open source):

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/java/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.java

Don't forget to grab the attribute resize_mode too:

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/res/values/attrs.xml#L18-L25

<attr name="resize_mode" format="enum">
  <enum name="fit" value="0"/>
  <enum name="fixed_width" value="1"/>
  <enum name="fixed_height" value="2"/>
  <enum name="fill" value="3"/>
  <enum name="zoom" value="4"/>
</attr>


问:
iPhone: UIImageView Fades in - Howto?
I have an UIImageView that I want to fade in.

Is there a way to enable that on an underlying UIViewController?

I have translated the simplest answer, though they all work, C# .NET for the MonoTouch users:

```<code>public override void ViewDidAppear (bool animated)
{
    base.ViewDidAppear (animated);
    UIView.BeginAnimations ("fade in");
    UIView.SetAnimationDuration (1);
    imageView.Alpha = 1;
    UIView.CommitAnimations ();
}
</code>```

答:
Use below in your UIViewController

```<code>// add the image view
[self.view addSubview:myImageView];
// set up a transition animation
CATransition *animate = [CATransition animation];
[animate setDuration:self.animationDelay];
[animate setType:kCATransitionPush];
[animate setSubtype:kCATransitionFade];
[animate setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

[[self layer] addAnimation:animate forKey:@"fade in"];
</code>```

Title: iPhone: UIImageView Fades in - Howto?

Body:
I have an UIImageView that I want to fade in.

Is there a way to enable that on an underlying UIViewController?

I have translated the simplest answer, though they all work, C# .NET for the MonoTouch users:

public override void ViewDidAppear (bool animated)
{
    base.ViewDidAppear (animated);
    UIView.BeginAnimations ("fade in");
    UIView.SetAnimationDuration (1);
    imageView.Alpha = 1;
    UIView.CommitAnimations ();
}

Body:
Use below in your UIViewController

// add the image view
[self.view addSubview:myImageView];
// set up a transition animation
CATransition *animate = [CATransition animation];
[animate setDuration:self.animationDelay];
[animate setType:kCATransitionPush];
[animate setSubtype:kCATransitionFade];
[animate setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

[[self layer] addAnimation:animate forKey:@"fade in"];


问:
Why are constructors not inherited in java?
I am a beginner in java programming language, recently I have studied that constructors can not be inherited in java, Can anyone please explain why?

I have already read this link of C++

答:
No as stated by Mikhail; constructors are not inherited.

You cannot inherit a constructor from superclass into your subclass. However when an object is instantiated with the "new" operator in java, that object inherit all constructors from it subclass to it superclass(parent) even including those in abstract class(since they are also super class).


问:
How to split string with ',' with a condition in regex java
I want to split a string using regex in java with ',' as delimiter with a condition. it will be a delimiter if only there is one '=' character before next ','.

ex :

```<code>    String test = "APPLICATION:1:1=SECTOR,APPLICATION:2:1=INDUSTRY,DESCRIPT:1:1=Sec,tor,DESCRIPT:2:1=Industry,"
    String [] testRegex = test.split(????)
</code>```

the value of testRegex should be :

```<code>     APPLICATION:1:1=SECTOR
     APPLICATION:2:1=INDUSTRY
     DESCRIPT:1:1=Sec,tor
     DESCRIPT:2:1=Industry
</code>```

is there any idea for the regex? i can't find any example yet till now :(

答:
If separator comma should be followed by a part containing equal sign, you may use positive lookahead. </p>

```<code>String parts[] = yourString.split(",(?=[^,]*=)");
</code>```

<p>(?=) is used for positive lookahead. It wont be used for split, it is just an assertion and will be discarded from match.</p>

Body:
I want to split a string using regex in java with ',' as delimiter with a condition. it will be a delimiter if only there is one '=' character before next ','.

ex :

    String test = "APPLICATION:1:1=SECTOR,APPLICATION:2:1=INDUSTRY,DESCRIPT:1:1=Sec,tor,DESCRIPT:2:1=Industry,"
    String [] testRegex = test.split(????)

the value of testRegex should be :

     APPLICATION:1:1=SECTOR
     APPLICATION:2:1=INDUSTRY
     DESCRIPT:1:1=Sec,tor
     DESCRIPT:2:1=Industry

is there any idea for the regex? i can't find any example yet till now :(

Body:
If separator comma should be followed by a part containing equal sign, you may use positive lookahead.

String parts[] = yourString.split(",(?=[^,]*=)");

(?=) is used for positive lookahead. It wont be used for split, it is just an assertion and will be discarded from match.


问:
How to get the "host" object java
I need to get the "host" object of another object. Here an example

Suppose I have the

```<code>class Peer {
    final Service service;
    public Peer(Service service) {
        this.service = service;
    }
    public void ping() {
        service.ping();
    }
}
</code>```

and

```<code>class Service {
    public String hola() {
        this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?
    }
}
</code>```

Then in Service class, I need to get the peer object. Is this possible?

答:
Thing is:

```<code>this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?
</code>```

There is no "command" to do that. Simply spoken: java objects have no notion of the context they were created in. The only way for an instance of Service to know about the Peer that created it: for example by passing a reference to that Service object, for example within its constructor. Or by having a setter method on the Service class that allows you to do that.

But of course: that sounds like the wrong way. A service instance should be really independent of the Peers using it! In other words: if it really makes sense that a Service knows one (or multiple?!) peers, then the Service class needs a field to "remember" that relationship. But at least the example given here rather suggests that your Service should not at all know (or care) about the Peers using it!

Title: How to get the "host" object java

Body:
I need to get the "host" object of another object. Here an example

Suppose I have the

class Peer {
    final Service service;
    public Peer(Service service) {
        this.service = service;
    }
    public void ping() {
        service.ping();
    }
}

and

class Service {
    public String hola() {
        this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?
    }
}

Then in Service class, I need to get the peer object. Is this possible?

Body:
Thing is:

this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?

There is no "command" to do that. Simply spoken: java objects have no notion of the context they were created in. The only way for an instance of Service to know about the Peer that created it: for example by passing a reference to that Service object, for example within its constructor. Or by having a setter method on the Service class that allows you to do that.

But of course: that sounds like the wrong way. A service instance should be really independent of the Peers using it! In other words: if it really makes sense that a Service knows one (or multiple?!) peers, then the Service class needs a field to "remember" that relationship. But at least the example given here rather suggests that your Service should not at all know (or care) about the Peers using it!


问:
Element not interactable/not Clickable at point(x,y)
Im trying to scrape articles from multiple pages from https://edm.com/news using Selenium with chromedriver and ran into multiple errors while trying to hit the "See More" button. Any ideas of what can i try?

I have tried working with ActionChains.move_to_element(..).click.perform()
also tried multiple time.sleep calls or WebDriverWait.until... nothing seems to do the trick.

```<code>start_url = "https://edm.com/news"
browser = webdriver.Chrome(executable_path='chromedriver.exe',      options=self.option)
browser.get(self.start_url)
# Wait max 10 secs for page to load
timeout = 10
WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="lyra-wrapper"]/div/div[3]/section/'
                                     'div[2]/section[2]/section/div/button')))
time.sleep(2)
button = browser.find_elements(By.XPATH, '//*[@id="lyra-wrapper"]/div/div[3]/section/'
                                         'div[2]/section[2]/section/div/button')[0]
button.click()
</code>```

```<code>  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (508, 4270)
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.17763 x86_64)```

```

答:
```<code><button class="m-component-footer--loader m-button" onclick="return phoenixTrackClickEvent(this, event);" phx-track-id="load more">
    <div class="m-component-footer--text m-component-footer--loading">Loading…</div>
    <div class="m-component-footer--text m-component-footer--button-text">See More</div>
</button>
</code>```

If you look closely, button tag has 2 div in it. So you need to use xpath for See More div which is //*[@id="lyra-wrapper"]/div/div[3]/section/div[2]/section[2]/section/div/button/div[2]. Then use click() on it.

Body:
Im trying to scrape articles from multiple pages from https://edm.com/news using Selenium with chromedriver and ran into multiple errors while trying to hit the "See More" button. Any ideas of what can i try?

I have tried working with ActionChains.move_to_element(..).click.perform()
also tried multiple time.sleep calls or WebDriverWait.until... nothing seems to do the trick.

start_url = "https://edm.com/news"
browser = webdriver.Chrome(executable_path='chromedriver.exe',      options=self.option)
browser.get(self.start_url)
# Wait max 10 secs for page to load
timeout = 10
WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="lyra-wrapper"]/div/div[3]/section/'
                                     'div[2]/section[2]/section/div/button')))
time.sleep(2)
button = browser.find_elements(By.XPATH, '//*[@id="lyra-wrapper"]/div/div[3]/section/'
                                         'div[2]/section[2]/section/div/button')[0]
button.click()

  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (508, 4270)
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.17763 x86_64)```

Body:
<button class="m-component-footer--loader m-button" onclick="return phoenixTrackClickEvent(this, event);" phx-track-id="load more">
    <div class="m-component-footer--text m-component-footer--loading">Loading…</div>
    <div class="m-component-footer--text m-component-footer--button-text">See More</div>
</button>

If you look closely, button tag has 2 div in it. So you need to use xpath for See More div which is //*[@id="lyra-wrapper"]/div/div[3]/section/div[2]/section[2]/section/div/button/div[2]. Then use click() on it.


问:
Add ALT attribute via jquery seems not working as expected
I'm trying to auto assign the alt attribute to images without it. This is my code:

```<code>$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});
</code>```

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.

答:
```<code>$("img").prop("alt", "This is some alt text");
</code>```

Body:
I'm trying to auto assign the alt attribute to images without it. This is my code:

$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.


问:
Classify file extension and applying logic
Need to execute logic depending on the file extension.

Input: $FileName = "ABC.tar.gz.manifest" or "ABC.tar.gz" or "ABC.zip"

```<code>$EXTZ = ".zip"
$EXTGZ = "tar.gz"
$EXT = $FileName -match "$EXTZ"

$EXT
if ($EXT = 'True') {
    Write-Host "$EXTZ"
} elseif ($EXT = 'False') {
   Write-Host "$EXTGZ"
}
</code>```

But the problem is some files are having the double extension.
How we can solve this?

If the extension is .zip need to print "ABC".

If the file extension is .tar.gz or .tar.gz.manifest need to print "XYZ".

答:
I'd use a Regular Expression and a switch instead of multiple if commands

```<code>## Q:\Test\2019\05\27\SO_56322763.ps1

foreach ($FileName in ("ABC.tar.gz.manifest","ABC.tar.gz","ABC.zip","foo.bar")){
    "`$FileName is: {0}" -f $FileName

    switch -regex ($FileName){
        "\.tar\.gz(\.manifest)?$" {"XYZ";Break}
        "\.zip$"                  {"ABC";Break}
        default                   {"anything"}
    }
}
</code>```

Sample output:

```<code>> Q:\Test\2019\05\27\SO_56322763.ps1
$FileName is: ABC.tar.gz.manifest
XYZ
$FileName is: ABC.tar.gz
XYZ
$FileName is: ABC.zip
ABC
$FileName is: foo.bar
anything
</code>```

Body:
Need to execute logic depending on the file extension.

Input: $FileName = "ABC.tar.gz.manifest" or "ABC.tar.gz" or "ABC.zip"

$EXTZ = ".zip"
$EXTGZ = "tar.gz"
$EXT = $FileName -match "$EXTZ"

$EXT
if ($EXT = 'True') {
    Write-Host "$EXTZ"
} elseif ($EXT = 'False') {
   Write-Host "$EXTGZ"
}

But the problem is some files are having the double extension.
How we can solve this?

If the extension is .zip need to print "ABC".

If the file extension is .tar.gz or .tar.gz.manifest need to print "XYZ".

Body:
I'd use a Regular Expression and a switch instead of multiple if commands

## Q:\Test\2019\05\27\SO_56322763.ps1

foreach ($FileName in ("ABC.tar.gz.manifest","ABC.tar.gz","ABC.zip","foo.bar")){
    "`$FileName is: {0}" -f $FileName

    switch -regex ($FileName){
        "\.tar\.gz(\.manifest)?$" {"XYZ";Break}
        "\.zip$"                  {"ABC";Break}
        default                   {"anything"}
    }
}

Sample output:

> Q:\Test\2019\05\27\SO_56322763.ps1
$FileName is: ABC.tar.gz.manifest
XYZ
$FileName is: ABC.tar.gz
XYZ
$FileName is: ABC.zip
ABC
$FileName is: foo.bar
anything


问:
Android Hide keyboard when changing fragments
When I change fragments. I am using this to close the keyboard because there is an EditText field on the screen. I just feel like there has to be a better way, but I havent found anything on detecting if the keyboard is on the screen.</p>

```<code>Activity activity = getActivity();
InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
try
{
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e)
{

}
</code>```

答:
You can use following code in pause method:</p>

```<code>@Override
protected void onPause() {
    super.onPause();

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}
</code>```

Body:
When I change fragments. I am using this to close the keyboard because there is an EditText field on the screen. I just feel like there has to be a better way, but I havent found anything on detecting if the keyboard is on the screen.

Activity activity = getActivity();
InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
try
{
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e)
{

}

Body:
You can use following code in pause method:

@Override
protected void onPause() {
    super.onPause();

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}


问:
How to get value
I have a problem and a code like this.

```<code>{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}
</code>```

I was difficult to get the value.
I need a value like this :

Success
F3YQ
10610
JKT2

答:
Suppose data is stored in a variable</p>

```<code>$data = {"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]};

$values = json_decode($data);

echo $values['description'][0]['STORECODE'];
</code>```

Title: How to get value

Body:
I have a problem and a code like this.

{"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]}

I was difficult to get the value.
I need a value like this :

Success
F3YQ
10610
JKT2

Body:
Suppose data is stored in a variable

$data = {"resultcode":"0","message":"Success","description":[{"STORECODE":"F3YQ","STORENAME":"BUNGUR BESAR 30B","ADDRESS":"JL.BUNGUR BESAR NO.30BGUNUNG SAHARI SELATAN","PHONE":"021","POSTALCODE":"10610","OPHOURS":"EVERYDAY (07.00-22.00)","LATITUDE":"-6.1605556","LONGITUDE":"106.8391667","DCCODE":"G137","DCNAME":"JKT2"}]};

$values = json_decode($data);

echo $values['description'][0]['STORECODE'];


问:
Using JQuery to call a WebMethod
I am having trouble getting inside my Search WebMethod from my JQuery call.
Maybe someone could help to point me in the right direction.

I also packed up everything into a zip file incase someone wants to check it out for a closer look.

http://www.filedropper.com/jsonexample

Thanks
Ryan

```<code>    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>JSON Example</title>
    <script type="text/javascript" language="JavaScript" src="jquery-1.3.1.min.js"></script>

<script type="text/javascript" language="javascript">

function Search() {
    var search = $("#searchbox").val();
    var options = {
        type: "POST",
        url: "Default.aspx/Search",
        data: "{text:" + search + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert('Success!');
        }
    };
    $.ajax(options);
}
</script>

</head>
<body>
    <form id="form1" runat="server">
        <input type="text" id="searchbox" size="40" />
        <a href="#" onclick="Search()" id="goSearch">Search</a>
        <br />
        <div id="Load" />
    </form>
</body>
</html>
</code>```

And here is the code behind for the default.aspx

```<code> Imports System.Data
    Imports System.Web.Services
    Imports System.Web.Script.Serialization

    Partial Class _Default
        Inherits System.Web.UI.Page

        <WebMethod()> _
        Public Shared Function Search(ByVal text As String) As IEnumerable
            Return "test"
        End Function

    End Class
</code>```

答:
To solve a problem like this, the first thing to do is watch it in Firebug.

If you click the "Search" link and watch the POST request/response in Firebug's console, you'll see it's throwing a 500 server error:  Invalid JSON Primitive.

The reason for that is because the key/value identifiers in your "data" JSON literal aren't quoted.  Line 17 should be:

```<code>data: "{'text':'" + search + "'}",
</code>```

Then, all will work as expected.

Note:  The suggested data { test: search } will not work.  If you provide jQuery with an actual JSON literal instead of a string, it will convert that into a key/value pair of test=search and POST that instead of the JSON.  That will also cause an ASP.NET AJAX ScriptService or PageMethod to throw the Invalid JSON Primitive error.

OwnerDisplayName: Ryan

LastEditorDisplayName: CQ

ContentLicense: CC BY-SA 2.5

Title: Using JQuery to call a WebMethod

Body:
I am having trouble getting inside my Search WebMethod from my JQuery call.
Maybe someone could help to point me in the right direction.

I also packed up everything into a zip file incase someone wants to check it out for a closer look.

http://www.filedropper.com/jsonexample

Thanks
Ryan

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>JSON Example</title>

    <form id="form1" runat="server">
        <input type="text" id="searchbox" size="40" />
        Search

    </form>

And here is the code behind for the default.aspx

 Imports System.Data
    Imports System.Web.Services
    Imports System.Web.Script.Serialization

    Partial Class _Default
        Inherits System.Web.UI.Page

        <WebMethod()> _
        Public Shared Function Search(ByVal text As String) As IEnumerable
            Return "test"
        End Function

    End Class

Body:
To solve a problem like this, the first thing to do is watch it in Firebug.

If you click the "Search" link and watch the POST request/response in Firebug's console, you'll see it's throwing a 500 server error:  Invalid JSON Primitive.

The reason for that is because the key/value identifiers in your "data" JSON literal aren't quoted.  Line 17 should be:

data: "{'text':'" + search + "'}",

Then, all will work as expected.

Note:  The suggested data { test: search } will not work.  If you provide jQuery with an actual JSON literal instead of a string, it will convert that into a key/value pair of test=search and POST that instead of the JSON.  That will also cause an ASP.NET AJAX ScriptService or PageMethod to throw the Invalid JSON Primitive error.

OwnerDisplayName: Dave Ward


问:
Define a variable in Helm template
I need to define a variable based on an if statement and use that variable multiple times.
In order not to repeat the if I tried something like this:

```<code>{{ if condition}}
    {{ $my_val = "http" }}
{{ else }}
    {{ $my_val = "https" }}
{{ end }}
{{ $my_val }}://google.com
</code>```

However this returns an error:

```<code>Error: render error in "templates/deployment.yaml":
template: templates/deployment.yaml:30:28:
executing "templates/deployment.yaml" at
<include (print $.Template.BasePath "/config.yaml") .>: error calling
include: template: templates/config.yaml:175:59:
executing "templates/config.yaml" at <"https">: undefined variable: $my_val
</code>```

Ideas?

答:
The most direct path to this is to use the ternary function provided by the Sprig library.  That would let you write something like

```<code>{{ $myVal := ternary "http" "https" condition -}}
{{ $myVal }}://google.com
</code>```

A simpler, but more indirect path, is to write a template that generates the value, and calls it

```<code>{{- define "scheme" -}}
{{- if condition }}http{{ else }}https{{ end }}
{{- end -}}

{{ template "scheme" . }}://google.com
</code>```

If you need to include this in another variable, Helm provides an include function that acts just like template except that it's an "expression" rather than something that outputs directly.

```<code>{{- $url := printf "%s://google.com" (include "scheme" .) -}}
</code>```

Title: Define a variable in Helm template

Body:
I need to define a variable based on an if statement and use that variable multiple times.
In order not to repeat the if I tried something like this:

{{ if condition}}
    {{ $my_val = "http" }}
{{ else }}
    {{ $my_val = "https" }}
{{ end }}
{{ $my_val }}://google.com

However this returns an error:

Error: render error in "templates/deployment.yaml":
template: templates/deployment.yaml:30:28:
executing "templates/deployment.yaml" at
<include (print $.Template.BasePath "/config.yaml") .>: error calling
include: template: templates/config.yaml:175:59:
executing "templates/config.yaml" at <"https">: undefined variable: $my_val

Ideas?

Body:
The most direct path to this is to use the ternary function provided by the Sprig library.  That would let you write something like

{{ $myVal := ternary "http" "https" condition -}}
{{ $myVal }}://google.com

A simpler, but more indirect path, is to write a template that generates the value, and calls it

{{- define "scheme" -}}
{{- if condition }}http{{ else }}https{{ end }}
{{- end -}}

{{ template "scheme" . }}://google.com

If you need to include this in another variable, Helm provides an include function that acts just like template except that it's an "expression" rather than something that outputs directly.

{{- $url := printf "%s://google.com" (include "scheme" .) -}}


答:
try finding the element by the text "See More"

```<code>start_url = "https://edm.com/news"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
browser.get(start_url)

# Wait max 10 secs for page to load
wait = WebDriverWait(browser, 10)
time.sleep(2)

close_advert = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="lyra-wrapper"]/div/div[4]/phoenix-ad[2]/div/div[2]')))
close_advert.click()

see_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(.,"See More")]')))

time.sleep(2)

try:
    see_more.click()
except:
    time.sleep(3)
    see_more.click()
</code>```

Title: Element not interactable/not Clickable at point(x,y)

Body:
try finding the element by the text "See More"

start_url = "https://edm.com/news"
browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
browser.get(start_url)

# Wait max 10 secs for page to load
wait = WebDriverWait(browser, 10)
time.sleep(2)

close_advert = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="lyra-wrapper"]/div/div[4]/phoenix-ad[2]/div/div[2]')))
close_advert.click()

see_more = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(.,"See More")]')))

time.sleep(2)

try:
    see_more.click()
except:
    time.sleep(3)
    see_more.click()


答:
It is quite straight forward,</p>

```<code>$a = json_decode($yourArr, true); // last parameter to convert it into array
echo $a['message'].' '.$a['description'][0]['STORECODE'].' '.$a['description'][0]['POSTALCODE'].' '.$a['description'][0]['DCNAME'];
</code>```

Title: How to get value

Body:
It is quite straight forward,

$a = json_decode($yourArr, true); // last parameter to convert it into array
echo $a['message'].' '.$a['description'][0]['STORECODE'].' '.$a['description'][0]['POSTALCODE'].' '.$a['description'][0]['DCNAME'];


问:
Create Flowable from while loop
I am pretty new to RxJava and I need to create repository with several datasources. It is complex to me because there are several smaller subtasks which I don't know how to implement with RxJava.

First I have self written dao, which process InputStream, and provides Items in the specified range. Currently it simply collects data in a list, but I want to provide Items one by one using flowable; Currently it privides Maybe<List<Item>>. Also there several errors need to be transmitted to higher level (datasource). Such as EndOfFile, to notify DataSource that data fully cached;

Dao.class:

```<code>List<Item> loadRange(int start, int number) throws ... {
    ...
    while(...) {
        ...
        //TODO contribute item to flowable
        resultList.add(new Item(...))

    }
    return resultList;
}
</code>```

Maybe<List<Item>> method just created Maybe.fromCallable();

Please help me!

答:
Something like this should work for this :

```<code>Flowable<Item> loadRange(int start, int number) {
        return Flowable.create(emitter -> {
            try {
                while (...){
                    emitter.onNext(new Item());
                }
                emitter.onComplete();
            } catch (IOException e) {
                emitter.onError(e);
            }
        }, BackpressureStrategy.BUFFER);
    }
</code>```

I assume once the loop is done you want to complete, also send errors downstream, rather than handle on the method signature.  Also you can change the BackPressureStrategy to suit your usecase i.e DROP, LATEST etc..

As you're new to RxJava, the anonymous class would be :

```<code>Flowable<Item> loadRange(int start, int number) {
        return Flowable.create(new FlowableOnSubscribe<Item>() {
            @Override public void subscribe(FlowableEmitter<Item> emitter) {
                try {
                    while (...){
                        emitter.onNext(new Item());
                    }
                    emitter.onComplete();
                } catch (IOException e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);
    }
</code>```

Title: Create Flowable from while loop

Body:
I am pretty new to RxJava and I need to create repository with several datasources. It is complex to me because there are several smaller subtasks which I don't know how to implement with RxJava.

First I have self written dao, which process InputStream, and provides Items in the specified range. Currently it simply collects data in a list, but I want to provide Items one by one using flowable; Currently it privides Maybe<List<Item>>. Also there several errors need to be transmitted to higher level (datasource). Such as EndOfFile, to notify DataSource that data fully cached;

Dao.class:

List<Item> loadRange(int start, int number) throws ... {
    ...
    while(...) {
        ...
        //TODO contribute item to flowable
        resultList.add(new Item(...))

    }
    return resultList;
}

Maybe<List<Item>> method just created Maybe.fromCallable();

Please help me!

Body:
Something like this should work for this :

Flowable<Item> loadRange(int start, int number) {
        return Flowable.create(emitter -> {
            try {
                while (...){
                    emitter.onNext(new Item());
                }
                emitter.onComplete();
            } catch (IOException e) {
                emitter.onError(e);
            }
        }, BackpressureStrategy.BUFFER);
    }

I assume once the loop is done you want to complete, also send errors downstream, rather than handle on the method signature.  Also you can change the BackPressureStrategy to suit your usecase i.e DROP, LATEST etc..

As you're new to RxJava, the anonymous class would be :

Flowable<Item> loadRange(int start, int number) {
        return Flowable.create(new FlowableOnSubscribe<Item>() {
            @Override public void subscribe(FlowableEmitter<Item> emitter) {
                try {
                    while (...){
                        emitter.onNext(new Item());
                    }
                    emitter.onComplete();
                } catch (IOException e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);
    }


问:
AWS CodeDeploy stuck in AllowTraffic step
I'm using AWS CodeDeploy to deploy my project (triggered by CodePipeline) to an autoscaling group (EC2 instances behind an ALB). This is my appSpec file:

version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html/test-deploy
    overwrite: true
permissions:
  - object: /var/www/html/test-deploy/codedeploy
    pattern: "*.sh"
    owner: root
    group: root
    mode: 755
    type:
      - file
hooks:
  BeforeInstall:
    - location: codedeploy/before_install.sh
      timeout: 180
  AfterInstall:
    - location: codedeploy/after_install.sh
      runas: centos
      timeout: 180```

The files get deployed successfully to the EC2 instance, but for some reason after the "BeforeAllowTraffic" nothing happens, like I waited 15 min and the next step was still at "pending".

The two .sh files do nothing fancy (and codedeploy passed those steps so I don't think that's the problem).

Can anyone point me to a direction? I don't get any error messages, so I don't even know how to debug it.

Thanks

答: I have got the same issue, after investigation, I found that my target group was "unhealthy". I just add the health check path/file i.e "/rorbots.txt" and rebooted the Ec2 Server and its fixed the problem. </p>

Body:
I'm using AWS CodeDeploy to deploy my project (triggered by CodePipeline) to an autoscaling group (EC2 instances behind an ALB). This is my appSpec file:

version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html/test-deploy
    overwrite: true
permissions:
  - object: /var/www/html/test-deploy/codedeploy
    pattern: "*.sh"
    owner: root
    group: root
    mode: 755
    type:
      - file
hooks:
  BeforeInstall:
    - location: codedeploy/before_install.sh
      timeout: 180
  AfterInstall:
    - location: codedeploy/after_install.sh
      runas: centos
      timeout: 180

The files get deployed successfully to the EC2 instance, but for some reason after the "BeforeAllowTraffic" nothing happens, like I waited 15 min and the next step was still at "pending".

The two .sh files do nothing fancy (and codedeploy passed those steps so I don't think that's the problem).

Can anyone point me to a direction? I don't get any error messages, so I don't even know how to debug it.

Thanks


问:
Invalid utf8 character string on mysqldump script
I've created a copy of a database and changed the collation and charset to utf8mb4 (originally it was latin1), then used mysqldump to create a script for a Flyway database migration.

When I run the following script

```<code>-- MySQL dump 10.13  Distrib 5.5.62, for Win64 (AMD64)
--
-- Host: localhost    Database: feedback
-- ------------------------------------------------------
-- Server version   8.0.15

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Dumping data for table `COMPONENT_GROUP`
--

LOCK TABLES `COMPONENT_GROUP` WRITE;
/*!40000 ALTER TABLE `COMPONENT_GROUP` DISABLE KEYS */;
INSERT INTO `COMPONENT_GROUP` VALUES ('AAAB','AAA - MOTOR','LUBRIFICAÇÃO DO MOTOR','LUBRIFICAÇÃO DO MOTOR',NULL,NULL,20181219,1)
UNLOCK TABLES;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2019-05-22 13:07:38
</code>```

flyway shows messages like these:

```<code>WARNING: DB: Invalid utf8 character string: 'C7C34F' (SQL State: HY000 - Error Code: 1300)
WARNING: DB: Incorrect string value: '\xC3O FUN...' for column 'claimed_name_pt' at row 10 (SQL State: HY000 - Error Code: 1366)
</code>```

When I run the dump script using tools like SQLyog and MySQL Workbench the data is correctly inserted, so how can I fix that for Flyway?

答:
Found the missing part to fix the migration issue. I had to add encoding settings to the Flyway's connection string:</p>

```<code>FLYWAY_URL="jdbc:mysql://${db_instance.default.address}:3306/${mysql_database.db-app.name}?characterEncoding=UTF-8&useUnicode=true"
</code>```

Body:
I've created a copy of a database and changed the collation and charset to utf8mb4 (originally it was latin1), then used mysqldump to create a script for a Flyway database migration.

When I run the following script

-- MySQL dump 10.13  Distrib 5.5.62, for Win64 (AMD64)
--
-- Host: localhost    Database: feedback
-- ------------------------------------------------------
-- Server version   8.0.15

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Dumping data for table `COMPONENT_GROUP`
--

LOCK TABLES `COMPONENT_GROUP` WRITE;
/*!40000 ALTER TABLE `COMPONENT_GROUP` DISABLE KEYS */;
INSERT INTO `COMPONENT_GROUP` VALUES ('AAAB','AAA - MOTOR','LUBRIFICAÇÃO DO MOTOR','LUBRIFICAÇÃO DO MOTOR',NULL,NULL,20181219,1)
UNLOCK TABLES;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2019-05-22 13:07:38

flyway shows messages like these:

WARNING: DB: Invalid utf8 character string: 'C7C34F' (SQL State: HY000 - Error Code: 1300)
WARNING: DB: Incorrect string value: '\xC3O FUN...' for column 'claimed_name_pt' at row 10 (SQL State: HY000 - Error Code: 1366)

When I run the dump script using tools like SQLyog and MySQL Workbench the data is correctly inserted, so how can I fix that for Flyway?

Body:
Found the missing part to fix the migration issue. I had to add encoding settings to the Flyway's connection string:

FLYWAY_URL="jdbc:mysql://${db_instance.default.address}:3306/${mysql_database.db-app.name}?characterEncoding=UTF-8&useUnicode=true"


问:
Force UITableView to scroll to top?
How would you go about forcing a UITableViewCell to scroll to the top if the tableview contains less than 10 or so cells? I support editing of Managed Object Contexts within my tableView cells while the tableview is in editing mode. Needless to say, if a cell is at the bottom of the tableview, it gets blocked by the keyboard when a user goes to edit the title or location of an event. I tried a solution like:

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if(_selectedIndex == indexPath.row){
        _selectedIndex = -1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        return;
    }

    if(_selectedIndex >= 0){
        NSIndexPath *previous = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
        _selectedIndex = indexPath.row;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previous]
                         withRowAnimation:UITableViewRowAnimationFade];
    }

    _selectedIndex = indexPath.row;
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [tableView setContentOffset:CGPointMake(0, [tableView rowHeight]*indexPath.row) animated:YES];
}
</code>```

But this does not keep the tableview at the contentOffset. it will snap to the top and then snap back

答:
More specified answer to your question:</p>

```<code>extension UITableView {

    func scrollToBottom(){

        DispatchQueue.main.async {
            let indexPath = IndexPath(
                row: self.numberOfRows(inSection:  self.numberOfSections -1) - 1,
                section: self.numberOfSections - 1)
            self.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }

    func scrollToTop() {

        DispatchQueue.main.async {
            let indexPath = IndexPath(row: 0, section: 0)
            self.scrollToRow(at: indexPath, at: .top, animated: false)
        }
    }
}
</code>```

Title: Force UITableView to scroll to top?

Body:
How would you go about forcing a UITableViewCell to scroll to the top if the tableview contains less than 10 or so cells? I support editing of Managed Object Contexts within my tableView cells while the tableview is in editing mode. Needless to say, if a cell is at the bottom of the tableview, it gets blocked by the keyboard when a user goes to edit the title or location of an event. I tried a solution like:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if(_selectedIndex == indexPath.row){
        _selectedIndex = -1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        return;
    }

    if(_selectedIndex >= 0){
        NSIndexPath *previous = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
        _selectedIndex = indexPath.row;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previous]
                         withRowAnimation:UITableViewRowAnimationFade];
    }

    _selectedIndex = indexPath.row;
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [tableView setContentOffset:CGPointMake(0, [tableView rowHeight]*indexPath.row) animated:YES];
}

But this does not keep the tableview at the contentOffset. it will snap to the top and then snap back

Body:
More specified answer to your question:

extension UITableView {

    func scrollToBottom(){

        DispatchQueue.main.async {
            let indexPath = IndexPath(
                row: self.numberOfRows(inSection:  self.numberOfSections -1) - 1,
                section: self.numberOfSections - 1)
            self.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }

    func scrollToTop() {

        DispatchQueue.main.async {
            let indexPath = IndexPath(row: 0, section: 0)
            self.scrollToRow(at: indexPath, at: .top, animated: false)
        }
    }
}


问:
Can i launch both IOS , Android and browsers in the same instance
i want to automate an application that has both androids and IOS versions, application Admins side is  web-based if User change the anything from the admin side this change impact on the Android and IOS version, I do not know how i can automate my application ? can it is possible in the same instance i can launch Browser, IOS, and Android native apps ?</p>

答:
You will have to have 3 different WebDriver instances:

AndroidDriver - to orchestrate Andorid device (or emulator)

IOSDriver - to control iOS device (or simulator)

An appropriate WebDriver implementation for the desktop browser

Make sure to write thread-safe code in particular:

Use Thread Local Storage pattern to avoid clashes between above 3 WebDrivers

Avoid using static fields and functions unless you explicitly need it

Your tests must be ACID

More information (including sample project you can use as a reference): Parallel Tests - Best Practices


问:
Creating "Not Exists"/Insert Into Statements - Stumped by nothing (NULL)
I need a script that generate insert statements but with check for if the data doesn't already exist, this because it should be periodically run on parallell systems where different dtata will be added to the systems but we want them tables to be in sync. I have the basic ides and borrowed parts of code but get a syntax error i have trouble solving.

I'm basing my code on the code Param Yadav showed at Converting Select results into Insert script - SQL Server but I need to check for data already in the table. (I need to add more "bells & whistles later, but take this step-by-step)

My own main addition is the @NOT_EXISTS part which should be in the WHERE clause of the NOT EXISTS check. If I replace that with a plain WHERE 0=1 I get no syntax error so it indicates the error is in my @NOT_EXISTS string.

Edit: Yesterday I thought I had an answer to my own question but when running on "real data" I saw that some lines are too long for QUOTENAME, I have to fix those quotation marks "manually" (concats in script) instead...

```<code>
SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
    @QUOTED_DATA VARCHAR(MAX),
    @NOT_EXISTS VARCHAR(MAX),
    @SQL_KOD VARCHAR(MAX),
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)='',
    @FIRST_COL INT,
    @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

--SELECT @CSV_COLUMN

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @QUOTED_DATA

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']=', 'ISNULL(QUOTENAME('+COLUMN_NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+') AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-4)

SELECT @NOT_EXISTS
--SELECT @NOT_EXISTS=' 0=1 '

SELECT @SQL_KOD='SELECT ''
    IF NOT EXISTS(SELECT 1
    FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ')
    BEGIN
        INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')
        VALUES('''+'+'+@QUOTED_DATA+'+'+''')
    END
    GO '''+' Insert_Scripts
FROM '+@TABLE_NAME + @FILTER_CONDITION

SELECT @SQL_KOD
EXECUTE (@SQL_KOD)

GO

[stackoverflow won't let me post code unless it's formatted, but then the strings below won't be as they are created in the script...]
When I do SELECT @NOT_EXISTS=' 0=1 ' I get an INSERT line for each row in my table:

IF NOT EXISTS(SELECT 1 FROM WorkflowError WHERE  0=1 )
    BEGIN
        INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
        VALUES('EttLiv','800','Value cannot be null.  Parameter name: source','0',NULL,'Value cannot be null.  Parameter name: source')
    END
GO

With my @NOT_EXISTS code the @SQL_KOD string becomes this:

SELECT 'IF NOT EXISTS(SELECT 1 FROM WorkflowError
                      WHERE [TargetSystem]=ISNULL(QUOTENAME(TargetSystem,''''),'NULL'))
BEGIN
    INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
    VALUES('+ISNULL(QUOTENAME(TargetSystem,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorCode,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorText,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryMaxCount,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryStrategyName,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorDescription,''''),'NULL')+')
END
GO ' Insert_Scripts FROM WorkflowError
However, trying to execute that @SQL_KOD line just gives:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'NULL'.

...and I can't find out where I have done wrong, if it's in my thinking or if it's just a misplaced quotation mark...
</code>```

答:
I originally used QUOTENAME as in the Param Yadav script I borrowed from but that function can't handle long strings. It doesn't complain, just returns NULL if the string is too long. Now the script is less readable (long lines of quotation marks) but now works.</p>

```<code>
SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @NOT_EXISTS VARCHAR(MAX),
        @SQL_KOD VARCHAR(MAX),
        @TABLE_NAME VARCHAR(MAX),
        @FILTER_CONDITION VARCHAR(MAX),
        @FIRST_COL INT,
        @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
SELECT @FILTER_CONDITION = ''
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL('''''''' + REPLACE('+NAME+','''''''','''''''''''') + '''''''','''+'NULL'''+''+')+'',''+'
     FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']='' + ', 'ISNULL('''''''' + REPLACE('+COLUMN_NAME+','''''''','''''''''''') + '''''''','''+'NULL'''+''+')+'' AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-6)

SELECT @SQL_KOD='SELECT ''IF NOT EXISTS(SELECT 1 FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ' + ' + ''') BEGIN INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+@QUOTED_DATA+'+'+''') END '''+' Insert_Scripts FROM ' + @TABLE_NAME + ' ' + @FILTER_CONDITION

EXECUTE (@SQL_KOD)

SET NOCOUNT OFF

</code>```

Body:
I need a script that generate insert statements but with check for if the data doesn't already exist, this because it should be periodically run on parallell systems where different dtata will be added to the systems but we want them tables to be in sync. I have the basic ides and borrowed parts of code but get a syntax error i have trouble solving.

I'm basing my code on the code Param Yadav showed at Converting Select results into Insert script - SQL Server but I need to check for data already in the table. (I need to add more "bells & whistles later, but take this step-by-step)

My own main addition is the @NOT_EXISTS part which should be in the WHERE clause of the NOT EXISTS check. If I replace that with a plain WHERE 0=1 I get no syntax error so it indicates the error is in my @NOT_EXISTS string.

Edit: Yesterday I thought I had an answer to my own question but when running on "real data" I saw that some lines are too long for QUOTENAME, I have to fix those quotation marks "manually" (concats in script) instead...

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
    @QUOTED_DATA VARCHAR(MAX),
    @NOT_EXISTS VARCHAR(MAX),
    @SQL_KOD VARCHAR(MAX),
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)='',
    @FIRST_COL INT,
    @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

--SELECT @CSV_COLUMN

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @QUOTED_DATA

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']=', 'ISNULL(QUOTENAME('+COLUMN_NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+') AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-4)

SELECT @NOT_EXISTS
--SELECT @NOT_EXISTS=' 0=1 '

SELECT @SQL_KOD='SELECT ''
    IF NOT EXISTS(SELECT 1
    FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ')
    BEGIN
        INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')
        VALUES('''+'+'+@QUOTED_DATA+'+'+''')
    END
    GO '''+' Insert_Scripts
FROM '+@TABLE_NAME + @FILTER_CONDITION

SELECT @SQL_KOD
EXECUTE (@SQL_KOD)

GO

[stackoverflow won't let me post code unless it's formatted, but then the strings below won't be as they are created in the script...]
When I do SELECT @NOT_EXISTS=' 0=1 ' I get an INSERT line for each row in my table:

IF NOT EXISTS(SELECT 1 FROM WorkflowError WHERE  0=1 )
    BEGIN
        INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
        VALUES('EttLiv','800','Value cannot be null.  Parameter name: source','0',NULL,'Value cannot be null.  Parameter name: source')
    END
GO

With my @NOT_EXISTS code the @SQL_KOD string becomes this:

SELECT 'IF NOT EXISTS(SELECT 1 FROM WorkflowError
                      WHERE [TargetSystem]=ISNULL(QUOTENAME(TargetSystem,''''),'NULL'))
BEGIN
    INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
    VALUES('+ISNULL(QUOTENAME(TargetSystem,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorCode,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorText,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryMaxCount,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryStrategyName,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorDescription,''''),'NULL')+')
END
GO ' Insert_Scripts FROM WorkflowError
However, trying to execute that @SQL_KOD line just gives:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'NULL'.

...and I can't find out where I have done wrong, if it's in my thinking or if it's just a misplaced quotation mark...

Body:
I originally used QUOTENAME as in the Param Yadav script I borrowed from but that function can't handle long strings. It doesn't complain, just returns NULL if the string is too long. Now the script is less readable (long lines of quotation marks) but now works.

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @NOT_EXISTS VARCHAR(MAX),
        @SQL_KOD VARCHAR(MAX),
        @TABLE_NAME VARCHAR(MAX),
        @FILTER_CONDITION VARCHAR(MAX),
        @FIRST_COL INT,
        @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
SELECT @FILTER_CONDITION = ''
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL('''''''' + REPLACE('+NAME+','''''''','''''''''''') + '''''''','''+'NULL'''+''+')+'',''+'
     FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']='' + ', 'ISNULL('''''''' + REPLACE('+COLUMN_NAME+','''''''','''''''''''') + '''''''','''+'NULL'''+''+')+'' AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-6)

SELECT @SQL_KOD='SELECT ''IF NOT EXISTS(SELECT 1 FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ' + ' + ''') BEGIN INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+@QUOTED_DATA+'+'+''') END '''+' Insert_Scripts FROM ' + @TABLE_NAME + ' ' + @FILTER_CONDITION

EXECUTE (@SQL_KOD)

SET NOCOUNT OFF


问:
Determine fundamental frequency of voice recordings
I am using the command line tool aubiopitch to analyze voice recordings. My goal is to determine the fundamental frequency of the voice recorded. I know, of course, that the frequency varies – that's why I want to calculate an "average" in Hz over a 30-second recording.

My question: aubio uses different methods to determine the pitch of a recording: Schmitt trigger, harmonic comb, yin, yinfft etc. Which one of those would be my preferred choice when dealing with pure human voice recordings (no background music, atmo etc.).

答:
I would recommend using yinfast or yinfft (default). For a discussion of the algorithms, their parameters, and their performance, see Chapter 3 of this document.

Note that the median is better suited than the average in this case.


问:
How to download from mail
Denar All!
I tried to add to my mail download attribute to download a picture to recipient pc/cell Phone, (right Click, inspect code, Edit html), and it accepts simple codes to "play with", but it just ignores 3 line w3schools code with download attribute. Do I Use the wrong pc or wrong doma in and what should it be like?

Just to add, I tried both options: with an internet photo/seems this would not work either, and with the picture from my own pc. For easy peasy code no result at all, makes me already desperated, is anyone willing to help, thanks in advance!

Using Chrome 84

答:
This is most likely a cross-domain or local resource issue. You can verify this by going to DevTools (Menu -> More Tools -> Developer Tools) and checking for errors in the Developer Console.

Try running a server locally, hosting an html page and image, and pointing the image to the URL that this server is also hosting. Here is one way to do it:

Install node

Node.js quick file server (static files over HTTP)

Within that folder set up the following folder structure:

directory

index.html

image.jpg

Create index.html to have the code you want and point at "./image.jpg" with your w3 code like so:

Hit your locally running server and try again: http://localhost/index.html

Title: How to download from mail

Body:
This is most likely a cross-domain or local resource issue. You can verify this by going to DevTools (Menu -> More Tools -> Developer Tools) and checking for errors in the Developer Console.

Try running a server locally, hosting an html page and image, and pointing the image to the URL that this server is also hosting. Here is one way to do it:

Install node

Node.js quick file server (static files over HTTP)

Within that folder set up the following folder structure:

directory

index.html

image.jpg

Create index.html to have the code you want and point at "./image.jpg" with your w3 code like so:

<a href="./image.jpg" download>
  <img src="./image.jpg" alt="W3Schools" width="104" height="142">
</a>

Hit your locally running server and try again: http://localhost/index.html