问:
Mobx @observable is not work if its init value is undefined in react-native 0.59
I'm migrating react-native 0.51.1 to 0.59.8. And I'm facing a problem of Mobx.

If an @observable decorated member have assigned init value like this

@observable cnt = 0;
```

<p>then it works.</p>

<p>But if it's undefined,</p>

<pre class="lang-js prettyprint-override"><code>@observable cnt;
</code>```

then it doesn't work.

I have many undefined observable stores and they worked in 0.51.0.

I want to make it work as undefined.

Babel decorate options have been changed during migration.

// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ['@babel/plugin-transform-flow-strip-types'],
    ['@babel/plugin-proposal-decorators', { 'legacy': true}],
    ['@babel/plugin-proposal-class-properties', { 'loose': true}],
  ],
}
```

<pre class="lang-js prettyprint-override"><code>//This doesn't work but worked in react-native 0.51.0
import { observable } from 'mobx';

export class Count {
  @observable cnt;

  constructor(initValue = 0) {
    this.cnt = initValue;
  }

  add(){
    this.cnt++;
  }
}
</code>```

//This works
import { observable } from 'mobx';

export class Count {
  @observable cnt = 0;

  constructor(initValue = 0) {
    this.cnt = initValue;
  }

  add(){
    this.cnt++;
  }
}
```

答:
I solved this declaring undefined explicitly.

@observable cnt = undefined;
```

Body:
I'm migrating react-native 0.51.1 to 0.59.8. And I'm facing a problem of Mobx.

If an @observable decorated member have assigned init value like this

@observable cnt = 0;

then it works.

But if it's undefined,

@observable cnt;

then it doesn't work.

I have many undefined observable stores and they worked in 0.51.0.

I want to make it work as undefined.

Babel decorate options have been changed during migration.

// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ['@babel/plugin-transform-flow-strip-types'],
    ['@babel/plugin-proposal-decorators', { 'legacy': true}],
    ['@babel/plugin-proposal-class-properties', { 'loose': true}],
  ],
}

//This doesn't work but worked in react-native 0.51.0
import { observable } from 'mobx';

export class Count {
  @observable cnt;

  constructor(initValue = 0) {
    this.cnt = initValue;
  }

  add(){
    this.cnt++;
  }
}

//This works
import { observable } from 'mobx';

export class Count {
  @observable cnt = 0;

  constructor(initValue = 0) {
    this.cnt = initValue;
  }

  add(){
    this.cnt++;
  }
}


来源: stackexchange

问:
How to change colors in react component
In reactstrap we can set colors with default styles(such as primary, secondary, success, warning....) but how do I change it with the Hex color code?
For example, how do I change 'warning' to '#008080'?

```<code><AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'warning'} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />
</code>```

I've also tried something like this but didn't work either:

```<code>state = {
  color: '#008080'
}

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'this.state.color'}
  default checked
  onChange={this.handler} />
</code>```

答:
You should define it in constants:</p>

```<code>const hexColor = {
  color: '#008080'
};

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={hexColor[color]} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to change colors in react component

Body:
In reactstrap we can set colors with default styles(such as primary, secondary, success, warning....) but how do I change it with the Hex color code?
For example, how do I change 'warning' to '#008080'?

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'warning'} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />

I've also tried something like this but didn't work either:

state = {
  color: '#008080'
}

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'this.state.color'}
  default checked
  onChange={this.handler} />

Body:
You should define it in constants:

const hexColor = {
  color: '#008080'
};

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={hexColor[color]} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />


问:
How to read and store complete Objects in ArrayList from Fire DB
I am currently developing an app with Android Studio.

Now I would like to use the Fire DB, in order to take over the information from the data base in an Arraylist when starting the app. In this case, a node in the database should be saved as an object with its attributes.

The structure of the DB is still flexible. I had the plan to make a numbering of 1 and below the indexes all the attributes of one objet.
If anything else makes sense, this can still be changed

How can I read these and store them in a object per index, which is then put into a Array list?

I had already found several online examples, but none got to work.

Therefore, I would be grateful for an input that I can test and then possibly discuss it.

答:
Please add some sample code to understand us what you do.

You need to do following things,

1) Model Class which contains setter and getter methods (same name as you store in firebase)

If you multiple node inside one object then,

2) RecyclerView and RecyclerAdapter Class

3) DatabaseRefrence to access your data.

example code to retrive data from firebase

```<code>   final List<Certificates> list=new ArrayList<>();

    DatabaseReference reference= FirebaseDatabase.getInstance().getReference().child("Object");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            list.clear();
            for (DataSnapshot snapshot:dataSnapshot.getChildren())
            {
                Model model=snapshot.getValue(Model.class);
                list.add(model);
            }

            RecyclerAdapter adapter=new RecyclerAdapter(list,Activity.this);
            recyclerView.setLayoutManager(new LinearLayoutManager(CertificatesActivity.this));
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError)
        {
            //handle error here
        }
    });
</code>```

If you need help to understand tell me.

Body:
Please add some sample code to understand us what you do.

You need to do following things,

1) Model Class which contains setter and getter methods (same name as you store in firebase)

If you multiple node inside one object then,

2) RecyclerView and RecyclerAdapter Class

3) DatabaseRefrence to access your data.

example code to retrive data from firebase

   final List<Certificates> list=new ArrayList<>();

    DatabaseReference reference= FirebaseDatabase.getInstance().getReference().child("Object");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            list.clear();
            for (DataSnapshot snapshot:dataSnapshot.getChildren())
            {
                Model model=snapshot.getValue(Model.class);
                list.add(model);
            }

            RecyclerAdapter adapter=new RecyclerAdapter(list,Activity.this);
            recyclerView.setLayoutManager(new LinearLayoutManager(CertificatesActivity.this));
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError)
        {
            //handle error here
        }
    });

If you need help to understand tell me.


问:
I need a way to keep adding custom objects to a file in a cycle
Essentially, I am trying to write some code that will keep adding my custom objects to a file in a cycle. Every iteration will save another object to that file, so that in the end the file will contain all of the objects, which I then want to add to a list. I don't want to completely re-write the file every time, just keep adding things to it.</p>

答:
You're looking for append mode: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files</p>

```<code>with open('some_file', 'a') as f:
    f.write('new line\n')
</code>```

Body:
You're looking for append mode: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

with open('some_file', 'a') as f:
    f.write('new line\n')


问:
would return 0 using C++ in a class outside of main close the application?
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

```<code>boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}
</code>```

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy

答:
No.

Think of what would happen if this was the case:

```<code>int add(int a, int b) { return a + b; }

// somewhere:
int zero = add(2, -2); // would this exit the program?
</code>```

It isn't the zero that is important in the return from main, it's the return.  You can return any value from main and doing so will cause the program to exit (after all global variables are cleaned up, streams are closed, and other cleanup tasks are completed).

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy

Body:
No.

Think of what would happen if this was the case:

int add(int a, int b) { return a + b; }

// somewhere:
int zero = add(2, -2); // would this exit the program?

It isn't the zero that is important in the return from main, it's the return.  You can return any value from main and doing so will cause the program to exit (after all global variables are cleaned up, streams are closed, and other cleanup tasks are completed).


问:
What will be regular expression of domain URL of "www.google.com"?
What will be the regex for RegularExpressionValidator in asp.net for domain name like "www.google.com"?

Valid Cases:

www.google.com

www.youwebsite.com

Invalid Cases:

http://www.google.com

https://www.google.com

google.com

www.google

Currently I used (?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9] but it fails for invalid case number 3 and 4.

答:
The pattern that you tried fails for the third and fourth of the invalid cases because in general you are matching a-z0-9 and then repeat 1+ times . followed by a-z0-9 which does not take a www into account.

If you want to keep your pattern, you should make sure that it starts with www.

```<code>^www\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$
</code>```

Regex demo

You might shorten your pattern and make the match a bit broader:

```<code>^www\.[a-z0-9-]+(?:\.[a-z0-9-]+)*\.com$
</code>```

Regex demo

You can always extend the character class if you want to allow matching more characters.

Body:
The pattern that you tried fails for the third and fourth of the invalid cases because in general you are matching a-z0-9 and then repeat 1+ times . followed by a-z0-9 which does not take a www into account.

If you want to keep your pattern, you should make sure that it starts with www.

^www\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$

Regex demo

You might shorten your pattern and make the match a bit broader:

^www\.[a-z0-9-]+(?:\.[a-z0-9-]+)*\.com$

Regex demo

You can always extend the character class if you want to allow matching more characters.


问:
kotlin class extensions resolve parent class's value instead of childs when used in list context
I'm working with class extensions in Kotlin (1.3.20), and I'm running into an issue when extending both the parent class and the child class on the same property and then using instances of those an a list.

Basically what happens is that the child class's instance returns the value set for the parent class's property, and I dont't understand why that is.
I expect line 16 in the code below to return "ext-special-thing" but it does return "ext-thing" even though the instance in b[1] definitely is of type ExtSpecialThing.

I suspect the cause is the way extension-properties/extension-functions work under the hood (btw: this issue exists with extension functions as well); but I'm not an expert in that regard.

tl;dr: line 16 fails ... why?

```<code>import kotlin.test.*

