问:
MYSQL: select latest record only (on left join table)
I have 2 tables:

Table1:

```<code>ID | Mobile Number | Name | Ordered Product| Order Date
</code>```

Table2:

```<code>ID(foreign_key can be inserted multipletimes in this table) |Contacted_for | Time(timestamp)
</code>```

I need a query to display all the data in Table1 and if the ID is present in Table 2, I need to display the last inserted record on Table2(with time) of that ID

My query is

```<code>select a.* , b.* FROM table1 a LEFT JOIN table2 b ON a.ID=b.ID GROUP BY a.ID ORDER BY b.Time DESC
</code>```

Here in my query when I remove Group By a.ID, it works but shows all results. But I want to show final record of table2 only(no duplicate ID records)

Thanks in advance

答:
You can also try this way.</p>

```<code>Select * from table1 a left join
(Select * from table2 where id in (select max(id) from table2 group by id) ) b on a.id=b.id
</code>```

Body:
I have 2 tables:

Table1:

ID | Mobile Number | Name | Ordered Product| Order Date

Table2:

ID(foreign_key can be inserted multipletimes in this table) |Contacted_for | Time(timestamp)

I need a query to display all the data in Table1 and if the ID is present in Table 2, I need to display the last inserted record on Table2(with time) of that ID

My query is

select a.* , b.* FROM table1 a LEFT JOIN table2 b ON a.ID=b.ID GROUP BY a.ID ORDER BY b.Time DESC

Here in my query when I remove Group By a.ID, it works but shows all results. But I want to show final record of table2 only(no duplicate ID records)

Thanks in advance

Body:
You can also try this way.

Select * from table1 a left join
(Select * from table2 where id in (select max(id) from table2 group by id) ) b on a.id=b.id


来源: stackexchange

问:
How would I remove words from dictionary key lists that contain 6 or more letters?
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

```<code>def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict
</code>```

```<code>words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }
</code>```

Should print:

```<code>1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']
</code>```

答:
Maybe not the cleanest way, this is not an effective way to do it, but it is readable and I wrote it this way so you can see the logic for it to work </p>

```<code> In [23]: def remove_word(my_dict):
    ...:     for key in my_dict:
    ...:         to_delete = []
    ...:         for values in my_dict[key]:
    ...:             if len(values) < 6:
    ...:                 to_delete.append(values)
    ...:         for word in to_delete:
    ...:             my_dict[key].remove(word)
    ...:     return my_dict
    ...:
    ...:
</code>```

<p>It will give you the desired output </p>

```<code>In [26]: remove_word(words_dict)
Out[26]:
{'colours': [],
 'places': ['america', 'malaysia', 'argentina'],
 'animals': ['monkey']}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict

words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }

Should print:

1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']

Body:
Maybe not the cleanest way, this is not an effective way to do it, but it is readable and I wrote it this way so you can see the logic for it to work

 In [23]: def remove_word(my_dict):
    ...:     for key in my_dict:
    ...:         to_delete = []
    ...:         for values in my_dict[key]:
    ...:             if len(values) < 6:
    ...:                 to_delete.append(values)
    ...:         for word in to_delete:
    ...:             my_dict[key].remove(word)
    ...:     return my_dict
    ...:
    ...:

It will give you the desired output

In [26]: remove_word(words_dict)
Out[26]:
{'colours': [],
 'places': ['america', 'malaysia', 'argentina'],
 'animals': ['monkey']}


问:
zeppelin_ipyspark.py at apache zeppelin get SyntaxError: invalid syntax
when i running code with pyspark in apache zeppelin 0.8.1 , i get error like

```<code>java.lang.NullPointerException
    at org.apache.thrift.transport.TSocket.open(TSocket.java:170)
    at org.apache.zeppelin.interpreter.remote.ClientFactory.create(ClientFactory.java:51)
</code>```

...

so i open all file in my folder zeppelin

and i try to running file zeppelin_ipyspark.py at D:\zeppelin-0.8.1-bin-all\interpreter\spark\python with cmd

and i get error

```<code>D:\zeppelin-0.8.1-bin-all\interpreter\spark\python>zeppelin_ipyspark.py
  File "D:\zeppelin-0.8.1-bin-all\interpreter\spark\python\zeppelin_ipyspark.py", line 29
    port=${JVM_GATEWAY_PORT}, auth_token=gateway_secret, auto_convert=True))
         ^
SyntaxError: invalid syntax
</code>```

so can you help me?

答:
@LSS zeppelin_ipyspark.py is not a standalone script.

It is invoked internally from Zeppelin's java code as part of Ipython interpreter, where the python script is processed to replace these strings(like JVM_GATEWAY_PORT etc) with actual values.

You can check the code references: 1, 2

Body:
when i running code with pyspark in apache zeppelin 0.8.1 , i get error like

java.lang.NullPointerException
    at org.apache.thrift.transport.TSocket.open(TSocket.java:170)
    at org.apache.zeppelin.interpreter.remote.ClientFactory.create(ClientFactory.java:51)

...

so i open all file in my folder zeppelin

and i try to running file zeppelin_ipyspark.py at D:\zeppelin-0.8.1-bin-all\interpreter\spark\python with cmd

and i get error

D:\zeppelin-0.8.1-bin-all\interpreter\spark\python>zeppelin_ipyspark.py
  File "D:\zeppelin-0.8.1-bin-all\interpreter\spark\python\zeppelin_ipyspark.py", line 29
    port=${JVM_GATEWAY_PORT}, auth_token=gateway_secret, auto_convert=True))
         ^
SyntaxError: invalid syntax

so can you help me?


问:
How do i remove the header in the curl request
I am using curl API for secured SSL connection.
My command line request to the server through curl in linux machine:

```<code>curl -k https://<ip>:<port> -H "User-agent:" -H "Host:" -H "Accept:" -X <request> -o ssl.txt
</code>```

Myrequest is going like this

GET
  /005F02007024058020C0100416476173900101001000000000000000010000000210120021001200344761739001010010D10122011138780893132333435363738313132323333343435353636373738C2115B54A8F08C150006303030303031
  HTTP/1.1

How do i remove this GET and HTTP/1.1 through command prompt? Please suggest me the Curl API to remopve this HTTP/1.1

答:
You should try to set CURLOPT_HEADER to 0.

If you set the CURLOPT_HEADER to 1,
  you will tell libcurl to get
  information about the target file and
  output "headers" about it. The headers
  will be in "HTTP-style", looking like
  they do in HTTP.

ContentLicense: CC BY-SA 3.0

Body:
I am using curl API for secured SSL connection.
My command line request to the server through curl in linux machine:

curl -k https://<ip>:<port> -H "User-agent:" -H "Host:" -H "Accept:" -X <request> -o ssl.txt

Myrequest is going like this

GET
  /005F02007024058020C0100416476173900101001000000000000000010000000210120021001200344761739001010010D10122011138780893132333435363738313132323333343435353636373738C2115B54A8F08C150006303030303031
  HTTP/1.1

How do i remove this GET and HTTP/1.1 through command prompt? Please suggest me the Curl API to remopve this HTTP/1.1


问:
Unable to parse valid json file

Logic

I've a JSON file as follows:

```<code>[
    {
        "title":"Article Title 1",
        "url":"https://mywebsite.com/articles/article1.html",
        "type":"codes"
    },
    {
        "title":"Article Title 2",
        "url":"https://mywebsite.com/articles/article2.html",
        "type":"games"
    },
    {
        "title":"Article Title 3",
        "url":"https://mywebsite.com/articles/article3.html",
        "type":"codes"
    }
]
</code>```

And I'm reading this file, then populating my html page for each item in the file (so there are 3 titles, means 3 containers on my page).

Problem

There was no error before, but now I get an error in console: *SyntaxError: JSON.parse: expected ',' or ']' after array element at line 12 column 2 of the JSON data*

BUT, it all works if there are only 2 articles! After adding the third dataset, there is error. The file format seems correct, there is "," at the right places, I converted it in different encodings but same error.

Code

Main Request:

I'm requesting JSON file on document load like this:

```<code>$(document).ready(function(){
    var reqdata = new XMLHttpRequest();
    reqdata.open('GET', "https://website.com/dat/data.json");
    reqdata.onload = function() {
        if (reqdata.status >= 200 && reqdata.status < 400) {
            try{
                var postData = JSON.parse(reqdata.responseText);
                render_posts(postData); // this creates dynamic content in html
                //console.log(postData);
            } catch (err) {
                alert(" JSON Parse Error :'( ")
            }
        } else { alert("JSON Requestion Server Error!") }
    }; reqdata.onerror = function() { alert("JSON Request Connection Error!") };
    reqdata.send();
});
</code>```

Populating HTML:

This is called from the code above if JSON.parse is working. This part works fine, just for reference..

```<code>function render_posts(data) {
    var htmldata = ""; var cardId = "";
    for (var x = 0; x < data.length; x++) {
        cardId = "card-type-" + data[x].type;
        htmldata += "<div class='card' id='" + cardId + "' onclick='card_clicker(\"" + data[x].url + "\")'><div class='header'>" + data[x].title + "</div><div class='decor'></div></div>";
    }
    cardWrapper.insertAdjacentHTML('beforeend', htmldata);
}
</code>```

Help: Any help is appreciated.. Can't figure out what's the real problem. The JSON file looks fine. I tried formatting it online, but same results. I'm quite new to AJAX. Tried other solutions on stackoverflow but still the same..

答:
It's a small url decoding problem with JSON decode. Instead of adding the url like:

```<code>"url":"https://mywebsite.com/articles/article2.html"
</code>```

It has to be given escape character backslash like this:

```<code>"url":"https:\/\/mywebsite.com\/articles\/article2.html"
</code>```

And now everything is working fine!

Title: Unable to parse valid json file

Body:
Logic

I've a JSON file as follows:

[
    {
        "title":"Article Title 1",
        "url":"https://mywebsite.com/articles/article1.html",
        "type":"codes"
    },
    {
        "title":"Article Title 2",
        "url":"https://mywebsite.com/articles/article2.html",
        "type":"games"
    },
    {
        "title":"Article Title 3",
        "url":"https://mywebsite.com/articles/article3.html",
        "type":"codes"
    }
]

And I'm reading this file, then populating my html page for each item in the file (so there are 3 titles, means 3 containers on my page).

Problem

There was no error before, but now I get an error in console: *SyntaxError: JSON.parse: expected ',' or ']' after array element at line 12 column 2 of the JSON data*

BUT, it all works if there are only 2 articles! After adding the third dataset, there is error. The file format seems correct, there is "," at the right places, I converted it in different encodings but same error.

Code

Main Request:

I'm requesting JSON file on document load like this:

$(document).ready(function(){
    var reqdata = new XMLHttpRequest();
    reqdata.open('GET', "https://website.com/dat/data.json");
    reqdata.onload = function() {
        if (reqdata.status >= 200 && reqdata.status < 400) {
            try{
                var postData = JSON.parse(reqdata.responseText);
                render_posts(postData); // this creates dynamic content in html
                //console.log(postData);
            } catch (err) {
                alert(" JSON Parse Error :'( ")
            }
        } else { alert("JSON Requestion Server Error!") }
    }; reqdata.onerror = function() { alert("JSON Request Connection Error!") };
    reqdata.send();
});

Populating HTML:

This is called from the code above if JSON.parse is working. This part works fine, just for reference..

function render_posts(data) {
    var htmldata = ""; var cardId = "";
    for (var x = 0; x < data.length; x++) {
        cardId = "card-type-" + data[x].type;
        htmldata += "

" + data[x].title + "

";
    }
    cardWrapper.insertAdjacentHTML('beforeend', htmldata);
}

Help: Any help is appreciated.. Can't figure out what's the real problem. The JSON file looks fine. I tried formatting it online, but same results. I'm quite new to AJAX. Tried other solutions on stackoverflow but still the same..

Body:
It's a small url decoding problem with JSON decode. Instead of adding the url like:

"url":"https://mywebsite.com/articles/article2.html"

It has to be given escape character backslash like this:

"url":"https:\/\/mywebsite.com\/articles\/article2.html"

And now everything is working fine!


问:
Convert single line RSA private ssh key to multi line
I have these private keys that have been converted to single line equivalent.

These keys are quite a lot.

So I decided to invest some time to write a script to convert.

This has not yielded to much.

```<code>-----BEGIN RSA PRIVATE KEY----pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= -----END RSA PRIVATE KEY-----
</code>```

I am using echo ~/.ssh/id_rsa | tr " " "\n"

This returns:

```<code>-----BEGIN
RSA
PRIVATE
KEY-----
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
-----END
RSA
PRIVATE
KEY-----

