问:
RegEx for validating integers or float with two decimals
I'm willing to get a regexp to allow the following price formats below (this is a string in a form)

ALLOW

(any price without decimals. can be [0-9] 1 or more times)

,# (any price with a single decimal)

,## (any price with two decimals)

DON'T ALLOW

Anything else... For example:

5,555... (3 decmails or longer)

Whatever string that contains more than 1 comma

Whatever string that contains any char that it's not a DIGIT

ETC

So far I got this:

/^[0-9]+(,[0-9][0-9]?)?$/

It seems to be working. But is it really doing what I want?

const priceRegex = /^[0-9]+(,[0-9][0-9]?)?$/;

const span1 = document.getElementById('span1');
const span2 = document.getElementById('span2');
const span3 = document.getElementById('span3');
const span4 = document.getElementById('span4');
const span5 = document.getElementById('span5');
const span6 = document.getElementById('span6');
const span7 = document.getElementById('span7');
const span8 = document.getElementById('span8');
const span9 = document.getElementById('span9');
const span10 = document.getElementById('span10');
const span11 = document.getElementById('span11');
const span12 = document.getElementById('span12');
const span13 = document.getElementById('span13');

span1.innerHTML = priceRegex.test('5') ? ' IS VALID' : ' IS NOT VALID';
span2.innerHTML = priceRegex.test('5,5') ? ' IS VALID' : ' IS NOT VALID';
span3.innerHTML = priceRegex.test('5,55') ? ' IS VALID' : ' IS NOT VALID';

span4.innerHTML = priceRegex.test('5,') ? ' IS VALID' : ' IS NOT VALID';
span5.innerHTML = priceRegex.test('5,555') ? ' IS VALID' : ' IS NOT VALID';
span6.innerHTML = priceRegex.test('5,5555') ? ' IS VALID' : ' IS NOT VALID';

span7.innerHTML = priceRegex.test('a') ? ' IS VALID' : ' IS NOT VALID';
span8.innerHTML = priceRegex.test('5a') ? ' IS VALID' : ' IS NOT VALID';
span9.innerHTML = priceRegex.test('a5') ? ' IS VALID' : ' IS NOT VALID';

span10.innerHTML = priceRegex.test('a,5') ? ' IS VALID' : ' IS NOT VALID';
span11.innerHTML = priceRegex.test('5,a') ? ' IS VALID' : ' IS NOT VALID';
span12.innerHTML = priceRegex.test('a5,5') ? ' IS VALID' : ' IS NOT VALID';
span13.innerHTML = priceRegex.test('5a,5') ? ' IS VALID' : ' IS NOT VALID';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  color: black;
}

span {
  color: blue;
}

.notValid {
  color: red;
}</code>```

5

5,5

5,55

5,

5,555

5,5555

a

5a

a5

a,5

5,a

a5,5

5a,5
```

答:
Here, we would likely start with two simple expressions, then join them with a logical OR, maybe something similar to:

```<code>^[0-9]+$|^[0-9]+,[0-9]{1,2}$
</code>```

DEMO

Test

const regex = /^[0-9]+$|^[0-9]+,[0-9]{1,2}$/gm;
const str = `5
5,5
5,55

5,
5,555
5,5555
a
5a
a5
a,5
5,a
a5,5
5a,5`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

Body:
I'm willing to get a regexp to allow the following price formats below (this is a string in a form)

ALLOW

(any price without decimals. can be [0-9] 1 or more times)

,# (any price with a single decimal)

,## (any price with two decimals)

DON'T ALLOW

Anything else... For example:

5,555... (3 decmails or longer)

Whatever string that contains more than 1 comma

Whatever string that contains any char that it's not a DIGIT

ETC

So far I got this:

/^[0-9]+(,[0-9][0-9]?)?$/

It seems to be working. But is it really doing what I want?

const priceRegex = /^[0-9]+(,[0-9][0-9]?)?$/;

const span1 = document.getElementById('span1');
const span2 = document.getElementById('span2');
const span3 = document.getElementById('span3');
const span4 = document.getElementById('span4');
const span5 = document.getElementById('span5');
const span6 = document.getElementById('span6');
const span7 = document.getElementById('span7');
const span8 = document.getElementById('span8');
const span9 = document.getElementById('span9');
const span10 = document.getElementById('span10');
const span11 = document.getElementById('span11');
const span12 = document.getElementById('span12');
const span13 = document.getElementById('span13');

span1.innerHTML = priceRegex.test('5') ? ' IS VALID' : ' IS NOT VALID';
span2.innerHTML = priceRegex.test('5,5') ? ' IS VALID' : ' IS NOT VALID';
span3.innerHTML = priceRegex.test('5,55') ? ' IS VALID' : ' IS NOT VALID';

span4.innerHTML = priceRegex.test('5,') ? ' IS VALID' : ' IS NOT VALID';
span5.innerHTML = priceRegex.test('5,555') ? ' IS VALID' : ' IS NOT VALID';
span6.innerHTML = priceRegex.test('5,5555') ? ' IS VALID' : ' IS NOT VALID';

span7.innerHTML = priceRegex.test('a') ? ' IS VALID' : ' IS NOT VALID';
span8.innerHTML = priceRegex.test('5a') ? ' IS VALID' : ' IS NOT VALID';
span9.innerHTML = priceRegex.test('a5') ? ' IS VALID' : ' IS NOT VALID';

span10.innerHTML = priceRegex.test('a,5') ? ' IS VALID' : ' IS NOT VALID';
span11.innerHTML = priceRegex.test('5,a') ? ' IS VALID' : ' IS NOT VALID';
span12.innerHTML = priceRegex.test('a5,5') ? ' IS VALID' : ' IS NOT VALID';
span13.innerHTML = priceRegex.test('5a,5') ? ' IS VALID' : ' IS NOT VALID';

div {
  color: black;
}

span {
  color: blue;
}

.notValid {
  color: red;
}

5

5,5

5,55

5,

5,555

5,5555

a

5a

a5

a,5

5,a

a5,5

5a,5

Body:
Here, we would likely start with two simple expressions, then join them with a logical OR, maybe something similar to:

^[0-9]+$|^[0-9]+,[0-9]{1,2}$

DEMO

Test

const regex = /^[0-9]+$|^[0-9]+,[0-9]{1,2}$/gm;
const str = `5
5,5
5,55

5,
5,555
5,5555
a
5a
a5
a,5
5,a
a5,5
5a,5`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.


来源: stackexchange

问:
How to use ILIKE for multiple values in single column in rails?
How to use ILIKE for multiple values in single column.

This is the solution for multiple values without using like condition:

```<code>Project.where(name: ["Arvind Oasis", "Prestige Jindal City"])
</code>```

In this example, it is taking the exact matches in my database. but i want to take similar matches for all the values.

How to use ILIKE for multiple values ["Arvind Oasis", "Rajkumar Jindal City"]

For single values i can use like this,

```<code>Project.where("name ILIKE ?", "%Prestige Kumar%")
</code>```

答:
You can try postgres SIMILAR TO operator like below

Project.where("name similar to
  '%(Arvind\sOasis|Rajkumar\sJindal\sCity)%'")

ContentLicense: CC BY-SA 4.0

Body:
How to use ILIKE for multiple values in single column.

This is the solution for multiple values without using like condition:

Project.where(name: ["Arvind Oasis", "Prestige Jindal City"])

In this example, it is taking the exact matches in my database. but i want to take similar matches for all the values.

How to use ILIKE for multiple values ["Arvind Oasis", "Rajkumar Jindal City"]

For single values i can use like this,

Project.where("name ILIKE ?", "%Prestige Kumar%")


问:
How can I call geoLocation in componentDidMount in React
So I was trying to use axios to pull up an api along with HTML5Geolocation.

I place it inside the componentDidMount and was expecting it to work atleast console.log the result using async and eventually set the state to the country.

```<code>componentDidMount(){
    async onLoad() {
        if (window.navigator.geolocation) {
           window.navigator.geolocation.getCurrentPosition(
           position => {
              const response = axios.get('http://ws.geonames.org/countryCode' , {
                   lat: position.coords.latitude,
                   lng: position.coords.longitude,
                   type: 'JSON'
               });
               console.log('here is the response >>>>', response.countryName);
               this.setState({ country: response.countryName })
           });

           }
         }

}
</code>```

However this is currently not working. I am using Geonames for my API

Any idea what am I doing wrong on my code?

答:
You are declaring the onLoad method but not calling it, remove the declaration and call the code directly because it makes no sense to declare a method inside componentDidMount

```<code>componentDidMount() {
  if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(
      position => {
        const response = axios.get('http://ws.geonames.org/countryCode', {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          type: 'JSON'
        });
        console.log('here is the response >>>>', response.countryName);
        this.setState({
          country: response.countryName
        })
      });
  }
}
</code>```

Body:
So I was trying to use axios to pull up an api along with HTML5Geolocation.

I place it inside the componentDidMount and was expecting it to work atleast console.log the result using async and eventually set the state to the country.

componentDidMount(){
    async onLoad() {
        if (window.navigator.geolocation) {
           window.navigator.geolocation.getCurrentPosition(
           position => {
              const response = axios.get('http://ws.geonames.org/countryCode' , {
                   lat: position.coords.latitude,
                   lng: position.coords.longitude,
                   type: 'JSON'
               });
               console.log('here is the response >>>>', response.countryName);
               this.setState({ country: response.countryName })
           });

           }
         }

}

However this is currently not working. I am using Geonames for my API

Any idea what am I doing wrong on my code?

Body:
You are declaring the onLoad method but not calling it, remove the declaration and call the code directly because it makes no sense to declare a method inside componentDidMount

componentDidMount() {
  if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(
      position => {
        const response = axios.get('http://ws.geonames.org/countryCode', {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          type: 'JSON'
        });
        console.log('here is the response >>>>', response.countryName);
        this.setState({
          country: response.countryName
        })
      });
  }
}