fun main (args : Array<String>) {
    assertEquals("ext-special-thing", ExtSpecialThing().prop)

    var a = listOf(ImplThing(), ImplSpecialThing())
    assertTrue(a[0] is ImplThing)
    assertTrue(a[1] is ImplSpecialThing)
    assertEquals("impl-thing",         a[0].prop)
    assertEquals("impl-special-thing", a[1].prop)

    var b = listOf(ExtThing(), ExtSpecialThing())
    assertTrue(b[0] is ExtThing)
    assertTrue(b[1] is ExtSpecialThing)
    assertEquals("ext-thing",         b[0].prop)
    assertEquals("ext-special-thing", b[1].prop) // fails ... why?
}

// ======================================
open class ImplThing () {
    open val prop : String = "impl-thing"
}
class ImplSpecialThing : ImplThing() {
    override val prop : String = "impl-special-thing"
}

// -------------------------------------
open class ExtThing () {}
class ExtSpecialThing : ExtThing () {}

val ExtThing.prop : String get() = "ext-thing"
val ExtSpecialThing.prop : String get() = "ext-special-thing"
</code>```

答:
This is described in the official docs:

We would like to emphasize that extension functions are dispatched statically, i.e. they are not virtual by receiver type. This means that the extension function being called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime.

So that means that the following will make your test successful:

```<code>assertEquals("ext-special-thing", (b[1] as ExtSpecialThing).prop)
</code>```

Body:
I'm working with class extensions in Kotlin (1.3.20), and I'm running into an issue when extending both the parent class and the child class on the same property and then using instances of those an a list.

Basically what happens is that the child class's instance returns the value set for the parent class's property, and I dont't understand why that is.
I expect line 16 in the code below to return "ext-special-thing" but it does return "ext-thing" even though the instance in b[1] definitely is of type ExtSpecialThing.

I suspect the cause is the way extension-properties/extension-functions work under the hood (btw: this issue exists with extension functions as well); but I'm not an expert in that regard.

tl;dr: line 16 fails ... why?

import kotlin.test.*

fun main (args : Array<String>) {
    assertEquals("ext-special-thing", ExtSpecialThing().prop)

    var a = listOf(ImplThing(), ImplSpecialThing())
    assertTrue(a[0] is ImplThing)
    assertTrue(a[1] is ImplSpecialThing)
    assertEquals("impl-thing",         a[0].prop)
    assertEquals("impl-special-thing", a[1].prop)

    var b = listOf(ExtThing(), ExtSpecialThing())
    assertTrue(b[0] is ExtThing)
    assertTrue(b[1] is ExtSpecialThing)
    assertEquals("ext-thing",         b[0].prop)
    assertEquals("ext-special-thing", b[1].prop) // fails ... why?
}

// ======================================
open class ImplThing () {
    open val prop : String = "impl-thing"
}
class ImplSpecialThing : ImplThing() {
    override val prop : String = "impl-special-thing"
}

// -------------------------------------
open class ExtThing () {}
class ExtSpecialThing : ExtThing () {}

val ExtThing.prop : String get() = "ext-thing"
val ExtSpecialThing.prop : String get() = "ext-special-thing"

Body:
This is described in the official docs:

We would like to emphasize that extension functions are dispatched statically, i.e. they are not virtual by receiver type. This means that the extension function being called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime.

So that means that the following will make your test successful:

assertEquals("ext-special-thing", (b[1] as ExtSpecialThing).prop)


问:
Redux form submit validation with redux thunk
In my form, I'm trying to check email by using reactive-thunk to determine if the email address was already received. Everything is working properly, except for one thing. I request the api and I'm sending the data to the reducer, but the component I have access to the state is empty. Because the state value in the component is working before the reducer.

Is there any help of how to do that?

Submit.js

```<code>onSubmit = data => {
    const { saveUser, validateEmail, emailValidate } = this.props;
    validateEmail(data.email); // action create for api request
    console.log(emailValidate); // fetch data in reducer(This data is empty because code run before reducer set state)
    if (emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }

const mapDispatchToProps = (dispatch) => {
    validateEmail(email) {
      dispatch(validateEmail(email));
    },
  };
};
const mapStateToProps = (state) => ({
  emailValidate: state.registrationFormEmailValidate.data,
});
</code>```

答:
```<code>onSubmit = data => {
  const { saveUser, validateEmail, emailValidate } = this.props;
  validateEmail(data.email); // action create for api request
}

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.emailValidate.statusMessage !== prevProps.emailValidate.statusMessage) {
    console.log(this.props.emailValidate);
    if (this.props.emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }
}
</code>```

If you are using class component, you can use componentDidUpdate()

Body:
In my form, I'm trying to check email by using reactive-thunk to determine if the email address was already received. Everything is working properly, except for one thing. I request the api and I'm sending the data to the reducer, but the component I have access to the state is empty. Because the state value in the component is working before the reducer.

Is there any help of how to do that?

Submit.js

onSubmit = data => {
    const { saveUser, validateEmail, emailValidate } = this.props;
    validateEmail(data.email); // action create for api request
    console.log(emailValidate); // fetch data in reducer(This data is empty because code run before reducer set state)
    if (emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }

const mapDispatchToProps = (dispatch) => {
    validateEmail(email) {
      dispatch(validateEmail(email));
    },
  };
};
const mapStateToProps = (state) => ({
  emailValidate: state.registrationFormEmailValidate.data,
});

Body:
onSubmit = data => {
  const { saveUser, validateEmail, emailValidate } = this.props;
  validateEmail(data.email); // action create for api request
}

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.emailValidate.statusMessage !== prevProps.emailValidate.statusMessage) {
    console.log(this.props.emailValidate);
    if (this.props.emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }
}

If you are using class component, you can use componentDidUpdate()


问:
Is it possible to prevent command-line CatBoost to shuffle of the input data in cross-validation mode?
My data contains of 10 weeks observations. I would like to cross-validate the model in 9-to-1 week mode. So, I dont want CatBoost to shuffle the data before splitting. Is it possible with command line?

I'm not sure if "--cv-rand 0" (or any other value) works as "non shuffle".

答:
Change parameter stratified

```<code>stratified = False
</code>```

Body:
Change parameter stratified

stratified = False


问:
Sending hex characters over a socket
I am trying to send a hex character to a socket to indicate a new message.  This code works:

```<code>  $socket->send("\x{0B}");
  $socket->send($contents);
  $socket->send("\x{1C}");
  $socket->send("\x{0D}");
</code>```

However, since this happens in a loop, I need variable hex characters, and I have not figure out how to get it to work.  This is what I have tried.

```<code>my $start_char = get(); # returns, for example 0B
my $end_char = get(); # 1C
my $end_seg = get(); #0D