</code>```

I have been trying to figure out the best possible way to get this back to the right format.

答:
Assuming a standard RSA private key that just had the newlines removed, a couple of sed replacements will get you back to the original format:

```<code>sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/"\
    -e "s/-----END RSA PRIVATE KEY-----/\n&/"\
    -e "s/\S\{64\}/&\n/g"\
    ~/.ssh/id_rsa
</code>```

The standard key format requires the BEGIN and END statements to be on a separate line, and the base64-encoded key to be formatted at 64 columns. The above command will get you there.

Body:
I have these private keys that have been converted to single line equivalent.

These keys are quite a lot.

So I decided to invest some time to write a script to convert.

This has not yielded to much.

-----BEGIN RSA PRIVATE KEY----pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= -----END RSA PRIVATE KEY-----

I am using echo ~/.ssh/id_rsa | tr " " "\n"

This returns:

-----BEGIN
RSA
PRIVATE
KEY-----
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
-----END
RSA
PRIVATE
KEY-----

I have been trying to figure out the best possible way to get this back to the right format.

Body:
Assuming a standard RSA private key that just had the newlines removed, a couple of sed replacements will get you back to the original format:

sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/"\
    -e "s/-----END RSA PRIVATE KEY-----/\n&/"\
    -e "s/\S\{64\}/&\n/g"\
    ~/.ssh/id_rsa

The standard key format requires the BEGIN and END statements to be on a separate line, and the base64-encoded key to be formatted at 64 columns. The above command will get you there.


问:
Elegant way to toggle back and force multiple css elements
I have 2 buttons with ids "videos-button" and "photos-button". On click of each button, I need to perform a set of action to changes css or remove/add class for certain HTML elements. Basically, for each of the element, I need to toggle their initial state back and force. See code for details:

```<code>$('#videos-button').on('click',function(){
            $("#ib-row").css({'display':'none'});
            $("#ib-pagination").css({'display':'none'});
            $("#ib-video-carousel-pagination").css({'display':'block'});
            $("#ib-video-carousel").css({'display':'block'});
            $("#photos-button").removeClass('image-block-media-button-selected');
            $("#videos-button").addClass('image-block-media-button-selected');
});

$('#photos-button').on('click',function(){
            $("#ib-row").css({'display':'block'});
            $("#ib-pagination").css({'display':'block'});
            $("#ib-video-carousel-pagination").css({'display':'none'});
            $("#ib-video-carousel").css({'display':'none'});
            $("#videos-button").removeClass('image-block-media-button-selected');
            $("#photos-button").addClass('image-block-media-button-selected');
        });
</code>```

How can I refactor it in more elegant way, without duplication?

答:
one way to refactor would be, create a function which takes videos-button or photos-button as input and returns a object(map) of ids and corresponding classes. i.e function(lets call it getClassMap) returning

```<code>{ '#id-row' : 'display: none', ... }
</code>```

when i/p is videos-button and

```<code>{ '#id-row' : 'display: block', ... }
</code>```

when i/p is photos-button.
Then move the logic of applying classes i.e

```<code>function applyStyles(id) {
    const styleIdMap = getClassMap(id);
    $("#ib-row").css(styleIdMap["#ib-row"]);
    $("#ib-pagination").css(styleIdMap["#ib-pagination"]);
    ...
}
</code>```

this way there is no repition in logic.

Body:
I have 2 buttons with ids "videos-button" and "photos-button". On click of each button, I need to perform a set of action to changes css or remove/add class for certain HTML elements. Basically, for each of the element, I need to toggle their initial state back and force. See code for details:

$('#videos-button').on('click',function(){
            $("#ib-row").css({'display':'none'});
            $("#ib-pagination").css({'display':'none'});
            $("#ib-video-carousel-pagination").css({'display':'block'});
            $("#ib-video-carousel").css({'display':'block'});
            $("#photos-button").removeClass('image-block-media-button-selected');
            $("#videos-button").addClass('image-block-media-button-selected');
});

$('#photos-button').on('click',function(){
            $("#ib-row").css({'display':'block'});
            $("#ib-pagination").css({'display':'block'});
            $("#ib-video-carousel-pagination").css({'display':'none'});
            $("#ib-video-carousel").css({'display':'none'});
            $("#videos-button").removeClass('image-block-media-button-selected');
            $("#photos-button").addClass('image-block-media-button-selected');
        });

How can I refactor it in more elegant way, without duplication?

Body:
one way to refactor would be, create a function which takes videos-button or photos-button as input and returns a object(map) of ids and corresponding classes. i.e function(lets call it getClassMap) returning

{ '#id-row' : 'display: none', ... }

when i/p is videos-button and

{ '#id-row' : 'display: block', ... }

when i/p is photos-button.
Then move the logic of applying classes i.e

function applyStyles(id) {
    const styleIdMap = getClassMap(id);
    $("#ib-row").css(styleIdMap["#ib-row"]);
    $("#ib-pagination").css(styleIdMap["#ib-pagination"]);
    ...
}

this way there is no repition in logic.


问:
Gradle 3.4.1 not able to parse the response into Object with Proguard
I just updated my Gradle to 3.4.1.
I am having an API call inside one of my module.
I am using the module inside the app :

```<code>implementation com.mindvalley.module_login:Module_Login:$rootConfiguration.loginLibraryVersion
</code>```

Now when I generate a signed build with ProGuard, the object is null, meaning retrofit is not able to parse the object.

P.S. : This works fine with debug mode or if I run the app with Gradle version 3.3.2

My Retrofit Proguard file :

```<code>-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}

-keepattributes Signature, InnerClasses, EnclosingMethod

-keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations
-keepclassmembers,allowshrinking,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}

-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-dontwarn javax.annotation.**

-dontwarn kotlin.Unit

-dontwarn retrofit2.KotlinExtensions

-if interface * { @retrofit2.http.* <methods>; }
-keep,allowobfuscation interface <1>

-dontwarn org.codehaus.mojo.**
-keepattributes *Annotation*

-keepattributes RuntimeVisibleAnnotations
-keepattributes RuntimeInvisibleAnnotations
-keepattributes RuntimeVisibleParameterAnnotations
-keepattributes RuntimeInvisibleParameterAnnotations

-keepattributes EnclosingMethod

-keepclasseswithmembers class * {
    @retrofit2.* <methods>;
}

-keepclasseswithmembers interface * {
    @retrofit2.* <methods>;
}
</code>```

My OkHttp proguard file :

```<code>-keepattributes Signature
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**

-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

-dontwarn org.codehaus.mojo.animal_sniffer.*

-dontwarn okhttp3.internal.platform.ConscryptPlatform

-dontwarn org.codehaus.mojo.animal_sniffer.*
</code>```

My GSON proguard file :

```<code>-keepattributes Signature
-keepattributes EnclosingMethod

-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
-dontwarn com.google.gson.internal.UnsafeAllocator

-keepattributes Signature

-keepattributes *Annotation*

-dontwarn sun.misc.**
-keep class com.google.gson.examples.android.model.** { <fields>; }