问:
How to handle callbacks in Python 3?
I have a custom HTTP method/verb (lets say LISTEN) which allows me to listen for an update on a resource stored on a remote server. The API available for this has a blocking call which will get my client code to listen for an update till I interrupt the execution of that call. Just to provide an example, if I were to perform a curl as follows:

```<code>curl -X LISTEN http://<IP-Address>:<Port>/resource
</code>```

The execution of this creates a blocking call, providing me updates on the resource whenever a new value for this resource is pushed to the server (similar to a pub-sub model), the response for that would look similar to this:

```<code>{"data":"value update 1","id":"id resource"}
{"data":"value update 2","id":"id resource"}
(...)
</code>```

If I were to write code to handle this in Python, how do I call my url using this custom verb and handle the blocking call/call back while ensuring that this does not block the execution of the rest of my code?

答:
If you're using Python requests lib with a custom HTTP verb and need to read stream content, you can do something like this:

import json
import requests  # sudo pip3 install requests

url = "http://........."
r = requests.request('LISTEN', url, stream=True)
for line in r.iter_lines():
    # filter out keep-alive new lines
    if line:
        decoded_line = line.decode('utf-8')
        print(json.loads(decoded_line))
```

Note: by default all requests calls are blocking, so you need to run this code in a separate thread/process to avoid that.

...while ensuring that this does not block the execution of the rest of my code

Since you provided no details about your application, I will try to list some general thoughts on question.

Your task can be solved in many ways. Solution depends on your app architecture.

If this is a web server, you can take a look at tornado(see streaming callback) or aiohttp streaming examples.

On the other hand you can run the code above in a separate process and communicate with other applications/services using RabbitMQ for example (or other ipc mechanism).

Title: How to handle callbacks in Python 3?

Body:
I have a custom HTTP method/verb (lets say LISTEN) which allows me to listen for an update on a resource stored on a remote server. The API available for this has a blocking call which will get my client code to listen for an update till I interrupt the execution of that call. Just to provide an example, if I were to perform a curl as follows:

curl -X LISTEN http://<IP-Address>:<Port>/resource

The execution of this creates a blocking call, providing me updates on the resource whenever a new value for this resource is pushed to the server (similar to a pub-sub model), the response for that would look similar to this:

{"data":"value update 1","id":"id resource"}
{"data":"value update 2","id":"id resource"}
(...)

If I were to write code to handle this in Python, how do I call my url using this custom verb and handle the blocking call/call back while ensuring that this does not block the execution of the rest of my code?

Body:
If you're using Python requests lib with a custom HTTP verb and need to read stream content, you can do something like this:

import json
import requests  # sudo pip3 install requests

url = "http://........."
r = requests.request('LISTEN', url, stream=True)
for line in r.iter_lines():
    # filter out keep-alive new lines
    if line:
        decoded_line = line.decode('utf-8')
        print(json.loads(decoded_line))

Note: by default all requests calls are blocking, so you need to run this code in a separate thread/process to avoid that.

...while ensuring that this does not block the execution of the rest of my code

Since you provided no details about your application, I will try to list some general thoughts on question.

Your task can be solved in many ways. Solution depends on your app architecture.

If this is a web server, you can take a look at tornado(see streaming callback) or aiohttp streaming examples.

On the other hand you can run the code above in a separate process and communicate with other applications/services using RabbitMQ for example (or other ipc mechanism).


问:
Why am I being displayed "TypeError: a float is required"?
My main issue is this error being displayed:

```<code>TypeError: a float is required
</code>```

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

```<code>from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

I want to be able to type in a number and it display the square root of it.

答:
Change your codes to convert string to float. Input results into a string format.

```<code>square_rooted = sqrt(float(n))
</code>```

Also; change your code in displaying the values. Use %s instead of number (%d)

```<code>"%s square rooted is %s."
</code>```

Sample:

```<code>Type number here: 81
81 square rooted is 9.0.
</code>```

Body:
My main issue is this error being displayed:

TypeError: a float is required

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

I want to be able to type in a number and it display the square root of it.

Body:
Change your codes to convert string to float. Input results into a string format.

square_rooted = sqrt(float(n))

Also; change your code in displaying the values. Use %s instead of number (%d)

"%s square rooted is %s."

Sample:

Type number here: 81
81 square rooted is 9.0.


问:
Dynamic Textview scrollbar not showing
I have created a textview dynamically and want to make it scrollable.

```<code>final RelativeLayout.LayoutParams params = parseLayoutParams(
                frameMargins, context);
tv.setText(Utility.getpropertyString(controls.getText()));
final String textColor = Utility.getpropertyString(controls.getTextcolor());
tv.setTextColor(Color.parseColor(textColor));
tv.setTextSize(12);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setTextSize(tSize);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setMaxLines(controls.getMaxlines());
tv.setTag(controls.getTagId());
tv.setLayoutParams(params);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setVisibility(controls.getVisibility());
tv.setVerticalScrollBarEnabled(isScrollable);
tv.setScroller(new Scroller(context));
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setScrollBarFadeDuration(0);
</code>```

But I am not able to see scrollbar in the textview niether when not scrolling nor when we scroll it. Please help!

答:
From Api 21, the View scrollbar visibility is only reserved for xml layouts because an important function called initializaScrollBars was removed due to an issue while passing TypeArray variable as a parameter.

So, to accomplish what you need programmatically, you can do it like this

Create an xml layout called scrolltextview.xml

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

Now, to create it programmatically

```<code>    TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.scrolltextview, null, false);
    // now decorate it as your needs
    tv.setText(m);
    tv.setTextColor(Color.BLUE);
    tv.setTextSize(23);
    ...
    tv.setMovementMethod(new ScrollingMovementMethod());

    // this is needed only if you want to show scrollbar also when text is not scrolling
    tv.setScrollBarFadeDuration(0);
    // thecontainer = the layout you want to add your new textview
    thecontainer.addView(tv);
</code>```

Title: Dynamic Textview scrollbar not showing

Body:
I have created a textview dynamically and want to make it scrollable.

final RelativeLayout.LayoutParams params = parseLayoutParams(
                frameMargins, context);
tv.setText(Utility.getpropertyString(controls.getText()));
final String textColor = Utility.getpropertyString(controls.getTextcolor());
tv.setTextColor(Color.parseColor(textColor));
tv.setTextSize(12);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setTextSize(tSize);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setMaxLines(controls.getMaxlines());
tv.setTag(controls.getTagId());
tv.setLayoutParams(params);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setVisibility(controls.getVisibility());
tv.setVerticalScrollBarEnabled(isScrollable);
tv.setScroller(new Scroller(context));
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setScrollBarFadeDuration(0);

But I am not able to see scrollbar in the textview niether when not scrolling nor when we scroll it. Please help!

Body:
From Api 21, the View scrollbar visibility is only reserved for xml layouts because an important function called initializaScrollBars was removed due to an issue while passing TypeArray variable as a parameter.

So, to accomplish what you need programmatically, you can do it like this

Create an xml layout called scrolltextview.xml

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

Now, to create it programmatically

    TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.scrolltextview, null, false);
    // now decorate it as your needs
    tv.setText(m);
    tv.setTextColor(Color.BLUE);
    tv.setTextSize(23);
    ...
    tv.setMovementMethod(new ScrollingMovementMethod());

    // this is needed only if you want to show scrollbar also when text is not scrolling
    tv.setScrollBarFadeDuration(0);
    // thecontainer = the layout you want to add your new textview
    thecontainer.addView(tv);


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
You don't need to abandon your SPROCs or hand crafted SQL with a good ORM like nHibernate.

I've replaced my ORM data access methods after the fact, it's not hard at all, it's the best of both worlds.

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: Webjedi


问:
Default argument in the middle of parameter list?
I saw a function declaration in our code that looked as follows

```<code>void error(char const *msg, bool showKind = true, bool exit);
</code>```

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

答:
The answer might be in 8.3.6:

8.3.6 Default Arguments

6 Except for member functions of class
  templates, the default arguments in a
  member function definition that
  appears outside of the class
  definition are added to the set of
  default arguments provided by the
  member function declaration in the
  class definition. Default arguments
  for a member function of a class
  template shall be specified on the
  initial declaration of the member
  function within the class template.

Example:

```<code>class C {
void f(int i = 3);
void g(int i, int j = 99);
};
void C::f(int i = 3) // error: default argument already
{ } // specified in class scope
void C::g(int i = 88, int j) // in this translation unit,
{ } // C::g can be called with no argument
</code>```

After reading this, I found that MSVC10 accepted the following with compiler extensions turned off:

```<code>void error(char const* msg, bool showKind, bool exit = false);

void error(char const* msg, bool showKind = false, bool exit)
{
    msg;
    showKind;
    exit;
}

int main()
{
    error("hello");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I saw a function declaration in our code that looked as follows

void error(char const *msg, bool showKind = true, bool exit);

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

Body:
The answer might be in 8.3.6:

8.3.6 Default Arguments

6 Except for member functions of class
  templates, the default arguments in a
  member function definition that
  appears outside of the class
  definition are added to the set of
  default arguments provided by the
  member function declaration in the
  class definition. Default arguments
  for a member function of a class
  template shall be specified on the
  initial declaration of the member
  function within the class template.

Example:

class C {
void f(int i = 3);
void g(int i, int j = 99);
};
void C::f(int i = 3) // error: default argument already
{ } // specified in class scope
void C::g(int i = 88, int j) // in this translation unit,
{ } // C::g can be called with no argument

After reading this, I found that MSVC10 accepted the following with compiler extensions turned off:

void error(char const* msg, bool showKind, bool exit = false);

void error(char const* msg, bool showKind = false, bool exit)
{
    msg;
    showKind;
    exit;
}

int main()
{
    error("hello");
}


问:
How Kotlin/Native garbage collector works in C?
I'm found some explanation of Kotlin/Native memory management model in JetBrains FAQ.

A: Kotlin/Native provides an automated memory management scheme,
  similar to what Java or Swift provides. The current implementation
  includes an automated reference counter with a cycle collector to
  collect cyclical garbage.

I understand more or less how it works in Java or Kotlin (JVM). Can any describe detailed how memory is managed in Kotlin/Native in projects with C?

Also, if there is the garbage collector, why do we need a Kotlin/Native function memScoped { }?

Also, I found here :

Kotlin/Native is a technology for compiling Kotlin to native binaries that run without any VM.
  Broadly speaking, Native code is any code whose memory is not managed by the underlying framework but has to be managed by the programmer themselves. i.e. there is no Garbage collection.
  e.g. C++’ delete and C’s free

which in my opinion contradicts what is written in JetBrains FAQ

答:
Memory Management in K/N is provided by the runtime. It consists of two main parts: automatic reference counting and cycle collector. This provides one with availability to write the code just as in the Kotlin/JVM. Some details on this topic can be found digging inside this file but all you need to know is that it is automatic by default.

About MemScoped etc. When you use interoperability with C, you have to deal with managing such a resource as native memory. Native memory is the memory provided to the application process by the operating system. As it has nothing to do with the Kotlin code, this resource can't be managed by K/N runtime. But all C struct s and variables you are going to use must be allocated there. You can do it straight by calling nativeHeap.alloc() function. When the need of this memory is gone, it can be freed by nativeHeap.free().
But to make your experience more comfortable, K/N also has Arena class, implementing region-based memory management. It simplifies memory management to just a series of alloc() wherever you need, and one deallocation by .clear() for all the region.
Also, there is a MemScoped {} blocks, that covers Arena from you, and lets to forget about even the freeing native memory. So in your code that includes some elements from C, you can just write MemScoped { ... }, and then put operations into it. You can see a lot of examples of this approach in the samples from the K/N repository


问:
How to forward event downstream from a Punctuator instance in a ValueTransformer?
In KafkaStream, when implementing a ValueTransformer or ValueTransformerWithKey, on transform() call, I schedule a new Punctuator. When method punctuate() of the Punctuator is executed I want it to forward an event downstream using the context instance. However, the context instance seems not defined when part of a DSL topology.

Any clue on how to do this with a Transformer ?

Using the same logic in a Processor, implementing the low-level processor topology it works.

In ValueTransformerWithKey:

```<code>@Override
    public Event transform(final String key, final Event event) {
        this.context.schedule(timeout.toMillis(), PunctuationType.WALL_CLOCK_TIME, new MyPunctuator(context, key, event));
        return null;
}
</code>```

In MyPunctuator:

```<code>private class MytPunctuator implements Punctuator {
    private String key;
    private ProcessorContext context;
    private Event event;

    MyPunctuator(ProcessorContext context, String key, Event event)
    {
        this.context = context;
        this.key = key;
        this.event = event;
    }

    @Override
    public void punctuate(final long timestamp) {
        context.forward(key, AlertEvent.builder().withSource(event).build());
        context.commit();
    }
}
</code>```

When executing

```<code>myStream
    .groupByKey(Serialized.with(Serdes.String(), Event.serde()))
    .reduce((k, v) -> v)
    .transformValues(() -> valueTransformerWithKey)
    .toStream().to(ALARM_TOPIC, Produced.with(Serdes.String(), AlarmEvent.serde()));
</code>```

I expect the Alarm event produced by the punctuator to be forwared to the ALARM topic once expired.

Instead I got the following exception: ProcessorContext.forward() not supported.

答:
As usual, I found the answer in the javadoc about ValueTransformerWithKey interface:
https://kafka.apache.org/20/javadoc/org/apache/kafka/streams/kstream/ValueTransformerWithKey.html

Note, that using ProcessorContext.forward(Object, Object) or ProcessorContext.forward(Object, Object, To) is not allowed within transform and will result in an exception.

However, implementing the Transformer interface instead allows the usage of context.forward(). Thanks @Matthias J. Sax

https://kafka.apache.org/20/javadoc/org/apache/kafka/streams/kstream/Transformer.html

If more than one output record should be forwarded downstream ProcessorContext.forward(Object, Object) and ProcessorContext.forward(Object, Object, To) can be used. If record should not be forwarded downstream, transform can return null.

Body:
In KafkaStream, when implementing a ValueTransformer or ValueTransformerWithKey, on transform() call, I schedule a new Punctuator. When method punctuate() of the Punctuator is executed I want it to forward an event downstream using the context instance. However, the context instance seems not defined when part of a DSL topology.

Any clue on how to do this with a Transformer ?

Using the same logic in a Processor, implementing the low-level processor topology it works.

In ValueTransformerWithKey:

@Override
    public Event transform(final String key, final Event event) {
        this.context.schedule(timeout.toMillis(), PunctuationType.WALL_CLOCK_TIME, new MyPunctuator(context, key, event));
        return null;
}

In MyPunctuator:

private class MytPunctuator implements Punctuator {
    private String key;
    private ProcessorContext context;
    private Event event;

    MyPunctuator(ProcessorContext context, String key, Event event)
    {
        this.context = context;
        this.key = key;
        this.event = event;
    }

    @Override
    public void punctuate(final long timestamp) {
        context.forward(key, AlertEvent.builder().withSource(event).build());
        context.commit();
    }
}

When executing

myStream
    .groupByKey(Serialized.with(Serdes.String(), Event.serde()))
    .reduce((k, v) -> v)
    .transformValues(() -> valueTransformerWithKey)
    .toStream().to(ALARM_TOPIC, Produced.with(Serdes.String(), AlarmEvent.serde()));

I expect the Alarm event produced by the punctuator to be forwared to the ALARM topic once expired.

Instead I got the following exception: ProcessorContext.forward() not supported.


问:
Acumatica run Generic Inquiry via REST API
How can I run a generic inquiry that I created via Acumatica's REST API?  I was using the Inventory Summary Inquiry before but it was not returning all of the data I needed so we created a Generic Inquiry to return available for shipment quantity for ALL stock items.  However I can't find how to get the data from this report via the API.

UPDATE:

I've tried creating an extended endpoint service and adding my endpoint for the report as described in I210 Documentation and then hitting via the REST API (which is not shown in I210).  I added all of the result fields to the fields tab of the endpoint that I need returned.

Here are the details I used:

```<code>Extended Endpoint Name: MyInventoryAvailable
Endpoint version: 6.00.001
Endpoint: GetAvailableInventory
URL: https://mycompany.acumatica.com/entity/MyInventoryAvailable/6.00.001/GetAvailableInventory?$expand=Results
</code>```

When I do a PUT request using the above details, this is the response I get:

```<code>{
    "message": "The request is invalid.",
    "modelState": {
        "": [
            "The request body should not be empty."
        ]
    }
}
</code>```

UPDATE 2

Here is the setup in Acumatica for the extended endpoint:

I've tried setting up a request body but with no success:

```<code>{
    "InventoryID": {
        "Value": "AB-CL-60"
    },
    "Description": {
        "Value": ""
    },
    "Location": {
        "Value": ""
    },
    "QtyHardAvailable":{
        "Value": 0.0
    },
    "QtyOnHand":{
        "Value": 0.0
    },
    "Warehouse":{
        "Value": 0.0
    }
}
</code>```

When sending any request body, regardless of the content I recieve this error:

```<code>"exceptionMessage": "The given key was not present in the dictionary.",
"exceptionType": "System.Collections.Generic.KeyNotFoundException",
</code>```

UPDATE 3 - Inquiry Structure

Here is the structure of the inquiry:

And here are the results in Acumatica's UI:

UPDATE 4

Expanded GetAvailableInventory node:

答:
This is how I structure Generic-Inquiries in Web-Service-Endpoints.

While other Endpoints contain any number of Mapped Objects, the Generic-Enquiry Endpoints only have

```<code>Enter-Keys, Filter, Result, and Values-for-Update
</code>```

The FIELDS for the ENDPOINT are the Filters (click POPULATE -> Filters). The example above does not seem to have any filters, which is fine, so this FIELDS should be empty.

To get the data from the Generic Inquiry, a "Detail" entity is added

click the Generic Inquiry

click "+ INSERT"

Fill in form with FieldName='GetAvailableInventoryResults', ObjectName='GetAvailableInventoryResults', ObjectType=Detail

Save

Now, add the results wanted by clicking on 'GetAvailableInventoryResults', then FIELDS (opens a popup). In the popup, select 'Result' and add all the fields you want. Don't select "Row Number" and "Selected" as these are not needed and can cause errors. SAVE.

To access the ENDPOINT, do a PUT to

```<code>   .../GetAvailableInventory?$expand=GetAvailableInventoryResults
</code>```

with a BODY of

```<code>{}
</code>```

since this ENDPOINT does not define any Filters, but a PUT requires this to exist.

Why do I use "GetAvailableInventoryResults"? Well, because I ran into issues with multiple Generic-Inquiry Endpoint's having Details with the same name, so I make sure they are all unique.

Body:
How can I run a generic inquiry that I created via Acumatica's REST API?  I was using the Inventory Summary Inquiry before but it was not returning all of the data I needed so we created a Generic Inquiry to return available for shipment quantity for ALL stock items.  However I can't find how to get the data from this report via the API.

UPDATE:

I've tried creating an extended endpoint service and adding my endpoint for the report as described in I210 Documentation and then hitting via the REST API (which is not shown in I210).  I added all of the result fields to the fields tab of the endpoint that I need returned.

Here are the details I used:

Extended Endpoint Name: MyInventoryAvailable
Endpoint version: 6.00.001
Endpoint: GetAvailableInventory
URL: https://mycompany.acumatica.com/entity/MyInventoryAvailable/6.00.001/GetAvailableInventory?$expand=Results

When I do a PUT request using the above details, this is the response I get:

{
    "message": "The request is invalid.",
    "modelState": {
        "": [
            "The request body should not be empty."
        ]
    }
}

UPDATE 2

Here is the setup in Acumatica for the extended endpoint:

I've tried setting up a request body but with no success:

{
    "InventoryID": {
        "Value": "AB-CL-60"
    },
    "Description": {
        "Value": ""
    },
    "Location": {
        "Value": ""
    },
    "QtyHardAvailable":{
        "Value": 0.0
    },
    "QtyOnHand":{
        "Value": 0.0
    },
    "Warehouse":{
        "Value": 0.0
    }
}

When sending any request body, regardless of the content I recieve this error:

"exceptionMessage": "The given key was not present in the dictionary.",
"exceptionType": "System.Collections.Generic.KeyNotFoundException",

UPDATE 3 - Inquiry Structure

Here is the structure of the inquiry:

And here are the results in Acumatica's UI:

UPDATE 4

Expanded GetAvailableInventory node:

Body:
This is how I structure Generic-Inquiries in Web-Service-Endpoints.

While other Endpoints contain any number of Mapped Objects, the Generic-Enquiry Endpoints only have

Enter-Keys, Filter, Result, and Values-for-Update

The FIELDS for the ENDPOINT are the Filters (click POPULATE -> Filters). The example above does not seem to have any filters, which is fine, so this FIELDS should be empty.

To get the data from the Generic Inquiry, a "Detail" entity is added

click the Generic Inquiry

click "+ INSERT"

Fill in form with FieldName='GetAvailableInventoryResults', ObjectName='GetAvailableInventoryResults', ObjectType=Detail

Save

Now, add the results wanted by clicking on 'GetAvailableInventoryResults', then FIELDS (opens a popup). In the popup, select 'Result' and add all the fields you want. Don't select "Row Number" and "Selected" as these are not needed and can cause errors. SAVE.

To access the ENDPOINT, do a PUT to

   .../GetAvailableInventory?$expand=GetAvailableInventoryResults

with a BODY of

{}

since this ENDPOINT does not define any Filters, but a PUT requires this to exist.

Why do I use "GetAvailableInventoryResults"? Well, because I ran into issues with multiple Generic-Inquiry Endpoint's having Details with the same name, so I make sure they are all unique.


问:
Hide echo from apt-get in python
How can i hide the process of installing java (apt-get openjdk-6-jre) when it's runned in python?
So i can replace it with
"Installing Java..." till it's ready.

Thanks in advance.

答:
Here's an implementation of @khachik's comment:

```<code>import os
from subprocess import STDOUT, check_call