$socket->send("\x{$start_char}");
$socket->send($contents);
$socket->send("\x{$end_char}");
$socket->send("\x{$end_seg}");
</code>```

I can verify that the variables returned by the function are correct on the perl side, but the server does not accept them as valid characters.  Any input regarding how to do this?

答:
Try ...send( chr($start_char) );, etc. (guessing that get() is actually returning integers).
If it really gives you strings like "0B", then ...send( chr(hex($start_chr)) );

Title: Sending hex characters over a socket

Body:
I am trying to send a hex character to a socket to indicate a new message.  This code works:

  $socket->send("\x{0B}");
  $socket->send($contents);
  $socket->send("\x{1C}");
  $socket->send("\x{0D}");

However, since this happens in a loop, I need variable hex characters, and I have not figure out how to get it to work.  This is what I have tried.

my $start_char = get(); # returns, for example 0B
my $end_char = get(); # 1C
my $end_seg = get(); #0D

$socket->send("\x{$start_char}");
$socket->send($contents);
$socket->send("\x{$end_char}");
$socket->send("\x{$end_seg}");

I can verify that the variables returned by the function are correct on the perl side, but the server does not accept them as valid characters.  Any input regarding how to do this?


问:
Angular Material Dropdown with Create Option
I am using Angular material to create select Dropdown of Religion. But the options I provided might not cover all the religion of the world. But I want to give option for the user to enter his/her religion in the field if not found. So, What I want to do, give an option named 'other option' and when he clicks on the option, an input field will be given to the option which will be treated as the 'formcontrolName' value for the the field.

If you provide the code at Stackblitz, it would be great to see clearly.

答:
It's simple,

Use a mat-autocomplete

Add an event (blur) to the input, check if the value is not an empty string
and if it's not in the options, add to the options


问:
Get latest entry by date (year) and add Value to field from this row
I will do the following:

Run a Query that return me the latest record from current year take a field from that record.

This is may Tabel I used for this:

```<code>ID(int,PK)    FremdID(int)    Erstellung(datetime)      Number(int)
1             10              2019-05-31 09:15:41.003   1
2             11              2019-05-31 09:15:42.154   3
</code>```

So if I run the query it should return Row with index 2 because we are in year 2019 and that is the latest entry from 2019.

If we are now in 2020 then the query should not return any row becuase there is no entry for 2020.

答:
This should do it</p>

```<code>SELECT a.Number
FROM [YourTable] a
JOIN (SELECT MAX(Erstellung) AS Erstellung
      FROM [YourTable]
      WHERE DATEPART(YEAR,Erstellung) = DATEPART(YEAR,GETDATE())
      ) b ON a.Erstellung = b.Erstellung

</code>```

Body:
I will do the following:

Run a Query that return me the latest record from current year take a field from that record.

This is may Tabel I used for this:

ID(int,PK)    FremdID(int)    Erstellung(datetime)      Number(int)
1             10              2019-05-31 09:15:41.003   1
2             11              2019-05-31 09:15:42.154   3

So if I run the query it should return Row with index 2 because we are in year 2019 and that is the latest entry from 2019.

If we are now in 2020 then the query should not return any row becuase there is no entry for 2020.

Body:
This should do it

SELECT a.Number
FROM [YourTable] a
JOIN (SELECT MAX(Erstellung) AS Erstellung
      FROM [YourTable]
      WHERE DATEPART(YEAR,Erstellung) = DATEPART(YEAR,GETDATE())
      ) b ON a.Erstellung = b.Erstellung


问:
How do I use webdriver with imported functions?
I have a function that opens up a webdriver session and then calls for external functions based on the input url.

```<code>from externalfunctions import *

def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
    'a': a,
    'b': b,
    'c': c
}

if name in options:
    ff = webdriver.Firefox()
    ff.get(url)
    result = options[name]()
    ff.quit()
    print(result)
    return result
</code>```

functions a,b,c are in externalfuntions.py

```<code>def a():
    x = ff.find_element_by_css_selector('body')
    return x
def b():
    x = ff.find_element_by_css_selector('span')
    return x
def c():
    x = ff.find_element_by_css_selector('html')
    return x
</code>```

When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.

How do I do this without having to start a webdriver session every time the a,b,c functions are run.

答:
You need to import the webdriver library (selenium) and declare the webdriver:

```<code>from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("window-size=1,1")

driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\XXX\chromedriver')
</code>```

and then you can use:

```<code>driver.get(url)
driver.find_element_by_css_selector('html')
</code>```

Body:
I have a function that opens up a webdriver session and then calls for external functions based on the input url.

from externalfunctions import *

def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
    'a': a,
    'b': b,
    'c': c
}

if name in options:
    ff = webdriver.Firefox()
    ff.get(url)
    result = options[name]()
    ff.quit()
    print(result)
    return result

functions a,b,c are in externalfuntions.py

def a():
    x = ff.find_element_by_css_selector('body')
    return x
def b():
    x = ff.find_element_by_css_selector('span')
    return x
def c():
    x = ff.find_element_by_css_selector('html')
    return x

When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.

How do I do this without having to start a webdriver session every time the a,b,c functions are run.

Body:
You need to import the webdriver library (selenium) and declare the webdriver:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("window-size=1,1")

driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\XXX\chromedriver')

and then you can use:

driver.get(url)
driver.find_element_by_css_selector('html')


问:
Simulate a TCP tarpit
I want to simulate test cross-platform connection failures / timeouts, starting with blocking connect()s:

```<code>#!/usr/bin/python3

import socket

s = socket.socket()
endpoint = ('localhost', 28813)
s.bind((endpoint))
# listen for connections, accept 0 connections kept waiting (backlog)
# all other connect()s should block indefinitely
s.listen(0)

for i in range(1,1000):
    c = socket.socket()
    c.connect(endpoint)
    # print number of successfully connected sockets
    print(i)
</code>```

On Linux, it prints "1" and hangs indefinitely (i.e. the behavior I want).

On Windows (Server 2012), it prints "1" and aborts with a ConnectionRefusedError.

On macOS, it prints all numbers from 1 to 128 and then hangs indefinitely.

Thus, I could accept the macOS ignores the backlog parameter and just connect enough sockets for clients to block on new connections.

How can I get Windows to also block connect() attempts?

答:
On Windows, the SO_CONDITIONAL_ACCEPT socket option allows the application to have the incoming connections wait until it's accept()ed. The constant (SO_CONDITIONAL_ACCEPT=0x3002) isn't exposed in the Python module, but can be supplied manually:

```<code>s.bind(endpoint)
s.setsockopt(socket.SOL_SOCKET, 0x3002, 1)
s.listen(0)
</code>```

It's so effective that even the first connect is kept waiting.

On macOS, backlog=0 is reset to backlog=SOMAXCONN, backlog=1 keeps all connections except the first waiting.

Title: Simulate a TCP tarpit

Body:
I want to simulate test cross-platform connection failures / timeouts, starting with blocking connect()s:

#!/usr/bin/python3

import socket

s = socket.socket()
endpoint = ('localhost', 28813)
s.bind((endpoint))
# listen for connections, accept 0 connections kept waiting (backlog)
# all other connect()s should block indefinitely
s.listen(0)

for i in range(1,1000):
    c = socket.socket()
    c.connect(endpoint)
    # print number of successfully connected sockets
    print(i)

On Linux, it prints "1" and hangs indefinitely (i.e. the behavior I want).

On Windows (Server 2012), it prints "1" and aborts with a ConnectionRefusedError.

On macOS, it prints all numbers from 1 to 128 and then hangs indefinitely.

Thus, I could accept the macOS ignores the backlog parameter and just connect enough sockets for clients to block on new connections.

How can I get Windows to also block connect() attempts?

Body:
On Windows, the SO_CONDITIONAL_ACCEPT socket option allows the application to have the incoming connections wait until it's accept()ed. The constant (SO_CONDITIONAL_ACCEPT=0x3002) isn't exposed in the Python module, but can be supplied manually:

s.bind(endpoint)
s.setsockopt(socket.SOL_SOCKET, 0x3002, 1)
s.listen(0)

It's so effective that even the first connect is kept waiting.

On macOS, backlog=0 is reset to backlog=SOMAXCONN, backlog=1 keeps all connections except the first waiting.


问:
How to pass 'page' dynamically to exportOptions>modifier in Datatable
For exporting the table data in excel file I wrote below code.

```<code>"buttons": [
        {
            extend: 'excelHtml5',
            text: 'Excel Export',
            filename: function () { return 'AllLists_' + time; },
            exportOptions: {
                columns: [0, 1, 2, 3, 4, 5, 6, 7],
                modifier: {
                    page: 'current',
                }
            },
        }
    ],
</code>```

Here at line page: 'all/current'want to select dynamically, so for this I write below code.

```<code><select class="form-control" id="selectDataOption">
     <option value="current">Current page</option>
     <option value="all">Entire table</option>