-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}
</code>```

答:
P.S. : This works fine with debug mode or if I run the app with Gradle version 3.3.2

Since, Gradle Plugin version 3.4.0, D8/R8 is enabled by default and obfuscation will be done by R8 instead of ProGuard.

See Stick to ProGuard Obfuscation for how to stick with Proguard.

See Android/java: Transition / Migration from ProGuard to R8?
  for how to migrate to R8.

Body:
I just updated my Gradle to 3.4.1.
I am having an API call inside one of my module.
I am using the module inside the app :

implementation com.mindvalley.module_login:Module_Login:$rootConfiguration.loginLibraryVersion

Now when I generate a signed build with ProGuard, the object is null, meaning retrofit is not able to parse the object.

P.S. : This works fine with debug mode or if I run the app with Gradle version 3.3.2

My Retrofit Proguard file :

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}

-keepattributes Signature, InnerClasses, EnclosingMethod

-keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations
-keepclassmembers,allowshrinking,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}

-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-dontwarn javax.annotation.**

-dontwarn kotlin.Unit

-dontwarn retrofit2.KotlinExtensions

-if interface * { @retrofit2.http.* <methods>; }
-keep,allowobfuscation interface <1>

-dontwarn org.codehaus.mojo.**
-keepattributes *Annotation*

-keepattributes RuntimeVisibleAnnotations
-keepattributes RuntimeInvisibleAnnotations
-keepattributes RuntimeVisibleParameterAnnotations
-keepattributes RuntimeInvisibleParameterAnnotations

-keepattributes EnclosingMethod

-keepclasseswithmembers class * {
    @retrofit2.* <methods>;
}

-keepclasseswithmembers interface * {
    @retrofit2.* <methods>;
}

My OkHttp proguard file :

-keepattributes Signature
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**

-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

-dontwarn org.codehaus.mojo.animal_sniffer.*

-dontwarn okhttp3.internal.platform.ConscryptPlatform

-dontwarn org.codehaus.mojo.animal_sniffer.*

My GSON proguard file :

-keepattributes Signature
-keepattributes EnclosingMethod

-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
-dontwarn com.google.gson.internal.UnsafeAllocator

-keepattributes Signature

-keepattributes *Annotation*

-dontwarn sun.misc.**
-keep class com.google.gson.examples.android.model.** { <fields>; }

-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}


问:
Any way that we can prevent the breakdown between reference and object when resize a vector?
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

```<code>#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}
</code>```

答:
There are several choices:

Don't use a vector.

Don't keep a reference.

Create a "smart reference" class that tracks the vector and the index and so it will obtain the appropriate object even if the vector moves.

Body:
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}


问:
Remove auto generate button in Humberger menu of Xamarin.Forms Shell using Shell.FlyoutHeader
I have started learning Xamarin Forms Shell. I've create my first app using Shell and add sample Home Page. In my AppShell Page I've add  and Shell.FlyoutHeader contains only boxview. When I run the application and click the Humberger Menu, there is additional button or Label(I'm not sure) that I didn't include in my FlyoutHeader Page. Please help me to remove that additional button. Thanks!

Shell Code:

```<code><Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamShell.Views.ListOfProductsPage"
             Visual="Material"
             xmlns:local="clr-namespace:XamShell.Views"
             FlyoutBehavior="Flyout"
             xmlns:controls="clr-namespace:XamShell.Controls"
             Routing.Route="ProductList">

    <Shell.FlyoutHeader>
        <controls:FlyoutHeader/>
    </Shell.FlyoutHeader>

    <local:HomePage />
</Shell>

FlyoutHeader
<Grid BackgroundColor="White">
        <BoxView
               BackgroundColor="Yellow"
               Opacity="0.6" />
        <Label Text="Animals"
               TextColor="Red"
               FontAttributes="Bold"
               HorizontalTextAlignment="Center"
               VerticalTextAlignment="Center" />
    </Grid>
</code>```

enter image description here

答:
Do you want to achieve the result like following GIF.

If so, First of all, Please refer to this screenshot.

Please If you want to remove these button, please make sure your AppShell.xaml AppShell.xaml.cs file did not include the FlyoutItem and <views:XXXPage IconImageSource="XXX.png" /><views:XXX IconImageSource="XXXX.png" /> like this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/flyout#flyout-items

But I suggest you to create a new project.

Create a new shell file like following code.

MainPage.xaml

```<code>  <?xml version="1.0" encoding="utf-8" ?>
  <Shell xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:SearchListDemo"
         xmlns:controls="clr-namespace:SearchListDemo.Controls"

   Navigating="OnNavigating"
   Navigated="OnNavigated"
   x:Class="SearchListDemo.MainPage">

<Shell.FlyoutHeader>
    <controls:FlyoutHeader/>
</Shell.FlyoutHeader>

<local:HomePage/>

</Shell>
</code>```

MainPage.xaml.cs

```<code>     [DesignTimeVisible(true)]
public partial class MainPage : Shell
{
    public Dictionary<string, Type> Routes { get { return routes; } }
    Dictionary<string, Type> routes = new Dictionary<string, Type>();
    public MainPage()
    {
       InitializeComponent();

        RegisterRoutes();

    }

    void RegisterRoutes()
    {
        routes.Add("homwpage", typeof(HomePage));

        foreach (var item in routes)
        {
            Routing.RegisterRoute(item.Key, item.Value);
        }
    }
    void OnNavigating(object sender, ShellNavigatingEventArgs e)
    {

    }

    void OnNavigated(object sender, ShellNavigatedEventArgs e)
    {
    }

}
</code>```

regist SetFlag before Xamarin.Forms.Forms.Init(e) in the MainActivity.cs

Xamarin.Forms.Forms.SetFlags("Shell_Experimental");

Body:
I have started learning Xamarin Forms Shell. I've create my first app using Shell and add sample Home Page. In my AppShell Page I've add  and Shell.FlyoutHeader contains only boxview. When I run the application and click the Humberger Menu, there is additional button or Label(I'm not sure) that I didn't include in my FlyoutHeader Page. Please help me to remove that additional button. Thanks!

Shell Code:

<Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamShell.Views.ListOfProductsPage"
             Visual="Material"
             xmlns:local="clr-namespace:XamShell.Views"
             FlyoutBehavior="Flyout"
             xmlns:controls="clr-namespace:XamShell.Controls"
             Routing.Route="ProductList">

    <Shell.FlyoutHeader>
        <controls:FlyoutHeader/>
    </Shell.FlyoutHeader>

    <local:HomePage />
</Shell>

FlyoutHeader
<Grid BackgroundColor="White">
        <BoxView
               BackgroundColor="Yellow"
               Opacity="0.6" />

    </Grid>

enter image description here

Body:
Do you want to achieve the result like following GIF.

If so, First of all, Please refer to this screenshot.

Please If you want to remove these button, please make sure your AppShell.xaml AppShell.xaml.cs file did not include the FlyoutItem and <views:XXXPage IconImageSource="XXX.png" /><views:XXX IconImageSource="XXXX.png" /> like this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/flyout#flyout-items

But I suggest you to create a new project.

Create a new shell file like following code.

MainPage.xaml

  <?xml version="1.0" encoding="utf-8" ?>
  <Shell xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:SearchListDemo"
         xmlns:controls="clr-namespace:SearchListDemo.Controls"

   Navigating="OnNavigating"
   Navigated="OnNavigated"
   x:Class="SearchListDemo.MainPage">

<Shell.FlyoutHeader>
    <controls:FlyoutHeader/>
</Shell.FlyoutHeader>

<local:HomePage/>

</Shell>

MainPage.xaml.cs

     [DesignTimeVisible(true)]
public partial class MainPage : Shell
{
    public Dictionary<string, Type> Routes { get { return routes; } }
    Dictionary<string, Type> routes = new Dictionary<string, Type>();
    public MainPage()
    {
       InitializeComponent();

        RegisterRoutes();

    }

    void RegisterRoutes()
    {
        routes.Add("homwpage", typeof(HomePage));

        foreach (var item in routes)
        {
            Routing.RegisterRoute(item.Key, item.Value);
        }
    }
    void OnNavigating(object sender, ShellNavigatingEventArgs e)
    {

    }

    void OnNavigated(object sender, ShellNavigatedEventArgs e)
    {
    }

}

regist SetFlag before Xamarin.Forms.Forms.Init(e) in the MainActivity.cs

Xamarin.Forms.Forms.SetFlags("Shell_Experimental");


问:
How to fix error used by new Place SDK for android
I want to get adderss used by new place sdk for android.

refer to https://developers.google.com/places/android-sdk/client-migration

I used com.google.android.libraries.places:places-compat:1.1.0

This is for : https://cloud.google.com/blog/products/maps-platform/introducing-new-improved-places-sdks

I had used com.google.android.gms:play-services-places:16.0.0

I used google sample code. (compat)

https://github.com/googlemaps/android-places-demos

I run this project and try to get current place(address).

I could get current place(address) for the first time.

but I could not get this second time.

error code : 9005: You have exceeded your daily request quota for this API. If you did not set a custom daily request quota, verify your project has an active billing account: http://g.co/dev/maps-no-account

If there is anyone who understands, thank you for your consideration.

答:
The issue is because you haven't created the billing account for your project.

Without billing account by default Places SDK will allow only one load per key per day.

You can follow these steps to resolve the issue :

1-Go to Google Cloud Platform Console.

2-Enable billing account for your project.

3-Select the project that contains the API you want to review.

4-From the list of APIs on the Dashboard, click the name of the API.

5-Near the top of the page, click Quotas or Usage and set the limit according to your usage.


问:
How to run .jar file by double click on Windows 7 64-bit?
Running a .jar file in a command line works fine, but i am not able to run any .jar file by double clicking on my Windows 7 (64). It seems nothing happens after the double click.

I tried the ftype hint, no success:

```<code>ftype jarfile="C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*
</code>```

I reinstalled the JDK 7 64-bit, no success.

Any idea?

答:
I had this same issue, and searched the internet for a solution and none of the suggestions didn’t not open by double clicking the .jar file.

In my case the reason is I have multiple JDK & JRE versions installed on my computer. Since I am a software developer working with several different versions for different clients I need to use multiple JDKs in my PC (Windows 10 Pro). So I do not want to change the system variables (i.e. JAVA_HOME, JRE_HOME or PATH), instead I use command prompt to run java in user process whenever I wanted to use a different version.

When installing JDK it registers the .jar file association with latest version we installed in the PC. If you right click on the .jar icon and select properties, it will show that file opens with “Java(TM) Platform SE Binary”.  If we look at the registry key: HKEY_CLASSES_ROOT\jarfile\shell\open\command, it will point to latest JDK version.

It is not a good idea (sometimes annoying) to change the registry key every time I want to run an app build from a different version.

So in my situation it is impossible to just double click the .jar file to execute it. But instead I found a work around solution myself.

Scenario:

Multiple JDKs (1.7, 1.8, 9.0, 10.0, 11.0, and 12.0)are installed in the PC, so the latest installed was 12.0.

Problem

Want to double click an executable .jar developed using JDK 1.8 and didn’t work

This is my work around solution:

Create a shortcut for the .jar file that you want to open.

Right click the shortcut icon and select properties -> Shortcut tab

Change the text in the target (for example "D:\Dev\JavaApp1.8.jar")
To

"C:\Program Files\Java\jdk1.8.0\bin\javaw.exe" -jar
    "D:\Dev\JavaApp1.8.jar"

Then click ok Double click the shortcut.

It should now open the app.

Body:
Running a .jar file in a command line works fine, but i am not able to run any .jar file by double clicking on my Windows 7 (64). It seems nothing happens after the double click.

I tried the ftype hint, no success:

ftype jarfile="C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

I reinstalled the JDK 7 64-bit, no success.

Any idea?


问:
How to deserialize base64-encoded data and use it with DRF
My goal is to come up with an endpoint that gets a base64-decoded string.
This is based described by an example

My input JSON looks like this:

```<code>{
    "encoded_data": "a2F0aWUsIGpvaG5zLCBrYXRpZUBnbWFpbC5jb20KdG9tbXksbGVlLHRvbW15QGdtYWlsLmNvbQ=="
}
</code>```

I have tried to implement it the following way, but I end up with the following error message:

```<code>JSON parse error - Expecting value: line 1 column 1 (char 0)
</code>```

Looks like I've messed up the concepts. Really need help on this:

```<code>class UsersFileUpload(APIView):
    #parser_classes = (MultiPartParser,)

    def post(self, request):
        stream = base64.b64decode(request.data['encoded_data'])

        stream = io.BytesIO(stream)
        data = JSONParser().parse(stream)
        serializer = UsersSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