check_call(['apt-get', 'install', 'openjdk-6-jre'],
           stdout=open(os.devnull,'wb'), stderr=STDOUT)
</code>```

It raises an exception in case of an error.

Title: Hide echo from apt-get in python

Body:
Here's an implementation of @khachik's comment:

import os
from subprocess import STDOUT, check_call

check_call(['apt-get', 'install', 'openjdk-6-jre'],
           stdout=open(os.devnull,'wb'), stderr=STDOUT)

It raises an exception in case of an error.


问:
Wordpress and Angular 7. How to get asset path?
I'm struggling to make Angular 7 and Wordpress work together. Well, actually, I've managed to make it to work without any plugins, that was not too hard itself, but I can't seem to make angular get any assets. The problem is that my Angular app sits on a URL like
https://mywordpresssite.com/dashboard
And my angulare project uses assets folter to store its images. When I build the app and place it on my site, Angular tries to get its assets from https://mywordpresssite.com/dashboard/assets/... (its base url is poiting to /dashboard) and, of course, wordpress spits out 404 page.
In wordpress itself I'm getting different images like this:

```<code>function _img($image_name) {
    echo get_template_directory_uri() . "/assets/{$image_name}";
}
</code>```

I wanted to use some custom routes and I've made a route to https://mywordpresssite.com/assets using this class https://github.com/anthonybudd/WP_route
like this

```<code>WP_Route::get("assets/{image_name}", 'get_image_for_angular');
function get_image_for_angular($image_name) {
    echo get_template_directory_uri() . "/{$image_name}";
}
</code>```

And it shows the correct path to the file but nonetheless, wordpress still shows 404 along with that.

I also tried to use file_get_contents, it shows the image's bytes and 404 contents after that

I'm completely stuck with this. Can anyone help me resolve this?
What is the corrent way to make Angular aware of the WP's asstets

p.s. My Angular project lives in other repo itself and does not know anything about the site's structure. I'm only building it to my site. I don't want to use any absolute paths, I need to keep angular as it is

答:
I've managed to resolve this by now. Here is my solution

```<code>WP_Route::get("assets/img/{image_name}", 'get_image_for_angular');
function get_image_for_angular($image_name) {
    $path = get_template_directory_uri() . "/img/{$image_name}";
    header("Location: {$path}", TRUE, 301);
    exit();
}
</code>```

It works. But I feel something bad about this. So I would still appreciate if someone told me about a better approach

Body:
I'm struggling to make Angular 7 and Wordpress work together. Well, actually, I've managed to make it to work without any plugins, that was not too hard itself, but I can't seem to make angular get any assets. The problem is that my Angular app sits on a URL like
https://mywordpresssite.com/dashboard
And my angulare project uses assets folter to store its images. When I build the app and place it on my site, Angular tries to get its assets from https://mywordpresssite.com/dashboard/assets/... (its base url is poiting to /dashboard) and, of course, wordpress spits out 404 page.
In wordpress itself I'm getting different images like this:

function _img($image_name) {
    echo get_template_directory_uri() . "/assets/{$image_name}";
}

I wanted to use some custom routes and I've made a route to https://mywordpresssite.com/assets using this class https://github.com/anthonybudd/WP_route
like this

WP_Route::get("assets/{image_name}", 'get_image_for_angular');
function get_image_for_angular($image_name) {
    echo get_template_directory_uri() . "/{$image_name}";
}

And it shows the correct path to the file but nonetheless, wordpress still shows 404 along with that.

I also tried to use file_get_contents, it shows the image's bytes and 404 contents after that

I'm completely stuck with this. Can anyone help me resolve this?
What is the corrent way to make Angular aware of the WP's asstets

p.s. My Angular project lives in other repo itself and does not know anything about the site's structure. I'm only building it to my site. I don't want to use any absolute paths, I need to keep angular as it is

Body:
I've managed to resolve this by now. Here is my solution

WP_Route::get("assets/img/{image_name}", 'get_image_for_angular');
function get_image_for_angular($image_name) {
    $path = get_template_directory_uri() . "/img/{$image_name}";
    header("Location: {$path}", TRUE, 301);
    exit();
}

It works. But I feel something bad about this. So I would still appreciate if someone told me about a better approach


问:
Is there a way to determine the type of edit used with onEdit in a Google Sheets Script?
I need to know if a user is deleting a row, editing a cell, or pasting a bunch of cells. I keep looking through documentation and I cannot find a way to determine what the user's action is. Is there a way in to know what kind of action is used in onEdit?</p>

答:
You can use the installable change event listener for Sheets.

https://developers.google.com/apps-script/guides/triggers/events#change

It is possible to determine if a row was deleted by testing for the REMOVE_ROW change type.

It is also possible to determine whether a single cell or multiple cells were edited.  See code below.

Pasting will not insert rows or columns, so if the change type "EDIT" happened, then you can assume that rows or columns were not inserted.  I don't know of any way to manually edit multiple cells at the same time, so if the active range includes multiple cells, then it was probably a "paste."

```<code>function nameOfFunction(e) {
  var A1Notation,typeOfChange;

  //Install this function as a trigger for Sheets change

  typeOfChange = e.changeType;//Get the type of change that was made
  Logger.log('typeOfChange: ' + typeOfChange)
  Logger.log('typeof typeOfChange: ' + typeof typeOfChange)

  switch(typeOfChange) {
    case 'REMOVE_ROW':
      Logger.log('A row was deleted')
      break;
    case 'EDIT':
      A1Notation = SpreadsheetApp.getActiveRange().getA1Notation();
      Logger.log('A1Notation: ' + A1Notation)
      if (A1Notation.indexOf(":") === -1) {//There is NOT a colon in the A1 notation
        Logger.log('An Edit was made to a single cell')
      } else {
        Logger.log('An Edit was made to MULTIPLE cells')
      }
      break;
    case 'OTHER':
      /*  This is NOT an edit of types
        EDIT, INSERT_ROW, INSERT_COLUMN, REMOVE_ROW, REMOVE_COLUMN, INSERT_GRID, REMOVE_GRID, FORMAT
      */
      Logger.log('This is NOT an edit or a row Deletion')
      break;
    default:

  }

}
</code>```

Body:
You can use the installable change event listener for Sheets.

https://developers.google.com/apps-script/guides/triggers/events#change

It is possible to determine if a row was deleted by testing for the REMOVE_ROW change type.

It is also possible to determine whether a single cell or multiple cells were edited.  See code below.

Pasting will not insert rows or columns, so if the change type "EDIT" happened, then you can assume that rows or columns were not inserted.  I don't know of any way to manually edit multiple cells at the same time, so if the active range includes multiple cells, then it was probably a "paste."

function nameOfFunction(e) {
  var A1Notation,typeOfChange;

  //Install this function as a trigger for Sheets change

  typeOfChange = e.changeType;//Get the type of change that was made
  Logger.log('typeOfChange: ' + typeOfChange)
  Logger.log('typeof typeOfChange: ' + typeof typeOfChange)

  switch(typeOfChange) {
    case 'REMOVE_ROW':
      Logger.log('A row was deleted')
      break;
    case 'EDIT':
      A1Notation = SpreadsheetApp.getActiveRange().getA1Notation();
      Logger.log('A1Notation: ' + A1Notation)
      if (A1Notation.indexOf(":") === -1) {//There is NOT a colon in the A1 notation
        Logger.log('An Edit was made to a single cell')
      } else {
        Logger.log('An Edit was made to MULTIPLE cells')
      }
      break;
    case 'OTHER':
      /*  This is NOT an edit of types
        EDIT, INSERT_ROW, INSERT_COLUMN, REMOVE_ROW, REMOVE_COLUMN, INSERT_GRID, REMOVE_GRID, FORMAT
      */
      Logger.log('This is NOT an edit or a row Deletion')
      break;
    default:

  }

}


问:
Convert inputted time (which is PDT/PST) to local Time
So far I have created a timezone list for PST, CST, EST, GMT, CEST, IST, AST which works perfectly. But I also want to add an input box that will always be PST and output a local time from it..

i.e. if a user puts in 09:00 then if they live in the UK it will output 17:00
So it basically registers where you are in relation to timezone and adds (or subtracts) from the inputted time. (UK is +8 so input + 8 gives output)

This is my FIDDLE of where I am at right now

https://jsfiddle.net/wayneker/unc7e64f/16/

Although I know this demo is ideal, I know I cannot currently make this (with my current knowledge).

https://greenwichmeantime.com/time/to/pst-local/

I have researched various pages and cannot understand a lot of them. But what I have seen is normally local to PST

window.setInterval(function(){

```<code>// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(offset) {
//function calcTime(city, offset) {