</select>
</code>```

I've used below code for selecting the dropdown dynamically -

```<code>$("#exportExcelbtn").on("click", function () {
  dt_tblOutForApproval.buttons.exportData({
    modifier: {
        page: function () {
            return ($("#selectDataOption").children("option").filter(":selected").val());
        }
     }
   });
});
</code>```

But this doesn't help. can anyone help me better solution or if am i missing something in my solution?

答:
The dt_tblOutForApproval.buttons.exportData() is not a function that exports data to file, but a function that returns data.

As for your question, there're two possible ways to do that :

Because the DataTable doesn't allow us to initialize the options again, we could drop the raw table and create a new table. But that's not an efficient way.

The second approach is to remove the old 'Excel Export' button and create a new button according to current mode dynamically. Since there will be a state of two modes (current & all), I create a ExcelExportManager() to manage current mode (state):

```<code>// dt is an object created by `$('#example').DataTable({})`
function ExcelExportManager(dt){
    function _createExportButtonOpt(pageOpt="current"){
        return {
            extend: 'excelHtml5',
            text: 'export ' + pageOpt,
            name : pageOpt,        // button name
            filename: function () { return 'AllLists_' + time; },
            exportOptions: {
                //columns: [0, 1, 2, 3, 4, 5, 6, 7],
                modifier:{ page: pageOpt },
            },
        };
    };

    function _setModeAsCurrent(){
        var current= dt.button().remove(0, "current:name");
        var current= dt.button().remove(0, "all:name");
        var current= dt.button().add(0, _createExportButtonOpt("current"));
    }

    function _setModeAsAll(){
        var current= dt.button().remove(0, "current:name");
        var current= dt.button().remove(0, "all:name");
        var current= dt.button().add(0, _createExportButtonOpt("all"));
    }

    var mode = "current";  // initial value
    Object.defineProperty(this,"exportMode",{
        get:function(){ return pageMode; },
        set:function(value){
            switch(value.toLowerCase()){
                case "current":
                    _setModeAsCurrent();
                    break;
                case "all":
                    _setModeAsAll();
                    break;
                default:
                    throw new Error("unsupported export mode");
            }
            mode = value;
        },
    });
};

// create an instance
var excelManager = new ExcelExportManager(dt_tblOutForApproval);
</code>```

In this way, when we want to change the mode, we could simply set the excelManager.exportModeproperty :

```<code>// a function that get current option selected by user
function getExportMode(){
    return exportOption=$("#selectDataOption").children("option")
        .filter(":selected")
        .val();
}
 // initialize
excelManager.exportMode = getExportMode();
// on change
$("#selectDataOption").change(function() { excelManager.exportMode = getExportMode(); });
</code>```

A demo:

To play online, click the Run code snippet

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css"
        href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-html5-1.5.6/datatables.min.css" />

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

                    Name
                    Position
                    Office
                    Age
                    Start date
                    Salary

                    Name
                    Position
                    Office
                    Age
                    Start date
                    Salary

                    Tiger Nixon
                    System Architect
                    Edinburgh
                    61
                    2011/04/25
                    $3,120

                    Garrett Winters
                    Director
                    Edinburgh
                    63
                    2011/07/25
                    $5,300

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

                    Ashton Cox

                        <123414124124.null@domain.com>

                    San Francisco
                    66
                    2009/01/12
                    $4,800

    <select class="form-control" id="selectDataOption">
        <option value="current">Current page</option>
        <option value="all">Entire table</option>
    </select>

```

Body:
For exporting the table data in excel file I wrote below code.

"buttons": [
        {
            extend: 'excelHtml5',
            text: 'Excel Export',
            filename: function () { return 'AllLists_' + time; },
            exportOptions: {
                columns: [0, 1, 2, 3, 4, 5, 6, 7],
                modifier: {
                    page: 'current',
                }
            },
        }
    ],

Here at line page: 'all/current'want to select dynamically, so for this I write below code.

<select class="form-control" id="selectDataOption">
     <option value="current">Current page</option>
     <option value="all">Entire table</option>
</select>

I've used below code for selecting the dropdown dynamically -

$("#exportExcelbtn").on("click", function () {
  dt_tblOutForApproval.buttons.exportData({
    modifier: {
        page: function () {
            return ($("#selectDataOption").children("option").filter(":selected").val());
        }
     }
   });
});

But this doesn't help. can anyone help me better solution or if am i missing something in my solution?

Body:
The dt_tblOutForApproval.buttons.exportData() is not a function that exports data to file, but a function that returns data.

As for your question, there're two possible ways to do that :

Because the DataTable doesn't allow us to initialize the options again, we could drop the raw table and create a new table. But that's not an efficient way.

The second approach is to remove the old 'Excel Export' button and create a new button according to current mode dynamically. Since there will be a state of two modes (current & all), I create a ExcelExportManager() to manage current mode (state):

// dt is an object created by `$('#example').DataTable({})`
function ExcelExportManager(dt){
    function _createExportButtonOpt(pageOpt="current"){
        return {
            extend: 'excelHtml5',
            text: 'export ' + pageOpt,
            name : pageOpt,        // button name
            filename: function () { return 'AllLists_' + time; },
            exportOptions: {
                //columns: [0, 1, 2, 3, 4, 5, 6, 7],
                modifier:{ page: pageOpt },
            },
        };
    };

    function _setModeAsCurrent(){
        var current= dt.button().remove(0, "current:name");
        var current= dt.button().remove(0, "all:name");
        var current= dt.button().add(0, _createExportButtonOpt("current"));
    }

    function _setModeAsAll(){
        var current= dt.button().remove(0, "current:name");
        var current= dt.button().remove(0, "all:name");
        var current= dt.button().add(0, _createExportButtonOpt("all"));
    }

    var mode = "current";  // initial value
    Object.defineProperty(this,"exportMode",{
        get:function(){ return pageMode; },
        set:function(value){
            switch(value.toLowerCase()){
                case "current":
                    _setModeAsCurrent();
                    break;
                case "all":
                    _setModeAsAll();
                    break;
                default:
                    throw new Error("unsupported export mode");
            }
            mode = value;
        },
    });
};

// create an instance
var excelManager = new ExcelExportManager(dt_tblOutForApproval);

In this way, when we want to change the mode, we could simply set the excelManager.exportModeproperty :

// a function that get current option selected by user
function getExportMode(){
    return exportOption=$("#selectDataOption").children("option")
        .filter(":selected")
        .val();
}
 // initialize
excelManager.exportMode = getExportMode();
// on change
$("#selectDataOption").change(function() { excelManager.exportMode = getExportMode(); });

A demo:

To play online, click the Run code snippet

<!DOCTYPE html>
<html>

<head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link rel="stylesheet" type="text/css"
        href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-html5-1.5.6/datatables.min.css" />

    <script type="text/javascript"
        src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-html5-1.5.6/datatables.min.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
</head>

<body>
    <div class="container">
        <table id="example" class="display nowrap" width="100%">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </thead>

            <tfoot>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </tfoot>

            <tbody>
                <tr>
                    <td>Tiger Nixon</td>
                    <td>System Architect</td>
                    <td>Edinburgh</td>
                    <td>61</td>
                    <td>2011/04/25</td>
                    <td>$3,120</td>
                </tr>
                <tr>
                    <td>Garrett Winters</td>
                    <td>Director</td>
                    <td>Edinburgh</td>
                    <td>63</td>
                    <td>2011/07/25</td>
                    <td>$5,300</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
                <tr>
                    <td>Ashton Cox</td>
                    <td>
                        <123414124124.null@domain.com>
                    </td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>2009/01/12</td>
                    <td>$4,800</td>
                </tr>
            </tbody>
        </table>
    </div>
    <select class="form-control" id="selectDataOption">
        <option value="current">Current page</option>
        <option value="all">Entire table</option>
    </select>
</body>

<script>
    $(document).ready(function () {

        var time = new Date();
        var dt_tblOutForApproval = $('#example').DataTable({
            dom: 'Bftrip',
            paging: true,
            pageLength: 5,
            buttons: [ ]
        });

        // dt is an object created by `$('#example').DataTable({})`
        function ExcelExportManager(dt){
            function _createExportButtonOpt(pageOpt="current"){
                return {
                    extend: 'excelHtml5',
                    text: 'export ' + pageOpt,
                    name : pageOpt,        // button name
                    filename: function () { return 'AllLists_' + time; },
                    exportOptions: {
                        //columns: [0, 1, 2, 3, 4, 5, 6, 7],
                        modifier:{ page: pageOpt },
                    },
                };
            };

            function _setModeAsCurrent(){
                var current= dt.button().remove(0, "current:name");
                var current= dt.button().remove(0, "all:name");
                var current= dt.button().add(0, _createExportButtonOpt("current"));
            }

            function _setModeAsAll(){
                var current= dt.button().remove(0, "current:name");
                var current= dt.button().remove(0, "all:name");
                var current= dt.button().add(0, _createExportButtonOpt("all"));
            }

            var mode = "current";  // initial value
            Object.defineProperty(this,"exportMode",{
                get:function(){ return pageMode; },
                set:function(value){
                    switch(value.toLowerCase()){
                        case "current":
                            _setModeAsCurrent();
                            break;
                        case "all":
                            _setModeAsAll();
                            break;
                        default:
                            throw new Error("unsupported export mode");
                    }
                    mode = value;
                },
            });
        };

        function getExportMode(){
            return exportOption=$("#selectDataOption").children("option")
                .filter(":selected")
                .val();
        }
        var excelManager = new ExcelExportManager(dt_tblOutForApproval);
        // initialize
        excelManager.exportMode = getExportMode();
        // on change
        $("#selectDataOption").change(function() { excelManager.exportMode = getExportMode(); });
    });
