问:
How to control the for loop with a if condition in it not to give output till the loop completes
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

```<code>public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}
</code>```

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

答:
If you have a return in the if then the for loop Will break and return the value.
Instead the if is not satisfied the for loop will terminate and return the null value outside the loop.

in a method the return break the function

Body:
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?


来源: stackexchange

问:
pod in Kubernetes cluster is unable to connect to internet with egress networkpolicy
I have deployed a vendor container in an on-prem Kubernetes cluster and the container in the pod needs to connect to internet to validate license and few other details. I have checked the environment and I don't see any existing network policies in the cluster and/or pod level.
I then added below networkpolicy entry for the pod namespace but still seeing following error in pods and service log.

level=fatal msg="Unable to connect to the license server"

.

```<code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
 name: allow-ingress-egress
 namespace: myappns
spec:
 podSelector:
 matchLabels: {}
 egress:
 - {}
 policyTypes:
 - Ingress
 - Egress
 ingress:
 - {}
 egress:
 - {}
</code>```

答: Realized that by default pod to pod and egress communication is allowed from all the pods in Kubernetes cluster. Maybe it was a temp network issue when I was testing, external/egress connections are working fine without any network policy rules in place. I am aware that this is not ideal for production environments, so will work on that part.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have deployed a vendor container in an on-prem Kubernetes cluster and the container in the pod needs to connect to internet to validate license and few other details. I have checked the environment and I don't see any existing network policies in the cluster and/or pod level.
I then added below networkpolicy entry for the pod namespace but still seeing following error in pods and service log.

level=fatal msg="Unable to connect to the license server"

.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
 name: allow-ingress-egress
 namespace: myappns
spec:
 podSelector:
 matchLabels: {}
 egress:
 - {}
 policyTypes:
 - Ingress
 - Egress
 ingress:
 - {}
 egress:
 - {}