// create Date object for current location
d = new Date();

//set options
var options = { weekday: "short", year: "numeric", month: "short",
               day: "numeric", hour: "numeric", minute: "numeric", second: "numeric"  };

// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
//return "The local time in " + city + " is " + nd.toLocaleString();
//return nd.toLocaleString();
return nd.toLocaleString("en-US", options);

}

Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.dst()) document.getElementById('dst').innerHTML = '';
</code>```

答:
Here is one way is to convert the PST time back to UTC and then apply the local offset.

```<code>function submitfunction() {

var value = document.getElementById("PSTPDT").value;

var parts = value.split(':');
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var offset = now.getTimezoneOffset()

var local = new Date(year, month, date, parts[0], parts[1], parts[2]);
local.setMinutes(local.getMinutes() + 420 - offset);

var result = document.getElementById("result");
result.innerHTML = local
}
</code>```

See example:
https://jsfiddle.net/p9u5j8dm/

Body:
So far I have created a timezone list for PST, CST, EST, GMT, CEST, IST, AST which works perfectly. But I also want to add an input box that will always be PST and output a local time from it..

i.e. if a user puts in 09:00 then if they live in the UK it will output 17:00
So it basically registers where you are in relation to timezone and adds (or subtracts) from the inputted time. (UK is +8 so input + 8 gives output)

This is my FIDDLE of where I am at right now

https://jsfiddle.net/wayneker/unc7e64f/16/

Although I know this demo is ideal, I know I cannot currently make this (with my current knowledge).

https://greenwichmeantime.com/time/to/pst-local/

I have researched various pages and cannot understand a lot of them. But what I have seen is normally local to PST

window.setInterval(function(){

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(offset) {
//function calcTime(city, offset) {

// create Date object for current location
d = new Date();

//set options
var options = { weekday: "short", year: "numeric", month: "short",
               day: "numeric", hour: "numeric", minute: "numeric", second: "numeric"  };

// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
//return "The local time in " + city + " is " + nd.toLocaleString();
//return nd.toLocaleString();
return nd.toLocaleString("en-US", options);

}

Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.dst()) document.getElementById('dst').innerHTML = '';

Body:
Here is one way is to convert the PST time back to UTC and then apply the local offset.

function submitfunction() {

var value = document.getElementById("PSTPDT").value;

var parts = value.split(':');
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var offset = now.getTimezoneOffset()

var local = new Date(year, month, date, parts[0], parts[1], parts[2]);
local.setMinutes(local.getMinutes() + 420 - offset);

var result = document.getElementById("result");
result.innerHTML = local
}

See example:
https://jsfiddle.net/p9u5j8dm/


问:
Custom QML module not found
I have a QML application. I have created my own QML module. called MyCustomModule. The module has the appropriate qmldir file, which is registered to the corresponding my_custom_module.qrc file. I also add the import path with addImportPath("qrc:///my_custom_module"); on application startup in C++. I am using CMake instead of QMake.

Where ever I import MyCustomModule QtCreator tells me QML module not found, but when I build the application builds without any issues and runs.

Am I missing something?

答:
My issue was that I was missing QML_IMPORT_PATH from my CMake file. Example:

```<code># Make Qt Creator aware of where the QML modules live
set (_QML_IMPORT_PATHS "")

## Add new module paths here.
list (APPEND _QML_IMPORT_PATHS ${CMAKE_CURRENT_SOURCE_DIR}/path/to/your/module)