答:
I don't think you're decoding your text correctly, you shouldn't need to use BytesIO.

You should decode the byte string returned from b64decode and then pass it to the JSONParser.

```<code>b64decoded_data = base64.b64decode(request.data['encoded_data']).decode('UTF-8')
data = JSONParser().parse(b64decoded_data)
</code>```

Body:
My goal is to come up with an endpoint that gets a base64-decoded string.
This is based described by an example

My input JSON looks like this:

{
    "encoded_data": "a2F0aWUsIGpvaG5zLCBrYXRpZUBnbWFpbC5jb20KdG9tbXksbGVlLHRvbW15QGdtYWlsLmNvbQ=="
}

I have tried to implement it the following way, but I end up with the following error message:

JSON parse error - Expecting value: line 1 column 1 (char 0)

Looks like I've messed up the concepts. Really need help on this:

class UsersFileUpload(APIView):
    #parser_classes = (MultiPartParser,)

    def post(self, request):
        stream = base64.b64decode(request.data['encoded_data'])

        stream = io.BytesIO(stream)
        data = JSONParser().parse(stream)
        serializer = UsersSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Body:
I don't think you're decoding your text correctly, you shouldn't need to use BytesIO.

You should decode the byte string returned from b64decode and then pass it to the JSONParser.

b64decoded_data = base64.b64decode(request.data['encoded_data']).decode('UTF-8')
data = JSONParser().parse(b64decoded_data)


问:
When is a variable declaration in another class actually ran?
I've never really found out when exactly a variable declaration is actually ran in a program, when the variable resides in another class.

For instance:

  public static void main(String[] args) {
        int x = 1;
        System.out.println(x);
    }
```

<p>This program seems fairly simplistic to understand in terms of when the declaration is ran.</p>

<p>However consider this:</p>

<pre class="lang-java prettyprint-override"><code>public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Test2 test2 = new Test2();
        System.out.println(test2.y);
    }
}
public class Test2 {
    public int y = 1;
}
</code>```

and:

public class Test {
    public static void main(String[] args) {
        System.out.println(Test2.y);
    }
}
public class Test2 {
    public static int y = 1;
}
```

<p>When is the </p>

<pre class="lang-java prettyprint-override"><code>public int y = 1;
</code>```

declaration ever ran in this program? It is only ever directly called, but isn't actually ran sequentially like the first example. Some clarification on how this actually works would be appreciated.

答:
The concept you are exploring is of variable bindings(basically associating variable with it's data type & value).

Moreover I would highlight a couple of more things here.

First: System.out.println(Test2.y); is wrong as you can not print or access any non static variable in a static manner.

Second: in the below code :

public Test() {
        Test2 test2 = new Test2();
        System.out.println(test2.y);
 }

you can see we have aggregated Test2 class object in Test class's constructor, therefore any new object of class Test will have the Test2 instance & thus your code will successfully print 1 in this regard.public int y = 1; is a declaration & definition which has run at the compile time itself i.e. this variable's binding occurred at compile time. You can explore more towards compile time & run time binding for more knowledge on this concept.

Body:
I've never really found out when exactly a variable declaration is actually ran in a program, when the variable resides in another class.

For instance:

  public static void main(String[] args) {
        int x = 1;
        System.out.println(x);
    }

This program seems fairly simplistic to understand in terms of when the declaration is ran.

However consider this:

public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Test2 test2 = new Test2();
        System.out.println(test2.y);
    }
}
public class Test2 {
    public int y = 1;
}

and:

public class Test {
    public static void main(String[] args) {
        System.out.println(Test2.y);
    }
}
public class Test2 {
    public static int y = 1;
}

When is the

public int y = 1;

declaration ever ran in this program? It is only ever directly called, but isn't actually ran sequentially like the first example. Some clarification on how this actually works would be appreciated.


问:
fscanf() function puts a \000 at the first char read
Im trying to read a file with this format:

```<code>05874121 A 7
07894544 C 3
05655454 B 5
05879544 B 6
05763465 C 2
</code>```

and assign each 'word' to different variables (dni, model, trash)

This code is running on Linux, and I use CLion for debugging.

```<code>char *path = "file.txt";
FILE *f;
int result;
char dni[9], model[1], trash[100];

f = fopen(path, "r");
do {
    result = fscanf(f, "%s %s %s", dni, model, trash);
    printf("DNI: %s\n", dni);
}
while( result > 0);

fclose(f);
</code>```

This should print the first column values, but when I execute the program, the output is just:
"DNI: "
"DNI: "
"DNI: "
... and so on.

While debugging, I realized that "dni" store correctly all the numbers (as chars), but the very first element, dni[0], is always: 0 '/000'
like if it was the end of the string.

I dont know why is happening this.

答:
I did 2 corrections in your code:

```<code>#include <stdio.h>
int main (int argc, char ** argv) {
        char *path = "file.txt";
        FILE *f;
        int result;
        char dni[9], model[2], trash[100];

        f = fopen(path, "r");
        while(1) {
            result = fscanf(f, "%s %s %s", dni, model, trash);
            if (result < 1) break;
            printf("DNI: %s model %s trash %s\n", dni, model, trash);
        }

        fclose(f);
        return 0;
}
</code>```

First, the variable model[2] must have an extra character for the end of the string.

Then, the line "if (result <1) break;".

Probably, the error was the model[1] with only one character. The \ 000 in dni can be the end of the model string.

Body:
Im trying to read a file with this format:

05874121 A 7
07894544 C 3
05655454 B 5
05879544 B 6
05763465 C 2

and assign each 'word' to different variables (dni, model, trash)

This code is running on Linux, and I use CLion for debugging.

char *path = "file.txt";
FILE *f;
int result;
char dni[9], model[1], trash[100];

f = fopen(path, "r");
do {
    result = fscanf(f, "%s %s %s", dni, model, trash);
    printf("DNI: %s\n", dni);
}
while( result > 0);

fclose(f);

This should print the first column values, but when I execute the program, the output is just:
"DNI: "
"DNI: "
"DNI: "
... and so on.

While debugging, I realized that "dni" store correctly all the numbers (as chars), but the very first element, dni[0], is always: 0 '/000'
like if it was the end of the string.

I dont know why is happening this.

Body:
I did 2 corrections in your code:

#include <stdio.h>
int main (int argc, char ** argv) {
        char *path = "file.txt";
        FILE *f;
        int result;
        char dni[9], model[2], trash[100];

        f = fopen(path, "r");
        while(1) {
            result = fscanf(f, "%s %s %s", dni, model, trash);
            if (result < 1) break;
            printf("DNI: %s model %s trash %s\n", dni, model, trash);
        }

        fclose(f);
        return 0;
}

First, the variable model[2] must have an extra character for the end of the string.

Then, the line "if (result <1) break;".

Probably, the error was the model[1] with only one character. The \ 000 in dni can be the end of the model string.