</script>

</html>


问:
Will Active Record help me concatenate two strings in a database-neutral way?
I'm adding SQLite support to a Rails 2.3 codebase designed for MySQL.

Most of the changes so far have been fairly straightforward, but I've now found some examples like the following code:

```<code>SomeModel.find(:first,
  :conditions => ["? LIKE CONCAT(some_attribute, '%')", a_variable]
)
</code>```

I can't just use the ANSI concatenation operator because the double-pipes mean something else to MySQL. That is to say, the following code passes on SQLite3 but fails on MySQL:

```<code>SomeModel.find(:first,
  :conditions => ["? LIKE some_attribute || '%')", a_variable]
)
</code>```

Is there something I cleaner I can do than some kind of case database_adapter when :mysql ...?

答:
My kinda-ugly solution:</p>

```<code>ActiveRecord::Base.connection.class.concat_sql("firstname", "' '", "lastname")

# config/initializers/active_record_hacks.rb
class ActiveRecord::ConnectionAdapters::MysqlAdapter
  def self.concat_sql(*values)
    "CONCAT(#{values * ', '})"
  end
end

class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  def self.concat_sql(*values)
    values * " || "
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm adding SQLite support to a Rails 2.3 codebase designed for MySQL.

Most of the changes so far have been fairly straightforward, but I've now found some examples like the following code:

SomeModel.find(:first,
  :conditions => ["? LIKE CONCAT(some_attribute, '%')", a_variable]
)

I can't just use the ANSI concatenation operator because the double-pipes mean something else to MySQL. That is to say, the following code passes on SQLite3 but fails on MySQL:

SomeModel.find(:first,
  :conditions => ["? LIKE some_attribute || '%')", a_variable]
)

Is there something I cleaner I can do than some kind of case database_adapter when :mysql ...?

Body:
My kinda-ugly solution:

ActiveRecord::Base.connection.class.concat_sql("firstname", "' '", "lastname")

# config/initializers/active_record_hacks.rb
class ActiveRecord::ConnectionAdapters::MysqlAdapter
  def self.concat_sql(*values)
    "CONCAT(#{values * ', '})"
  end
end

class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  def self.concat_sql(*values)
    values * " || "
  end
end


问:
How to display database data from an activity?
I have an android application and i want to display database data in one of the activity in a listview. I already managed to display it in a listview on a fragment, but now i want to apply the same process to an activity.

I already tried to take the code i used to display data on my fragment, and use it for my activity, but didn't work even after making some change, and i'm still getting an error on @Override.

Here is my activity code :

```<code>
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;

import java.util.ArrayList;
import java.util.HashMap;

public class AdminEvenementActivity3 extends AppCompatActivity {

    private TextView Date;

    DBHelper SchoolDB;

    String CONTENU_ANG;
    String CONTENU_ANG_DATE;

    HashMap<String,String> user;

    ListView CDCANGList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_evenement3);

        Date = (TextView) findViewById(R.id.Date);

        Intent incomingIntent = getIntent();
        String date = incomingIntent.getStringExtra("date");
        Date.setText(date);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);

        CDCANGList = rootView.findViewById(R.id.CDCANGList);
        SchoolDB = new DBHelper(AdminEvenementActivity3.this);

        SQLiteDatabase db = SchoolDB.getReadableDatabase();

        ArrayList<HashMap<String, String>> userList = new ArrayList<>();

        Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
        if (view.moveToFirst()){
            do {
                // Passing values

                user = new HashMap<>();

                CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));

                CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));

                user.put("Contenu",CONTENU_ANG);

                user.put("Date",CONTENU_ANG_DATE);

                userList.add(user);

            } while(view.moveToNext());

            Log.d("Contenu",userList.toString());

            Log.d("Date",userList.toString());

            ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[] .
    {R.id.ContenuANG, R.id.ContenuANGDate});
            CDCANGList.setAdapter(adapter);

        }
        view.close();
        db.close();

        return rootView;
    }

    }```

Here is my layout holding the listview :

    ```<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/CDCANGList"/>

    </RelativeLayout>```

And here is my layout for the arrangement of each row of the listview :

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

    <TextView
        android:id="@+id/ContenuANG"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/ContenuANGDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/textView7"
        app:layout_constraintTop_toBottomOf="@+id/ContenuANG" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:drawableLeft="@drawable/ic_histgeo"
        android:text="Travail effectuer :"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginLeft="72dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="152dp"
        android:layout_marginRight="152dp"
        android:text="Date : "
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>```

I'm expecting each row of the table to display in the listview of my activity. I'm getting the following error message caused by the "@Override" : "error: method does not override or implement a method from a supertype".
```

答:
'onCreateView() method is only for fragment it cannot be override in activity.'

put you all the code in onCreate() method of your activity. it will be working pretty fine Thanks

if you feel any other problem please discuss

Body:
I have an android application and i want to display database data in one of the activity in a listview. I already managed to display it in a listview on a fragment, but now i want to apply the same process to an activity.

I already tried to take the code i used to display data on my fragment, and use it for my activity, but didn't work even after making some change, and i'm still getting an error on @Override.

Here is my activity code :

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;

import java.util.ArrayList;
import java.util.HashMap;

public class AdminEvenementActivity3 extends AppCompatActivity {

    private TextView Date;

    DBHelper SchoolDB;

    String CONTENU_ANG;
    String CONTENU_ANG_DATE;

    HashMap<String,String> user;

    ListView CDCANGList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_evenement3);

        Date = (TextView) findViewById(R.id.Date);

        Intent incomingIntent = getIntent();
        String date = incomingIntent.getStringExtra("date");
        Date.setText(date);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);

        CDCANGList = rootView.findViewById(R.id.CDCANGList);
        SchoolDB = new DBHelper(AdminEvenementActivity3.this);

        SQLiteDatabase db = SchoolDB.getReadableDatabase();

        ArrayList<HashMap<String, String>> userList = new ArrayList<>();

        Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
        if (view.moveToFirst()){
            do {
                // Passing values

                user = new HashMap<>();

                CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));

                CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));

                user.put("Contenu",CONTENU_ANG);

                user.put("Date",CONTENU_ANG_DATE);

                userList.add(user);

            } while(view.moveToNext());

            Log.d("Contenu",userList.toString());

            Log.d("Date",userList.toString());

            ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[] .
    {R.id.ContenuANG, R.id.ContenuANGDate});
            CDCANGList.setAdapter(adapter);

        }
        view.close();
        db.close();

        return rootView;
    }

    }```

Here is my layout holding the listview :

    ```<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/CDCANGList"/>

    </RelativeLayout>```

And here is my layout for the arrangement of each row of the listview :

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

    <TextView
        android:id="@+id/ContenuANG"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/ContenuANGDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/textView7"
        app:layout_constraintTop_toBottomOf="@+id/ContenuANG" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:drawableLeft="@drawable/ic_histgeo"
        android:text="Travail effectuer :"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginLeft="72dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="152dp"
        android:layout_marginRight="152dp"
        android:text="Date : "
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>```

I'm expecting each row of the table to display in the listview of my activity. I'm getting the following error message caused by the "@Override" : "error: method does not override or implement a method from a supertype".


问:
How to limit Azure Application Insights to only log custom events in dotnet core project?
I am using an dotnet core api project and have enables it with Azure Application Insight, a loots of data is been sent to Microsoft Azure, how could I limit it so it only sents my custome TrackEvent and disable the rest. Am I able to cofigure it using appsettings.json or programmatically?</p>

答:
What you need is ITelemetryProcessor.

For .net core, sample code like below:

Add a class(assume the class name is MyTelemetryProcessor) to the project:

```<code>    public class MyTelemetryProcessor : ITelemetryProcessor
    {
        private ITelemetryProcessor Next { get; set; }

        public MyTelemetryProcessor(ITelemetryProcessor next)
        {
            this.Next = next;
        }

        public void Process(ITelemetry telemetry)
        {
            if (!(telemetry is EventTelemetry))
            {
                //if it's not EventTelemetry, abandon it
                return;
            }

            this.Next.Process(telemetry);
        }
    }