set (
    QML_IMPORT_PATH
    ${_QML_IMPORT_PATHS}
    CACHE
    STRING
    "Path used to locate CMake modules by Qt Creator"
    FORCE
)
</code>```

One important side note is that the ${CMAKE_CURRENT_SOURCE_DIR}/path/to/your/module should point to the folder where the module lives and not to the module folder itself. So if you have a path like this:
/path/to/your/module/MyCustomModule, the CMake should contain the path /path/to/your/module.

Title: Custom QML module not found

Body:
My issue was that I was missing QML_IMPORT_PATH from my CMake file. Example:

# Make Qt Creator aware of where the QML modules live
set (_QML_IMPORT_PATHS "")

## Add new module paths here.
list (APPEND _QML_IMPORT_PATHS ${CMAKE_CURRENT_SOURCE_DIR}/path/to/your/module)

set (
    QML_IMPORT_PATH
    ${_QML_IMPORT_PATHS}
    CACHE
    STRING
    "Path used to locate CMake modules by Qt Creator"
    FORCE
)

One important side note is that the ${CMAKE_CURRENT_SOURCE_DIR}/path/to/your/module should point to the folder where the module lives and not to the module folder itself. So if you have a path like this:
/path/to/your/module/MyCustomModule, the CMake should contain the path /path/to/your/module.


问:
Why doesn't my use of "protected" work?
I have read that a protected member can be accessed from derived classes, but the following does not work.</p>

```<code>class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}
</code>```

答:
You can access the Test int within the B class itself. However, you cannot access properties of an instance. A does not know that it is a child of B so won't give access to its property.

```<code>class A
{
    protected int Test;
}
class B : A
{
    public B()
    {
       Test = 3; //possible
       base.Test = 3;  //explicitly calling base member, but not necessary in this case
    }
}
</code>```

Title: Why doesn't my use of "protected" work?

Body:
I have read that a protected member can be accessed from derived classes, but the following does not work.

class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}

Body:
You can access the Test int within the B class itself. However, you cannot access properties of an instance. A does not know that it is a child of B so won't give access to its property.

class A
{
    protected int Test;
}
class B : A
{
    public B()
    {
       Test = 3; //possible
       base.Test = 3;  //explicitly calling base member, but not necessary in this case
    }
}


问:
Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Symptoms

This is a symptom specifically when compiling an Excel VBA project. The following error occurs:

User-defined type not defined

However, the code that produces this error is not highlighted by the compiler and so I cannot identify the issue.

What I already know and have tried

This is a "User-defined type not defined" error that I have seen before with simple issues such as naming something As Strig instead of As String. However, this particular error is only popping up during the Debug > Compile VBAProject menu option and when the error message box pops up it does not highlight the line of code that the error is occurring in.

After a lot of research I have found that this bug can be related to missing references and I have ruled this out as I have included all needed references and Toolbox objects.

To ensure I wasn't missing any obvious missing Dim statements I have added Option Explicit to all code pages (forms included) to make sure nothing was missing. The error still shows when running a compile.

There is also this known bug that states the issue has been known to happen because of the VB6 projects using binary compatibility:

Turn off Binary Compatibility and compile the project. Visual Basic
  will highlight the line of code that contains the User Defined Type
  that is not defined. After resolving the problem, Binary Compatibility
  can be turned back on.

I found this article via this Question and Answer, however, I cannot find this option in the standard Excel VBA editor.

Help save mine and others' sanity!

I know from Google searches and other questions that I am not the only one who has had this issue.

I have tried going through the code manually but there are simply too many lines to feasibly do so.

Is there a way of turning off Binary Compatibility in Excel VBA projects? How do people find this offending line of code if they can't debug to what they need to change? Any help would be lovely!

Thank you in advance.

Edit: I have found the offending line of code and so my particular issue is solved The problem is still here after removing that particular line - it was a misspelt control name on a form being referenced in its code. This still does not solve the particular issue of how you would go about finding this offending code was the issue. Are we able to find a good way of finding the offending code when this bug happens so others in the future can avoid this agony?

答:
When I had this error in a MS Access database I used the /decompile command line switch along with the Compact/Repair option. Worked for me.
I had removed a reference that I was sure my code no longer used and started getting this error.</p>


问:
How can i orchestrate batch executions?
Description :

I have created a batch that generates some zip files (ZIP_BATCH).

I have another batch that sends those zips via ftp (FTP_BATCH).

I have a main entry from which i can execute any batch i want (cmd -batch=batch_name).

In that main entry class there some control and initialisation logic.

Problem:

I want to execute the FTP_BATCH after ZIP_BATCH.

I can't integrate FTP_BATCH as a job because of the main entry logic.

Is there an optimal way to orchestrate executions ?

答:
JobStep is probably what you are looking for. It allows you to create a job of jobs and orchestrate them as needed.

Hope this helps.

Title: How can i orchestrate batch executions?


问:
How can I rotate disclosure indicator on tap?
I want to rotate the disclosure indicator when I tap on my cell

I think this might be done with didSelectRowAt but don't know how to do it

答:
Probably you will need to use an icon. The disclosure indicator of native cells can't be rotated because you don't have access to the icon.

Try to get an disclosure icon, put it as an image in your cell then you can do anything with the image.


问:
Whats is the meaning of "rel" in the optional elements such as collectionResourceRel in RepositoryRestResource annotation?
Can you please help me understand the meaning of "rel" mentioned optional element of RepositoryRestResource annotation's collectionResourceRel?
I have gone through Java Docs here.

Below is what is written in the documentation.

collectionResourceRel The rel value to use when generating links to
  the collection resource.

答:
Basicly rel is an attribute of @RestResource annotation. It means "relationship"

e.g. an order might have a "rel" : "customer" relationship that links the order to its customer.

From https://docs.spring.io/spring-data/rest/docs/current/reference/html/ :

For instance, in the default configuration, if you issue a request to http://localhost:8080/persons/search to find out what query methods are exposed, you get back a list of links similar to the following:

```<code>{
  "_links" : {
    "findByName" : {
      "href" : "http://localhost:8080/persons/search/findByName"
    }
  }
}
</code>```

To change the rel value, use the rel property on the @RestResource annotation, as the following example shows:

```<code>@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}
</code>```

The preceding example results in the following link value:

```<code>{
  "_links" : {
    "names" : {
      "href" : "http://localhost:8080/persons/search/names"
    }
  }
}
</code>```

You can change the rel of a repository, as the following example shows:

```<code>@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}
</code>```

Altering the rel of a repository changes the top-level name, as the following example output shows:

```<code>{
  "_links" : {
    "people" : {  // rel = "people"
      "href" : "http://localhost:8080/people"
    },
    …
  }
}
</code>```

rel = "people" changed the name of that link to people.

Q: Do you have an example showing "an order might have a "rel" : "customer" relationship that links the order to its customer."? Does it also consider relationship between the entities such as OneToMany, ManyToMany etc.

It is different from the relationship between the entities such as OneToMany, ManyToMany.

The relation describes how the current resource is related to the target resource.

Here is a good example from https://restfulapi.net/hateoas/ to understand  rel :

Below given JSON response may be from an API like HTTP GET http://api.domain.com/management/departments/10

```<code>{
    "departmentId": 10,
    "departmentName": "Administration",
    "locationId": 1700,
    "managerId": 200,
    "links": [
        {
            "href": "10/employees",
            "rel": "employees",
            "type" : "GET"
        }
    ]
}
</code>```

In the preceding example, the response returned by the server contains hypermedia links to employee resources 10/employees, which can be traversed by the client to read employees belonging to the department.

It is between presentation and data layer. The link created with the help of rel and other attributes:

```<code>{
    "href": "10/employees",
    "rel": "employees",
    "type" : "GET"
}
</code>```

helps the application to go to the right direction (repository, method etc. ) to retrieve the data (employees belonging to the department)

According to your design you can also create relations between entities in the data layer. But these are different things.

Body:
Basicly rel is an attribute of @RestResource annotation. It means "relationship"

e.g. an order might have a "rel" : "customer" relationship that links the order to its customer.

From https://docs.spring.io/spring-data/rest/docs/current/reference/html/ :

For instance, in the default configuration, if you issue a request to http://localhost:8080/persons/search to find out what query methods are exposed, you get back a list of links similar to the following:

{
  "_links" : {
    "findByName" : {
      "href" : "http://localhost:8080/persons/search/findByName"
    }
  }
}

To change the rel value, use the rel property on the @RestResource annotation, as the following example shows:

@RepositoryRestResource(path = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}

The preceding example results in the following link value:

{
  "_links" : {
    "names" : {
      "href" : "http://localhost:8080/persons/search/names"
    }
  }
}

You can change the rel of a repository, as the following example shows:

@RepositoryRestResource(path = "people", rel = "people")
interface PersonRepository extends CrudRepository<Person, Long> {

  @RestResource(path = "names", rel = "names")
  List<Person> findByName(String name);
}

Altering the rel of a repository changes the top-level name, as the following example output shows:

{
  "_links" : {
    "people" : {  // rel = "people"
      "href" : "http://localhost:8080/people"
    },
    …
  }
}

rel = "people" changed the name of that link to people.

Q: Do you have an example showing "an order might have a "rel" : "customer" relationship that links the order to its customer."? Does it also consider relationship between the entities such as OneToMany, ManyToMany etc.

It is different from the relationship between the entities such as OneToMany, ManyToMany.

The relation describes how the current resource is related to the target resource.

Here is a good example from https://restfulapi.net/hateoas/ to understand  rel :

Below given JSON response may be from an API like HTTP GET http://api.domain.com/management/departments/10

{
    "departmentId": 10,
    "departmentName": "Administration",
    "locationId": 1700,
    "managerId": 200,
    "links": [
        {
            "href": "10/employees",
            "rel": "employees",
            "type" : "GET"
        }
    ]
}

In the preceding example, the response returned by the server contains hypermedia links to employee resources 10/employees, which can be traversed by the client to read employees belonging to the department.

It is between presentation and data layer. The link created with the help of rel and other attributes:

{
    "href": "10/employees",
    "rel": "employees",
    "type" : "GET"
}

helps the application to go to the right direction (repository, method etc. ) to retrieve the data (employees belonging to the department)

According to your design you can also create relations between entities in the data layer. But these are different things.


问:
how to center and bottom an button
I'm new to CSS , can anyone help me with the layout. Below is the layout I have

I want the green button to be center and in the bottom of its container div (the white area) and I'm using flexbox. Below is my code:

```<code>//html

 <div className="box-layout">
        <div className="box-layout__box">
            <h1 className="box-layout__title">Expensify</h1>
            <p>It's time to get your expenses under control</p>
            <button className="button" onClick={startLogin}>Login with Google</button>
            <button className="button_anon" onClick={startLoginAnonymously}>Try it</button>
        </div>
    </div>
</code>```

and css

```<code>.box-layout {
    background: url('/images/bg.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
}

.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
}

.button {
    background: $blue;
    border: none;
    color: white;
    font-weight: 300;
    font-size: $font-size-large;
    padding: $s-size;
}

.button_anon {
    background: green;
    border: none;
    color: white;
    font-weight: 300;
    font-size: 1.5rem;
    padding: 0.8rem;

}
</code>```

答:
I belive code below should do what you want

```<code>.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
    flex-direction: column;
    justify-content: center;
}
</code>```

There is pretty nice article about flexbox and how to use it

Title: how to center and bottom an button

Body:
I'm new to CSS , can anyone help me with the layout. Below is the layout I have

I want the green button to be center and in the bottom of its container div (the white area) and I'm using flexbox. Below is my code:

//html

Expensify

It's time to get your expenses under control

            <button className="button" onClick={startLogin}>Login with Google</button>
            <button className="button_anon" onClick={startLoginAnonymously}>Try it</button>

and css

.box-layout {
    background: url('/images/bg.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
}

.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
}

.button {
    background: $blue;
    border: none;
    color: white;
    font-weight: 300;
    font-size: $font-size-large;
    padding: $s-size;
}

.button_anon {
    background: green;
    border: none;
    color: white;
    font-weight: 300;
    font-size: 1.5rem;
    padding: 0.8rem;

}

Body:
I belive code below should do what you want

.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
    flex-direction: column;
    justify-content: center;
}

There is pretty nice article about flexbox and how to use it


问:
How to Add changable text on splash screen?
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

```<code><TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>
</code>```

in list.xml

```<code><string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>
</code>```

答:
Generate a random number and get an item from the array in this random position.

Sample code:

```<code>TextView quote = findViewById(R.id.quote);
String[] quoteArray = getResources().getStringArray(R.array.quote_array);

int randomPosition = (int)(Math.random()*(quoteArray.length-1))

quote.setText(quoteArray[randomPosition]);
</code>```

Body:
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

<TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>

in list.xml

<string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>

Body:
Generate a random number and get an item from the array in this random position.

Sample code:

TextView quote = findViewById(R.id.quote);
String[] quoteArray = getResources().getStringArray(R.array.quote_array);

int randomPosition = (int)(Math.random()*(quoteArray.length-1))

quote.setText(quoteArray[randomPosition]);


问:
Upload data to Apache server keep failing if uploading lasts more than 20 sec
I have a website where users can upload images to my hosting Apache/PHP server.
If files uploading lasts less than 20 sec everything is fine.
But if it lasts more (no matter what image filesize is), upload fails.

In .htaccess I already have:

```<code>php_value upload_max_filesize 10M
php_value post_max_size 70M
php_value max_execution_time 180
php_value max_input_time 180
</code>```

And in php script, returng result of:

```<code>echo "-max_execution_time  ".ini_get('max_execution_time');
echo "-max_input_time ".ini_get('max_input_time');
echo "-upload_max_filesize  ".ini_get('upload_max_filesize');
echo "-post_max_size  ".ini_get('post_max_size');
echo "-memory_limit   ".ini_get('memory_limit');
</code>```

is as excepted:

```<code>-max_execution_time  180