问:
How to use Message Selectors to filter messages In JMS
I have ejb-jar.xml which contain <message-selector> destinationInstance IN(a', 'b','c')</message-selector>.

How we can implement message selector in standalone java program.

JMSMessageListener has been registered on queue and whenever there is message on queue , onMessage method of listener will be called.

I Have Try this.? Does It work...

public void messageSelector() {

```<code>List<String> url=StCotants.getUrls();

    for(String obj:url){

        ConnectionFactory factory = new ActiveMQConnectionFactory(obj);

        System.out.println(factory);

        try{
            Connection connection = factory.createConnection();

            connection.start();

            Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

             Queue queue = session.createQueue("queue");

             MessageConsumer consumer = session.createConsumer(queue,"destinationInstance IN('a', 'b','c')");

             XyzMDBClient xyzClientlistener=new XyzMDBClient();

             consumer.setMessageListener(xyzClientlistener);

        }
        catch(Exception e){

            e.printStackTrace();

        }

    }
</code>```

答:
Back in time I was looking for examples on how to use message selectors and I found this site very usefull: How to use Message Selectors to filter messages

Very concise article about what selectors are and how to use them.

Message Selectors allow you to filter the messages that a MessageConsumer will receive. The filter is a relatively complex language that mimics the syntax of an SQL WHERE clause. The selector can use all message headers and properties for filtering, but can not use the message content.
  Selectors are mostly useful for Topics that broadcast a very large number of messages to its subscribers.

They way selectors work depends on the destination type:

*On Queues, only messages that match the selector will be returned. Others stay in the queue (and thus can be read by a MessageConsumer with different selector).

*On Topics, messages that do not match the selector will be ignored as if they have not been published.
  In order to create a selection, you need to pass it to the createConsumer or createDurableSubscriber invocation:

Code examples:

```<code>    Session session = ...
MessageConsumer consumer1 = session.createConsumer(queue,
                       "(releaseYear < 1980) OR (releaseYear > 1989)");

MessageConsumer consumer2 = session.createConsumer(queue,
                       "(releaseYear BETWEEN 1980 AND 1989) AND title LIKE 'Michael%'");

MessageConsumer consumer3 = session.createConsumer(queue,
                       "(releaseYear = 1982) OR (title = 'Thriller')");

MessageConsumer consumer4 = session.createDurableConsumer(queue,
                       "title IN ('Off the wall', 'Thriller', 'Bad')");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have ejb-jar.xml which contain <message-selector> destinationInstance IN(a', 'b','c')</message-selector>.

How we can implement message selector in standalone java program.

JMSMessageListener has been registered on queue and whenever there is message on queue , onMessage method of listener will be called.

I Have Try this.? Does It work...

public void messageSelector() {

List<String> url=StCotants.getUrls();

    for(String obj:url){

        ConnectionFactory factory = new ActiveMQConnectionFactory(obj);

        System.out.println(factory);

        try{
            Connection connection = factory.createConnection();

            connection.start();

            Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

             Queue queue = session.createQueue("queue");

             MessageConsumer consumer = session.createConsumer(queue,"destinationInstance IN('a', 'b','c')");

             XyzMDBClient xyzClientlistener=new XyzMDBClient();

             consumer.setMessageListener(xyzClientlistener);

        }
        catch(Exception e){

            e.printStackTrace();

        }

    }

Body:
Back in time I was looking for examples on how to use message selectors and I found this site very usefull: How to use Message Selectors to filter messages

Very concise article about what selectors are and how to use them.

Message Selectors allow you to filter the messages that a MessageConsumer will receive. The filter is a relatively complex language that mimics the syntax of an SQL WHERE clause. The selector can use all message headers and properties for filtering, but can not use the message content.
  Selectors are mostly useful for Topics that broadcast a very large number of messages to its subscribers.

They way selectors work depends on the destination type:

*On Queues, only messages that match the selector will be returned. Others stay in the queue (and thus can be read by a MessageConsumer with different selector).

*On Topics, messages that do not match the selector will be ignored as if they have not been published.
  In order to create a selection, you need to pass it to the createConsumer or createDurableSubscriber invocation:

Code examples:

    Session session = ...
MessageConsumer consumer1 = session.createConsumer(queue,
                       "(releaseYear < 1980) OR (releaseYear > 1989)");

MessageConsumer consumer2 = session.createConsumer(queue,
                       "(releaseYear BETWEEN 1980 AND 1989) AND title LIKE 'Michael%'");

MessageConsumer consumer3 = session.createConsumer(queue,
                       "(releaseYear = 1982) OR (title = 'Thriller')");

MessageConsumer consumer4 = session.createDurableConsumer(queue,
                       "title IN ('Off the wall', 'Thriller', 'Bad')");


问:
python sqlite3 not working
```<code>try:
    c = db.cursor()
    c.execute("insert or replace into registrations values " +
              "(?, ?, datetime('now'))", (user, identity))
    print '\t<update>true</update>'
except Exception,inst:
    print inst.args
</code>```

insert create table not working. How do I fetch the exception details?

答:
If you read this Python PEP, it should describe the exception classes for the Sqlite Python module.

Have you tried something like this:

```<code>try:
  db_cursor.execute('some hopefully valid SQL;')
except sqlite3.Error, msg:
  print msg
</code>```

Title: python sqlite3 not working

Body:
try:
    c = db.cursor()
    c.execute("insert or replace into registrations values " +
              "(?, ?, datetime('now'))", (user, identity))
    print '\t<update>true</update>'
except Exception,inst:
    print inst.args

insert create table not working. How do I fetch the exception details?

Body:
If you read this Python PEP, it should describe the exception classes for the Sqlite Python module.

Have you tried something like this:

try:
  db_cursor.execute('some hopefully valid SQL;')
except sqlite3.Error, msg:
  print msg


问:
Image vertically aligned in div
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

```<code><div class="site-header">
            <img class="logo" src="CGLOGO.png" alt="logo">
</div>
</code>```

My CSS:

```<code>html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }
</code>```

Result:

答:
there are several ways to vertically center on a div one of it is </p>

```<code><div class="site-header">
   <img class="logo" src="CGLOGO.png" alt="logo">
</div>

<style>
.site-header {
   position:relative;
   height:400px;
   width:100%;
}
.site-header img {
   position:absolute;
   top:50%;
   height: 100px;
   transform:translateY(-50%);
}
</style>
</code>```

Title: Image vertically aligned in div

Body:
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

My CSS:

html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }

Result:

Body:
there are several ways to vertically center on a div one of it is

<div class="site-header">
   <img class="logo" src="CGLOGO.png" alt="logo">
</div>

<style>
.site-header {
   position:relative;
   height:400px;
   width:100%;
}
.site-header img {
   position:absolute;
   top:50%;
   height: 100px;
   transform:translateY(-50%);
}
</style>


问:
What do square brackets mean after a dict variable
I just wanted to know what does the square bracket mean in check[] and what does this square bracket do, because all I know that {} are dictionaries and [] are lists.

```<code>n = int(input().strip())
check = {True: "Not Weird", False: "Weird"}

print(check[
    n%2==0 and (
        n in range(2,6) or
        n > 20)
])
</code>```

答:
check is a dictionary and check[k] looks up the key k in this dictionary and returns the associated value.

This is a "clever" way of writing:

```<code>n = int(input().strip())

if n%2==0 and (n in range(2,6) or n > 20):
    print("Not Weird")
else:
    print("Weird")
</code>```

Body:
I just wanted to know what does the square bracket mean in check[] and what does this square bracket do, because all I know that {} are dictionaries and [] are lists.

n = int(input().strip())
check = {True: "Not Weird", False: "Weird"}

print(check[
    n%2==0 and (
        n in range(2,6) or
        n > 20)
])

Body:
check is a dictionary and check[k] looks up the key k in this dictionary and returns the associated value.

This is a "clever" way of writing:

n = int(input().strip())

if n%2==0 and (n in range(2,6) or n > 20):
    print("Not Weird")
else:
    print("Weird")


问:
Compile-time Size of Struct Minus Padding
I'm trying to use Boost MPL and Fusion to calculate the size of a struct exclusive of any padding. This is my current best attempt:

Live example

```<code>template<class T>
constexpr std::size_t sizeof_members(void)
{
    using namespace std;
    namespace mpl = boost::mpl;
    namespace fusion = boost::fusion;

    //This works, but only for structs containing exactly 4 members...
    typedef typename mpl::apply<mpl::unpack_args<mpl::vector<mpl::_1, mpl::_2, mpl::_3, mpl::_4>::type >, T>::type member_types;

    typedef typename mpl::transform<member_types, mpl::sizeof_<mpl::_1> >::type member_sizes;
    typedef typename mpl::accumulate<member_sizes, mpl::int_<0>, mpl::plus<mpl::_1, mpl::_2> >::type sum;
    return sum();
}

BOOST_FUSION_DEFINE_STRUCT(
    (), Foo_t,
    (std::uint8_t,  a)
    (std::uint16_t, b)
    (std::uint32_t, c)
    (std::uint64_t, d)
);
static_assert(sizeof_members<struct Foo_t>() == 15);

int main()
{
    std::cout << "sizeof_members = " << sizeof_members<struct Foo_t>() << std::endl;
    std::cout << "sizeof = " << sizeof(struct Foo_t) << std::endl;

    return 0;
}
</code>```

Expected output:

```<code>sizeof_members<struct Foo_t>() = 15
sizeof(struct Foo_t) = 16
</code>```

I can transform a Sequence of types to a Sequence of integers containing the size of each type, and I can compute the sum over that Sequence, but I'm having trouble with the first step of turning the struct into a Sequence of types. The Fusion docs say that BOOST_FUSION_DEFINE_STRUCT generates boilerplate to define and adapt an arbitrary struct as a model of Random Access Sequence, which I believe should be compatible with mpl::transform, however there seems to be some glue code that I'm missing to make this work. My current approach using mpl::unpack_args works but only for structs with exactly four fields.

How can I extend this to arbitrary structs with more or fewer fields?

答:
Since you tagged this C++17, the answer is: don't use Boost.MPL. Given C++11 even, the metaprogramming library you want is Boost.Mp11 - it's substantially better in all respects.

The newer, easier-to-use, ridiculously-more-compile-time-efficient version of Boost.Fusion that you want to use is Boost.Hana:

```<code>struct Foo_t {
    BOOST_HANA_DEFINE_STRUCT(Foo_t,
        (std::uint8_t, a),
        (std::uint16_t, b),
        (std::uint32_t, c),
        (std::uint64_t, d)
    );
};
</code>```

And the reason you want to use Boost.Hana is because sizeof_members (for any number of members) can be written as:

template <typename T>
constexpr auto sizeof_members() -> size_t
{
    return hana::fold(hana::accessors<T>(), size_t{},
        [](size_t s, auto mem){
            return s + sizeof(hana::second(mem)(std::declval<T>()));
        });
}

static_assert(sizeof_members<Foo_t>() == 15);
```

This mostly reads exactly like what you actually want to do: you want to fold over all the members, starting at 0, with an accumulation function that adds the size of the next member (accessors<T>() gives you a Sequence of pairs where the first is the name of the accessor and the second is a function that takes an object and returns that member).

Demo.

Body:
I'm trying to use Boost MPL and Fusion to calculate the size of a struct exclusive of any padding. This is my current best attempt:

Live example

template<class T>
constexpr std::size_t sizeof_members(void)
{
    using namespace std;
    namespace mpl = boost::mpl;
    namespace fusion = boost::fusion;

    //This works, but only for structs containing exactly 4 members...
    typedef typename mpl::apply<mpl::unpack_args<mpl::vector<mpl::_1, mpl::_2, mpl::_3, mpl::_4>::type >, T>::type member_types;

    typedef typename mpl::transform<member_types, mpl::sizeof_<mpl::_1> >::type member_sizes;
    typedef typename mpl::accumulate<member_sizes, mpl::int_<0>, mpl::plus<mpl::_1, mpl::_2> >::type sum;
    return sum();
}

BOOST_FUSION_DEFINE_STRUCT(
    (), Foo_t,
    (std::uint8_t,  a)
    (std::uint16_t, b)
    (std::uint32_t, c)
    (std::uint64_t, d)
);
static_assert(sizeof_members<struct Foo_t>() == 15);

int main()
{
    std::cout << "sizeof_members = " << sizeof_members<struct Foo_t>() << std::endl;
    std::cout << "sizeof = " << sizeof(struct Foo_t) << std::endl;

    return 0;
}

Expected output:

sizeof_members<struct Foo_t>() = 15
sizeof(struct Foo_t) = 16

I can transform a Sequence of types to a Sequence of integers containing the size of each type, and I can compute the sum over that Sequence, but I'm having trouble with the first step of turning the struct into a Sequence of types. The Fusion docs say that BOOST_FUSION_DEFINE_STRUCT generates boilerplate to define and adapt an arbitrary struct as a model of Random Access Sequence, which I believe should be compatible with mpl::transform, however there seems to be some glue code that I'm missing to make this work. My current approach using mpl::unpack_args works but only for structs with exactly four fields.

How can I extend this to arbitrary structs with more or fewer fields?

Body:
Since you tagged this C++17, the answer is: don't use Boost.MPL. Given C++11 even, the metaprogramming library you want is Boost.Mp11 - it's substantially better in all respects.

The newer, easier-to-use, ridiculously-more-compile-time-efficient version of Boost.Fusion that you want to use is Boost.Hana:

struct Foo_t {
    BOOST_HANA_DEFINE_STRUCT(Foo_t,
        (std::uint8_t, a),
        (std::uint16_t, b),
        (std::uint32_t, c),
        (std::uint64_t, d)
    );
};

And the reason you want to use Boost.Hana is because sizeof_members (for any number of members) can be written as:

template <typename T>
constexpr auto sizeof_members() -> size_t
{
    return hana::fold(hana::accessors<T>(), size_t{},
        [](size_t s, auto mem){
            return s + sizeof(hana::second(mem)(std::declval<T>()));
        });
}

static_assert(sizeof_members<Foo_t>() == 15);

This mostly reads exactly like what you actually want to do: you want to fold over all the members, starting at 0, with an accumulation function that adds the size of the next member (accessors<T>() gives you a Sequence of pairs where the first is the name of the accessor and the second is a function that takes an object and returns that member).

Demo.


问:
How do I add a string to each key of a dictionary?
I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

```<code>def dict_change(dicto):
    for key,value in dicto.items():
        for numb in value:
            if numb >= 100:
                numb = 'D' + str(numb)
            else:
                numb = 'DI' + str(numb)
    return dicto

new_dict = dict_change(old_dict)
</code>```

Thank you! :)

答:
Using map and a dict comprehension:

```<code>dct = {"a": [100, 200, 300], "b": [-100, 200, 100]}

def changer(number):
    char = "D" if number > 100 else "DI"
    return f"{char}{number}"

new_dct = {key: list(map(changer, values)) for key, values in dct.items()}
print(new_dct)
</code>```

Output

```<code>{'a': ['DI100', 'D200', 'D300'], 'b': ['DI-100', 'D200', 'DI100']}
</code>```

Body:
I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

def dict_change(dicto):
    for key,value in dicto.items():
        for numb in value:
            if numb >= 100:
                numb = 'D' + str(numb)
            else:
                numb = 'DI' + str(numb)
    return dicto

new_dict = dict_change(old_dict)

Thank you! :)

Body:
Using map and a dict comprehension:

dct = {"a": [100, 200, 300], "b": [-100, 200, 100]}

def changer(number):
    char = "D" if number > 100 else "DI"
    return f"{char}{number}"