</code>```

Then, in the Startup.cs -> ConfigureServices method, add the following code:

```<code>        public void ConfigureServices(IServiceCollection services)
        {
            //your other code

            services.AddApplicationInsightsTelemetry();
            services.AddApplicationInsightsTelemetryProcessor<MyTelemetryProcessor>();
        }
</code>```

Body:
What you need is ITelemetryProcessor.

For .net core, sample code like below:

Add a class(assume the class name is MyTelemetryProcessor) to the project:

    public class MyTelemetryProcessor : ITelemetryProcessor
    {
        private ITelemetryProcessor Next { get; set; }

        public MyTelemetryProcessor(ITelemetryProcessor next)
        {
            this.Next = next;
        }

        public void Process(ITelemetry telemetry)
        {
            if (!(telemetry is EventTelemetry))
            {
                //if it's not EventTelemetry, abandon it
                return;
            }

            this.Next.Process(telemetry);
        }
    }

Then, in the Startup.cs -> ConfigureServices method, add the following code:

        public void ConfigureServices(IServiceCollection services)
        {
            //your other code

            services.AddApplicationInsightsTelemetry();
            services.AddApplicationInsightsTelemetryProcessor<MyTelemetryProcessor>();
        }


问:
net::ERR_EMPTY_RESPONSE for XMLHttpRequest POST Javascript
This might be a duplicate question. I tried other solution but did not meet with the result. I have the following function sending some data to API, but getting

net::ERR_EMPTY_RESPONSE

error. If I try this API URL with exactly the same data in POSTMAN, there I get 200 response with the output. But in a javascript file, it's failing with readystate 1. Please help me with the solution.

```<code>function sendSignTransaction(address,balance,nonce,type,input1,privatekey){
  var xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.response);
      console.log(this.responseText);
    }
  };
  xhttp.open("POST", "http://3.112.106.186:9997/signTransaction",true);
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  var trinput = JSON.stringify({
    "fee": 100000000000000000,
    "address": address,
    "balance": balance,
    "nonce": nonce,
    "type": type,
    "input": input1,
    "PrivateKey": privatekey,
    "crypto": "cic"
  });
  xhttp.send(trinput);
}
</code>```

答: I referred this link, https://salesforce.stackexchange.com/questions/158448/response-status-is-0-in-jquery-ajax and got to know that there is a problem in API settings, allowing cross-origin and all. When API developer does changes, my problem solved. </p>

Body:
This might be a duplicate question. I tried other solution but did not meet with the result. I have the following function sending some data to API, but getting

net::ERR_EMPTY_RESPONSE

error. If I try this API URL with exactly the same data in POSTMAN, there I get 200 response with the output. But in a javascript file, it's failing with readystate 1. Please help me with the solution.

function sendSignTransaction(address,balance,nonce,type,input1,privatekey){
  var xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.response);
      console.log(this.responseText);
    }
  };
  xhttp.open("POST", "http://3.112.106.186:9997/signTransaction",true);
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  var trinput = JSON.stringify({
    "fee": 100000000000000000,
    "address": address,
    "balance": balance,
    "nonce": nonce,
    "type": type,
    "input": input1,
    "PrivateKey": privatekey,
    "crypto": "cic"
  });
  xhttp.send(trinput);
}


问:
How to access keyword of keyword?
I am trying to access keyword of keyword -specifically, I have:

```<code>import matplotlib.pyplot as plt
fig = plt.figure()
plot1 = fig.add_subplot(211, ylabel = 'foo',xlabel='bar')
</code>```

and I want to change to font size of the ylabel to 10 and font size of xlabel to 20. ylabel and xlabel both have their own keywords (i.e. https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.axes.Axes.set_ylabel.html#matplotlib.axes.Axes.set_ylabel) but I am not sure how I can control their keywords in the same line that I called add_subplot.

Of course, I can do this:

```<code>import matplotlib.pyplot as plt
fig = plt.figure()
plot1 = fig.add_subplot(211)
fig.set_ylabel(ylabel = 'foo', fontsize = 10)
fig.set_xlabel(xlabel = 'bar', fontsize = 20)
</code>```

But this way requires more lines of code than I'd like.

I've tried calling ylabel.fontsize but that didn't work:

fig.add_subplot(211, ylabel.fontsize = 50)

Which just gives SyntaxError: keyword can't be an expression

答:
But this way requires more lines of code than I'd like.

For a 2D plot, they are literally just 2 (short) lines of code. I would strongly advise against "saving" lines of code, especially in a language like Python where the PEP standard for line length is 80 characters, i.e. many short lines are better than few long lines.

For the problem at hand If you really want to  to save (maximum) 1 line of code you could try updating the rcParams dictionary.

```<code>import matplotlib.pyplot as plt

plt.rcParams.update({'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'})
fig = plt.figure()
plot1 = fig.add_subplot(211)
</code>```

Careful though, this dictionary update is overriding the default label sizes for this script, not just for the figure at hand.

Title: How to access keyword of keyword?

Body:
I am trying to access keyword of keyword -specifically, I have:

import matplotlib.pyplot as plt
fig = plt.figure()
plot1 = fig.add_subplot(211, ylabel = 'foo',xlabel='bar')

and I want to change to font size of the ylabel to 10 and font size of xlabel to 20. ylabel and xlabel both have their own keywords (i.e. https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.axes.Axes.set_ylabel.html#matplotlib.axes.Axes.set_ylabel) but I am not sure how I can control their keywords in the same line that I called add_subplot.

Of course, I can do this:

import matplotlib.pyplot as plt
fig = plt.figure()
plot1 = fig.add_subplot(211)
fig.set_ylabel(ylabel = 'foo', fontsize = 10)
fig.set_xlabel(xlabel = 'bar', fontsize = 20)

But this way requires more lines of code than I'd like.

I've tried calling ylabel.fontsize but that didn't work:

fig.add_subplot(211, ylabel.fontsize = 50)

Which just gives SyntaxError: keyword can't be an expression

Body:
But this way requires more lines of code than I'd like.

For a 2D plot, they are literally just 2 (short) lines of code. I would strongly advise against "saving" lines of code, especially in a language like Python where the PEP standard for line length is 80 characters, i.e. many short lines are better than few long lines.

For the problem at hand If you really want to  to save (maximum) 1 line of code you could try updating the rcParams dictionary.

import matplotlib.pyplot as plt

plt.rcParams.update({'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'})
fig = plt.figure()
plot1 = fig.add_subplot(211)

Careful though, this dictionary update is overriding the default label sizes for this script, not just for the figure at hand.


问:
Detecting Network Connectivity Changes using Reachability, NSNotification and Network Link Conditioner in Swift
From iOS 12 you simply use NWPathMonitor which is a line of code (example).

For historic purposes:

I'm trying to integrate network connectivity detection into my app, however it seems that somewhere along the line I have made a mistake as my network changes are not being detected/printed out into the console.

As mentioned in the post, I'm currently using these following classes and tools for the job:

Reachability {.h, .m}

NSNotificationCenter

Network Link Conditioner

Code

In the AppDelegate.Swift, I've set up the NSNotificationCenter to detect changes:

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // ...
    // A: Checks if the device is connected to the internet

    var defaultCenter: Void = NSNotificationCenter().addObserver(self, selector:"checkForReachability", name: kReachabilityChangedNotification, object: nil)
}
</code>```

In the same class AppDelegate, I've also created this function to be triggered whenever there is a change:

```<code>func checkForReachability () {
    var networkReachability = Reachability.reachabilityForInternetConnection()
    networkReachability.startNotifier()

    var remoteHostStatus = networkReachability.currentReachabilityStatus()
    if (remoteHostStatus.value == NotReachable.value) {
        println("Not Reachable")
    } else if (remoteHostStatus.value == ReachableViaWiFi.value) {
        println("Reachable via Wifi")
    } else {
        println("Reachable")
    }
}
</code>```

However, when using the Network Link Conditioner to manipulate and simulate changes in conditions, I haven't been able to see any of those changes reflected in the console.

答:
Based on this open source solution
Wrapped to class

Swift 5

```<code>import Foundation

final class ReachabilityHandler {

  private var reachability: Reachability? = Reachability()

  // MARK: - LifeCycle

  init() {
    configure()
  }

  deinit {
    NotificationCenter.default.removeObserver(self)
    reachability?.stopNotifier()
  }

  // MARK: - Private

  private func configure() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(ReachabilityHandler.checkForReachability(notification:)),
                                           name: Notification.Name.reachabilityChanged,
                                           object: nil)
    try? reachability?.startNotifier()

  }

  @objc private func checkForReachability(notification: NSNotification) {
    let networkReachability = notification.object as? Reachability
    if let remoteHostStatus = networkReachability?.connection {
      switch remoteHostStatus {
        case .none:

        case .wifi,
             .cellular:

      }
    }
  }
}
</code>```