-max_input_time 180

-upload_max_filesize  10M

-post_max_size  70M

-memory_limit   128M
</code>```

These are requests - all failed after 22sec with error net::ERR_SPDY_PROTOCOL_ERROR (in firefox they fail after 20sec)

https://cdn1.imggmi.com/uploads/2019/5/8/fadd31a1a22674cfc3cc4603c97762ff-full.jpg

What I am missing here???
Once again, if uploading duration is less than 20 sec - everything is fine...

答:
I also encountered a similar problem at my apache2.4-rails-passenger-aws-ec2 project.
When I upload a large file (over 500MB), it times out in about 20 seconds.

I was trying to change apache's Timeout related configuration, but it didn't get better.

I switched my application server from apache-passenger to thin, then uploading was no problem.
Since this ask was posted recently, I thought that a recent release of apache had a problem.

After all, I downgraded apache at executing following commands, it's working properly.

```<code>$ sudo yum list httpd24
Installed packages
httpd24.x86_64  2.4.39-1.87.amzn1
$ sudo yum erase httpd24 httpd24-tools httpd24-devel
$ sudo yum install httpd24-2.4.38-1.86.amzn1 httpd24-2.4.38-1.86.amzn1 httpd24-devel-2.4.38-1.86.amzn1
</code>```

After I read this ask's answers, I re-upgrade apache to 2.4.39 and commented out the following line to disable mod_reqtimeout, it's also working.

```<code># LoadModule reqtimeout_module modules/mod_reqtimeout.so
</code>```

I think the cause of the problem is in a change of apache through 2.4.38 to 2.4.39.

Body:
I have a website where users can upload images to my hosting Apache/PHP server.
If files uploading lasts less than 20 sec everything is fine.
But if it lasts more (no matter what image filesize is), upload fails.

In .htaccess I already have:

php_value upload_max_filesize 10M
php_value post_max_size 70M
php_value max_execution_time 180
php_value max_input_time 180

And in php script, returng result of:

echo "-max_execution_time  ".ini_get('max_execution_time');
echo "-max_input_time ".ini_get('max_input_time');
echo "-upload_max_filesize  ".ini_get('upload_max_filesize');
echo "-post_max_size  ".ini_get('post_max_size');
echo "-memory_limit   ".ini_get('memory_limit');

is as excepted:

-max_execution_time  180

-max_input_time 180

-upload_max_filesize  10M

-post_max_size  70M

-memory_limit   128M

These are requests - all failed after 22sec with error net::ERR_SPDY_PROTOCOL_ERROR (in firefox they fail after 20sec)

https://cdn1.imggmi.com/uploads/2019/5/8/fadd31a1a22674cfc3cc4603c97762ff-full.jpg

What I am missing here???
Once again, if uploading duration is less than 20 sec - everything is fine...

Body:
I also encountered a similar problem at my apache2.4-rails-passenger-aws-ec2 project.
When I upload a large file (over 500MB), it times out in about 20 seconds.

I was trying to change apache's Timeout related configuration, but it didn't get better.

I switched my application server from apache-passenger to thin, then uploading was no problem.
Since this ask was posted recently, I thought that a recent release of apache had a problem.

After all, I downgraded apache at executing following commands, it's working properly.

$ sudo yum list httpd24
Installed packages
httpd24.x86_64  2.4.39-1.87.amzn1
$ sudo yum erase httpd24 httpd24-tools httpd24-devel
$ sudo yum install httpd24-2.4.38-1.86.amzn1 httpd24-2.4.38-1.86.amzn1 httpd24-devel-2.4.38-1.86.amzn1

After I read this ask's answers, I re-upgrade apache to 2.4.39 and commented out the following line to disable mod_reqtimeout, it's also working.

# LoadModule reqtimeout_module modules/mod_reqtimeout.so

I think the cause of the problem is in a change of apache through 2.4.38 to 2.4.39.


答:
Subclasses can access their own inherited members that are marked as protected.

```<code>class A
{
   protected int Test;
}

class B : A
{
   public B()
   {
     this.Test = 42; // Possible
   }
}
</code>```

Title: Why doesn't my use of "protected" work?

Body:
Subclasses can access their own inherited members that are marked as protected.

class A
{
   protected int Test;
}

class B : A
{
   public B()
   {
     this.Test = 42; // Possible
   }
}


问:
State change not reflecting on the UI of child component
I have two component FirstParent and SecondParent both of them have the same child component Child.

If I click on the Icon when in FirstParent, the state (redux) gets updated and the UI reflects the value of Text as 20.

But If I do the same from SecondParent, only the state (redux) gets updated but the UI doesn't display the value of Text as 20.

What am I missing here?

FirstParentComponent

```<code>handleRender = ({ item }) => {
  // some code here
  return (
    <Child foo={item} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}
</code>```

SecondParentComponent

```<code>render() {
  const { item } = this.props;

  // some code here
  <Child foo={item} />
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const item = state.data.find(
    foo => foo.id === ownProps.navigation.getParam('foo', {}).id)
  )
 return { item };
);
</code>```

ChildComponent

```<code>updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);
</code>```

答:
I was able to get the second component to reflect the change in state by shifting things around. But i'm still not satisfied since now i have to iterate over the state to retrieve the item.

FirstParentComponent

```<code>handleRender = ({ item }) => {
  // some code here
  return (
    <Child fooId={item.id} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}
</code>```

SecondParentComponent

```<code>render() {
  const { itemId } = this.props;

  // some code here
  <Child fooId={itemId} />
}
</code>```

ChildComponent

```<code>updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const foo = state.data.find(
    foo => foo.id === ownProps.fooId)
  )
 return { foo };
);

const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);
</code>```

Body:
I have two component FirstParent and SecondParent both of them have the same child component Child.

If I click on the Icon when in FirstParent, the state (redux) gets updated and the UI reflects the value of Text as 20.

But If I do the same from SecondParent, only the state (redux) gets updated but the UI doesn't display the value of Text as 20.

What am I missing here?

FirstParentComponent

handleRender = ({ item }) => {
  // some code here
  return (
    <Child foo={item} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}

SecondParentComponent

render() {
  const { item } = this.props;

  // some code here
  <Child foo={item} />
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const item = state.data.find(
    foo => foo.id === ownProps.navigation.getParam('foo', {}).id)
  )
 return { item };
);

ChildComponent

updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);

Body:
I was able to get the second component to reflect the change in state by shifting things around. But i'm still not satisfied since now i have to iterate over the state to retrieve the item.

FirstParentComponent

handleRender = ({ item }) => {
  // some code here
  return (
    <Child fooId={item.id} />
  )
}

render() {
  <FlatList
    renderItem={this.handleRender}
    // other attributes
  />
}

SecondParentComponent

render() {
  const { itemId } = this.props;

  // some code here
  <Child fooId={itemId} />
}

ChildComponent

updateFoo = (id, value) => {
  const { updateReduxState} = this.props;

  // some code here
  updateReduxState({ id, value })
}

render() {
  const { foo: { id, value} } = this.props;

  // some code here
  <Icon onPress={() => { this.updateFoo(id, 20); }}
  <Text>{value}</Text>
}

// some code here
const mapStateToProps = (state, ownProps) => (
  const foo = state.data.find(
    foo => foo.id === ownProps.fooId)
  )
 return { foo };
);

const mapDispatchToProps = dispatch => (
  bindActionCreators(
      { updateReduxState: updateValue},
       dispatch,
    )
  )
);


问:
Vue.js child component with object literals as props unexpectedly updates when its parent renders
I've got several Vue components passed with some object literals as props like

<child :prop1="{ foo: 'bar' }"></child>
```

However, when parent component rerenders, as the minimal codesandbox example below shows, prop1 changes (detected by watcher) and causes Child to update. If the prop is an object reference, it stays unchanged.

Why does this happen and does it mean it may not be 'safe' to use object literals(and perhaps array literal) as props?

https://codesandbox.io/s/vue-template-jj0tb

答:
Each time the template runs it will create a new object when it hits that section. The same would apply to any reference type, so arrays, functions, etc.

It's similar to objects, etc. that are created in JavaScript code. e.g.

function getObject() {
    return {};
}

console.log(getObject() === getObject()); // false
```

<p>Each time <code>getObject</code> is called it will return a new object and object equality is based on reference and not whether the objects contain the same values. This is effectively what Vue does when checking for changed props. Remember that a Vue template is compiled down to a <code>render</code> function and that's just plain JavaScript. Any object literals will still be object literals in that <code>render</code> function.</p>

<p>In the case of your example the render function for the parent would look something like this, assuming there's nothing else in the template:</p>

<pre class="lang-js prettyprint-override"><code>function render(h) {
    return h('child', {
        props: {
            prop1: {foo: 'bar'}
        }
    })
}
</code>```

So each time it runs there'll be a new object for prop1.

As you've already mentioned, moving the object to your data and then referencing it by name will ensure that the same object is used each time, avoiding the child updates.

Whether it's worth worrying about will depend on the specifics of your scenario but it can have performance implications if there are enough children being updated like this. The child rendering shouldn't need to update the actual DOM but any computed properties, watches or templates will run if they rely on that prop.

Body:
I've got several Vue components passed with some object literals as props like

<child :prop1="{ foo: 'bar' }"></child>