new_dct = {key: list(map(changer, values)) for key, values in dct.items()}
print(new_dct)

Output

{'a': ['DI100', 'D200', 'D300'], 'b': ['DI-100', 'D200', 'DI100']}


问:
ScrollView height adapting to content
I can't seem to manage this simple layout and all the tricks I find for ScrollView don't match my case.
My content has a header and a footer that should "stick" to it.
But when my content becomes too big, the header should be naturally stuck at the top of the screen, the footer at the bottom of the screen, and the middle part is taken by the content which should be scrollable.
Here is the code for the layout and I join some screens.

Red: screen

Blue: content header

Green: content (Scrollview)

Yellow:  content footer

```<code><View style={styles.screen}>
    <View style={styles.contentHeader}>
        {contentHeader}
    </View>
    <ScrollView style={styles.content}>
        {content}
    </ScrollView>
    <View style={styles.contentFooter}>
        {contentFooter}
    </View>
</View>
</code>```

My problem is that the ScrollView should take only the height required by its content but it does not.
Any suggestions ?

答:
You can use FlatList and use its ListFoooterComponent and ListHeaderComponent for rendering your header and footer you can also render these with ScrollView but its recommended to use FlatList for more performant and support.

Have a look at this to FlatList

https://reactnative.dev/docs/flatlist

Otherwise, you can use stickyHeaderIndices prop for rendering header in ScollView and place your footer outside of the ScrollView with these styles.

This will work

```<code><View style={styles.screen}>
    <ScrollView style={styles.content} stickyHeaderIndices={[0]}>
       <View style={styles.contentHeader}>
            {contentHeader}
       </View>
       {content}
    </ScrollView>
    <View style={[styles.contentFooter, {position: 'absolute, bottom: 0}]}>
        {contentFooter}
    </View>
</View>
</code>```

Title: ScrollView height adapting to content

Body:
I can't seem to manage this simple layout and all the tricks I find for ScrollView don't match my case.
My content has a header and a footer that should "stick" to it.
But when my content becomes too big, the header should be naturally stuck at the top of the screen, the footer at the bottom of the screen, and the middle part is taken by the content which should be scrollable.
Here is the code for the layout and I join some screens.

Red: screen

Blue: content header

Green: content (Scrollview)

Yellow:  content footer

<View style={styles.screen}>
    <View style={styles.contentHeader}>
        {contentHeader}
    </View>
    <ScrollView style={styles.content}>
        {content}
    </ScrollView>
    <View style={styles.contentFooter}>
        {contentFooter}
    </View>
</View>

My problem is that the ScrollView should take only the height required by its content but it does not.
Any suggestions ?

Body:
You can use FlatList and use its ListFoooterComponent and ListHeaderComponent for rendering your header and footer you can also render these with ScrollView but its recommended to use FlatList for more performant and support.

Have a look at this to FlatList

https://reactnative.dev/docs/flatlist

Otherwise, you can use stickyHeaderIndices prop for rendering header in ScollView and place your footer outside of the ScrollView with these styles.

This will work