In AppDelegate

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

  private var rechabilityObserver: ReachabilityHandler?

  var window: UIWindow?

  // MARK: - LifeCycle

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    rechabilityObserver = ReachabilityHandler()

    return true
  }
}
</code>```

Body:
From iOS 12 you simply use NWPathMonitor which is a line of code (example).

For historic purposes:

I'm trying to integrate network connectivity detection into my app, however it seems that somewhere along the line I have made a mistake as my network changes are not being detected/printed out into the console.

As mentioned in the post, I'm currently using these following classes and tools for the job:

Reachability {.h, .m}

NSNotificationCenter

Network Link Conditioner

Code

In the AppDelegate.Swift, I've set up the NSNotificationCenter to detect changes:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // ...
    // A: Checks if the device is connected to the internet

    var defaultCenter: Void = NSNotificationCenter().addObserver(self, selector:"checkForReachability", name: kReachabilityChangedNotification, object: nil)
}

In the same class AppDelegate, I've also created this function to be triggered whenever there is a change:

func checkForReachability () {
    var networkReachability = Reachability.reachabilityForInternetConnection()
    networkReachability.startNotifier()

    var remoteHostStatus = networkReachability.currentReachabilityStatus()
    if (remoteHostStatus.value == NotReachable.value) {
        println("Not Reachable")
    } else if (remoteHostStatus.value == ReachableViaWiFi.value) {
        println("Reachable via Wifi")
    } else {
        println("Reachable")
    }
}

However, when using the Network Link Conditioner to manipulate and simulate changes in conditions, I haven't been able to see any of those changes reflected in the console.

Body:
Based on this open source solution
Wrapped to class

Swift 5

import Foundation

final class ReachabilityHandler {

  private var reachability: Reachability? = Reachability()

  // MARK: - LifeCycle

  init() {
    configure()
  }

  deinit {
    NotificationCenter.default.removeObserver(self)
    reachability?.stopNotifier()
  }

  // MARK: - Private

  private func configure() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(ReachabilityHandler.checkForReachability(notification:)),
                                           name: Notification.Name.reachabilityChanged,
                                           object: nil)
    try? reachability?.startNotifier()

  }

  @objc private func checkForReachability(notification: NSNotification) {
    let networkReachability = notification.object as? Reachability
    if let remoteHostStatus = networkReachability?.connection {
      switch remoteHostStatus {
        case .none:

        case .wifi,
             .cellular:

      }
    }
  }
}

In AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {

  private var rechabilityObserver: ReachabilityHandler?

  var window: UIWindow?

  // MARK: - LifeCycle

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    rechabilityObserver = ReachabilityHandler()

    return true
  }
}


问:
How to implement a delayed reply/timeout correctly between serverHTTP and a channel?
I have a concept here which I don't know how I should solve correctly with minimum impact on the system in Go.

I'm making a 'print-spooler' where clients can call in on an API (/StartJob) to process printjobs.

Since there is only one printer so the bottleneck is a single worker that processes each job at a time, but clients can pass one job at any given time, it will just queue up and the worker will process each job in the time it takes step by step.

The way I'm doing it is that ServeHTTP pushes the job onto the channel (note here I just pass on the ID it the worker will look up the printdata from that):

```<code>func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }
</code>```

The Worker then just runs all the time and processes any jobs coming in. Real code there is a bit more but in the end it executes an external process:

```<code>  func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec ("START /i /b processAndPrint.exe -"+job.jobid)
      }
</code>```

The thing here is the external process can take time to execute, sometimes its instant but under some circumstances it can take 1 minute to perform the task before it returns.

My problem here is that now in serverHTTP, I write back to the client instantly with no knowledge if the job was the first in line and instantly can be processed, or if it has been queued up and maybe will be seconds away or minutes away before its processed:

```<code>  fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
</code>```

What I would like is to give the client up to 5 seconds to get a reply back if his job was processed within that time, or if not, tell him he needs to call back later to check the status of his job.

I had several approaches in mind:

In my QueueElemnt I pass on the http.ResponseWriter so I'm able to write to the responsewriter (reply back to client) from the Worker. This I can do if I let the serveHTTP sleep as the ResponseWriter will shut down when the go routine exists. So here I would need to wait in serveHTTP and then when its waiting the worker is allowed to write to the ResponseWriter.

The problem with this approach is that if the job is minutes away, the Worker won't write anything to that ResponseWriter, and the serveHTTP wouldn't know if a reply had been sent from the worker.

I could create a channel for each QueueElement so the serveHTTP and not only the worker but the actual job if being processed by the worker are able to communicate to each other.

This approach I haven't tested, but I also worry here that its overkill and heavy on the system as we can have a situation where we have many many many api requests coming in and thereby a big queue that's being processed, so even though I would need to timeout/cancel it after 5 seconds, I think the concept is overkill?

I could maybe pass on a mutexed value in the queueElement that both serveHTTP could check for up to 5 seconds and the queue could check/manipulate but in case a job is finished then the queueElement disappears so this maybe results in conflicts.

I could do a variation of no 1) where I write my own responsewriter and use the flag if something has been written to it already, so the serveHTTP would check for up to 5 seconds on that to check if the Worker already wrote a reply back to the client and in that case exit serveHTTP with no answer, or in case no writes then serveHTTP would write the message back to the client,  a bit along the lines of this.

But none of these I feel are very smooth and I don't want to launch forever amount of go-routines or channels or lock myself into mutuxes everywhere as I don't know the impact of what it has on the system.

Can anyone assist me in a working correct way to implement such a thing? I've been reading page up page down and haven't found a nice and clean way of achieving this.

答:
I think the easiest approach is the first one slightly modified. You can pass the http.ResponseWriter to the worker, which spanws another worker that actually carries out the job, while the "parent" worker waits for its completition or a timeout. It will reply to the HTTP client as soon as one of the two events occurs first.

```<code>func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {writer: w, jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }

func worker(jobs <-chan QueueElement) {
    for {
        done := make(chan struct{})
        job := <-jobs

        go func(d chan struct{}, q QueueElement) {
            processExec ("START /i /b processAndPrint.exe -"+q.jobid)
            d <- struct{}{}
        }(done, job)

        select {
            //Timeout
            case <-time.After(time.Second * 5):
                fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
            //Job processing finished in time
            case <-done:
                fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
        }
   }
</code>```

You can spawn the "waiting" goroutine as soon as you receive the HTTP request. In this way the timeout timer will take into account the entire processing of the request/job.

Example:

```<code>package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        doneC := make(chan struct{}, 1) //Buffered channel in order not to block the worker routine
        newPrintJob := QueueElement{
            doneChan: doneC,
            jobid:    "jobid",
        }
        go func(doneChan chan struct{}) {
            ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
            defer cancel()
            select {
            //If this triggers first, then this waiting goroutine would exit
            //and nobody would be listeding the 'doneChan'. This is why it has to be buffered.
            case <-ctx.Done():
                fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
            case <-doneChan:
                fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
            }
        }(doneC)
        gv.printQueue <- newPrintJob

    default:
        fmt.Fprintf(w, "No such Api")
    }
}