However, when parent component rerenders, as the minimal codesandbox example below shows, prop1 changes (detected by watcher) and causes Child to update. If the prop is an object reference, it stays unchanged.

Why does this happen and does it mean it may not be 'safe' to use object literals(and perhaps array literal) as props?

https://codesandbox.io/s/vue-template-jj0tb

Body:
Each time the template runs it will create a new object when it hits that section. The same would apply to any reference type, so arrays, functions, etc.

It's similar to objects, etc. that are created in JavaScript code. e.g.

function getObject() {
    return {};
}

console.log(getObject() === getObject()); // false

Each time getObject is called it will return a new object and object equality is based on reference and not whether the objects contain the same values. This is effectively what Vue does when checking for changed props. Remember that a Vue template is compiled down to a render function and that's just plain JavaScript. Any object literals will still be object literals in that render function.

In the case of your example the render function for the parent would look something like this, assuming there's nothing else in the template:

function render(h) {
    return h('child', {
        props: {
            prop1: {foo: 'bar'}
        }
    })
}

So each time it runs there'll be a new object for prop1.

As you've already mentioned, moving the object to your data and then referencing it by name will ensure that the same object is used each time, avoiding the child updates.

Whether it's worth worrying about will depend on the specifics of your scenario but it can have performance implications if there are enough children being updated like this. The child rendering shouldn't need to update the actual DOM but any computed properties, watches or templates will run if they rely on that prop.


问:
How to access Android resource strings from Flutter Plugin
I'm building a plugin for Flutter and I want to access the Android app resource strings from the plugin.

I'm trying using:

@Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {
            case "example":
                String value = context.getString(R.string.name);
                result.success(value);
                break;
            default:
                result.notImplemented();
                break;
        }
    }
```

But R.string points to the plugin resources, not the app resources.

Regards

答:
OK I found a solution.
I got this function from the Auth0 Android repo

So basically to get app resources from a plugin they use this function

private static String getResourceFromContext(@NonNull Context context, String resName) {
        final int stringRes = context.getResources().getIdentifier(resName, "string", context.getPackageName());
        if (stringRes == 0) {
            throw new IllegalArgumentException(String.format("The 'R.string.%s' value it's not defined in your project's resources file.", resName));
        }
        return context.getString(stringRes);
    }
```

Body:
I'm building a plugin for Flutter and I want to access the Android app resource strings from the plugin.

I'm trying using:

@Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {
            case "example":
                String value = context.getString(R.string.name);
                result.success(value);
                break;
            default:
                result.notImplemented();
                break;
        }
    }

But R.string points to the plugin resources, not the app resources.

Regards


问:
Android Travis CI Error: Invalid --abi armeabi-v7a for the selected target
My Travis build keeps failing because apparently it does not recognize the arm abi. Here's my full .travis.yml:

```<code>language: android
sudo: required

env:
  global:
  - ANDROID_API_LEVEL=28
  - ANDROID_BUILD_TOOLS_VERSION=28.0.3
  - ANDROID_ABI=armeabi-v7a
  - ANDROID_EMU_API_LEVEL=27

android:
  components:
    - tools
    - platform-tools
    - tools # appears twice as per Travis docs
    - build-tools-$ANDROID_BUILD_TOOLS_VERSION
    - android-$ANDROID_API_LEVEL
    - android-$ANDROID_EMU_API_LEVEL
    - extra-android-m2repository
    - sys-img-${ANDROID_ABI}-android-${ANDROID_EMU_API_LEVEL}
  licenses:
    - 'android-sdk-preview-license-52d11cd2'
    - 'android-sdk-license-.+'
    - 'google-gdk-license-.+'

before_cache:
  - rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
  - rm -fr $HOME/.gradle/caches/*/plugin-resolution/

cache:
  directories:
  - $HOME/.gradle/caches/
  - $HOME/.gradle/wrapper/
  - $HOME/.android/build-cache

before_script:
  - echo no | android create avd --force -n test -t android-$ANDROID_EMU_API_LEVEL --abi $ANDROID_ABI -c 100M
  - emulator -avd test -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &
  - chmod +x gradlew

script:
  - android list target
  - ./gradlew clean build
  - ./gradlew test
  - ./gradlew connectedCheck
</code>```

I have also tried to change the abi in the emulator to google_apis/armeabi-v7a to no avail. Also tried to add google_apis in the system image download. I have currently tried API_LEVEL 22, 27 and 28.
What is the issue here?

答:
I don't know if this is still relevant since it was asked 4 months ago, but I also just recently had this same issue. I tried many different things people suggested and none of it worked till I set it up this way:</p>

```<code>language: android
sudo: required
jdk: oraclejdk8

env:
  global:
  - ANDROID_API_LEVEL=28
  - ANDROID_BUILD_TOOLS_VERSION=28.0.3
  - ANDROID_ABI=armeabi-v7a

android:
  components:
    - tools
    - platform-tools
    - tools
    - extra-android-m2repository
  licenses:
    - 'android-sdk-preview-license-52d11cd2'
    - 'android-sdk-license-.+'
    - 'google-gdk-license-.+'

before_install:
  - touch $HOME/.android/repositories.cfg
  - yes | sdkmanager "platforms;android-28"
  - yes | sdkmanager "build-tools;28.0.3"

before_cache:
  - rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
  - rm -fr $HOME/.gradle/caches/*/plugin-resolution/

cache:
  directories:
  - $HOME/.gradle/caches/
  - $HOME/.gradle/wrapper/
  - $HOME/.android/build-cache

before_script:
  - chmod +x gradlew

script:
  - ./gradlew clean build
  - ./gradlew test
</code>```

Body:
My Travis build keeps failing because apparently it does not recognize the arm abi. Here's my full .travis.yml:

language: android
sudo: required

env:
  global:
  - ANDROID_API_LEVEL=28
  - ANDROID_BUILD_TOOLS_VERSION=28.0.3
  - ANDROID_ABI=armeabi-v7a
  - ANDROID_EMU_API_LEVEL=27

android:
  components:
    - tools
    - platform-tools
    - tools # appears twice as per Travis docs
    - build-tools-$ANDROID_BUILD_TOOLS_VERSION
    - android-$ANDROID_API_LEVEL
    - android-$ANDROID_EMU_API_LEVEL
    - extra-android-m2repository
    - sys-img-${ANDROID_ABI}-android-${ANDROID_EMU_API_LEVEL}
  licenses:
    - 'android-sdk-preview-license-52d11cd2'
    - 'android-sdk-license-.+'
    - 'google-gdk-license-.+'

before_cache:
  - rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
  - rm -fr $HOME/.gradle/caches/*/plugin-resolution/

cache:
  directories:
  - $HOME/.gradle/caches/
  - $HOME/.gradle/wrapper/
  - $HOME/.android/build-cache

before_script:
  - echo no | android create avd --force -n test -t android-$ANDROID_EMU_API_LEVEL --abi $ANDROID_ABI -c 100M
  - emulator -avd test -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &
  - chmod +x gradlew

script:
  - android list target
  - ./gradlew clean build
  - ./gradlew test
  - ./gradlew connectedCheck

I have also tried to change the abi in the emulator to google_apis/armeabi-v7a to no avail. Also tried to add google_apis in the system image download. I have currently tried API_LEVEL 22, 27 and 28.
What is the issue here?

Body:
I don't know if this is still relevant since it was asked 4 months ago, but I also just recently had this same issue. I tried many different things people suggested and none of it worked till I set it up this way:

language: android
sudo: required
jdk: oraclejdk8

env:
  global:
  - ANDROID_API_LEVEL=28
  - ANDROID_BUILD_TOOLS_VERSION=28.0.3
  - ANDROID_ABI=armeabi-v7a

android:
  components:
    - tools
    - platform-tools
    - tools
    - extra-android-m2repository
  licenses:
    - 'android-sdk-preview-license-52d11cd2'
    - 'android-sdk-license-.+'
    - 'google-gdk-license-.+'

before_install:
  - touch $HOME/.android/repositories.cfg
  - yes | sdkmanager "platforms;android-28"
  - yes | sdkmanager "build-tools;28.0.3"

before_cache:
  - rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
  - rm -fr $HOME/.gradle/caches/*/plugin-resolution/

cache:
  directories:
  - $HOME/.gradle/caches/
  - $HOME/.gradle/wrapper/
  - $HOME/.android/build-cache

before_script:
  - chmod +x gradlew

script:
  - ./gradlew clean build
  - ./gradlew test


问:
Is it possible to have a negative, not multiple of 4 offset in a load/store instruction?
During an exam of MIPSx32 Assembly, I found this instruction:

```<code>Lw $8, -2($4)
</code>```

My question is if that instruction is correct or not. If it is correct, can anyone tell me why?

答:
My question is if that instruction is correct or not. If it is correct, can anyone tell me why?

I just looked up the manual of an R4400 CPU, a real MIPS CPU:

The instruction 0x8C88FFFE means: lw $8,-2($4) (and not lw $8,-8($4) as other CPU types would interpret the constant -2 in word operations).

So at least the instruction exists.

Next thing the manual says is that it is not allowed to access unaligned memory. This means that ($x)+a must be a multiple of 4 in the instruction lw $y,a($x).

In other words: If ($4)=0x1002, then lw $8,-2($4) will access the address 0x1000 which is a multiple of 4. No problem.

However, lw $8,4($4) would access the address 0x1006 in this case. And 0x1006 is not a multiple of 4. This will be problem although the offset is a multiple of 4.

Body:
During an exam of MIPSx32 Assembly, I found this instruction:

Lw $8, -2($4)

My question is if that instruction is correct or not. If it is correct, can anyone tell me why?