<View style={styles.screen}>
    <ScrollView style={styles.content} stickyHeaderIndices={[0]}>
       <View style={styles.contentHeader}>
            {contentHeader}
       </View>
       {content}
    </ScrollView>
    <View style={[styles.contentFooter, {position: 'absolute, bottom: 0}]}>
        {contentFooter}
    </View>
</View>


问:
How do I specify which font weights are available for a given font family?
I'm using a web font, and including weights 300 (light) and 700 (bold). Those are the only weights the site uses, and I specify on my html element that the default font-weight should be 300.

When the browser comes across a  tag, the default styling applied (not sure if it's the browser's default sheet or normalize.css) is font-weight: bolder. This makes sense to me: I want to move one step bolder. And say I had three weights, I'd want it just to move to the next step from whatever the inherited weight would otherwise be.

However, bolder on a  element somewhere in regular body text is bumping the weight up from 300 to 400, and the browser is rendering this with the same 300-weight font as the surrounding text. Clearly I want it to realize the next weight available is 700, and to use that.

Is there a way to tell CSS/the browser which font weights are available for a given font family, for the purposes of lighter and bolder?

答:
What about creating an additional @font-face rule, specifying font-weight: 400, and using the font files from the font-weight: 700 rule?

/* Rules generated by Google Fonts */
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: local('Raleway Light'), local('Raleway-Light'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwIYqWqZPANqczVs.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 700;
  font-display: swap;
  src: local('Raleway Bold'), local('Raleway-Bold'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwJYtWqZPANqczVs.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

/* Fix for `font-weight: bolder` of a `font-weight: 300` parent */
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Raleway Bold'), local('Raleway-Bold'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwJYtWqZPANqczVs.woff2) format('woff2'); /* the same as for font-weight: 700 */
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}```

This only one additional font-face rule seems to be clean enough for me, and is even completely safe if you are self-hosting the font files.

Body:
What about creating an additional @font-face rule, specifying font-weight: 400, and using the font files from the font-weight: 700 rule?

/* Rules generated by Google Fonts */
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 300;
  font-display: swap;
  src: local('Raleway Light'), local('Raleway-Light'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwIYqWqZPANqczVs.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 700;
  font-display: swap;
  src: local('Raleway Bold'), local('Raleway-Bold'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwJYtWqZPANqczVs.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

/* Fix for `font-weight: bolder` of a `font-weight: 300` parent */
@font-face {
  font-family: 'Raleway';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Raleway Bold'), local('Raleway-Bold'), url(https://fonts.gstatic.com/s/raleway/v14/1Ptrg8zYS_SKggPNwJYtWqZPANqczVs.woff2) format('woff2'); /* the same as for font-weight: 700 */
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

This only one additional font-face rule seems to be clean enough for me, and is even completely safe if you are self-hosting the font files.


问:
How to pass single touches to underlying views but keep the UIPanGestureRecognizer working?
I have built a custom index view for my table and collection views, so user can easily scroll through the content.
However, some cells have the accessory button in them that is placed on right side of the cell.
If the index view is too wide it blocks the button from receiving the touch.

I don't want the index view to respond to single touches, only swipes so I've used the UIPanGestureRecognizer for it and fiddled with UIGestureRecognizedDelegate methods to achieve that but I didn't find any solution. I can't set userInteractionEnabled on the index view because it would break the pan gesture recognizer.

Is this even possible to achieve this effect?

答:
Add this in your custom index view's subclass :-

```<code>override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    var hitTestView = super.hitTest(point, with: event)
    if (event?.type == UIEvent.EventType.touches) && (hitTestView is Self) {
        hitTestView = nil
    }
    return hitTestView
}
</code>```

hitTest is a very powerful method. It can also be used to determine which view should receive the touch if there are multiple overlapping views or subviews at the same point. This is a pretty good tutorial to know more about this feature (though it is in Objective C) :- Hit Test iOS

Body:
Add this in your custom index view's subclass :-

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    var hitTestView = super.hitTest(point, with: event)
    if (event?.type == UIEvent.EventType.touches) && (hitTestView is Self) {
        hitTestView = nil
    }
    return hitTestView
}

hitTest is a very powerful method. It can also be used to determine which view should receive the touch if there are multiple overlapping views or subviews at the same point. This is a pretty good tutorial to know more about this feature (though it is in Objective C) :- Hit Test iOS


问:
Delphi Embarcadero XE: tons of warnings with String and PAnsiChar
I'm trying to migrate from Delphi 2007 to Embarcadero RAD Studio XE.
I'm getting tons of warnings.
They all look like this: I have a procedure where I declare a "String":

```<code>procedure SendMail( ADestinataire,ASubject : String);
</code>```

And I'm trying to call Windows API like:

```<code>  Res := MAPIResolveName(Session, Application.Handle,
    PAnsiChar(ADestinataire), MAPI_LOGON_UI, 0, PRecip);
</code>```

So the warnings are:

W1044: Transtyping string into PAnsiChar suspect.

What am I doing wrong / how should I correct this (350 warnings...)?

Thank you very much

答:
MAPIResolveName uses LPSTR parameter, which is PAnsiChar in Delphi. Simple MAPI does not support UTF16 strings (though it can be used with UTF8 strings), so if you adhere to simple MAPI you should use AnsiStrings, for example

```<code>procedure SendMail( ADestinataire,ASubject : AnsiString);
</code>```

or better you can use

```<code>procedure SendMail( ADestinataire,ASubject : String);
</code>```

and explicitly convert string parameters to AnsiStrings prior to calling MAPIResolveName

Update
The whole Simple MAPI is now deprecated; Simple MAPI can be used with UTF8 strings, but it requires some changes in code and registry.

So if the question is about quick porting old ANSI Simple MAPI to Unicode Delphi, the best is to adhere to AnsiStrings.

A more solid approach is to abandon Simple MAPI completely and use Extended MAPI instead.

Body:
I'm trying to migrate from Delphi 2007 to Embarcadero RAD Studio XE.
I'm getting tons of warnings.
They all look like this: I have a procedure where I declare a "String":

procedure SendMail( ADestinataire,ASubject : String);

And I'm trying to call Windows API like:

  Res := MAPIResolveName(Session, Application.Handle,
    PAnsiChar(ADestinataire), MAPI_LOGON_UI, 0, PRecip);

So the warnings are:

W1044: Transtyping string into PAnsiChar suspect.

What am I doing wrong / how should I correct this (350 warnings...)?

Thank you very much

Body:
MAPIResolveName uses LPSTR parameter, which is PAnsiChar in Delphi. Simple MAPI does not support UTF16 strings (though it can be used with UTF8 strings), so if you adhere to simple MAPI you should use AnsiStrings, for example

procedure SendMail( ADestinataire,ASubject : AnsiString);

or better you can use

procedure SendMail( ADestinataire,ASubject : String);

and explicitly convert string parameters to AnsiStrings prior to calling MAPIResolveName

Update
The whole Simple MAPI is now deprecated; Simple MAPI can be used with UTF8 strings, but it requires some changes in code and registry.

So if the question is about quick porting old ANSI Simple MAPI to Unicode Delphi, the best is to adhere to AnsiStrings.

A more solid approach is to abandon Simple MAPI completely and use Extended MAPI instead.


问:
extract a specific tag from xml file using beautiful soup in python
I have an xml file (lets call is abc.xml) which looks like this.

```<code><?xml version="1.0" encoding="UTF-8"?>

<properties>
  <product name="XYZ" version="123"/>
  <application-links>
    <application-links>
      <id>111111111111111</id>
      <name>Link_1</name>
      <primary>true</primary>
      <type>applinks.ABC</type>
      <display-url>http://ABC.displayURL</display-url>
      <rpc-url>http://ABC.displayURL</rpc-url>
    </application-links>
  </application-links>
</properties>
</code>```

my python code is like this

```<code>f = open ('file.xml', 'r')
from bs4 import BeautifulSoup
soup = BeautifulSoup(f,'lxml')

print(soup.product)

for applinks in soup.application-links:
    print(applinks)
</code>```

which prints the following

```<code><product name="XYZ" version="123"></product>
Traceback (most recent call last):
  File "parse.py", line 7, in <module>
    for applinks in soup.application-links:
NameError: name 'links' is not defined
</code>```

Please can you help me understand how to print lines which have tags including a dash/hyphen '-'

答:
I don't know if beautifulsoup is the best option here, but I really suggest using the ElementTree module in python like so:

```<code>>>> import xml.etree.ElementTree as ET
>>> root = ET.parse('file.xml').getroot()
>>> for app in root.findall('*/application-links/'):
...     print(app.text)
111111111111111
Link_1
true
applinks.ABC
http://ABC.displayURL
http://ABC.displayURL
</code>```

So, to print the value inside the <name> tag, you can do so:

```<code>>>> for app in root.findall('*/application-links/name'):
...     print(app.text)
Link_1
</code>```

Body:
I have an xml file (lets call is abc.xml) which looks like this.

<?xml version="1.0" encoding="UTF-8"?>

<properties>
  <product name="XYZ" version="123"/>
  <application-links>
    <application-links>
      <id>111111111111111</id>
      <name>Link_1</name>
      <primary>true</primary>
      <type>applinks.ABC</type>
      <display-url>http://ABC.displayURL</display-url>
      <rpc-url>http://ABC.displayURL</rpc-url>
    </application-links>
  </application-links>
</properties>

my python code is like this

f = open ('file.xml', 'r')
from bs4 import BeautifulSoup
soup = BeautifulSoup(f,'lxml')

print(soup.product)

for applinks in soup.application-links:
    print(applinks)

which prints the following

<product name="XYZ" version="123"></product>
Traceback (most recent call last):
  File "parse.py", line 7, in <module>
    for applinks in soup.application-links:
NameError: name 'links' is not defined

Please can you help me understand how to print lines which have tags including a dash/hyphen '-'

Body:
I don't know if beautifulsoup is the best option here, but I really suggest using the ElementTree module in python like so:

>>> import xml.etree.ElementTree as ET
>>> root = ET.parse('file.xml').getroot()
>>> for app in root.findall('*/application-links/'):
...     print(app.text)
111111111111111
Link_1
true
applinks.ABC
http://ABC.displayURL
http://ABC.displayURL

So, to print the value inside the <name> tag, you can do so:

>>> for app in root.findall('*/application-links/name'):
...     print(app.text)
Link_1


问:
Redux dispatching actions in a specific order
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

```<code>export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}
</code>```

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

```<code>IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......
</code>```

Whereas the 2nd IS_DONE action is supposed to be carried out the last

答:
Try putting them in a try-catch block and call the action dispatch as async for each of your dispatch calls - generally it looks like:

```<code>export const actionName = ({VariablesToPassToTheAction}) => async(dispatch) => {

};
</code>```

Try adapting this mechanism for all your actions that involve api calls. Finally wrap your stuff inside try-catch blocks. If an error occurs, subsequent dispatches fail and the catch block is called, otherwise they are executed in order:

```<code>export const selectObjectTransition = (transition) => async(dispatch) => {
    try{
dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }

  catch(err){
    //control shifts here if any dispatch fails. Don't forget to handle the error
    }
}
</code>```

Body:
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......

Whereas the 2nd IS_DONE action is supposed to be carried out the last

Body:
Try putting them in a try-catch block and call the action dispatch as async for each of your dispatch calls - generally it looks like:

export const actionName = ({VariablesToPassToTheAction}) => async(dispatch) => {

};

Try adapting this mechanism for all your actions that involve api calls. Finally wrap your stuff inside try-catch blocks. If an error occurs, subsequent dispatches fail and the catch block is called, otherwise they are executed in order:

export const selectObjectTransition = (transition) => async(dispatch) => {
    try{
dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }

  catch(err){
    //control shifts here if any dispatch fails. Don't forget to handle the error
    }
}


问:
Is it possible to use Docker.DotNet to start a container programmatically on Azure Pipelines?
I have a microservices application and I wan't to start the whole stack to run integration tests. The idea is to be able to run the tests from Test Explorer within Visual Studio. So I don't want to create a shell script to be able to accomplish this.

The idea is to start all external microservice dependencies in containers and then run a TestServer of the system under test to receive the test requests so that the system can call other microservices.

I found this library and liked the idea of start containers programmatically to achieve the afore mentioned.

What I don't know, is if this would work running on an Azure Pipeline. What would be the correct docker engine address on Azure to initialize Docker.DotNet?

```<code>// Default Docker Engine on Windows
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("npipe://./pipe/docker_engine"))
     .CreateClient();
// Default Docker Engine on Linux
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("unix:///var/run/docker.sock"))
     .CreateClient();
</code>```

答:
I did a little research and found that both Windows and Linux images for Ms-hosted agents have Docker and Docker-Compose pre-installed, so it is possible to start containers using these agents.

My problem was that I didn't realize that the Ops team configured a Linux agent. I was trying to execute using a Windows named pipe and not a Unix socket.

I changed the Docker Engine API address accordingly and it worked.

Here is my code in case someone is interested in creating Integration Tests that start containers for microservices dependencies:

```<code>using Docker.DotNet;
using System;
using System.Runtime.InteropServices;

namespace Relationship.Promotion.Applier.IntegrationTest.Helpers
{
    public class DockerClientFactory
    {
        private static readonly Uri defaultWindowsDockerEngineUri = new Uri("npipe://./pipe/docker_engine");
        private static readonly Uri defaultLinuxDockerEngineUri = new Uri("unix:///var/run/docker.sock");

        public static DockerClient CreateInstance()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                return new DockerClientConfiguration(defaultWindowsDockerEngineUri).CreateClient();
            else
                return new DockerClientConfiguration(defaultLinuxDockerEngineUri).CreateClient();
        }
    }
}