问:
Detect phone number in Lex/Lambda from a Twilio SMS service
I'm building a chatbot using Twilio -> Lex -> Lambda -> DynamoDB.
I would like to capture the phone number of the party that initiated the chat so I can contact them again later (if they opt in). Unfortunately, I can't figure out what I need to do so that Lambda can see this value and write it to DynamoDB.

Based on this documentation, the value exists and is readable in Twilio:
... I'm just not sure how to read from Lex and send to Lambda. Any guidance would be greatly appreciated!!

答:
Twilio developer evangelist here.

As far as I can tell from the documentation, when you connect Twilio to Lex and Lex to a Lambda function, Lex will set a couple of Request Attributes specific to the platform. Request attributes appear in the input event that is sent to the Lambda under the requestAttributes key.

The from phone number that sent the message to the Twilio number appears as the user-id attribute. But note, all attributes sent through by Lex take the x-amz-lex: namespace. So you can read the phone number from the input event as:

```<code>event['requestAttributes']['x-amz-lex:user-id']
</code>```

Let me know if that helps at all.

Body:
Twilio developer evangelist here.

As far as I can tell from the documentation, when you connect Twilio to Lex and Lex to a Lambda function, Lex will set a couple of Request Attributes specific to the platform. Request attributes appear in the input event that is sent to the Lambda under the requestAttributes key.

The from phone number that sent the message to the Twilio number appears as the user-id attribute. But note, all attributes sent through by Lex take the x-amz-lex: namespace. So you can read the phone number from the input event as:

event['requestAttributes']['x-amz-lex:user-id']

Let me know if that helps at all.


问:
ArrayList capacity increase numbers
just a quick question. Can anyone confirm if the following is the correct sequence of the new size of an ArrayList after adding one element past the capacity? I know it grows with a factor of 1.5 but that + 1 in the source code makes me doubt my answer. It starts off with capacity of 10 but the reason I am asking is because I want to test the efficiency of add method against linked list when the size becomes very large. I learnt that average add is constant because of amortized analysis but I just want to confirm by actually working this out.

10, 15, 23, 35, 53, 80, 121.....

Thanks in advance!

答:
I did a testing, check the source below:

import java.lang.reflect.Field;
import java.util.ArrayList;

public class MyArrayList<E> extends ArrayList<E> {
    private int capacity = 0;

    public MyArrayList() {
        super();
    }

    public MyArrayList(int capacity) {
        super(capacity);
    }