func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec("START /i /b processAndPrint.exe -" + job.jobid)
        job.doneChan <- struct{}{}

    }
}
</code>```

Body:
I have a concept here which I don't know how I should solve correctly with minimum impact on the system in Go.

I'm making a 'print-spooler' where clients can call in on an API (/StartJob) to process printjobs.

Since there is only one printer so the bottleneck is a single worker that processes each job at a time, but clients can pass one job at any given time, it will just queue up and the worker will process each job in the time it takes step by step.

The way I'm doing it is that ServeHTTP pushes the job onto the channel (note here I just pass on the ID it the worker will look up the printdata from that):

func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }

The Worker then just runs all the time and processes any jobs coming in. Real code there is a bit more but in the end it executes an external process:

  func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec ("START /i /b processAndPrint.exe -"+job.jobid)
      }

The thing here is the external process can take time to execute, sometimes its instant but under some circumstances it can take 1 minute to perform the task before it returns.

My problem here is that now in serverHTTP, I write back to the client instantly with no knowledge if the job was the first in line and instantly can be processed, or if it has been queued up and maybe will be seconds away or minutes away before its processed:

  fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

What I would like is to give the client up to 5 seconds to get a reply back if his job was processed within that time, or if not, tell him he needs to call back later to check the status of his job.

I had several approaches in mind:

In my QueueElemnt I pass on the http.ResponseWriter so I'm able to write to the responsewriter (reply back to client) from the Worker. This I can do if I let the serveHTTP sleep as the ResponseWriter will shut down when the go routine exists. So here I would need to wait in serveHTTP and then when its waiting the worker is allowed to write to the ResponseWriter.

The problem with this approach is that if the job is minutes away, the Worker won't write anything to that ResponseWriter, and the serveHTTP wouldn't know if a reply had been sent from the worker.

I could create a channel for each QueueElement so the serveHTTP and not only the worker but the actual job if being processed by the worker are able to communicate to each other.

This approach I haven't tested, but I also worry here that its overkill and heavy on the system as we can have a situation where we have many many many api requests coming in and thereby a big queue that's being processed, so even though I would need to timeout/cancel it after 5 seconds, I think the concept is overkill?

I could maybe pass on a mutexed value in the queueElement that both serveHTTP could check for up to 5 seconds and the queue could check/manipulate but in case a job is finished then the queueElement disappears so this maybe results in conflicts.

I could do a variation of no 1) where I write my own responsewriter and use the flag if something has been written to it already, so the serveHTTP would check for up to 5 seconds on that to check if the Worker already wrote a reply back to the client and in that case exit serveHTTP with no answer, or in case no writes then serveHTTP would write the message back to the client,  a bit along the lines of this.

But none of these I feel are very smooth and I don't want to launch forever amount of go-routines or channels or lock myself into mutuxes everywhere as I don't know the impact of what it has on the system.

Can anyone assist me in a working correct way to implement such a thing? I've been reading page up page down and haven't found a nice and clean way of achieving this.

Body:
I think the easiest approach is the first one slightly modified. You can pass the http.ResponseWriter to the worker, which spanws another worker that actually carries out the job, while the "parent" worker waits for its completition or a timeout. It will reply to the HTTP client as soon as one of the two events occurs first.

func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        newPrintJob := QueueElement {writer: w, jobid: "jobid"}
        gv.printQueue <- newPrintJob
        fmt.Fprintf(w, "instant reply from serveHTTP\r\n")

    default:
        fmt.Fprintf(w, "No such Api")
    }
  }

func worker(jobs <-chan QueueElement) {
    for {
        done := make(chan struct{})
        job := <-jobs

        go func(d chan struct{}, q QueueElement) {
            processExec ("START /i /b processAndPrint.exe -"+q.jobid)
            d <- struct{}{}
        }(done, job)

        select {
            //Timeout
            case <-time.After(time.Second * 5):
                fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
            //Job processing finished in time
            case <-done:
                fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
        }
   }

You can spawn the "waiting" goroutine as soon as you receive the HTTP request. In this way the timeout timer will take into account the entire processing of the request/job.

Example:

package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func (gv *GlobalVariables) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    switch r.URL.Path {
    case "/StartJob":
        doneC := make(chan struct{}, 1) //Buffered channel in order not to block the worker routine
        newPrintJob := QueueElement{
            doneChan: doneC,
            jobid:    "jobid",
        }
        go func(doneChan chan struct{}) {
            ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
            defer cancel()
            select {
            //If this triggers first, then this waiting goroutine would exit
            //and nobody would be listeding the 'doneChan'. This is why it has to be buffered.
            case <-ctx.Done():
                fmt.Fprintf(w, "job is taking more than 5 seconds to complete\r\n")
            case <-doneChan:
                fmt.Fprintf(w, "instant reply from serveHTTP\r\n")
            }
        }(doneC)
        gv.printQueue <- newPrintJob

    default:
        fmt.Fprintf(w, "No such Api")
    }
}

func worker(jobs <-chan QueueElement) {
    for {
        job := <-jobs
        processExec("START /i /b processAndPrint.exe -" + job.jobid)
        job.doneChan <- struct{}{}

    }
}


问:
multiple aggregate functions with sails await function dose not return result values
My code requires to run multiple aggregate functions and combine the result of each aggregate calls to make final result dataset.

I am using await so as my first query complete to combine all result but not getting results and view is rendered before query execution.

```<code>  fn: async function (inputs, exits) {
  var users = await Logger.native(function(err, collection) {
        collection.aggregate([.......], function(err, results){
            return results;
        })
  })
  console.log(users)

  var users2 = await Logger.native(function(err, collection) {
        collection.aggregate([.......], function(err, results){
            return results;
        })
  })
  console.log(users2)

  return exits.success({results: {"user": users, "emp": users2});
</code>```

The above code is giving undefined users and user2 value. Any idea what I am missing or doing wrong here.

答:
You can't just await callback style function and expect result.
To make this work you will need to wrap it inside promise and then await.

```<code>fn: async function(inputs, exits) {
        var users = await new Promise((resolve, reject) => {
            Logger.native(function(err, collection) {
                if (err) return reject(err)
                collection.aggregate([.......], function(err, results) {
                    if (err) return reject(err)
                    resolve(results)
                })
            })
        })
        console.log(users)

        var users2 = await new Promise((resolve, reject) => {
            await Logger.native(function(err, collection) {
                if (err) return reject(err)
                collection.aggregate([.......], function(err, results) {
                    if (err) return reject(err)
                    resolve(results);
                })
            })
        })
        console.log(users2)

        return exits.success({results: {"user": users, "emp": users2});
</code>```

Handle callback errors by returning reject(err) and resolve needed data when you get results using resolve(results)

Body:
My code requires to run multiple aggregate functions and combine the result of each aggregate calls to make final result dataset.

I am using await so as my first query complete to combine all result but not getting results and view is rendered before query execution.

  fn: async function (inputs, exits) {
  var users = await Logger.native(function(err, collection) {
        collection.aggregate([.......], function(err, results){
            return results;
        })
  })
  console.log(users)

  var users2 = await Logger.native(function(err, collection) {
        collection.aggregate([.......], function(err, results){
            return results;
        })
  })
  console.log(users2)

  return exits.success({results: {"user": users, "emp": users2});

The above code is giving undefined users and user2 value. Any idea what I am missing or doing wrong here.

Body:
You can't just await callback style function and expect result.
To make this work you will need to wrap it inside promise and then await.

fn: async function(inputs, exits) {
        var users = await new Promise((resolve, reject) => {
            Logger.native(function(err, collection) {
                if (err) return reject(err)
                collection.aggregate([.......], function(err, results) {
                    if (err) return reject(err)
                    resolve(results)
                })
            })
        })
        console.log(users)

        var users2 = await new Promise((resolve, reject) => {
            await Logger.native(function(err, collection) {
                if (err) return reject(err)
                collection.aggregate([.......], function(err, results) {
                    if (err) return reject(err)
                    resolve(results);
                })
            })
        })
        console.log(users2)

        return exits.success({results: {"user": users, "emp": users2});

Handle callback errors by returning reject(err) and resolve needed data when you get results using resolve(results)


问:
Timeout function after 10 seconds Swift/iOS
I want to display a "Network Error" message if after 10 seconds of trying to connect, a login does not succeed.

How can I stop my login function after 10 seconds and show this error message?

I'm using AlamoFire.

I don't have the full implementation, but this is the skeleton of what I want my function to behave like:

```<code>func loginFunc() {

    /*Start 10 second timer, if in 10 seconds
     loginFunc() is still running, break and show NetworkError*/

    <authentication code here>
}
</code>```

答:
Here is the solution for Swift 4</p>

```<code>DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}
</code>```

Body:
I want to display a "Network Error" message if after 10 seconds of trying to connect, a login does not succeed.

How can I stop my login function after 10 seconds and show this error message?

I'm using AlamoFire.

I don't have the full implementation, but this is the skeleton of what I want my function to behave like:

func loginFunc() {

    /*Start 10 second timer, if in 10 seconds
     loginFunc() is still running, break and show NetworkError*/

    <authentication code here>
}

Body:
Here is the solution for Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}


问:
in Info.plist , I have already added NSSpeechRecognitionUsageDescription with string. but still showing same error
In Info.plist I have already added NSSpeechRecognitionUsageDescription with string. But it still shows the same error:

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSSpeechRecognitionUsageDescription key with a string value explaining to the user how the app uses this data.

How to solve this?

答:
if you are using App test and App UItest then there would be multple plist files in your project just make it sure you are adding description in right plist which is inside your project folder.

circled one plist is right one which is in your project.