namespace Relationship.Promotion.Applier.IntegrationTest
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        private readonly DockerClient dockerClient;
        private readonly PromotionContainer promotionContainer;
        private readonly StoreContainer storeContainer;
        private readonly ConversionContainer conversionContainer;

        public CustomWebApplicationFactory()
        {
            try
            {
                // Alternative to Docker.DotNet
                // https://github.com/Deffiss/testenvironment-docker
                dockerClient = DockerClientFactory.CreateInstance();

                DockerContainerBase.CleanupOrphanedContainers(dockerClient).Wait(300.Seconds());

                if (!dockerClient.Networks.ListNetworksAsync().Result.Select(n => n.Name).Contains("boti-network"))
                {
                    var result = dockerClient.Networks.CreateNetworkAsync(new Docker.DotNet.Models.NetworksCreateParameters()
                    {
                        Name = "boti-network",
                        Driver = "bridge"
                    }).Result;
                }

                promotionContainer = new PromotionContainer(imageName: "promotion-engine-promotion-api");
                promotionContainer.Start(dockerClient).Wait(300.Seconds());

                conversionContainer = new ConversionContainer(imageName: "promotion-engine-conversion-api");
                conversionContainer.Start(dockerClient).Wait(300.Seconds());

                storeContainer = new StoreContainer("promotion-engine-store-api");
                storeContainer.Start(dockerClient).Wait(300.Seconds());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                throw;
            }
        }

        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return base.CreateWebHostBuilder().UseEnvironment("Docker");
        }

        protected override void Dispose(bool itIsSafeToAlsoFreeManagedObjects)
        {
            if (!itIsSafeToAlsoFreeManagedObjects) return;

            promotionContainer.Remove(dockerClient).Wait(300.Seconds());
            conversionContainer.Remove(dockerClient).Wait(300.Seconds());
            storeContainer.Remove(dockerClient).Wait(300.Seconds());

            dockerClient.Dispose();

            base.Dispose(itIsSafeToAlsoFreeManagedObjects);
        }
    }
}
</code>```

Body:
I have a microservices application and I wan't to start the whole stack to run integration tests. The idea is to be able to run the tests from Test Explorer within Visual Studio. So I don't want to create a shell script to be able to accomplish this.

The idea is to start all external microservice dependencies in containers and then run a TestServer of the system under test to receive the test requests so that the system can call other microservices.

I found this library and liked the idea of start containers programmatically to achieve the afore mentioned.

What I don't know, is if this would work running on an Azure Pipeline. What would be the correct docker engine address on Azure to initialize Docker.DotNet?

// Default Docker Engine on Windows
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("npipe://./pipe/docker_engine"))
     .CreateClient();
// Default Docker Engine on Linux
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("unix:///var/run/docker.sock"))
     .CreateClient();

Body:
I did a little research and found that both Windows and Linux images for Ms-hosted agents have Docker and Docker-Compose pre-installed, so it is possible to start containers using these agents.

My problem was that I didn't realize that the Ops team configured a Linux agent. I was trying to execute using a Windows named pipe and not a Unix socket.

I changed the Docker Engine API address accordingly and it worked.

Here is my code in case someone is interested in creating Integration Tests that start containers for microservices dependencies:

using Docker.DotNet;
using System;
using System.Runtime.InteropServices;

namespace Relationship.Promotion.Applier.IntegrationTest.Helpers
{
    public class DockerClientFactory
    {
        private static readonly Uri defaultWindowsDockerEngineUri = new Uri("npipe://./pipe/docker_engine");
        private static readonly Uri defaultLinuxDockerEngineUri = new Uri("unix:///var/run/docker.sock");

        public static DockerClient CreateInstance()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                return new DockerClientConfiguration(defaultWindowsDockerEngineUri).CreateClient();
            else
                return new DockerClientConfiguration(defaultLinuxDockerEngineUri).CreateClient();
        }
    }
}

namespace Relationship.Promotion.Applier.IntegrationTest
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        private readonly DockerClient dockerClient;
        private readonly PromotionContainer promotionContainer;
        private readonly StoreContainer storeContainer;
        private readonly ConversionContainer conversionContainer;

        public CustomWebApplicationFactory()
        {
            try
            {
                // Alternative to Docker.DotNet
                // https://github.com/Deffiss/testenvironment-docker
                dockerClient = DockerClientFactory.CreateInstance();

                DockerContainerBase.CleanupOrphanedContainers(dockerClient).Wait(300.Seconds());

                if (!dockerClient.Networks.ListNetworksAsync().Result.Select(n => n.Name).Contains("boti-network"))
                {
                    var result = dockerClient.Networks.CreateNetworkAsync(new Docker.DotNet.Models.NetworksCreateParameters()
                    {
                        Name = "boti-network",
                        Driver = "bridge"
                    }).Result;
                }

                promotionContainer = new PromotionContainer(imageName: "promotion-engine-promotion-api");
                promotionContainer.Start(dockerClient).Wait(300.Seconds());

                conversionContainer = new ConversionContainer(imageName: "promotion-engine-conversion-api");
                conversionContainer.Start(dockerClient).Wait(300.Seconds());

                storeContainer = new StoreContainer("promotion-engine-store-api");
                storeContainer.Start(dockerClient).Wait(300.Seconds());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                throw;
            }
        }

        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return base.CreateWebHostBuilder().UseEnvironment("Docker");
        }

        protected override void Dispose(bool itIsSafeToAlsoFreeManagedObjects)
        {
            if (!itIsSafeToAlsoFreeManagedObjects) return;

            promotionContainer.Remove(dockerClient).Wait(300.Seconds());
            conversionContainer.Remove(dockerClient).Wait(300.Seconds());
            storeContainer.Remove(dockerClient).Wait(300.Seconds());

            dockerClient.Dispose();

            base.Dispose(itIsSafeToAlsoFreeManagedObjects);
        }
    }
}


问:
How do you delete queried data from firebase locally?
In my react native app, users are able to create and see posts (that can contain media) which are stored in Firebase's realtime database. It works correctly, however the size of the app increases greatly over time, which I assume is because more and more posts are queried and stored. Is this likely to be what causes the increased size of the app? If so, is it possible to delete such local data in the componentDidMount function?

答:
There is no API to tell Firebase to clear its cache. But if you find that the size of the cache grows beyond what is reasonable for your app, you can explicitly set the cache size to something that works better for your users.

A few notes:

Storing images in the JSON database is in general not recommended, for many reasons. But one of them is precisely because those image would disproportionally affect the cache size. Consider storing the images in a dedicated file storage solution, like Cloud Storage for Firebase, and using a image-caching library.

Firebase's local persistence functions as a cache. You should not treat Firebase as a purely local database, as its local performance will deteriorate over time as the cache grows. If your clients never connect to the Firebase servers, you might want to consider using another database, which is optimized for pure local usage.


问:
How to Verify using C# if a XML file is broken
Is there anything built in to determine if an XML file is valid. One way would be to read the entire content and verify if the string represents valid XML content. Even then, how to determine if string contains valid XML data.</p>

答:
Create an XmlReader around a StringReader with the XML and read through the reader:

```<code>using (var reader = XmlReader.Create(something))
    while(reader.Read())
        ;
</code>```

If you don't get any exceptions, the XML is well-formed.

Unlike XDocument or XmlDocument, this will not hold an entire DOM tree in memory, so it will run quickly even on extremely large XML files.

Body:
Create an XmlReader around a StringReader with the XML and read through the reader:

using (var reader = XmlReader.Create(something))
    while(reader.Read())
        ;

If you don't get any exceptions, the XML is well-formed.

Unlike XDocument or XmlDocument, this will not hold an entire DOM tree in memory, so it will run quickly even on extremely large XML files.


问:
Why can't I get the MouseDown event of a Control via Reflection
I try to remove a EventHandler with .NET Reflection.
When I use my own testclass (changed the argument from Control that to TestClass that), it works.

But when I want to do it with a WindowsForms Control, I can't get the public field of the event (strictly speaking  I dont get any public instance field).
What differs between my TestClass and a WindowsForms Control.
The "MouseDown" event and the event in my TestClass are both public.

```<code>        static void  RemoveHandler( Control that )
        {
            //adding an eventhandler for testing
            that.MouseDown += (obj,arg) => { };

            string eventName = "MouseDown";
            //this works, but I need the Field, to get the Invocationlist
            var testEventInfo = that.GetType().GetEvent( eventName, BindingFlags.Public | BindingFlags.Instance );

            if ( testEventInfo != null )
            {
                //this fails, Declaring Type of my Event "MouseDown" is Control  testEventFieldInfo stays null
                var testEventFieldInfo = testEventInfo.DeclaringType.GetField( testEventInfo.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );

                //trying to get all public events fails too, fields is always empty
                // var fields = testEventInfo.DeclaringType.GetFields( BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );
                if ( testEventFieldInfo != null )
                {
                    var testEventFieldValue = (System.Delegate)testEventFieldInfo.GetValue( that );
                    if ( testEventFieldValue != null ) // if its null no Delegates are hooked
                    {
                        var invocationList = testEventFieldValue.GetInvocationList();
                        //var removeMethod = testEventInfo.GetRemoveMethod();

                        foreach ( var eventHandlerDelegate in invocationList )
                        {

                            testEventInfo.RemoveEventHandler( that, eventHandlerDelegate );
                        }
                    }
                }
            }
        }