    public void printCapacity() {
        try {
            Field elementData = ArrayList.class.getDeclaredField("elementData");
            elementData.setAccessible(true);
            Object[] arr = (Object[]) elementData.get(this);
            if (arr.length != capacity) {
                capacity = arr.length;
                System.out.println("Capacity == " + arr.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class ResizeDemo {
    public static void main(String[] args) {
        MyArrayList<Integer> myArrayList = new MyArrayList<>();
        for (int i = 0; i < 1002; i++) {
            myArrayList.add(i);
            myArrayList.printCapacity();
        }
    }
}
</code>```

It prints:

```<code>Capacity == 10
Capacity == 15
Capacity == 22
Capacity == 33
Capacity == 49
Capacity == 73
Capacity == 109
Capacity == 163
Capacity == 244
Capacity == 366
Capacity == 549
Capacity == 823
Capacity == 1234
</code>```

Title: ArrayList capacity increase numbers

Body:
I did a testing, check the source below:

import java.lang.reflect.Field;
import java.util.ArrayList;

public class MyArrayList<E> extends ArrayList<E> {
    private int capacity = 0;

    public MyArrayList() {
        super();
    }

    public MyArrayList(int capacity) {
        super(capacity);
    }

    public void printCapacity() {
        try {
            Field elementData = ArrayList.class.getDeclaredField("elementData");
            elementData.setAccessible(true);
            Object[] arr = (Object[]) elementData.get(this);
            if (arr.length != capacity) {
                capacity = arr.length;
                System.out.println("Capacity == " + arr.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class ResizeDemo {
    public static void main(String[] args) {
        MyArrayList<Integer> myArrayList = new MyArrayList<>();
        for (int i = 0; i < 1002; i++) {
            myArrayList.add(i);
            myArrayList.printCapacity();
        }
    }
}

It prints:

Capacity == 10
Capacity == 15
Capacity == 22
Capacity == 33
Capacity == 49
Capacity == 73
Capacity == 109
Capacity == 163
Capacity == 244
Capacity == 366
Capacity == 549
Capacity == 823
Capacity == 1234


问:
How to add a scheduler job after last job is over
I know that apscheduler was able to do schedule jobs with:

```<code>scheduler = BackgroundScheduler()
scheduler.add_job(run, 'interval', seconds=60)
</code>```

but now I want the next job started after last job is finished 1mins later, I wonder if it can be relized.

答:
It is possible to attach an event listener to a job which gets called at job completion. https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events

Within that listener, you can schedule the next job 60 seconds in the future.

Body:
I know that apscheduler was able to do schedule jobs with:

scheduler = BackgroundScheduler()
scheduler.add_job(run, 'interval', seconds=60)

but now I want the next job started after last job is finished 1mins later, I wonder if it can be relized.


答: You can create a vector of std::shared_ptr<> as well and keep the values instead of the interators.

Title: Any way that we can prevent the breakdown between reference and object when resize a vector?


问:
How can I convert Entity to Object in java
I define a general List which can add any type elements, define as:List<List<Object>> rows = new ArrayList<>(); but when I get a list from my service layer, the compile process would throw a incompatible types exception, codes sample as below:

```<code>List<List<Object>> rows = new ArrayList<>();
List<ProductEntity> result = searchResponse.getProducts();
rows.add(result);
</code>```

the exception is: incompatible types: java.util.List<com.shopee.data.webapispec.brandseller.entity.product.ProductEntity> cannot be converted to java.util.List<java.lang.Object> when I run the command "mvn clean install", anyone knows how to handle it?

答:
ProductEntity is a sub class of Object. However List<ProductEntity> is not a subclass of List<Object>.

You need to have List<List<? extends Object>> rows = new ArrayList<>(); to make this work.

See here for details on Generics and Object Hierarchies

Body:
I define a general List which can add any type elements, define as:List<List<Object>> rows = new ArrayList<>(); but when I get a list from my service layer, the compile process would throw a incompatible types exception, codes sample as below:

List<List<Object>> rows = new ArrayList<>();
List<ProductEntity> result = searchResponse.getProducts();
rows.add(result);

the exception is: incompatible types: java.util.List<com.shopee.data.webapispec.brandseller.entity.product.ProductEntity> cannot be converted to java.util.List<java.lang.Object> when I run the command "mvn clean install", anyone knows how to handle it?


问:
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

答:
Here you go, map either returns a list or iterator, so this modification will work in either case. (python2 vs python3) </p>

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', len(list(numwords)))
</code>```

Title: Using map function instead of for loop

Body:
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)

Body:
Here you go, map either returns a list or iterator, so this modification will work in either case. (python2 vs python3)

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', len(list(numwords)))


问:
Add padding to a custom contentComponent for a DrawerNavigator to avoid overlaying the status bar
When using a basic DrawerNavigator, there is proper paddingTop that avoids overlaying content over the status bar; however, when adding a custom contentComponent, the padding is not there. Code: https://github.com/myplaceonline/testreactexpo/tree/drawermargin

Without custom contentComponent on Android:

With custom contentComponent on Android:

I can add some explicit margin, but what value should I choose? I'm already using SafeAreaView, but I believe that's only for iOS.

Here's the code. Comment the contentComponent: CustomDrawerContentComponent, line to see the working view.

```<code>import React from 'react';
import { SafeAreaView, ScrollView, Text, View } from 'react-native';
import { createAppContainer, createDrawerNavigator, createStackNavigator, DrawerItems } from 'react-navigation';

class TestScreen extends React.Component {
  static navigationOptions = {
    title: "Test",
  };
  render() {
    return (
      <View style={{flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Test</Text>
      </View>
    );
  }
}

const CustomDrawerContentComponent = props => (
  <SafeAreaView style={{flex: 1}} forceInset={{ top: "always", horizontal: "never" }}>
    <ScrollView>
      <DrawerItems {...props} />
    </ScrollView>
  </SafeAreaView>
);

export default AppDrawer = createAppContainer(
  createDrawerNavigator(
    {
      DrawerTest: {
        screen: createStackNavigator(
          {
            Test: TestScreen
          },
        ),
        navigationOptions: {
          drawerLabel: "Test",
        }
      },
    },
    {
      contentComponent: CustomDrawerContentComponent,
    }
  )
);
</code>```

```

答:
Solved with:</p>

```<code>import Constants from 'expo-constants';

<ScrollView style={{paddingTop: Constants.statusBarHeight}}>
</code>```

Body:
When using a basic DrawerNavigator, there is proper paddingTop that avoids overlaying content over the status bar; however, when adding a custom contentComponent, the padding is not there. Code: https://github.com/myplaceonline/testreactexpo/tree/drawermargin

Without custom contentComponent on Android:

With custom contentComponent on Android:

I can add some explicit margin, but what value should I choose? I'm already using SafeAreaView, but I believe that's only for iOS.

Here's the code. Comment the contentComponent: CustomDrawerContentComponent, line to see the working view.

import React from 'react';
import { SafeAreaView, ScrollView, Text, View } from 'react-native';
import { createAppContainer, createDrawerNavigator, createStackNavigator, DrawerItems } from 'react-navigation';

class TestScreen extends React.Component {
  static navigationOptions = {
    title: "Test",
  };
  render() {
    return (
      <View style={{flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Test</Text>
      </View>
    );
  }
}

const CustomDrawerContentComponent = props => (
  <SafeAreaView style={{flex: 1}} forceInset={{ top: "always", horizontal: "never" }}>
    <ScrollView>
      <DrawerItems {...props} />
    </ScrollView>
  </SafeAreaView>
);

export default AppDrawer = createAppContainer(
  createDrawerNavigator(
    {
      DrawerTest: {
        screen: createStackNavigator(
          {
            Test: TestScreen
          },
        ),
        navigationOptions: {
          drawerLabel: "Test",
        }
      },
    },
    {
      contentComponent: CustomDrawerContentComponent,
    }
  )
);

Body:
Solved with:

import Constants from 'expo-constants';

<ScrollView style={{paddingTop: Constants.statusBarHeight}}>


问:
Jmeter:Able to get the required value from XML,using the JSR223 PostProcessor.Need to Store it in a variable,so that I can be used across threads
1)  I get response in a XML format.

2)  I’m able to process the XML format using JSR223 PostProcessor.

3)  Also able to get the required value from XML response.

How do I store this value in a variable, so that it can be used across threads?
NOTE:

1)  Log.info is working correctly in JSR223 PostProcessor i.e the value gets printed correctly in the jmeter.log file , but when I use ${__setProperty(storeid, ${storeid})}; this is not working.

2)  I have added BeanShell Assertion too but still its not working.

Am I missing anything here?

答:
Move JMeter variable x to property y using props and vars

```<code>props.put("y", vars.get("x));
</code>```

In your case both names are storeid

Body:
Move JMeter variable x to property y using props and vars

props.put("y", vars.get("x));

In your case both names are storeid


问:
How to decode special character in Xamarin forms?
How to decode spacial character in xamairn forms

Inside my label text = "Sample & Text"
instead of showing original text, its showing "Sample & Text"

so how to solve this?

答:
& is used for displaying & in XAML. If you want to display Sample & Text on code behind, there's no need to encode it to Sample & Text. You could set the value directly. i.e. here is a list view's items source:

```<code>var list = new List<string>();
for (int i=0; i<10; i++)
{
    var str = "Sample & Text";
    list.Add(str);
}
listView.ItemsSource = list;
</code>```

It shows correctly:

However, if your original text from the server is Sample & Text and you want to display the decoded format, you can try System.Net.WebUtility.HtmlDecode():

```<code>var str = System.Net.WebUtility.HtmlDecode("Sample & Text");
</code>```

Body:
&amp; is used for displaying & in XAML. If you want to display Sample & Text on code behind, there's no need to encode it to Sample &amp; Text. You could set the value directly. i.e. here is a list view's items source:

var list = new List<string>();
for (int i=0; i<10; i++)
{
    var str = "Sample & Text";
    list.Add(str);
}
listView.ItemsSource = list;

It shows correctly:

However, if your original text from the server is Sample &amp; Text and you want to display the decoded format, you can try System.Net.WebUtility.HtmlDecode():

var str = System.Net.WebUtility.HtmlDecode("Sample &amp; Text");


问:
Maximum number of entries in Node.js Map?
I was making a large Map in Node.js v11.9.0 and it kept failing with "FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory". My map's keys and values shouldn't be getting anywhere near the size of Node's heap size, so I tried just making a map and inserting numeric keys and values into it:

```<code>var N = Math.pow(2, 26);
var map = new Map();
for (var i = 0; i < N; i++) {
  map.set(i, i + 1);
  if (i % 1e5 === 0) { console.log(i / 1e6); }
}
</code>```

This program crashes Node after inserting roughly 16.6 million entries. That number seemed suspiciously close to 2^24, so replacing the logging above with if (i > 16777200) { console.log(i); }, I see that the program crashes immediately after successfully printing "16777215", which is one less than 2^24.

Question. Is there a documented limit on the number of entries in Node's Map close to 2^24? Is there any way to raise that limit?

(N.B. Running Node as node --max-old-space-size=4096 doesn't prevent the crash, since Node is using far less than 4 GB RAM.)

(N.B. 2. I don't think this is a hash collision issue since in my actual code, the map contains (short-ish) strings rather than numbers.)

(N.B. 3. Running the above programs in Firefox's JavaScript Console does not kill Firefox–Firefox keeps adding entries well past 30 million. However, Chrome crashes just like Node. So this is likely a V8 limitation.)

答:
i wrote BigMap and BigSet classes that allow to go beyond that limit i simply create new Maps (or Sets) when the limit is reached. the API is exactly the same as with the built in Map and Set.

const kMaxSize = Math.pow(2, 24)

const BigMap = class {
  /*
    public api, compatible with "Map"
  */

  constructor (...parameters) {
    this.maps = [new Map(...parameters)]
  }

  set (key, value) {
    const map = this.maps[this.maps.length - 1]

    if (map.size === kMaxSize) {
      this.maps.push(new Map())
      return this.set(key, value)
    } else {
      return map.set(key, value)
    }
  }

  has (key) {
    return _mapForKey(this.maps, key) !== undefined
  }

  get (key) {
    return _valueForKey(this.maps, key)
  }

  delete (key) {
    const map = _mapForKey(this.maps, key)

    if (map !== undefined) {
      return map.delete(key)
    }

    return false
  }

  clear () {
    for (let map of this.maps) {
      map.clear()
    }
  }

  get size () {
    let size = 0

    for (let map of this.maps) {
      size += map.size
    }

    return size
  }

  forEach (callbackFn, thisArg) {
    if (thisArg) {
      for (let value of this) {
        callbackFn.call(thisArg, value)
      }
    } else {
      for (let value of this) {
        callbackFn(value)
      }
    }
  }

  entries () {
    return _iterator(this.maps, 'entries')
  }

  keys () {
    return _iterator(this.maps, 'keys')
  }

  values () {
    return _iterator(this.maps, 'values')
  }

  [Symbol.iterator] () {
    return _iterator(this.maps, Symbol.iterator)
  }
}

/*
  private function
*/

function _mapForKey (maps, key) {
  for (let index = maps.length - 1; index >= 0; index--) {
    const map = maps[index]

    if (map.has(key)) {
      return map
    }
  }
}

function _valueForKey (maps, key) {
  for (let index = maps.length - 1; index >= 0; index--) {
    const map = maps[index]
    const value = map.get(key)

    if (value !== undefined) {
      return value
    }
  }
}

function _iterator (items, name) {
  let index = 0

  var iterator = items[index][name]()

  return {
    next: () => {
      let result = iterator.next()

      if (result.done && index < (items.length - 1)) {
        index++
        iterator = items[index][name]()
        result = iterator.next()
      }

      return result
    },
    [Symbol.iterator]: function () {
      return this
    }
  }
}

BigMap.length = 0

/*
 Big Set
 */

const BigSet = class {
  /*
    public api, compatible with "Set"
  */

  constructor (...parameters) {
    this.sets = [new Set(...parameters)]
  }

  add (key) {
    const set = this.sets[this.sets.length - 1]

    if (set.size === kMaxSize) {
      this.sets.push(new Set())
      return this.add(key)
    } else {
      return set.add(key)
    }
  }

  has (key) {
    return _setForKey(this.sets, key) !== undefined
  }

  delete (key) {
    const set = _setForKey(this.sets, key)

    if (set !== undefined) {
      return set.delete(key)
    }

    return false
  }

  clear () {
    for (let set of this.sets) {
      set.clear()
    }
  }

  get size () {
    let size = 0

    for (let set of this.sets) {
      size += set.size
    }

    return size
  }

  forEach (callbackFn, thisArg) {
    if (thisArg) {
      for (let value of this) {
        callbackFn.call(thisArg, value)
      }
    } else {
      for (let value of this) {
        callbackFn(value)
      }
    }
  }

  entries () {
    return _iterator(this.sets, 'entries')
  }

  keys () {
    return _iterator(this.sets, 'keys')
  }

  values () {
    return _iterator(this.sets, 'values')
  }

  [Symbol.iterator] () {
    return _iterator(this.sets, Symbol.iterator)
  }
}

/*
  private function
*/

function _setForKey (sets, key) {
  for (let index = sets.length - 1; index >= 0; index--) {
    const set = sets[index]

    if (set.has(key)) {
      return set
    }
  }
}

function _iterator (items, name) {
  let index = 0

  var iterator = items[index][name]()

  return {
    next: () => {
      let result = iterator.next()

      if (result.done && index < (items.length - 1)) {
        index++
        iterator = items[index][name]()
        result = iterator.next()
      }

      return result
    },
    [Symbol.iterator]: function () {
      return this
    }
  }
}

BigSet.length = 0```

Body:
I was making a large Map in Node.js v11.9.0 and it kept failing with "FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory". My map's keys and values shouldn't be getting anywhere near the size of Node's heap size, so I tried just making a map and inserting numeric keys and values into it:

var N = Math.pow(2, 26);
var map = new Map();
for (var i = 0; i < N; i++) {
  map.set(i, i + 1);
  if (i % 1e5 === 0) { console.log(i / 1e6); }
}

This program crashes Node after inserting roughly 16.6 million entries. That number seemed suspiciously close to 2^24, so replacing the logging above with if (i > 16777200) { console.log(i); }, I see that the program crashes immediately after successfully printing "16777215", which is one less than 2^24.

Question. Is there a documented limit on the number of entries in Node's Map close to 2^24? Is there any way to raise that limit?

(N.B. Running Node as node --max-old-space-size=4096 doesn't prevent the crash, since Node is using far less than 4 GB RAM.)

(N.B. 2. I don't think this is a hash collision issue since in my actual code, the map contains (short-ish) strings rather than numbers.)

(N.B. 3. Running the above programs in Firefox's JavaScript Console does not kill Firefox–Firefox keeps adding entries well past 30 million. However, Chrome crashes just like Node. So this is likely a V8 limitation.)


问:
Is there any way to make a drawer with three-states?
I would like to make a drawer with three different states. The drawer opened state, a closed state and a third semi-open mini drawer state like:

I have been able to implement mini drawer and open using the material drawer library but have been unable to close it.

Any suggestions on how to do this? (Either Kotlin or Java is fine)

答: The project does not support this. A custom layout must be implemented.</p>


问:
C# Generic Copy Constructor
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

```<code>interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}
</code>```

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

```<code>public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}
</code>```

Calling the method requires the type:

```<code>someFoo.Clone<T> ...
</code>```

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

```<code>IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;
</code>```

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

答: If it works for your scenario you could have an IFoo<T>. Also if you don't mind having specific extension methods, you could just receive an Foo<T>. You really need to pass something that references the T so the compiler can infer the appropriate type.

OwnerDisplayName: blu

ContentLicense: CC BY-SA 2.5

Title: C# Generic Copy Constructor

Body:
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}

Calling the method requires the type:

someFoo.Clone<T> ...

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

LastEditorDisplayName: blu

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
How to calculate table values dynamically and find Min and Max target from parameter in SQL Server
I want to calculate table values dynamically and find Min and Max target from parameter

I have the following target table with data:

```<code>Name        Quarter Method  MethodID    GivenTarget Percentage
Json Ray    1       AB      1           153000      0.2
Json Ray    1       BC      2           208000      0.5
Json Ray    1       CD      3           252000      0.8
Json Ray    1       DE      4           450000      0.2
Json Ray    2       AB      1           223000      1.4
Json Ray    2       BC      2           308000      1.8
Json Ray    2       CD      3           352000      1.2
Json Ray    2       DE      4           550000      1.5
Json Ray    3       AB      1           323000      2.8
Json Ray    3       BC      2           408000      2.3
Json Ray    3       CD      3           552000      2.4
Json Ray    3       DE      4           650000      2.9
Json Ray    4       AB      1           423000      2.2
Json Ray    4       BC      2           508000      3.3
Json Ray    4       CD      3           652000      3.5
Json Ray    4       DE      4           750000      3.9
</code>```

I am passing a parameter AchievedTarget for a particular quarter (1, 2, 3, 4).

IF quarter = 1 and AchievedTarget = 250000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 1 and AchievedTarget = 400000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 2 and AchievedTarget = 400000, I want to sum GivenTarget column  from Target tables where Quarter = 1, Method = ’AB’, Method_ID = 1
With  Quarter= 2  Method = ’AB’ Method_ID = 1 and so on for add each respective method and Method_ID with quarters, and need to pick Percentage values from current Quarter i.e Quarter 2 in this case with respective Method and Method_ID

Expected New Target tables for Quarter 2 should be as follows:

Now depend upon above table I want to calculate Min_Target  and Max_Target as calculated earlier

Expected output with Quarter= 2   and AchievedTarget= 500000 should be:

Following is the code which i was trying, its gives me output for Quarter = 1 only

```<code>--DECLARE Input Parameters
DECLARE @AchievedTarget Money =200000
DECLARE @Name varchar(30)='Json Ray' , @Quarter int =1, @Mothod varchar(10)='AB'

--DECLARE Ouput variable
DECLARE @Min_Target Money, @Max_Target Money, @Min_Percenatge float ,@Max_Percenatge float

--Finding Min_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] desc)
IF @Min_Target IS Null
SET @Min_Target=(@AchievedTarget)

--Finding Max_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] ASC)
IF @Max_Target IS Null
SET @Max_Target=(@AchievedTarget)

--Finding @Min_Percenatge
SET @Min_Percenatge=(SELECT TOP 1 [Percenatge] AS Min_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target))

--Finding @Max_Percenatge
SET @Max_Percenatge=(SELECT TOP 1 [Percenatge] AS Max_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target)
ORDER BY [Percenatge] DESC)

--Display Ouput
SELECT @Name, @Quarter,@Mothod ,@Min_Target, @Max_Target, @Min_Percenatge,@Max_Percenatge
</code>```

I am not able to calculate table values dynamically and find Min and Max target from parameter quarter.

答:
You should be able to just use the WHERE clause on a subquery that calculates min and max. Something like this:</p>

```<code>declare @quarter int = 2;
declare @achieved_target money = 300000.00;

SELECT *
FROM (select name, min(achieved_target) as min_target, max(achieved_target) as max_target FROM table WHERE quarter = @quarter GROUP BY name) as t1
WHERE @achieved_target BETWEEN min_target and max_target;
</code>```

Body:
I want to calculate table values dynamically and find Min and Max target from parameter

I have the following target table with data:

Name        Quarter Method  MethodID    GivenTarget Percentage
Json Ray    1       AB      1           153000      0.2
Json Ray    1       BC      2           208000      0.5
Json Ray    1       CD      3           252000      0.8
Json Ray    1       DE      4           450000      0.2
Json Ray    2       AB      1           223000      1.4
Json Ray    2       BC      2           308000      1.8
Json Ray    2       CD      3           352000      1.2
Json Ray    2       DE      4           550000      1.5
Json Ray    3       AB      1           323000      2.8
Json Ray    3       BC      2           408000      2.3
Json Ray    3       CD      3           552000      2.4
Json Ray    3       DE      4           650000      2.9
Json Ray    4       AB      1           423000      2.2
Json Ray    4       BC      2           508000      3.3
Json Ray    4       CD      3           652000      3.5
Json Ray    4       DE      4           750000      3.9

I am passing a parameter AchievedTarget for a particular quarter (1, 2, 3, 4).

IF quarter = 1 and AchievedTarget = 250000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 1 and AchievedTarget = 400000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 2 and AchievedTarget = 400000, I want to sum GivenTarget column  from Target tables where Quarter = 1, Method = ’AB’, Method_ID = 1
With  Quarter= 2  Method = ’AB’ Method_ID = 1 and so on for add each respective method and Method_ID with quarters, and need to pick Percentage values from current Quarter i.e Quarter 2 in this case with respective Method and Method_ID

Expected New Target tables for Quarter 2 should be as follows:

Now depend upon above table I want to calculate Min_Target  and Max_Target as calculated earlier

Expected output with Quarter= 2   and AchievedTarget= 500000 should be:

Following is the code which i was trying, its gives me output for Quarter = 1 only

--DECLARE Input Parameters
DECLARE @AchievedTarget Money =200000
DECLARE @Name varchar(30)='Json Ray' , @Quarter int =1, @Mothod varchar(10)='AB'

--DECLARE Ouput variable
DECLARE @Min_Target Money, @Max_Target Money, @Min_Percenatge float ,@Max_Percenatge float

--Finding Min_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] desc)
IF @Min_Target IS Null
SET @Min_Target=(@AchievedTarget)

--Finding Max_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] ASC)
IF @Max_Target IS Null
SET @Max_Target=(@AchievedTarget)

--Finding @Min_Percenatge
SET @Min_Percenatge=(SELECT TOP 1 [Percenatge] AS Min_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target))

--Finding @Max_Percenatge
SET @Max_Percenatge=(SELECT TOP 1 [Percenatge] AS Max_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target)
ORDER BY [Percenatge] DESC)

--Display Ouput
SELECT @Name, @Quarter,@Mothod ,@Min_Target, @Max_Target, @Min_Percenatge,@Max_Percenatge

I am not able to calculate table values dynamically and find Min and Max target from parameter quarter.

Body:
You should be able to just use the WHERE clause on a subquery that calculates min and max. Something like this:

declare @quarter int = 2;
declare @achieved_target money = 300000.00;

SELECT *
FROM (select name, min(achieved_target) as min_target, max(achieved_target) as max_target FROM table WHERE quarter = @quarter GROUP BY name) as t1
WHERE @achieved_target BETWEEN min_target and max_target;


问:
Elegant way to toggle back and force multiple css elements
I have 2 buttons with ids "videos-button" and "photos-button". On click of each button, I need to perform a set of action to changes css or remove/add class for certain HTML elements. Basically, for each of the element, I need to toggle their initial state back and force. See code for details:

```<code>$('#videos-button').on('click',function(){
            $("#ib-row").css({'display':'none'});
            $("#ib-pagination").css({'display':'none'});
            $("#ib-video-carousel-pagination").css({'display':'block'});
            $("#ib-video-carousel").css({'display':'block'});
            $("#photos-button").removeClass('image-block-media-button-selected');
            $("#videos-button").addClass('image-block-media-button-selected');
});

$('#photos-button').on('click',function(){
            $("#ib-row").css({'display':'block'});
            $("#ib-pagination").css({'display':'block'});
            $("#ib-video-carousel-pagination").css({'display':'none'});
            $("#ib-video-carousel").css({'display':'none'});
            $("#videos-button").removeClass('image-block-media-button-selected');
            $("#photos-button").addClass('image-block-media-button-selected');
        });
</code>```

How can I refactor it in more elegant way, without duplication?

答:
You can try this:</p>

```<code>const ibRowAndPagination = ['#ib-row', '#ib-pagination'];
const ibVideoCarouselAndPagination = ['#ib-video-carousel-pagination', '#ib-video-carousel'];
const photosAndVideosButtons = ['#photos-button', '#videos-button'];
const photosAndVideosButtonsToggleClass = () => photosAndVideosButtons.forEach(el => $(el).toggleClass('image-block-media-button-selected'));

$('#videos-button').on('click', function() {
  ibRowAndPagination.forEach(el => $(el).css({'display':'none'}));
  ibVideoCarouselAndPagination.forEach(el => $(el).css({'display':'block'}));
  photosAndVideosButtonsToggleClass();
});

$('#photos-button').on('click', function() {
  ibRowAndPagination.forEach(el => $(el).css({'display':'block'}));
  ibVideoCarouselAndPagination.forEach(el => $(el).css({'display':'none'}));
  photosAndVideosButtonsToggleClass();
});
</code>```

Body:
I have 2 buttons with ids "videos-button" and "photos-button". On click of each button, I need to perform a set of action to changes css or remove/add class for certain HTML elements. Basically, for each of the element, I need to toggle their initial state back and force. See code for details:

$('#videos-button').on('click',function(){
            $("#ib-row").css({'display':'none'});
            $("#ib-pagination").css({'display':'none'});
            $("#ib-video-carousel-pagination").css({'display':'block'});
            $("#ib-video-carousel").css({'display':'block'});
            $("#photos-button").removeClass('image-block-media-button-selected');
            $("#videos-button").addClass('image-block-media-button-selected');
});

$('#photos-button').on('click',function(){
            $("#ib-row").css({'display':'block'});
            $("#ib-pagination").css({'display':'block'});
            $("#ib-video-carousel-pagination").css({'display':'none'});
            $("#ib-video-carousel").css({'display':'none'});
            $("#videos-button").removeClass('image-block-media-button-selected');
            $("#photos-button").addClass('image-block-media-button-selected');
        });

How can I refactor it in more elegant way, without duplication?

Body:
You can try this:

const ibRowAndPagination = ['#ib-row', '#ib-pagination'];
const ibVideoCarouselAndPagination = ['#ib-video-carousel-pagination', '#ib-video-carousel'];
const photosAndVideosButtons = ['#photos-button', '#videos-button'];
const photosAndVideosButtonsToggleClass = () => photosAndVideosButtons.forEach(el => $(el).toggleClass('image-block-media-button-selected'));

$('#videos-button').on('click', function() {
  ibRowAndPagination.forEach(el => $(el).css({'display':'none'}));
  ibVideoCarouselAndPagination.forEach(el => $(el).css({'display':'block'}));
  photosAndVideosButtonsToggleClass();
});

$('#photos-button').on('click', function() {
  ibRowAndPagination.forEach(el => $(el).css({'display':'block'}));
  ibVideoCarouselAndPagination.forEach(el => $(el).css({'display':'none'}));
  photosAndVideosButtonsToggleClass();
});


问:
How to test cloudformation lambda functions locally?
Usecase

I have cloudformation stack which has around 25 lambda functions. Before deploying into production i need to test all the functions locally.

I know aws has SAM Cli to test serverless functions which has completely different syntax when compare to cloudformation lambdas.

Is there any possible tool from aws  that solves my usecase ?

Because it gonna take quite a lot of time for converting cfn lambdas to sam syntax and also sam dont have that much options as cloudformation has.

Any help is appreciated
Thanks

答:
I know you have picked SAM cli to build your templates, but I would suggest you to move to Serverless (npm i serverless -g) as they are more advanced. Serverless is a framework which has been built by engineers and has no Cloud Provider attached/dependent to it, hence you would be able to easily switch from Azure to AWS from your template.

Because it is supported by a big dev community the framework has a variety of plugins, including serverless offline plugin which will allow you to run your API locally as if you were just running node index.js. There are also plugins like "serverless-jest" or "serverless-mocha" for unit tests, but I ended up using the normal "Jest" running integration test (I use cognito user pool and need to check the auth token).

If you really want to test your code of cloudformation architecture, you can have a JS file with your function and run it with node locally and instead of having the code in your cloudformation template, you will need to zip ip, upload on S3 and then inform the path on your template.

In summary, I know you asked how to test your SAM Serverless, but since you would like to have a proper development flow (local execution, unit test, pipeline, etc) switching to Serverless framework would be the solution. You can simulate the functions through node, but this will increase your manual management of something which a framework already does.


问:
Singletons in multi threaded environment
when using singletons, if the class has instance fields should you be careful when several threads might be using the singleton? (And the fields are mutable and their values can be changed)

I havn't tried but in theory it seems like the answer is yes and you would need synchronization (or skip the singleton)

答: As with many multi-threading questions, the answer is it depends. ;)  read-only fields won't need extra synchronization while any read-write fields will most definitely require it.</p>


问:
Access is denied when trying to pip install a package on Windows
How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!

Could not install packages due to an EnvironmentError: [WinError 5]

Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry_points.txt'

Consider using the --user option or check the permissions

答:
Run your command prompt on admin mode.
type :

cd\

then type:

cd [Your python location path]

on mycomputer it's:
cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32
then type:

```<code>python -m pip install --upgrade pip
</code>```

You can follow this guide~
https://datatofish.com/upgrade-pip/

Body:
Run your command prompt on admin mode.
type :

cd\

then type:

cd [Your python location path]

on mycomputer it's:
cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32
then type:

python -m pip install --upgrade pip

You can follow this guide~
https://datatofish.com/upgrade-pip/


问:
Databinding during Navigation in UWP
I'm using Windows Template Studio to create a simple UWP app. I'm using the built-in MVVM template for Multiple Pages.
I have 2 Pages on the app. Both the pages contain the few textboxes where the user can enter some values. Data binding is working perfectly on both the pages individually. My problem is:
When I navigate to Page 2 and return back on Page 1, the value in the Textboxes return to the original initialization values and do not remain the last updated values.

I am expecting that when I return to Page 1 from Page 2, the values on Page 1 should be the last updated values.
I've followed a lot of tutorials but could not find a comprehensive solution to it.
I am just getting started with UWP and MVVM so it may be hard for me to wrap my head around some of the basic concepts.
Any help in this regard is appreciated.

答:
You need to think about saving these TextBox values in the ApplicationData. For example, the ApplicationData.LocalSettings.

When you navigate from page1 to page2, you could save the value in localSettings.

```<code>var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["exampleSetting"] = "Hello Windows";
</code>```

When you get back from page2 to page1. You could get the value from LocalSettings.

```<code>Object value = localSettings.Values["exampleSetting"];
</code>```

Please see the Application data sample for more details.

Title: Databinding during Navigation in UWP

Body:
You need to think about saving these TextBox values in the ApplicationData. For example, the ApplicationData.LocalSettings.

When you navigate from page1 to page2, you could save the value in localSettings.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["exampleSetting"] = "Hello Windows";

When you get back from page2 to page1. You could get the value from LocalSettings.

Object value = localSettings.Values["exampleSetting"];

Please see the Application data sample for more details.


问:
How to display different navigation for different language in XenForo 2?
I want to show personalized menu for different languages in XenForo 2.

I did not find any clue how to do that, except it has this option to display navigation item in condition. (see image)

What must be the conditional expression for example if i want to display an item only when the language is in english?

I tried this, but it did not work:

```<code>{$xf.visitorLanguage.language_code} == 'en'
</code>```

example

答: You need to use "en-US" not "en"</p>

Body:
I want to show personalized menu for different languages in XenForo 2.

I did not find any clue how to do that, except it has this option to display navigation item in condition. (see image)

What must be the conditional expression for example if i want to display an item only when the language is in english?

I tried this, but it did not work:

{$xf.visitorLanguage.language_code} == 'en'

example

Body: You need to use "en-US" not "en"


问:
Show real runtime hyperlink when using asp tag helper
when I generate a hyperlink with asp-tag helpers it looks like this:

```<code><a asp-page="/demo">Demo</a>
</code>```

The html output looks like that:

```<code><a href="/test/Demo">Demo</a>
</code>```

But I want to show the user not the hyperlink "Demo" but instead the real address at runtime (localhost:xxxx/test/demo).

The problem ist that at compile time I did not know that. Is there an easy way that the asp-page feature generates me the hyperlink content?

答:
For this requirement, you need to implement your own AnchorTagHelper with steps below:

Custom AnchorTagHelper

```<code>[HtmlTargetElement("a-link")]
public class MyAnchorTagHelper : AnchorTagHelper
{
    private readonly HttpContext _httpContext;
    public MyAnchorTagHelper(IHtmlGenerator generator
        , IHttpContextAccessor httpContextAccessor) : base(generator)
    {
        _httpContext = httpContextAccessor.HttpContext;
    }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);
        output.TagName = "a";
        var basePath = $"{_httpContext.Request.Scheme}://{_httpContext.Request.Host}{_httpContext.Request.PathBase}";
        TagHelperAttribute href;
        if (output.Attributes.TryGetAttribute("href", out href))
        {
            output.Attributes.SetAttribute("href", $"{basePath}{href.Value}");
        }
    }
}
</code>```

Register MyAnchorTagHelper in _ViewImports.cshtml with @addTagHelper *, namespace

```<code>@using Microsoft.AspNetCore.Identity
@using TestRazor2_2
@using TestRazor2_2.Data
@namespace TestRazor2_2.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, TestRazor2_2
</code>```

UseCase

```<code><a-link href="/test/Demo">Demo</a-link>
</code>```

Body:
when I generate a hyperlink with asp-tag helpers it looks like this:

Demo

The html output looks like that:

Demo

But I want to show the user not the hyperlink "Demo" but instead the real address at runtime (localhost:xxxx/test/demo).

The problem ist that at compile time I did not know that. Is there an easy way that the asp-page feature generates me the hyperlink content?

Body:
For this requirement, you need to implement your own AnchorTagHelper with steps below:

Custom AnchorTagHelper

[HtmlTargetElement("a-link")]
public class MyAnchorTagHelper : AnchorTagHelper
{
    private readonly HttpContext _httpContext;
    public MyAnchorTagHelper(IHtmlGenerator generator
        , IHttpContextAccessor httpContextAccessor) : base(generator)
    {
        _httpContext = httpContextAccessor.HttpContext;
    }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);
        output.TagName = "a";
        var basePath = $"{_httpContext.Request.Scheme}://{_httpContext.Request.Host}{_httpContext.Request.PathBase}";
        TagHelperAttribute href;
        if (output.Attributes.TryGetAttribute("href", out href))
        {
            output.Attributes.SetAttribute("href", $"{basePath}{href.Value}");
        }
    }
}

Register MyAnchorTagHelper in _ViewImports.cshtml with @addTagHelper *, namespace

@using Microsoft.AspNetCore.Identity
@using TestRazor2_2
@using TestRazor2_2.Data
@namespace TestRazor2_2.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, TestRazor2_2

UseCase

<a-link href="/test/Demo">Demo</a-link>