</code>```

What I tried is dealing with inheritance.
(TestClass is a drived Class, and the base Class declares the event)
Found out that .GetEvent gets also Event from all base classes, but GetField does not, so I added the access to the .DeclaringType of the Field. All this works with my TestClass, but not with a Control-derrived type (i.e. Button or ListBox)

What I found out too is, that there is a field "EventMouseDown", which is NonPublic and Static. But I cant find any Documentation on this. And the Name I hooked on is "MouseDown"

So maybe you know, where is my lack of knowledge.
Thank you very much.

答:
Maybe, I've just found a way, it seem to work, but I dont know why (let me know, if you know how this WindowsFormsEvent are structured)
The answer is a modification of this article:
GetField unable to obtain EventClick

```<code>//Important is, that the Field is NoPublic and Static and is Named "Event~"
//What does the .GetValue(null)
var field = testEventInfo.DeclaringType.GetField( "EventMouseDown", BindingFlags.NonPublic | BindingFlags.Static ).GetValue( null );
//Then you take the so called EventHandlerList which is also Static
// and NoPublic and use your instance to get the Value of it
var eventList = (EventHandlerList)testEventInfo.DeclaringType.GetProperty( "Events", BindingFlags.Instance | BindingFlags.NonPublic ).GetValue( that );
//the trick is now, to use the field as a key for the eventList
var mouseDownEvent = eventList[field];
if ( mouseDownEvent != null)
{
    var invList = mouseDownEvent.GetInvocationList();
    foreach (var eventHandlerDelegate in invList )
    {
        testEventInfo.RemoveEventHandler( that, eventHandlerDelegate );
    }
}
//Now the invocation List ist empty
var modifiedEventList = (EventHandlerList)testEventInfo.DeclaringType.GetProperty( "Events", BindingFlags.Instance | BindingFlags.NonPublic ).GetValue( that );
var modifiedMouseDownEvent = eventList[field];
//modifiedMouseDownEvent is null now, no delegate is attached anymore
</code>```

But why is the event named "EventMouseDown" and it's NoPublic and Static? I dont know, it just works for me.
Maybe I can save the handlers and save them, and hook them back later, as I need it.

Body:
I try to remove a EventHandler with .NET Reflection.
When I use my own testclass (changed the argument from Control that to TestClass that), it works.

But when I want to do it with a WindowsForms Control, I can't get the public field of the event (strictly speaking  I dont get any public instance field).
What differs between my TestClass and a WindowsForms Control.
The "MouseDown" event and the event in my TestClass are both public.

        static void  RemoveHandler( Control that )
        {
            //adding an eventhandler for testing
            that.MouseDown += (obj,arg) => { };

            string eventName = "MouseDown";
            //this works, but I need the Field, to get the Invocationlist
            var testEventInfo = that.GetType().GetEvent( eventName, BindingFlags.Public | BindingFlags.Instance );

            if ( testEventInfo != null )
            {
                //this fails, Declaring Type of my Event "MouseDown" is Control  testEventFieldInfo stays null
                var testEventFieldInfo = testEventInfo.DeclaringType.GetField( testEventInfo.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );

                //trying to get all public events fails too, fields is always empty
                // var fields = testEventInfo.DeclaringType.GetFields( BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );
                if ( testEventFieldInfo != null )
                {
                    var testEventFieldValue = (System.Delegate)testEventFieldInfo.GetValue( that );
                    if ( testEventFieldValue != null ) // if its null no Delegates are hooked
                    {
                        var invocationList = testEventFieldValue.GetInvocationList();
                        //var removeMethod = testEventInfo.GetRemoveMethod();

                        foreach ( var eventHandlerDelegate in invocationList )
                        {

                            testEventInfo.RemoveEventHandler( that, eventHandlerDelegate );
                        }
                    }
                }
            }
        }

What I tried is dealing with inheritance.
(TestClass is a drived Class, and the base Class declares the event)
Found out that .GetEvent gets also Event from all base classes, but GetField does not, so I added the access to the .DeclaringType of the Field. All this works with my TestClass, but not with a Control-derrived type (i.e. Button or ListBox)

What I found out too is, that there is a field "EventMouseDown", which is NonPublic and Static. But I cant find any Documentation on this. And the Name I hooked on is "MouseDown"

So maybe you know, where is my lack of knowledge.
Thank you very much.

Body:
Maybe, I've just found a way, it seem to work, but I dont know why (let me know, if you know how this WindowsFormsEvent are structured)
The answer is a modification of this article:
GetField unable to obtain EventClick

//Important is, that the Field is NoPublic and Static and is Named "Event~"
//What does the .GetValue(null)
var field = testEventInfo.DeclaringType.GetField( "EventMouseDown", BindingFlags.NonPublic | BindingFlags.Static ).GetValue( null );
//Then you take the so called EventHandlerList which is also Static
// and NoPublic and use your instance to get the Value of it
var eventList = (EventHandlerList)testEventInfo.DeclaringType.GetProperty( "Events", BindingFlags.Instance | BindingFlags.NonPublic ).GetValue( that );
//the trick is now, to use the field as a key for the eventList
var mouseDownEvent = eventList[field];
if ( mouseDownEvent != null)
{
    var invList = mouseDownEvent.GetInvocationList();
    foreach (var eventHandlerDelegate in invList )
    {
        testEventInfo.RemoveEventHandler( that, eventHandlerDelegate );
    }
}
//Now the invocation List ist empty
var modifiedEventList = (EventHandlerList)testEventInfo.DeclaringType.GetProperty( "Events", BindingFlags.Instance | BindingFlags.NonPublic ).GetValue( that );
var modifiedMouseDownEvent = eventList[field];
//modifiedMouseDownEvent is null now, no delegate is attached anymore

But why is the event named "EventMouseDown" and it's NoPublic and Static? I dont know, it just works for me.
Maybe I can save the handlers and save them, and hook them back later, as I need it.


问:
what is causing this error message [Error]: "Client 'host' unknown - use 'client' command to create it."?
Whenver I try to run p4 command p4 change -o or pythonically p4.fetch_change()

I get this error message !

[Error]: "Client 'hostname' unknown - use 'client' command to create it."

Does anyone know why am I getting this ?

答:
You don't have a client workspace defined.  The changelist spec you get from p4 change -o is the spec for the default pending changelist associated with your current client.  If you don't have a client, you'll get that error.  You'll see the same behavior for any other command that depends on a client spec (which is most of them).

As the error says, use p4 client to define a new client specification.  If you already have a client for hostname, use p4 set to set P4CLIENT to the name of that client.


问:
Every spawning creep with same role and unable to change
I am very new to this game.
I followed the tutorial and tried to auto-spawn some creeps, but every creep is spawning with the same role and when I change in memory, in the next tick it gets changed back to 'upgrader'.

My main script

var _ = require('lodash');

var roleAttacker = require('role.attacker');
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');

module.exports.loop = function () {

    for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing non-existing creep memory:', name);
        }
    }

    var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
    var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
    var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role = 'upgrader');

    if(harvesters.length > 2) {
        var newName = 'Harvester' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'harvester'}});
    }

    if(upgraders.length < 1 && Game.spawns.Spawn1.energy >= 200 && harvesters.length == 2) {
        var newName = 'Upgrader' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'upgrader'}});
    }

    if(builders.length < 1 && Game.spawns.Spawn1.energy >= 200 && harvesters.length == 2 && upgraders.length == 1) {
        var newName = 'Builder' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'builder'}});
    }

     if(Game.spawns['Spawn1'].spawning) {
        var spawningCreep = Game.creeps[Game.spawns['Spawn1'].spawning.name];
        Game.spawns['Spawn1'].room.visual.text(
            '' + spawningCreep.memory.role,
            Game.spawns['Spawn1'].pos.x + 1,
            Game.spawns['Spawn1'].pos.y,
            {align: 'left', opacity: 0.8});
    }

    var tower = Game.getObjectById('TOWER_ID');
    if(tower) {
        var closestDamagedStructure = tower.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: (structure) => structure.hits < structure.hitsMax
        });
        if(closestDamagedStructure) {
            tower.repair(closestDamagedStructure);
        }

        var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(closestHostile) {
            tower.attack(closestHostile);
        }
    }

    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        switch(creep.memory.role) {
            case 'harvester':
                roleHarvester.run(creep);
                break;
            case 'upgrader':
                roleUpgrader.run(creep);
                break;
            case 'builder':
                roleBuilder.run(creep);
                break;
            case 'attacker':
                roleAttacker.run(creep);
                break;
            default:
                roleHarvester.run(creep);
        }
     }
}
```

<p>I am pasting only the upgrade role, but I can update it with other roles.</p>

<p>role.upgrader.js</p>

<pre class="lang-js prettyprint-override"><code>var roleUpgrader = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if(creep.memory.upgrading && creep.store[RESOURCE_ENERGY] == 0) {
            creep.memory.upgrading = false;
            creep.say(' harvest');
        }
        if(!creep.memory.upgrading && creep.store.getFreeCapacity() == 0) {
            creep.memory.upgrading = true;
            creep.say('⚡ upgrade');
        }

        if(creep.memory.upgrading) {
            if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
            }
        }
        else {
            var sources = creep.room.find(FIND_SOURCES);
            if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}});
            }
        }
    }
};
module.exports = roleUpgrader;
</code>```

Thank you in advance.

答:
I just found the problem, I forgot a = when I'm filtering upgraders:

```<code>var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');
</code>```

Body:
I am very new to this game.
I followed the tutorial and tried to auto-spawn some creeps, but every creep is spawning with the same role and when I change in memory, in the next tick it gets changed back to 'upgrader'.

My main script

var _ = require('lodash');

var roleAttacker = require('role.attacker');
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');

module.exports.loop = function () {

    for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing non-existing creep memory:', name);
        }
    }

    var harvesters = _.filter(Game.creeps, (creep) => creep.memory.role == 'harvester');
    var builders = _.filter(Game.creeps, (creep) => creep.memory.role == 'builder');
    var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role = 'upgrader');

    if(harvesters.length > 2) {
        var newName = 'Harvester' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'harvester'}});
    }

    if(upgraders.length < 1 && Game.spawns.Spawn1.energy >= 200 && harvesters.length == 2) {
        var newName = 'Upgrader' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'upgrader'}});
    }

    if(builders.length < 1 && Game.spawns.Spawn1.energy >= 200 && harvesters.length == 2 && upgraders.length == 1) {
        var newName = 'Builder' + Game.time;
        console.log('Spawning: ' + newName)
        Game.spawns['Spawn1'].spawnCreep([WORK,CARRY,MOVE], newName,
            {memory: {role: 'builder'}});
    }

     if(Game.spawns['Spawn1'].spawning) {
        var spawningCreep = Game.creeps[Game.spawns['Spawn1'].spawning.name];
        Game.spawns['Spawn1'].room.visual.text(
            '' + spawningCreep.memory.role,
            Game.spawns['Spawn1'].pos.x + 1,
            Game.spawns['Spawn1'].pos.y,
            {align: 'left', opacity: 0.8});
    }

    var tower = Game.getObjectById('TOWER_ID');
    if(tower) {
        var closestDamagedStructure = tower.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: (structure) => structure.hits < structure.hitsMax
        });
        if(closestDamagedStructure) {
            tower.repair(closestDamagedStructure);
        }

        var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(closestHostile) {
            tower.attack(closestHostile);
        }
    }

    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        switch(creep.memory.role) {
            case 'harvester':
                roleHarvester.run(creep);
                break;
            case 'upgrader':
                roleUpgrader.run(creep);
                break;
            case 'builder':
                roleBuilder.run(creep);
                break;
            case 'attacker':
                roleAttacker.run(creep);
                break;
            default:
                roleHarvester.run(creep);
        }
     }
}

I am pasting only the upgrade role, but I can update it with other roles.

role.upgrader.js

var roleUpgrader = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if(creep.memory.upgrading && creep.store[RESOURCE_ENERGY] == 0) {
            creep.memory.upgrading = false;
            creep.say(' harvest');
        }
        if(!creep.memory.upgrading && creep.store.getFreeCapacity() == 0) {
            creep.memory.upgrading = true;
            creep.say('⚡ upgrade');
        }

        if(creep.memory.upgrading) {
            if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
            }
        }
        else {
            var sources = creep.room.find(FIND_SOURCES);
            if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}});
            }
        }
    }
};
module.exports = roleUpgrader;

Thank you in advance.

Body:
I just found the problem, I forgot a = when I'm filtering upgraders:

var upgraders = _.filter(Game.creeps, (creep) => creep.memory.role == 'upgrader');


答:
Here is most compact one-line way:

```<code>src = {(11, 12, 13, 14, 15, 16): 'ba', (125, 126, 127, 128): 'pa'}

d_out = {tuple(['Di','D'][i>100]+ str(i) for i in k):v for k,v in src.items()}

print(d_out)

Out[1]:
{('Di11', 'Di12', 'Di13', 'Di14', 'Di15', 'Di16'): 'ba',
 ('D125', 'D126', 'D127', 'D128'): 'pa'}
</code>```

To make it clear

in a case if i less than or equal 100 the
['DI','D'][i>100] gives you ['DI','D'][False] which interpreted as ['DI','D'][0] and return 'DI'

in a case if i great than 100 the
['DI','D'][i>100] gives you ['DI','D'][True] which interpreted as ['DI','D'][1] and return 'D'

Title: How do I add a string to each key of a dictionary?

Body:
I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

def dict_change(dicto):
    for key,value in dicto.items():
        for numb in value:
            if numb >= 100:
                numb = 'D' + str(numb)
            else:
                numb = 'DI' + str(numb)
    return dicto

new_dict = dict_change(old_dict)

Thank you! :)

Body:
Here is most compact one-line way:

src = {(11, 12, 13, 14, 15, 16): 'ba', (125, 126, 127, 128): 'pa'}

d_out = {tuple(['Di','D'][i>100]+ str(i) for i in k):v for k,v in src.items()}

print(d_out)

Out[1]:
{('Di11', 'Di12', 'Di13', 'Di14', 'Di15', 'Di16'): 'ba',
 ('D125', 'D126', 'D127', 'D128'): 'pa'}

To make it clear

in a case if i less than or equal 100 the
['DI','D'][i>100] gives you ['DI','D'][False] which interpreted as ['DI','D'][0] and return 'DI'

in a case if i great than 100 the
['DI','D'][i>100] gives you ['DI','D'][True] which interpreted as ['DI','D'][1] and return 'D'


问:
Posting memory utilization metrics of aws instance by using nodeJs
I want to get Memory utilization metrics' data of aws instance on my project using nodeJs but i found out that memory Utilization metrics is not a default metrics so i have tried what's given on this page - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html and it worked as shown in figure memory Utilization metrics but i want to know how to post this metric using nodeJs.

This is the params i have written while using putMetricData -

```<code>AWS.config.update({ region: 'ap-south-1' });
var instanceId = 'i-096d2fed45f9ee1'
var params = {
    MetricData: [ /* required */
      {
        MetricName: 'MemoryUtilization', /* required */
        // Counts: [
        //   'NUMBER_VALUE',
        //   /* more items */
        // ],
        Dimensions: [
          {
            Name: 'InstanceId', /* required */
            Value: instanceId /* required */
          },
          /* more items */
        ],
        StatisticValues: {
          Maximum: 100, /* required */
          Minimum: 5, /* required */
          SampleCount: 1, /* required */
          Sum: 5 /* required */
        },
        // Timestamp: new Date || 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)' || 123456789,
        // Unit: Percent,
        // Value: 'NUMBER_VALUE',
        // Values: [
        //   'NUMBER_VALUE',
        //   /* more items */
        // ]
      },
      /* more items */
    ],
    Namespace: 'System/Linux' /* required */
};
cw.putMetricData(params, function(err, data) {
        if (err) {
          console.log("Error", err);
        } else {
          console.log("Metrics", JSON.stringify(data));
        }
});
</code>```

I didn't get any error but value of memory utilization are coming like this as shown in image - memory Util metrics after posting through putMetricsData which is not correct if you see memory Utilization metrics generated by CloudWatch monitoring scripts.

答:
Using the CloudWatch NodeJS SDK and calling the PutMetricData API.

This article might help you get the metrics you want in NodeJS.

However, I don't understand why you would want to do this. I would suggest instead configuring the CloudWatch Agent to collect these metrics independently of any application code.

EDIT BASED ON UPDATED QUESTION:

You are hard coding StatisticValues. Based on the screenshot it looks like you are graphing either Sum or Minimum which you have hard coded to 5. How do you expect CloudWatch to show anything different to what you send it?

If you want to publish memory data, you need to get memory data using NodeJS by making some API/Library call e.g. What I linked above. You then pass this value to the CloudWatch PutMetricData call...

The CloudWatch client can't magically know that because you set MetricName=MemoryUtilization that you want NodeJS to publish memory metrics. MetricName is just a label, it can be absolutely anything you want e.g. HowManyBeersIHadLastNight, HowLongThatPieceOfCodeTookToExecute

Also, on another note, using StatisicValues, i.e. a StatisticSet is a legacy and not recommended use of the CloudWatch APIs. Publishing your metrics like this prevents CloudWatch from being able to calculate rich percentiles. Either use Value or Values & Counts instead.

Body:
I want to get Memory utilization metrics' data of aws instance on my project using nodeJs but i found out that memory Utilization metrics is not a default metrics so i have tried what's given on this page - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html and it worked as shown in figure memory Utilization metrics but i want to know how to post this metric using nodeJs.

This is the params i have written while using putMetricData -

AWS.config.update({ region: 'ap-south-1' });
var instanceId = 'i-096d2fed45f9ee1'
var params = {
    MetricData: [ /* required */
      {
        MetricName: 'MemoryUtilization', /* required */
        // Counts: [
        //   'NUMBER_VALUE',
        //   /* more items */
        // ],
        Dimensions: [
          {
            Name: 'InstanceId', /* required */
            Value: instanceId /* required */
          },
          /* more items */
        ],
        StatisticValues: {
          Maximum: 100, /* required */
          Minimum: 5, /* required */
          SampleCount: 1, /* required */
          Sum: 5 /* required */
        },
        // Timestamp: new Date || 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)' || 123456789,
        // Unit: Percent,
        // Value: 'NUMBER_VALUE',
        // Values: [
        //   'NUMBER_VALUE',
        //   /* more items */
        // ]
      },
      /* more items */
    ],
    Namespace: 'System/Linux' /* required */
};
cw.putMetricData(params, function(err, data) {
        if (err) {
          console.log("Error", err);
        } else {
          console.log("Metrics", JSON.stringify(data));
        }
});

I didn't get any error but value of memory utilization are coming like this as shown in image - memory Util metrics after posting through putMetricsData which is not correct if you see memory Utilization metrics generated by CloudWatch monitoring scripts.


问:
Using body in GET requests
Why are url query strings is superior to the values in the body?

There are some obvious differences between the two ways to request data - like being able to see the parameters in the url, or the fact that the requests can be saved in the brower's history.

But is there anything more to it?
Is it bad to request data with body?

答:
Is it bad to request data with body?

Yes, it is bad.

The problem is that, in HTTP, GET method is specifically defined to not to include a request body.

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request. -- RFC 7231

What's going on here, largely, is that early versions of the HTTP specification had some ambiguities about the handling of message-bodies in requests.  In effect, putting a message-body into a GET request was "undefined behavior".

The working group is strongly motivated to ensure that the standard remains backwards compatible.

Part of the point of REST is that we are all using a common standard, so that the general purpose tools (browsers, caches, reverse proxies, spiders...) work for everybody -- or more specifically for everybody that abides by the standard.

With regards to GET, including a message body doesn't make sense when you consider caching semantics.  Caching semantics in HTTP are currently defined by RFC 7134, the high level summary is that the target-uri is the primary cache key; caches only need to understand the metadata in the HTTP request to do their job properly.

If we were to apply semantics to the body of a GET request, we'd also need to define, in a general way, how those semantics affect cache behavior.

For instance, if you imagine a query scenario (like GraphQL), the expected representations in the response depend on the information encoded into the request body.  So now you need to start defining when two request bodies are "the same" - is white space significant? does the content encoding matter?  what about if the body is zipped? and so on....

We don't have this kind of problem with unsafe requests (for example, POST), because standards compliant caches MUST write through requests that are unsafe.  There's no need to explore the representation of the message-body of the request because there are no circumstances where the contents would change this requirement.

There have been attempts at creating a new standard for the HTTP method that is safe and includes a message body.  It's probably doable; in the sense that we introduce a new method token, and declare the semantics to be safe (so that we can perform preemptive fetching, and repeat requests on an unreliable network) and perhaps that public caches cannot store the responses, but must instead forward each request to the origin server.

That said, people have been aware of the gap for a while, and the problem doesn't yet have a standardized solution - so there may be some difficult aspect to it that isn't obvious (in addition to the political problems of adoption vs inertia).

Title: Using body in GET requests


问:
Why does iAd still load data after it has been removed from it's superview, and can this be stopped?
I have a small app with iAds, and allow people to pay to upgrade.

The iAd is setup in the application's NIB.  I check the purchase status in the viewDidLoad method of the main UIViewController, and call the following methods on the ADBannerView outlet member:

```<code>[adBanner removeFromSuperview];
adBanner = nil;
</code>```

Unfortunately if I watch the device's data usage, some data is still downloaded for the Ad.

Is there any way to properly kill the iAd so it doesn't load any data?

I know I could create the iAd view programatically and then add it only if the user has not purchased the product, but my product is working nicely from the NIB and I'd rather not change it for this reason.

UPDATE:

In my .h file I have:

```<code>IBOutlet ADBannerView* adBanner;
</code>```

In the .m file in - (void)viewDidLoad method I have:

```<code>if (purchased) {
    [adBanner removeFromSuperview];
    adBanner.delegate = nil;
    adBanner = nil;
}
</code>```

I would hope this would be enough to remove the iAd before it gets a chance to download any data.

Alas, this isn't enough to prevent the view from downloading data. I suspect there is a delay in it being fully dealloc'd at that time – but I don't know how to do this, short of calling dealloc itself.

Does anyone know of a better/correct way to completely destroy an object loaded via the XIB and assigned to an IBOutlet?

答:
I think you'll have to use a second nib, without the iAd banner. The nib loading process will instantiate all elements of the nib before passing control back to your objects.  That's why you can't stop the iAd from trying to load an ad.

First, duplicate the current nib, and just delete the iAd banner view. Then override the view controller's initWithNibName:bundle: method to check for paid status. If paid, change the nib name to the non iAd nib, and call the superclass's method with the other nib.

Body:
I have a small app with iAds, and allow people to pay to upgrade.

The iAd is setup in the application's NIB.  I check the purchase status in the viewDidLoad method of the main UIViewController, and call the following methods on the ADBannerView outlet member:

[adBanner removeFromSuperview];
adBanner = nil;

Unfortunately if I watch the device's data usage, some data is still downloaded for the Ad.

Is there any way to properly kill the iAd so it doesn't load any data?

I know I could create the iAd view programatically and then add it only if the user has not purchased the product, but my product is working nicely from the NIB and I'd rather not change it for this reason.

UPDATE:

In my .h file I have:

IBOutlet ADBannerView* adBanner;

In the .m file in - (void)viewDidLoad method I have:

if (purchased) {
    [adBanner removeFromSuperview];
    adBanner.delegate = nil;
    adBanner = nil;
}

I would hope this would be enough to remove the iAd before it gets a chance to download any data.

Alas, this isn't enough to prevent the view from downloading data. I suspect there is a delay in it being fully dealloc'd at that time – but I don't know how to do this, short of calling dealloc itself.

Does anyone know of a better/correct way to completely destroy an object loaded via the XIB and assigned to an IBOutlet?


问:
Powershell returning System.Object[] instead of information due to multiple results
Ive a script that emails information of login to us.

I am calling username like this :
$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User

The reason i am doing this as someone helped me to avoid the username from task manager and call the real users that are logged in instead of the account the task is running under.

The issue I am having is as there are multiple users logged in I am getting System.Object[] returned to me instead of the actually results.

Here is an example of my code :

```<code>$IP = Get-NetTCPConnection -state ESTABLISHED -Localport 3389 | Select -ExpandProperty RemoteAddress
$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User
</code>```

Then I just call these in my body as so :

```<code>$message = "`nUsername :",$username ,....etc
$body = $message
</code>```

Would anyone know why this would be returning System.Object[]?

Thank you.

答:
The powershell syntax "abc","def" is the same as @("abc","def") both of which returns a string array.

You could use one of these syntaxes instead:

```<code>$message = "`nUsername : $username"
$message = "`nUsername : " + $username
</code>```

In case you get several user names (maybe "$usernames" would be more suitable), just use something like

```<code>$message = "`nUsernames : " + $usernames -join ", "
</code>```

In case you don't know if you get 1 or more usernames, you might want to use this instead:

```<code>$username = @(Get-WmiObject [...] -Expand User)
</code>```

Body:
Ive a script that emails information of login to us.

I am calling username like this :
$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User

The reason i am doing this as someone helped me to avoid the username from task manager and call the real users that are logged in instead of the account the task is running under.

The issue I am having is as there are multiple users logged in I am getting System.Object[] returned to me instead of the actually results.

Here is an example of my code :

$IP = Get-NetTCPConnection -state ESTABLISHED -Localport 3389 | Select -ExpandProperty RemoteAddress
$username = Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | ForEach-Object { $_.GetOwner() } | Select-Object -Unique -Expand User

Then I just call these in my body as so :

$message = "`nUsername :",$username ,....etc
$body = $message

Would anyone know why this would be returning System.Object[]?

Thank you.

Body:
The powershell syntax "abc","def" is the same as @("abc","def") both of which returns a string array.

You could use one of these syntaxes instead:

$message = "`nUsername : $username"
$message = "`nUsername : " + $username

In case you get several user names (maybe "$usernames" would be more suitable), just use something like

$message = "`nUsernames : " + $usernames -join ", "

In case you don't know if you get 1 or more usernames, you might want to use this instead:

$username = @(Get-WmiObject [...] -Expand User)