问:
displaying records from mysql in ul and li format with php
i want to display the mysql's fetched results with php and html in unordered list and list format  as like http://www.miniclip.com/games/en/. you can see in the all games categories in the footer in alphabetical order. the same requirement i do have. i guess i have written the logic its working fine. but i am unable to represent it properly. you can see in the following link above the footer. http://www.playtoongames.com/play1...

code:

```<code><?php
$gameQuery = mysql_query ("SELECT name, LEFT(name, 1) AS first_char FROM games WHERE UPPER(name) BETWEEN 'A' AND 'Z' OR name BETWEEN '0' AND '9' ORDER BY name");
$current_char = '';
   while ($gameRow = mysql_fetch_assoc($gameQuery)){
     if ($_SESSION['lang'] == 'fr'){
         $description = $gameRow['description_fr'];
     }else{
   $description = $gameRow['description'];
 }
?>

<div style='float:left' title="<img src='<?php echo $gameRow['sitePath'];?>games/images/<?php echo $gameRow['img_100x75'];?>' width='230' height='112' class='thumb' alt='<?php echo $gameRow['name'];?>'/>" class='tooltip'>

                     <ul>
                     <li>
     <a href='<?php echo $gameRow['sitePath'];?>play/<?php echo str_replace(' ','_',$gameRow['name']);?>'><?php echo $gameRow['name'];?></a>
                     </li>
                      </ul>
</div>
</code>```

can anybody look into this...

Regards,
sam.

答:
On the Playtoons site, each
 is in its' own individual
 - this means you're creating a new list for each item:

```<code><ul>
  <li>13 More Days</li>
</ul>
<ul>
  <li>A Bikers Heaven</li>
</ul>
</code>```

What you should be doing is using one
 which contains all the items as
s:

```<code><ul>
  <li>13 More Days</li>
  <li>A Bikers Heaven</li>
</ul>
</code>```

Body:
i want to display the mysql's fetched results with php and html in unordered list and list format  as like http://www.miniclip.com/games/en/. you can see in the all games categories in the footer in alphabetical order. the same requirement i do have. i guess i have written the logic its working fine. but i am unable to represent it properly. you can see in the following link above the footer. http://www.playtoongames.com/play1...

code:

<?php
$gameQuery = mysql_query ("SELECT name, LEFT(name, 1) AS first_char FROM games WHERE UPPER(name) BETWEEN 'A' AND 'Z' OR name BETWEEN '0' AND '9' ORDER BY name");
$current_char = '';
   while ($gameRow = mysql_fetch_assoc($gameQuery)){
     if ($_SESSION['lang'] == 'fr'){
         $description = $gameRow['description_fr'];
     }else{
   $description = $gameRow['description'];
 }
?>

<div style='float:left' title="<img src='<?php echo $gameRow['sitePath'];?>games/images/<?php echo $gameRow['img_100x75'];?>' width='230' height='112' class='thumb' alt='<?php echo $gameRow['name'];?>'/>" class='tooltip'>

     <a href='<?php echo $gameRow['sitePath'];?>play/<?php echo str_replace(' ','_',$gameRow['name']);?>'><?php echo $gameRow['name'];?>

can anybody look into this...

Regards,
sam.

Body:
On the Playtoons site, each <li> is in its' own individual <ul> - this means you're creating a new list for each item:

<ul>
  <li>13 More Days</li>
</ul>
<ul>
  <li>A Bikers Heaven</li>
</ul>

What you should be doing is using one <ul> which contains all the items as <li>s:

<ul>
  <li>13 More Days</li>
  <li>A Bikers Heaven</li>
</ul>


来源: stackexchange

问:
how to call FileHelpers.RecordTypeSelector correctly?
I'm working with FileHelpers: https://www.filehelpers.net/

I have a source file which contains a set of approximately 10 different RecordTypes. To accommodate, I intend to use a MultiRecordEngine (https://www.filehelpers.net/example/Advanced/MultiRecordEngine/).

As I read the instructions, I should declare the engine

```<code>var engine = new MultiRecordEngine(typeof (Orders),
    typeof (Customer),
    typeof (SampleType));
</code>```

... and then feed the "CustomSelector" ...

```<code>engine.RecordSelector = new RecordTypeSelector(CustomSelector);
</code>```

Looking at the documentation at the link provided, "CustomSelector" is a private method inside Selector.cs.

```<code>private Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;
    if (Char.IsLetter(recordLine[0]))
        return typeof (Customer);
    else if (recordLine.Length == 14)
        return typeof (SampleType);
    else
        return typeof (Orders);
}
</code>```

There's no mention of a delegate, and declaring one didn't improve Mister Compiler's opinion of my code. Does anybody have experience with MultiRecordEngine to tell me what perfectly obvious fact I'm missing? Thanks!

答:
Okay, the documentation and my eyes were having a tiff. As given, this code...

```<code>engine.RecordSelector = new RecordTypeSelector(CustomSelector);
</code>```

... is useful only if CustomSelector is a local function, which strikes me as bad form. I stuck with a separate Selector class, and declared "CustomSelector" as public static:

```<code>public static Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;
    if (Char.IsLetter(recordLine[0]))
        return typeof (Customer);
    else if (recordLine.Length == 14)
        return typeof (SampleType);
    else
        return typeof (Orders);
}
</code>```

Once I tell MultiRecordEngine where to find it,

```<code>engine.RecordSelector = new RecordTypeSelector(Selector.CustomSelector);
</code>```

... you're golden.

I hope this helps save the next person the 10 minutes I spent typing the question and answer. Enjoy! :)

ContentLicense: CC BY-SA 4.0

Body:
I'm working with FileHelpers: https://www.filehelpers.net/

I have a source file which contains a set of approximately 10 different RecordTypes. To accommodate, I intend to use a MultiRecordEngine (https://www.filehelpers.net/example/Advanced/MultiRecordEngine/).

As I read the instructions, I should declare the engine

var engine = new MultiRecordEngine(typeof (Orders),
    typeof (Customer),
    typeof (SampleType));

... and then feed the "CustomSelector" ...

engine.RecordSelector = new RecordTypeSelector(CustomSelector);

Looking at the documentation at the link provided, "CustomSelector" is a private method inside Selector.cs.

private Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;
    if (Char.IsLetter(recordLine[0]))
        return typeof (Customer);
    else if (recordLine.Length == 14)
        return typeof (SampleType);
    else
        return typeof (Orders);
}

There's no mention of a delegate, and declaring one didn't improve Mister Compiler's opinion of my code. Does anybody have experience with MultiRecordEngine to tell me what perfectly obvious fact I'm missing? Thanks!

Body:
Okay, the documentation and my eyes were having a tiff. As given, this code...

engine.RecordSelector = new RecordTypeSelector(CustomSelector);

... is useful only if CustomSelector is a local function, which strikes me as bad form. I stuck with a separate Selector class, and declared "CustomSelector" as public static:

public static Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;
    if (Char.IsLetter(recordLine[0]))
        return typeof (Customer);
    else if (recordLine.Length == 14)
        return typeof (SampleType);
    else
        return typeof (Orders);
}

Once I tell MultiRecordEngine where to find it,

engine.RecordSelector = new RecordTypeSelector(Selector.CustomSelector);

... you're golden.

I hope this helps save the next person the 10 minutes I spent typing the question and answer. Enjoy! :)


问:
Running a simulation without using looping in R
I have the following code for a Monte Carlo simulation: </p>

```<code>function (muC1,sigmaC1,muC2,sigmaC2,Msim=10000) {
# a grand loop simulation program for the lifetime of
# a simple system of components. This system has
# two branches. The first branch fails when C1 fails.
# The second branch fails as soon as either of C2 or C3 fails.
#
# get alpha's and lambda's for Gamma lifetime RVs from the
# mu's and sigma's.
# Note C2 has the same distribution as C3, i.e.
# alpha3=alpha2, lambda3=lambda2
lambda1 = muC1/sigmaC1^2
alpha1 = muC1*lambda1
lambda2 = muC2/sigmaC2^2
alpha2 = muC2*lambda2
#
# initialize simulation summary holders
count.C1fail = 0   # number of times C1 fails before branch2
system.lifetime = rep(NA,Msim)
#
# begin grand loop
for (i in 1:Msim) {
C1 = rgamma(1,alpha1,lambda1)
C2 = rgamma(1,alpha2,lambda2)
C3 = rgamma(1,alpha2,lambda2)
branch2 = min(C2,C3)
system.lifetime[i] = max(C1,branch2)
if (C1 < branch2) count.C1fail = count.C1fail+1
} # end grand loop
#
# final summary calculations and wrapup
PC1fail = count.C1fail/Msim
hist(system.lifetime,main="Simulated System Lifetimes")
meanL = mean(system.lifetime)
stddevL = sd(system.lifetime)
MOEL95pct = 1.96*stddevL/sqrt(Msim)
out = list(muC1,sigmaC1,muC2,sigmaC2,Msim,PC1fail,meanL,MOEL95pct)
names(out) = c("muC1","sigmaC1","muC2","sigmaC2","Msim","PC1fail","meanL","MOEL95pct")
out
}
</code>```

<p>This simulation works perfectly for what I need, but for an assignment I need to run the same simulation (muC1 = 100, sigmaC1 = 20, muC2 = 80, sigmaC2 = 40, Msim = 10000) WITHOUT a grand loop. Any tips? </p>

答:
You can eliminate the loop by just drawing all your random values at once.

```<code>C1 <- rgamma(Msim, alpha1, lambda1)
C2 <- rgamma(Msim, alpha2, lambda2)
C3 <- rgamma(Msim, alpha2, lambda2)
branch2 <- pmin(C2, C3)
system.lifetime <- pmax(C1, branch2)
count.C1fail <- sum(C1 < branch2)
</code>```

Then since we want to operate on vectors rather that just two values, we switch from min and max to pmin and pmax (the vectorized versions of the function). Finally, to count events in vectors we often just sum() over TRUE/FALSE values because TRUE is converted to 1 and FALSE 0 so we just get the count of TRUE events.

Doing it this way also means that it's not necessary to initialize count.C1fail or system.lifetime ahead of time.

Body:
I have the following code for a Monte Carlo simulation:

function (muC1,sigmaC1,muC2,sigmaC2,Msim=10000) {
# a grand loop simulation program for the lifetime of
# a simple system of components. This system has
# two branches. The first branch fails when C1 fails.
# The second branch fails as soon as either of C2 or C3 fails.
#
# get alpha's and lambda's for Gamma lifetime RVs from the
# mu's and sigma's.
# Note C2 has the same distribution as C3, i.e.
# alpha3=alpha2, lambda3=lambda2
lambda1 = muC1/sigmaC1^2
alpha1 = muC1*lambda1
lambda2 = muC2/sigmaC2^2
alpha2 = muC2*lambda2
#
# initialize simulation summary holders
count.C1fail = 0   # number of times C1 fails before branch2
system.lifetime = rep(NA,Msim)
#
# begin grand loop
for (i in 1:Msim) {
C1 = rgamma(1,alpha1,lambda1)
C2 = rgamma(1,alpha2,lambda2)
C3 = rgamma(1,alpha2,lambda2)
branch2 = min(C2,C3)
system.lifetime[i] = max(C1,branch2)
if (C1 < branch2) count.C1fail = count.C1fail+1
} # end grand loop
#
# final summary calculations and wrapup
PC1fail = count.C1fail/Msim
hist(system.lifetime,main="Simulated System Lifetimes")
meanL = mean(system.lifetime)
stddevL = sd(system.lifetime)
MOEL95pct = 1.96*stddevL/sqrt(Msim)
out = list(muC1,sigmaC1,muC2,sigmaC2,Msim,PC1fail,meanL,MOEL95pct)
names(out) = c("muC1","sigmaC1","muC2","sigmaC2","Msim","PC1fail","meanL","MOEL95pct")
out
}

This simulation works perfectly for what I need, but for an assignment I need to run the same simulation (muC1 = 100, sigmaC1 = 20, muC2 = 80, sigmaC2 = 40, Msim = 10000) WITHOUT a grand loop. Any tips?

Body:
You can eliminate the loop by just drawing all your random values at once.

C1 <- rgamma(Msim, alpha1, lambda1)
C2 <- rgamma(Msim, alpha2, lambda2)
C3 <- rgamma(Msim, alpha2, lambda2)
branch2 <- pmin(C2, C3)
system.lifetime <- pmax(C1, branch2)
count.C1fail <- sum(C1 < branch2)

Then since we want to operate on vectors rather that just two values, we switch from min and max to pmin and pmax (the vectorized versions of the function). Finally, to count events in vectors we often just sum() over TRUE/FALSE values because TRUE is converted to 1 and FALSE 0 so we just get the count of TRUE events.

Doing it this way also means that it's not necessary to initialize count.C1fail or system.lifetime ahead of time.


问:
html from requests not the same as source code
I'm trying to scrape this link:
34th government

(https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp)

which has several tables, but when i perform a request using this code:

```<code>import requests
from bs4 import BeautifulSoup

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
website_url = requests.get(govts_url).text
soup = BeautifulSoup(website_url, 'lxml')
print(f"HTML: \n {soup.prettify()}")
</code>```

I get the following result:

```<code> <html>
 <head>
  <meta charset="utf-8"/>
  <script>
   window.rbzid="Q5gSRBmIWVopQazRgPTWKOEV0wGh1o+KvPO3KMiDuHxM9vVecPeHn4ult+Ba/KU9zInGRSRXUggEmkFs+D5NKSC/WEkCn+B4PCw9CeWkT+Q=";
        u82222.O=function(x){return x;};u82222.E=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.i=function(x,y){return x+y;};u82222.A=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.Y=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.n=function(x,y){return x+y;};u82222.f=function(x,y){return x+y;};u82222.u=function(){var M=function(K,N){var I=N&0xffff;var r=N-I;return(r*K|0)+(I*K|0)|0;},Y=function(x,d,Z){var n=0xcc9e2d51,b=0x1b873593;var E=Z;var O=d&~0x3;for(var w=0;w<O;w+=4){var e=x.charCodeAt(w)&0xff|(x.charCodeAt(w+1)&0xff)<<8|(x.charCodeAt(w+2)&0xff)<<16|(x.charCodeAt(w+3)&0xff)<<24;e=M(e,n);e=(e&0x1ffff)<<15|e>>>17;e=M(e,b);E^=e;E=(E&0x7ffff)<<13|E>>>19;E=E*5+0xe6546b64|0;}e=0;switch(d%4){case 3:e=(x.charCodeAt(O+2)&0xff)<<16;case 2:e|=(x.charCodeAt(O+1)&0xff)<<8;case 1:e|=x.charCodeAt(O)&0xff;e=M(e,n);e=(e&0x1ffff)<<15|e>>>17;e=M(e,b);E^=e;}E^=d;E^=E>>>16;E=M(E,0x85ebca6b);E^=E>>>13;E=M(E,0xc2b2ae35);E^=E>>>16;return E;};return{u:Y};}();u82222.d=function(x,y){return x+y;};u82222.K=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.N=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.Z=function(x,y){return x+y;};u82222.I=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.e=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.t=function(){return{u:function(K){var A='',I=decodeURI("1?'%1CYH.=uVWU~%254_hW,o,WKM%22(-W%5BW,o,LU%075?'%1CH%5D9.5LU%07#?'%1C@W,o6LU%07%22?'%1Ch%5C$.%25N%07D1?'%1C%5DW,o4LU%07%124=LU%07%3C.%25N%07F=?'%1COW,o7bAH%3E?'%1CL%5B.=uF@F%3E%02%25N%07v%0F13SG%5D?,:AWU~13LU%07%3E?'%1CvY8%205FFD.=uF%5BF%3C-%25N%07J1?'%1C%5CW,o7");for(var Y=0,M=0;Y<I.length;Y++,M++){if(M===K.length){M=0;}A+=String.fromCharCode(I.charCodeAt(Y)^K.charCodeAt(M));}A=A.split('~|.');return function(t){return A[t];};}('PA[2))')};}();u82222.o=function(x,y){return x+y;};u82222.r=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};u82222.b=function(x,y){return x+y;};u82222.w=function(x){return x;};u82222.s=function(x,y){return x+y;};u82222.F=function(x,y){return x+y;};u82222.M=function (){return typeof u82222.u.u==='function'?u82222.u.u.apply(u82222.u,arguments):u82222.u.u;};u82222.T=function(x,y){return x>y;};function u82222(){}u82222.x=function (){return typeof u82222.t.u==='function'?u82222.t.u.apply(u82222.t,arguments):u82222.t.u;};(typeof window==="object"?window:global).u82222=u82222;_=window;if(u82222.w(u82222.O(_[u82222.r(24)+u82222.e(0)+u82222.E(25)+u82222.E(14)+u82222.e(18)])||_[u82222.N(26)]||_[u82222.d(u82222.F(u82222.n(u82222.e(28),u82222.r(30))+u82222.N(20),u82222.N(14)),u82222.r(18))]||_[u82222.x(23)])||_[u82222.b(u82222.x(16),u82222.x(19))+u82222.r(6)+u82222.x(11)]||_[u82222.Z(u82222.E(6)+u82222.x(10)+u82222.e(9),u82222.x(14))]||_[u82222.s(u82222.T(975.11,476.89)?u82222.N(8):(13,105.77),u82222.E(1))+u82222.E(5)+u82222.N(25)]||_[u82222.E(4)]||_[u82222.o(u82222.x(3)+u82222.N(29)+u82222.e(14),u82222.e(15))+u82222.N(10)+u82222.x(7)]||_[u82222.i(u82222.e(2)+u82222.N(18)+u82222.N(12)+u82222.e(13)+u82222.x(22)+u82222.E(15)+u82222.E(25),u82222.e(27))+u82222.E(21)]){}else{location[u82222.f(u82222.r(11)+u82222.x(6)+u82222.e(17)+u82222.N(0),u82222.e(2))]();}
  </script>
 </head>
 <body>
 </body>
</html>
</code>```

Which is, of course, not the content i desire.
I guess i'm missing some kind of "activation" to the site, to see the true content. But how can i see it?

Thx!

答:
I tried with selenium (download the driver that you would, in my case Chromedriver) and it works, you can get the full html source os the page and from here you can continue with the web scraping. I hope this helps you :)</p>

```<code>from bs4 import BeautifulSoup
from selenium import webdriver

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
exe_path = r'C:\Users\JRV\Desktop\WebCrawling/chromedriver.exe'

browser = webdriver.Chrome(exe_path)
browser.get(govts_url)
page = browser.page_source
browser.close()

soup = BeautifulSoup(page, 'html.parser')
print(f"HTML: \n {soup}")
</code>```

Body:
I'm trying to scrape this link:
34th government

(https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp)

which has several tables, but when i perform a request using this code:

import requests
from bs4 import BeautifulSoup

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
website_url = requests.get(govts_url).text
soup = BeautifulSoup(website_url, 'lxml')
print(f"HTML: \n {soup.prettify()}")

I get the following result:

  <meta charset="utf-8"/>

Which is, of course, not the content i desire.
I guess i'm missing some kind of "activation" to the site, to see the true content. But how can i see it?

Thx!

Body:
I tried with selenium (download the driver that you would, in my case Chromedriver) and it works, you can get the full html source os the page and from here you can continue with the web scraping. I hope this helps you :)

from bs4 import BeautifulSoup
from selenium import webdriver

govts_url = r'https://knesset.gov.il/govt/eng/GovtByNumber_eng.asp'
exe_path = r'C:\Users\JRV\Desktop\WebCrawling/chromedriver.exe'

browser = webdriver.Chrome(exe_path)
browser.get(govts_url)
page = browser.page_source
browser.close()

soup = BeautifulSoup(page, 'html.parser')
print(f"HTML: \n {soup}")


问:
timeout has expired, giving up wake lock!
I have a doubt...i am not sure whether its some carelessness from my part.
I was using  mBitmap.compress(Bitmap.CompressFormat.PNG,100, out); to save a bitmap to png .
In the code the line beneath this code does not respond along with this.
Let me make it clear,
I have given Log.i(xy,xy); in all the alternating lines in the method to trace the issue, but all the Log until the line before mBitmap.compress(Bitmap.CompressFormat.PNG,100, out); prints and I have included the whole code in a try-catch, but no exception was caught. I have checked whether the parameter and the object were null, but no they are not. I am confused here..please help ...

Thanks in advance

Logcat

```<code>05-17 10:07:24.819: WARN/ActivityManager(73): Launch timeout has expired, giving up wake lock!
05-17 10:07:24.849: WARN/ActivityManager(73): Activity idle timeout for ActivityRecord{40968180 com.test.android.sk/.FPaint}
</code>```

Edit

```<code>    public String cReatePNG(){

        Log.i("cp1", "in the create png");

          try{
              Log.i("cp2", "in the create png");
              flag=true;
              DataBaseHelper  myDbHelper = new DataBaseHelper(this);

              String pattern= "dd-MM-yyyy-HHmmss"   ;
              SimpleDateFormat format = new SimpleDateFormat(pattern);
              String formattedDate = format.format(new Date());
            Log.i("cp3", "in the create png");
              tmpfile= CreateTempDir.createTempDir();

              File file = new File(Environment.getExternalStorageDirectory()
                + File.separator+"/SK_Temp/img-"+formattedDate+".png");

            try{

                Log.i("cp4", "in the create png"+file);
                  FileOutputStream  out = new FileOutputStream(file);
                Log.i("cp5", "in the create png");
                Log.i("view",out.toString());
                view.mBitmap.compress(Bitmap.CompressFormat.PNG,100,out); // <----issue with this line
             }catch(Exception e){ e.printStackTrace();}
                Log.i("CP#file_creation", "PNG file created");
                filename=file.toString();
            }catch(Exception e){e.printStackTrace();}
</code>```

答: The app could have exceeded the VM buget and ran out of memory..</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a doubt...i am not sure whether its some carelessness from my part.
I was using  mBitmap.compress(Bitmap.CompressFormat.PNG,100, out); to save a bitmap to png .
In the code the line beneath this code does not respond along with this.
Let me make it clear,
I have given Log.i(xy,xy); in all the alternating lines in the method to trace the issue, but all the Log until the line before mBitmap.compress(Bitmap.CompressFormat.PNG,100, out); prints and I have included the whole code in a try-catch, but no exception was caught. I have checked whether the parameter and the object were null, but no they are not. I am confused here..please help ...

Thanks in advance

Logcat

05-17 10:07:24.819: WARN/ActivityManager(73): Launch timeout has expired, giving up wake lock!
05-17 10:07:24.849: WARN/ActivityManager(73): Activity idle timeout for ActivityRecord{40968180 com.test.android.sk/.FPaint}

Edit

    public String cReatePNG(){

        Log.i("cp1", "in the create png");

          try{
              Log.i("cp2", "in the create png");
              flag=true;
              DataBaseHelper  myDbHelper = new DataBaseHelper(this);

              String pattern= "dd-MM-yyyy-HHmmss"   ;
              SimpleDateFormat format = new SimpleDateFormat(pattern);
              String formattedDate = format.format(new Date());
            Log.i("cp3", "in the create png");
              tmpfile= CreateTempDir.createTempDir();

              File file = new File(Environment.getExternalStorageDirectory()
                + File.separator+"/SK_Temp/img-"+formattedDate+".png");

            try{

                Log.i("cp4", "in the create png"+file);
                  FileOutputStream  out = new FileOutputStream(file);
                Log.i("cp5", "in the create png");
                Log.i("view",out.toString());
                view.mBitmap.compress(Bitmap.CompressFormat.PNG,100,out); // <----issue with this line
             }catch(Exception e){ e.printStackTrace();}
                Log.i("CP#file_creation", "PNG file created");
                filename=file.toString();
            }catch(Exception e){e.printStackTrace();}


问:
How to merge two arrays in JavaScript and remove the duplicate items?
I have two arrays

```<code>var array1 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];
var array2 = [{firstName:'Jen', age:29, email:'abc1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];
</code>```

I would like to merge the two arrays and get the below output

```<code>var array3 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}, {firstName: 'Jen', age: 29, email: 'abc1@email.com'}];
</code>```

Would like to know best way to merge two arrays in JavaScript so that I get only the unique items from each array?

答:
Answer

You can do this using Rest Operators, the Set Object and JSON methods:

```<code>[ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
</code>```

Example

var array1 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];
var array2 = [{firstName:'Jen', age:29, email:'abc1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];

function joinArrays(a1, a2) {
 return [ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
}

console.log(joinArrays(array1, array2));```
</div>
</div>
</p>

<h2>Explanation:</h2>

<p>You combine Arrays by using Rest Operators: </p>

```[...a1, ...a2]
```

<p>You turn the Objects into Strings with <code>JSON.stringify</code>:</p>

```[...a1, ...a2].map(JSON.stringify)
```

<p>You place these Strings into a <code>Set</code>. Sets do not allow duplicate Primitive Values( <em>strings, numbers, etc</em> )</p>

```new Set([...a1, ...a2].map(JSON.stringify))
```

<p>You use the Rest Operator to place the <code>Set</code> into an <code>Array</code></p>

```[...new Set([...a1, ...a2].map(JSON.stringify))]
```

<p>You map the Array using <code>JSON.parse</code> to turn the strings back into Objects, minus duplicates. </p>

```[ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
```

Body:
I have two arrays

var array1 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];
var array2 = [{firstName:'Jen', age:29, email:'abc1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];

I would like to merge the two arrays and get the below output

var array3 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}, {firstName: 'Jen', age: 29, email: 'abc1@email.com'}];

Would like to know best way to merge two arrays in JavaScript so that I get only the unique items from each array?

Body:
Answer

You can do this using Rest Operators, the Set Object and JSON methods:

[ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);

Example

var array1 = [{firstName:'John', age:32, email:'xyz1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];
var array2 = [{firstName:'Jen', age:29, email:'abc1@email.com'}, {firstName:'Jack', age:40, email:'xyz2@email.com'}];

function joinArrays(a1, a2) {
 return [ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);
}

console.log(joinArrays(array1, array2));

Explanation:

You combine Arrays by using Rest Operators:

[...a1, ...a2]

You turn the Objects into Strings with JSON.stringify:

[...a1, ...a2].map(JSON.stringify)

You place these Strings into a Set. Sets do not allow duplicate Primitive Values( strings, numbers, etc )

new Set([...a1, ...a2].map(JSON.stringify))

You use the Rest Operator to place the Set into an Array

[...new Set([...a1, ...a2].map(JSON.stringify))]

You map the Array using JSON.parse to turn the strings back into Objects, minus duplicates.

[ ...new Set([...a1, ...a2].map(JSON.stringify)) ].map(JSON.parse);


问:
Mount a volume in docker-compose conditionally
I have a docker-compose.yml configuration. In one of the containers there is a Tomcat server and it has some default .war file deployed in webapps directory.

I want to have an ability to pass (override) the war archive to be deployed by some which resides on the host machine. I think the best would be to have ability somehow switch / override starting docker-compose: as a default, I want to run the webapp (war file) which is inside the container, but I want to have a possibility to mount a directory from my host (for example during development / debugging) if need be.

Currently, I have the following line in my docker-compose.yml, which is commented out if I need the default.

```<code>volumes:
# By default, there is the latest version of the application already present in the container
# If you want to provider the container with your own .war file, uncomment the following line
# - ./application/webapps:/usr/local/tomcat/webapps
</code>```

Is there a better way how to achieve that?

答:
Since extend has been removed in version 3 there's a new way of overriding settings by providing multiple -f params where the next file extends the previous config

The docs are mixed between versions https://docs.docker.com/compose/extends/#multiple-compose-files

i.e. to run in development mode

```<code>docker-compose -f docker-compose.yml -f docker-compose.dev.yml
</code>```

Where docker-compose.yml contains the full config and docker-compose.dev.yml only adds a volume

```<code>services:
  serviceA:
    volumes:
      -.:/usr/local/abc/service
</code>```

Body:
I have a docker-compose.yml configuration. In one of the containers there is a Tomcat server and it has some default .war file deployed in webapps directory.

I want to have an ability to pass (override) the war archive to be deployed by some which resides on the host machine. I think the best would be to have ability somehow switch / override starting docker-compose: as a default, I want to run the webapp (war file) which is inside the container, but I want to have a possibility to mount a directory from my host (for example during development / debugging) if need be.

Currently, I have the following line in my docker-compose.yml, which is commented out if I need the default.

volumes:
# By default, there is the latest version of the application already present in the container
# If you want to provider the container with your own .war file, uncomment the following line
# - ./application/webapps:/usr/local/tomcat/webapps

Is there a better way how to achieve that?

Body:
Since extend has been removed in version 3 there's a new way of overriding settings by providing multiple -f params where the next file extends the previous config

The docs are mixed between versions https://docs.docker.com/compose/extends/#multiple-compose-files

i.e. to run in development mode

docker-compose -f docker-compose.yml -f docker-compose.dev.yml

Where docker-compose.yml contains the full config and docker-compose.dev.yml only adds a volume

services:
  serviceA:
    volumes:
      -.:/usr/local/abc/service


问:
Is there any issue with MAP in codes in R
I have a large database and I am not able to produce them here. I have two data databases as follows.

```<code>df1 <- read.table(text="A1  B1  C1  D1  E1
1234Z   721 224 223 987L
224 321 224 331 987L
321 321 224 441 141
321 440 456Y    331 141
321 1234Q   456Y    441 321
218 221 456Y    12A 321
218 440 19  223 321
161 1234Q   19  12A 123Q
1234Z   123Q    77  11A 123Q", header=TRUE)

df2 <- read.table(text=" BCG1   BCG2    BCG3    BCG4    BCG5
1   11  13  18  24
4   9   13  19  24
5   9   13  20  22
5   10  14  19  22
5   6   14  20  23
3   8   14  17  23
3   10  12  18  23
2   6   12  17  21
1   7   15  16  21", header=TRUE)
</code>```

Df1 are factors which are coded by df2. I have used the following code:

```<code>df3 <- do.call(cbind.fill, c(Map(function(x,y)
data.frame(col=x,col2=unique(y)),
lapply(df1,unique),split(df2, col(df2))))
names(df3)<-c(rbind(df1), paste0("Zo", seq_along((df1))))
</code>```

I wan to get  the following table

```<code>A1     BCG1   B1      BCG2   C1      BCG3    D1      BCG4    E1      BCG5
1234Z  1      721     11     224     13      223     18      987L    24
224    4      321     9      456Y    14      331     19      141     22
321    5      221     8      19      12      441     20      321     23
218    3      440     10     77      15      12A     17      123Q    21
161    2      1234Q   6                      11A     16
              123Q    7
</code>```

I am open to other codes. Thanks for your help

答:
Try the following.

```<code>library(dplyr)
library(purrr)

df3 <- c(df1, df2) %>%
  `[`(c(matrix(names(.), nrow = 2, byrow = T))) %>%
  map(~ as.character(unique(.))) %>%
  map_dfc(`[`, 1:max(lengths(.))) %>%
  mutate_all(coalesce, "")

# # A tibble: 6 x 10
#   A1    BCG1  B1    BCG2  C1    BCG3  D1    BCG4  E1    BCG5
#   <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
# 1 1234Z 1     721   11    224   13    223   18    987L  24
# 2 224   4     321   9     456Y  14    331   19    141   22
# 3 321   5     440   10    19    12    441   20    321   23
# 4 218   3     1234Q 6     77    15    12A   17    123Q  21
# 5 161   2     221   8     ""    ""    11A   16    ""    ""
# 6 ""    ""    123Q  7     ""    ""    ""    ""    ""    ""
</code>```

The outcome df3 is a tbl object and the empty character strings will be printed as "" by default. If you don't want to see the quotes, there are two choices:

as.data.frame(df3)

print.data.frame(df3)

The former coerces df3 from tbl to data.frame and the latter doesn't change the class of object.

The result will be

```<code>#      A1 BCG1    B1 BCG2   C1 BCG3  D1 BCG4   E1 BCG5
# 1 1234Z    1   721   11  224   13 223   18 987L   24
# 2   224    4   321    9 456Y   14 331   19  141   22
# 3   321    5   440   10   19   12 441   20  321   23
# 4   218    3 1234Q    6   77   15 12A   17 123Q   21
# 5   161    2   221    8           11A   16
# 6             123Q    7
</code>```

Body:
I have a large database and I am not able to produce them here. I have two data databases as follows.

df1 <- read.table(text="A1  B1  C1  D1  E1
1234Z   721 224 223 987L
224 321 224 331 987L
321 321 224 441 141
321 440 456Y    331 141
321 1234Q   456Y    441 321
218 221 456Y    12A 321
218 440 19  223 321
161 1234Q   19  12A 123Q
1234Z   123Q    77  11A 123Q", header=TRUE)

df2 <- read.table(text=" BCG1   BCG2    BCG3    BCG4    BCG5
1   11  13  18  24
4   9   13  19  24
5   9   13  20  22
5   10  14  19  22
5   6   14  20  23
3   8   14  17  23
3   10  12  18  23
2   6   12  17  21
1   7   15  16  21", header=TRUE)

Df1 are factors which are coded by df2. I have used the following code:

df3 <- do.call(cbind.fill, c(Map(function(x,y)
data.frame(col=x,col2=unique(y)),
lapply(df1,unique),split(df2, col(df2))))
names(df3)<-c(rbind(df1), paste0("Zo", seq_along((df1))))

I wan to get  the following table

A1     BCG1   B1      BCG2   C1      BCG3    D1      BCG4    E1      BCG5
1234Z  1      721     11     224     13      223     18      987L    24
224    4      321     9      456Y    14      331     19      141     22
321    5      221     8      19      12      441     20      321     23
218    3      440     10     77      15      12A     17      123Q    21
161    2      1234Q   6                      11A     16
              123Q    7

I am open to other codes. Thanks for your help

Body:
Try the following.

library(dplyr)
library(purrr)

df3 <- c(df1, df2) %>%
  `[`(c(matrix(names(.), nrow = 2, byrow = T))) %>%
  map(~ as.character(unique(.))) %>%
  map_dfc(`[`, 1:max(lengths(.))) %>%
  mutate_all(coalesce, "")

# # A tibble: 6 x 10
#   A1    BCG1  B1    BCG2  C1    BCG3  D1    BCG4  E1    BCG5
#   <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
# 1 1234Z 1     721   11    224   13    223   18    987L  24
# 2 224   4     321   9     456Y  14    331   19    141   22
# 3 321   5     440   10    19    12    441   20    321   23
# 4 218   3     1234Q 6     77    15    12A   17    123Q  21
# 5 161   2     221   8     ""    ""    11A   16    ""    ""
# 6 ""    ""    123Q  7     ""    ""    ""    ""    ""    ""

The outcome df3 is a tbl object and the empty character strings will be printed as "" by default. If you don't want to see the quotes, there are two choices:

as.data.frame(df3)

print.data.frame(df3)

The former coerces df3 from tbl to data.frame and the latter doesn't change the class of object.

The result will be

#      A1 BCG1    B1 BCG2   C1 BCG3  D1 BCG4   E1 BCG5
# 1 1234Z    1   721   11  224   13 223   18 987L   24
# 2   224    4   321    9 456Y   14 331   19  141   22
# 3   321    5   440   10   19   12 441   20  321   23
# 4   218    3 1234Q    6   77   15 12A   17 123Q   21
# 5   161    2   221    8           11A   16
# 6             123Q    7


问:
Animating the letters in a word w the app opens - SwiftUI
I'm trying to get a dancing letters effect when my app first opens.

I'm close. The coding below almost does what I want. I use a ForEach loop to loop through the letters of the word and apply an animation to each letter. And I use the onAppear function to set the drag amount when the app opens.

With this coding I can get the 'forward' motion but I can't get the animation to reverse so that the letters end up in their original position. I've tried adding a repeat with reverse, but, again, the letters never return to their original position

Does anyone have any idea how to do this?

```<code>struct ContentView: View {
  let letters = Array("Math Fun!")
  @State private var enabled = false
  @State private var dragAmount = CGSize.zero

  var body: some View {
    HStack(spacing: 0) {
      ForEach(0..<letters.count) { num in
        Text(String(self.letters[num]))
          .padding(5)
          .font(.title)
          .background(self.enabled ? Color.blue : Color.red)
          .offset(self.dragAmount)
          .animation(Animation.default.delay(Double(num)/20).repeatCount(3, autoreverses: true))
      }
    }
    .onAppear {
      self.dragAmount = CGSize(width: 0, height: 80)
      self.enabled.toggle()
    }
  }

}
</code>```

答:
You can use AnimatableModifier to achieve this effect. here is a sample code:

extension Double {
    var rad: Double { return self * .pi / 180 }
    var deg: Double { return self * 180 / .pi }
}

struct ContentView: View {
    @State private var flag = false

    var body: some View {
        VStack {
            Spacer()
            Color.clear.overlay(WaveText("Your Text That Need Animate", waveWidth: 6, pct: flag ? 1.0 : 0.0).foregroundColor(.blue)).frame(height: 40)
            Spacer()
        }.onAppear {
            withAnimation(Animation.easeInOut(duration: 2.0).repeatForever()) {
                self.flag.toggle()
            }
        }
    }
}

struct WaveText: View {
    let text: String
    let pct: Double
    let waveWidth: Int
    var size: CGFloat

    init(_ text: String, waveWidth: Int, pct: Double, size: CGFloat = 34) {
        self.text = text
        self.waveWidth = waveWidth
        self.pct = pct
        self.size = size
    }

    var body: some View {
        Text(text).foregroundColor(Color.clear).modifier(WaveTextModifier(text: text, waveWidth: waveWidth, pct: pct, size: size))
    }

    struct WaveTextModifier: AnimatableModifier {
        let text: String
        let waveWidth: Int
        var pct: Double
        var size: CGFloat

        var animatableData: Double {
            get { pct }
            set { pct = newValue }
        }

        func body(content: Content) -> some View {

            HStack(spacing: 0) {
                ForEach(Array(text.enumerated()), id: \.0) { (n, ch) in
                    Text(String(ch))
                        .scaleEffect(self.effect(self.pct, n, self.text.count, Double(self.waveWidth)))
                }
            }
        }

        func effect(_ pct: Double, _ n: Int, _ total: Int, _ waveWidth: Double) -> CGFloat {
            let n = Double(n)
            let total = Double(total)

            return CGFloat(1 + valueInCurve(pct: pct, total: total, x: n/total, waveWidth: waveWidth))
        }

        func valueInCurve(pct: Double, total: Double, x: Double, waveWidth: Double) -> Double {
            let chunk = waveWidth / total
            let m = 1 / chunk
            let offset = (chunk - (1 / total)) * pct
            let lowerLimit = (pct - chunk) + offset
            let upperLimit = (pct) + offset

            guard x >= lowerLimit && x < upperLimit else { return 0 }

            let angle = ((x - pct - offset) * m)*360-90

            return (sin(angle.rad) + 1) / 2
        }
    }
}

```

You can find refrence and compelete answer here

Body:
I'm trying to get a dancing letters effect when my app first opens.

I'm close. The coding below almost does what I want. I use a ForEach loop to loop through the letters of the word and apply an animation to each letter. And I use the onAppear function to set the drag amount when the app opens.

With this coding I can get the 'forward' motion but I can't get the animation to reverse so that the letters end up in their original position. I've tried adding a repeat with reverse, but, again, the letters never return to their original position

Does anyone have any idea how to do this?

struct ContentView: View {
  let letters = Array("Math Fun!")
  @State private var enabled = false
  @State private var dragAmount = CGSize.zero

  var body: some View {
    HStack(spacing: 0) {
      ForEach(0..<letters.count) { num in
        Text(String(self.letters[num]))
          .padding(5)
          .font(.title)
          .background(self.enabled ? Color.blue : Color.red)
          .offset(self.dragAmount)
          .animation(Animation.default.delay(Double(num)/20).repeatCount(3, autoreverses: true))
      }
    }
    .onAppear {
      self.dragAmount = CGSize(width: 0, height: 80)
      self.enabled.toggle()
    }
  }

}

Body:
You can use AnimatableModifier to achieve this effect. here is a sample code:

extension Double {
    var rad: Double { return self * .pi / 180 }
    var deg: Double { return self * 180 / .pi }
}

struct ContentView: View {
    @State private var flag = false

    var body: some View {
        VStack {
            Spacer()
            Color.clear.overlay(WaveText("Your Text That Need Animate", waveWidth: 6, pct: flag ? 1.0 : 0.0).foregroundColor(.blue)).frame(height: 40)
            Spacer()
        }.onAppear {
            withAnimation(Animation.easeInOut(duration: 2.0).repeatForever()) {
                self.flag.toggle()
            }
        }
    }
}

struct WaveText: View {
    let text: String
    let pct: Double
    let waveWidth: Int
    var size: CGFloat

    init(_ text: String, waveWidth: Int, pct: Double, size: CGFloat = 34) {
        self.text = text
        self.waveWidth = waveWidth
        self.pct = pct
        self.size = size
    }

    var body: some View {
        Text(text).foregroundColor(Color.clear).modifier(WaveTextModifier(text: text, waveWidth: waveWidth, pct: pct, size: size))
    }

    struct WaveTextModifier: AnimatableModifier {
        let text: String
        let waveWidth: Int
        var pct: Double
        var size: CGFloat

        var animatableData: Double {
            get { pct }
            set { pct = newValue }
        }

        func body(content: Content) -> some View {

            HStack(spacing: 0) {
                ForEach(Array(text.enumerated()), id: \.0) { (n, ch) in
                    Text(String(ch))
                        .scaleEffect(self.effect(self.pct, n, self.text.count, Double(self.waveWidth)))
                }
            }
        }

        func effect(_ pct: Double, _ n: Int, _ total: Int, _ waveWidth: Double) -> CGFloat {
            let n = Double(n)
            let total = Double(total)

            return CGFloat(1 + valueInCurve(pct: pct, total: total, x: n/total, waveWidth: waveWidth))
        }

        func valueInCurve(pct: Double, total: Double, x: Double, waveWidth: Double) -> Double {
            let chunk = waveWidth / total
            let m = 1 / chunk
            let offset = (chunk - (1 / total)) * pct
            let lowerLimit = (pct - chunk) + offset
            let upperLimit = (pct) + offset

            guard x >= lowerLimit && x < upperLimit else { return 0 }

            let angle = ((x - pct - offset) * m)*360-90

            return (sin(angle.rad) + 1) / 2
        }
    }
}

You can find refrence and compelete answer here


问:
xml parser problem in alexa using javascript
```<code>    var xml = require('XML-Parser-master');
        const fs = require('fs');
 var responseString = 'html string';

        var finalString="";

        var xmlDoc = new xml.DOM(xml.parse(responseString));

        const items =xmlDoc.document.getElementsByTagName("item");
        for (var i = 0; i < items.length ; i++) {
          const item = items[i];
          var name = (item.getElementsByTagName("name")[0]),
             status = (item.getElementsByTagName('status')[0]),
             device = (item.getElementsByTagName('device')[0]),
             probe = (item.getElementsByTagName('probe')[0]),
             message_raw = (item.getElementsByTagName('message_raw')[0]);

            finalString += "Il sensore "+name+ ", sul server "+device+ " del  "+probe+ " è nello stato"+status+". Il messaggio di errore è: "+ message_raw+". ";

        }

          });
           res.on('end', function(res)
            {
                const speechOutput = finalString;
                console.log("==> Answering: ",speechOutput);
                mythis.emit(':tell', speechOutput);
            });
</code>```

The proble is that it returns " [object Object] " when it should add a different string to  name,status,device,probe and message_raw.
Example:

il sensore [object Object], sul server [object Object] del  [object Object] è nello stato[object Object]. Il messaggio di errore è: undefined."
      }

parser used is : https://github.com/MauriceConrad/XML-Parser#readme

答:
After looking at the XML Parse module XML Parse npm module docs, it looks like you just need to set the variable to the text property of the object.

For example,

```<code>var name = (item.getElementsByTagName("name")[0]).text;
</code>```

Body:
    var xml = require('XML-Parser-master');
        const fs = require('fs');
 var responseString = 'html string';

        var finalString="";

        var xmlDoc = new xml.DOM(xml.parse(responseString));

        const items =xmlDoc.document.getElementsByTagName("item");
        for (var i = 0; i < items.length ; i++) {
          const item = items[i];
          var name = (item.getElementsByTagName("name")[0]),
             status = (item.getElementsByTagName('status')[0]),
             device = (item.getElementsByTagName('device')[0]),
             probe = (item.getElementsByTagName('probe')[0]),
             message_raw = (item.getElementsByTagName('message_raw')[0]);

            finalString += "Il sensore "+name+ ", sul server "+device+ " del  "+probe+ " è nello stato"+status+". Il messaggio di errore è: "+ message_raw+". ";

        }

          });
           res.on('end', function(res)
            {
                const speechOutput = finalString;
                console.log("==> Answering: ",speechOutput);
                mythis.emit(':tell', speechOutput);
            });

The proble is that it returns " [object Object] " when it should add a different string to  name,status,device,probe and message_raw.
Example:

il sensore [object Object], sul server [object Object] del  [object Object] è nello stato[object Object]. Il messaggio di errore è: undefined."
      }

parser used is : https://github.com/MauriceConrad/XML-Parser#readme

Body:
After looking at the XML Parse module XML Parse npm module docs, it looks like you just need to set the variable to the text property of the object.

For example,

var name = (item.getElementsByTagName("name")[0]).text;


问:
How to expand path in binary PowerShell module?
I'm writing a simple sample binary PowerShell module:

using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace MyModule
{
    [Cmdlet(VerbsDiagnostic.Test,"SampleCmdlet")]
    [OutputType(typeof(System.String))]
    public class TestSampleCmdletCommand : PSCmdlet
    {
        [Parameter(
            Mandatory = true,
            Position = 0,
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true)]
        public string Path { get; set; }

        // This method gets called once for each cmdlet in the pipeline when the pipeline starts executing
        protected override void BeginProcessing()
        {
            WriteVerbose("Begin!");
        }

        // This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called
        protected override void ProcessRecord()
        {
            WriteObject( Path );
            WriteObject( System.IO.Path.GetFullPath(Path) );
        }

        // This method will be called once at the end of pipeline execution; if no input is received, this method is not called
        protected override void EndProcessing()
        {
            WriteVerbose("End!");
        }
    }

}
```

<p>When I import the module and run the code, GetFullPath() always returns a path relative to the user profile and not the real full path:</p>

```PS C:\Users\User\GitHub\MyModule\source\MyModule> Import-Module -Name .\bin\Debug\netstandard2.0\MyModule.dll
PS C:\Users\User\GitHub\MyModule\source\MyModule> cd \
PS C:\> Test-SampleCmdlet -Path .\Temp\
.\Temp\
C:\Users\User\Temp\
PS C:\>
```

How can I expand the path parameter properly?

答:
.NET methods use the process-wide current directory as reflected in Environment.CurrentDirectory, which is not the same as PowerShell's runspace-specific (thread-specific) current location.[1]

You cannot directly rely on System.IO.Path.GetFullPath(), at least not without also specifying the runspace's current file-system location as the optional 2nd basePath argument - which is only available in .NET Core / PowerShell [Core] 6+.

To robustly refer to the calling runspace's current file-system location, even when a different provider's location happens to be the current one[2], you can use .CurrentProviderLocation("FileSystem").ProviderPath as follows in PowerShell [Core] 6+ / .NET Core (Path is the property representing the cmdlet's -Path parameter, i.e. the input path):

```<code># Get the runspace's file-system location.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# .NET Core ONLY: Resolve the given path to a full path as a native path.
#                 relative to the given base path.
string fullPath = System.IO.Path.GetFullPath(Path, currentDir);
</code>```

In Windows PowerShell more work is needed:

```<code># Get the runspace's file-system location as a native path.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# Requires `using System.Text.RegularExpressions;`
# Strips a ".\" or "./" prefix from a relative path.
string relativePathWithoutPrefix = Regex.Replace(Path, @"^.[\\/]", "")

# Caveat: Combine() will not resolve any additional, *interior* .
#         or .. components, should they be present in relativePathWithoutPrefix.
string fullPath = System.IO.Path.Combine(currentDir, relativePathWithoutPrefix);
</code>```

Both methods will pass a Path value that already is a full path through.

Note:

The resulting path is by design a native file-system path, even if the runspace's current file-system location is based on a PowerShell-only drive (created with New-PSDrive).

The approach implies that your cmdlet supports file-system paths only.

For information about how to work with PS provider locations more generally, including wildcard resolution, see this answer.

[1] This discrepancy is an unfortunate side effect of PowerShell supporting multiple runspaces (threads) inside a single process, all of which need to have their own current location - see this GitHub issue for background information.

[2] For instance, the runspace's current location may be a registry location such as HKCU:\Console.

Body:
I'm writing a simple sample binary PowerShell module:

using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace MyModule
{
    [Cmdlet(VerbsDiagnostic.Test,"SampleCmdlet")]
    [OutputType(typeof(System.String))]
    public class TestSampleCmdletCommand : PSCmdlet
    {
        [Parameter(
            Mandatory = true,
            Position = 0,
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true)]
        public string Path { get; set; }

        // This method gets called once for each cmdlet in the pipeline when the pipeline starts executing
        protected override void BeginProcessing()
        {
            WriteVerbose("Begin!");
        }

        // This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called
        protected override void ProcessRecord()
        {
            WriteObject( Path );
            WriteObject( System.IO.Path.GetFullPath(Path) );
        }

        // This method will be called once at the end of pipeline execution; if no input is received, this method is not called
        protected override void EndProcessing()
        {
            WriteVerbose("End!");
        }
    }

}

When I import the module and run the code, GetFullPath() always returns a path relative to the user profile and not the real full path:

PS C:\Users\User\GitHub\MyModule\source\MyModule> Import-Module -Name .\bin\Debug\netstandard2.0\MyModule.dll
PS C:\Users\User\GitHub\MyModule\source\MyModule> cd \
PS C:\> Test-SampleCmdlet -Path .\Temp\
.\Temp\
C:\Users\User\Temp\
PS C:\>

How can I expand the path parameter properly?

Body:
.NET methods use the process-wide current directory as reflected in Environment.CurrentDirectory, which is not the same as PowerShell's runspace-specific (thread-specific) current location.[1]

You cannot directly rely on System.IO.Path.GetFullPath(), at least not without also specifying the runspace's current file-system location as the optional 2nd basePath argument - which is only available in .NET Core / PowerShell [Core] 6+.

To robustly refer to the calling runspace's current file-system location, even when a different provider's location happens to be the current one[2], you can use .CurrentProviderLocation("FileSystem").ProviderPath as follows in PowerShell [Core] 6+ / .NET Core (Path is the property representing the cmdlet's -Path parameter, i.e. the input path):

# Get the runspace's file-system location.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# .NET Core ONLY: Resolve the given path to a full path as a native path.
#                 relative to the given base path.
string fullPath = System.IO.Path.GetFullPath(Path, currentDir);

In Windows PowerShell more work is needed:

# Get the runspace's file-system location as a native path.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# Requires `using System.Text.RegularExpressions;`
# Strips a ".\" or "./" prefix from a relative path.
string relativePathWithoutPrefix = Regex.Replace(Path, @"^.[\\/]", "")

# Caveat: Combine() will not resolve any additional, *interior* .
#         or .. components, should they be present in relativePathWithoutPrefix.
string fullPath = System.IO.Path.Combine(currentDir, relativePathWithoutPrefix);

Both methods will pass a Path value that already is a full path through.

Note:

The resulting path is by design a native file-system path, even if the runspace's current file-system location is based on a PowerShell-only drive (created with New-PSDrive).

The approach implies that your cmdlet supports file-system paths only.

For information about how to work with PS provider locations more generally, including wildcard resolution, see this answer.

[1] This discrepancy is an unfortunate side effect of PowerShell supporting multiple runspaces (threads) inside a single process, all of which need to have their own current location - see this GitHub issue for background information.

[2] For instance, the runspace's current location may be a registry location such as HKCU:\Console.


问:
Use pipe on bindLabel at <ng-select>
```<code><ng-select
    [items]="prozessItem$ | async"
    [multiple]="true"
    bindLabel="itemName | umlautsPipe"
    bindValue="nrItems"
></ng-select>
</code>```

I want to pipe the itemName from "üäößTEST" to "ueaeoessTest". The async pipe works just fine and without the pipe I get "üäößTEST". Ng-select only accepts a string value in the attribute. I may be misunderstanding it but I believe that when I use bindLabel="itemName | umlautsPipe", ng-select is attempting to reference item[itemName | umlautsPipe] which does not exist.

So how can I transform the name of the item?

答:
It seems like you have to use a template, try:</p>
```<code><ng-select
    [items]="prozessItem$ | async"
    [multiple]="true"
    bindValue="nrItems"
>
  <ng-template ng-option-tmp ng-label-tmp let-item="item">
      {{ item.itemName | umlautsPipe }}
   </ng-template>
</ng-select>
</code>```

Title: Use pipe on bindLabel at <ng-select>

Body:
<ng-select
    [items]="prozessItem$ | async"
    [multiple]="true"
    bindLabel="itemName | umlautsPipe"
    bindValue="nrItems"
></ng-select>

I want to pipe the itemName from "üäößTEST" to "ueaeoessTest". The async pipe works just fine and without the pipe I get "üäößTEST". Ng-select only accepts a string value in the attribute. I may be misunderstanding it but I believe that when I use bindLabel="itemName | umlautsPipe", ng-select is attempting to reference item[itemName | umlautsPipe] which does not exist.

So how can I transform the name of the item?

Body:
It seems like you have to use a template, try:

<ng-select
    [items]="prozessItem$ | async"
    [multiple]="true"
    bindValue="nrItems"
>
  <ng-template ng-option-tmp ng-label-tmp let-item="item">
      {{ item.itemName | umlautsPipe }}
   </ng-template>
</ng-select>


问:
Issue in SQL query full scanning twice?
Table A

```<code>ID    EmpNo   Grade
--------------------
1      100    HIGH
2      105    LOW
3      100    MEDIUM
4      100    LOW
5      105    LOW
</code>```

Query:

```<code>select *
from A
where EMPNO = 100
  and rownum <= 2
order by ID desc
</code>```

I tried this query to retrieve max and max-1 value; I need to compare the grade from max and max-1, if equals I need to set the flag as 'Y' or 'N' without using a cursor. Also I don't want to scan the entire record twice.

Please help me.

答:
ROWNUM is applied before ORDER BY, so you need to nest the query like this:

```<code>select * from
(select * from A where EMPNO =100 order by ID desc)
where rownum<=2
</code>```

That only performs one table scan (or it may use an index on EMPNO).

Title: Issue in SQL query full scanning twice?

Body:
Table A

ID    EmpNo   Grade
--------------------
1      100    HIGH
2      105    LOW
3      100    MEDIUM
4      100    LOW
5      105    LOW

Query:

select *
from A
where EMPNO = 100
  and rownum <= 2
order by ID desc

I tried this query to retrieve max and max-1 value; I need to compare the grade from max and max-1, if equals I need to set the flag as 'Y' or 'N' without using a cursor. Also I don't want to scan the entire record twice.

Please help me.

Body:
ROWNUM is applied before ORDER BY, so you need to nest the query like this:

select * from
(select * from A where EMPNO =100 order by ID desc)
where rownum<=2

That only performs one table scan (or it may use an index on EMPNO).


问:
Override eslint settings in non-ejected create-react-app?
I've found a ton of "solutions" for this, ranging from simple package.json additions to custom hack modules, but none worked for me.

I simply want to override the eslint settings for an out-of-the-box, NON ejected create-react-app.

Namely, the rule "no-unused-vars".

I'm using Visual Studio Code.

答:
its not hard, just follow these steps:

npm i -D eslint eslint-plugin-react

npx eslint --init

edit the generated config file, for example .eslintrc.json

put your rules in the "rules": { ... } section


问:
Heroku CLI error: unable to get local issuer certificate
I am behind in my company's firewall. We use a certificate file *.crt provided from our company to access SSL enabled web sites.

So I am getting unable to get local issuer certificate error when using heroku login.

I am using Windows 10 and Heroku CLI 7.14.1 and tried adding HEROKU_SSL_VERIFY=disable and SSL_CERT_FILE=C:\certificate.crt as environment variable but no success.

How can I solve that?

答:
Ask your organization network team to provide the ca cert or pem file. Once you have the cer or .pem file in your local computer, place it in some directory and set it in environment variable.

For example: I have .pem file placed in this location. 'C:\keys\xxx.pem'.
In environment variable i will add new system variable with below given name and value.

Variable Name: 'NODE_EXTRA_CA_CERTS'

Variable Value: 'C:\keys\xxx.pem'

Once the above steps are followed, open command prompt (close if you have one already opened) and try to enter 'heroku login' and press any key on your keyboard to take you to browser. It will take you to browser to authenticate your user credentials. If your organization has SSO enabled it will take care of itself if not you have to enter your heroku user credentials to authenticate. Once successfully authenticated, you will get back to command prompt with below messages.

Opening browser to 'https://cli-auth.heroku.com/auth/cli/browser/XXXXXXXX'

Logging in... done

Logged in as 'your user name appear here'

That's it.


问:
Why does file redirection succeed where cp/mv fail?
I'm trying to overwrite /etc/resolv.conf in a Docker container running Alpine Linux on EKS. Copy and move both fail:

~ # cp /tmp/resolv.conf /etc/resolv.conf
cp: can't create '/etc/resolv.conf': File exists
~ # mv /tmp/resolv.conf /etc/resolv.conf
mv: can't rename '/tmp/resolv.conf': Resource busy
```

<p>But shell redirection succeeds, and preserves the inode:</p>

<pre class="lang-sh prettyprint-override"><code>~ # ls -li /etc/resolv.conf
1412461 -rw-r--r--    1 root     root           131 Feb 17 20:45 /etc/resolv.conf
~ # cat /tmp/resolv.conf.1386 > /etc/resolv.conf
~ # ls -li /etc/resolv.conf
1412461 -rw-r--r--    1 root     root            39 Feb 18 19:17 /etc/resolv.conf
</code>```

Why does redirection succeed on a busy file?

答:
Redirection doesn't change the directory the file is contained in, whereas mv does. This is critical when -- as here -- your "directory entry" is actually a mount point, where the kernel is overriding a directory entry and not letting the usual contents be exposed.

That is:

What mv foo bar does

```<code>mv foo bar
</code>```

...is, at an operating system level, invoking the syscall rename("foo", "bar"), replacing the directory entry bar with the inode that the directory entry foo currently points at. It never opens or changes the preexisting bar file at all; the only thing it does is change the directory that previously contained that file to instead point at a different file in the entry with the same name.

What echo hello > bar does

By contrast, echo hello >bar isn't changing the directory entry at all; it's only changing the file that directory entry points at. Specifically, it's running open("bar", O_TRUNC), and write(<fdno>, "hello\n") to the file descriptor that open() returned.

So, what's cp doing?

...that's a good question. In general, cp modifies the existing file in-place. You can test that as follows:

```<code>echo ORIGINAL > file1
ln file1 file2
echo REPLACED > file3
cp file3 file1
cat file2
</code>```

If cp were replacing file1 with a completely new file, then the inode that file2 is associated with would be unchanged (containing "ORIGINAL"). That's not what happens, though -- file2 is modified by the cp that only directly identified file1 as its output file, changing that file to contain REPLACED.

I'd need to see the output of strace cp /tmp/resolv.conf /etc/resolv.conf to diagnose the behavior described.

Body:
I'm trying to overwrite /etc/resolv.conf in a Docker container running Alpine Linux on EKS. Copy and move both fail:

~ # cp /tmp/resolv.conf /etc/resolv.conf
cp: can't create '/etc/resolv.conf': File exists
~ # mv /tmp/resolv.conf /etc/resolv.conf
mv: can't rename '/tmp/resolv.conf': Resource busy

But shell redirection succeeds, and preserves the inode:

~ # ls -li /etc/resolv.conf
1412461 -rw-r--r--    1 root     root           131 Feb 17 20:45 /etc/resolv.conf
~ # cat /tmp/resolv.conf.1386 > /etc/resolv.conf
~ # ls -li /etc/resolv.conf
1412461 -rw-r--r--    1 root     root            39 Feb 18 19:17 /etc/resolv.conf

Why does redirection succeed on a busy file?

Body:
Redirection doesn't change the directory the file is contained in, whereas mv does. This is critical when -- as here -- your "directory entry" is actually a mount point, where the kernel is overriding a directory entry and not letting the usual contents be exposed.

That is:

What mv foo bar does

mv foo bar

...is, at an operating system level, invoking the syscall rename("foo", "bar"), replacing the directory entry bar with the inode that the directory entry foo currently points at. It never opens or changes the preexisting bar file at all; the only thing it does is change the directory that previously contained that file to instead point at a different file in the entry with the same name.

What echo hello > bar does

By contrast, echo hello >bar isn't changing the directory entry at all; it's only changing the file that directory entry points at. Specifically, it's running open("bar", O_TRUNC), and write(<fdno>, "hello\n") to the file descriptor that open() returned.

So, what's cp doing?

...that's a good question. In general, cp modifies the existing file in-place. You can test that as follows:

echo ORIGINAL > file1
ln file1 file2
echo REPLACED > file3
cp file3 file1
cat file2

If cp were replacing file1 with a completely new file, then the inode that file2 is associated with would be unchanged (containing "ORIGINAL"). That's not what happens, though -- file2 is modified by the cp that only directly identified file1 as its output file, changing that file to contain REPLACED.

I'd need to see the output of strace cp /tmp/resolv.conf /etc/resolv.conf to diagnose the behavior described.


问:
Is there a better way to accomplish this loop?
I'm pretty new with VBA, but I've been muddling through to make a program for my team.
This piece of code works most of the time, but tends to hang on occasion. I can't figure out why it would hang sometimes, and work perfectly most of the time, so I'm now trying to figure out a better way to accomplish this loop. I know that this method of looping isn't the best way to do things, but not sure how to accomplish the task.

My webpage operates in a PEGA Web application, and the native IE ready state indicators are always 'ready' so I have to use the web application's ready state markers.

Can anyone help me out?

```<code>Public Sub WaitingForRS()
' FIND THE C360 WINDOW
        Marker = 0
        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count
        For x = 0 To (IE_count - 1)
            On Error Resume Next
            my_url = objShell.Windows(x).Document.Location
            my_title = objShell.Windows(x).Document.title

            If my_title Like "Coverage User" & "*" Then
                Set C360Window = objShell.Windows(x)
                Marker = 1
                Exit For
            Else
            End If
        Next

        If Marker = 0 Then
            MsgBox ("C360 window is not found. Please ensure C360 is open in Internet Explorer and try again")
        Else
        End If

'FIND THE READY STATE INDICATOR
    RSIndicatorDocMarker = 0
    RSIndicatorDataMarker = 0
    Set RSIndicatorPage = C360Window.Document
    Set RSIndicatorClass = RSIndicatorPage.getelementsbyclassname("document-statetracker")(0)

RSIndicatorCheck:
'CHECK THE READY STATE DOC STATUS
    If RSIndicatorClass.getattribute("data-state-doc-status") = "ready" Then
        RSIndicatorDocMarker = 1
        Else: RSIndicatorDocMarker = 0
    End If

'CHECK THE READY STATE
    If RSIndicatorClass.getattribute("data-state-busy-status") = "none" Then
        RSIndicatorDataMarker = 1
        Else: RSIndicatorDataMarker = 0
    End If

'Compare the RSIndicators
    If RSIndicatorDataMarker = 1 And RSIndicatorDocMarker = 1 Then

    Else: GoTo RSIndicatorCheck
    End If
End Sub
</code>```

答:
Maybe try using OnTime instead of the tight loop you currently have:

```<code>Public Sub WaitingForRS()

    Dim win As Object
    Dim w As Object, el, ready As Boolean, idle As Boolean

    For Each w In CreateObject("Shell.Application").Windows
        If w.Name Like "*Internet*" Then
            If w.Title Like "Coverage user*" Then
                Set win = w
                Exit For
            End If
        End If
    Next

    If Not win Is Nothing Then

        Set el = win.document.getelementsbyclassname("document-statetracker")(0)
        ready = (el.getattribute("data-state-doc-status") = "ready")
        idle = (el.getattribute("data-state-busy-status") = "none")

        If ready And idle Then
            ProceedWithNextSteps win 'do whatever comes next: pass in the window
        Else
            'wait for a while then try again
            Application.OnTime Now + TimeSerial(0, 0, 1), "WaitingForRS"
        End If

    Else
        MsgBox "Window not found!"
    End If

End Sub
</code>```

Might want to add a time limit so it doesn't keep looping forever if the page isn't "ready".

Body:
I'm pretty new with VBA, but I've been muddling through to make a program for my team.
This piece of code works most of the time, but tends to hang on occasion. I can't figure out why it would hang sometimes, and work perfectly most of the time, so I'm now trying to figure out a better way to accomplish this loop. I know that this method of looping isn't the best way to do things, but not sure how to accomplish the task.

My webpage operates in a PEGA Web application, and the native IE ready state indicators are always 'ready' so I have to use the web application's ready state markers.

Can anyone help me out?

Public Sub WaitingForRS()
' FIND THE C360 WINDOW
        Marker = 0
        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count
        For x = 0 To (IE_count - 1)
            On Error Resume Next
            my_url = objShell.Windows(x).Document.Location
            my_title = objShell.Windows(x).Document.title

            If my_title Like "Coverage User" & "*" Then
                Set C360Window = objShell.Windows(x)
                Marker = 1
                Exit For
            Else
            End If
        Next

        If Marker = 0 Then
            MsgBox ("C360 window is not found. Please ensure C360 is open in Internet Explorer and try again")
        Else
        End If

'FIND THE READY STATE INDICATOR
    RSIndicatorDocMarker = 0
    RSIndicatorDataMarker = 0
    Set RSIndicatorPage = C360Window.Document
    Set RSIndicatorClass = RSIndicatorPage.getelementsbyclassname("document-statetracker")(0)

RSIndicatorCheck:
'CHECK THE READY STATE DOC STATUS
    If RSIndicatorClass.getattribute("data-state-doc-status") = "ready" Then
        RSIndicatorDocMarker = 1
        Else: RSIndicatorDocMarker = 0
    End If

'CHECK THE READY STATE
    If RSIndicatorClass.getattribute("data-state-busy-status") = "none" Then
        RSIndicatorDataMarker = 1
        Else: RSIndicatorDataMarker = 0
    End If

'Compare the RSIndicators
    If RSIndicatorDataMarker = 1 And RSIndicatorDocMarker = 1 Then

    Else: GoTo RSIndicatorCheck
    End If
End Sub

Body:
Maybe try using OnTime instead of the tight loop you currently have:

Public Sub WaitingForRS()

    Dim win As Object
    Dim w As Object, el, ready As Boolean, idle As Boolean

    For Each w In CreateObject("Shell.Application").Windows
        If w.Name Like "*Internet*" Then
            If w.Title Like "Coverage user*" Then
                Set win = w
                Exit For
            End If
        End If
    Next

    If Not win Is Nothing Then

        Set el = win.document.getelementsbyclassname("document-statetracker")(0)
        ready = (el.getattribute("data-state-doc-status") = "ready")
        idle = (el.getattribute("data-state-busy-status") = "none")

        If ready And idle Then
            ProceedWithNextSteps win 'do whatever comes next: pass in the window
        Else
            'wait for a while then try again
            Application.OnTime Now + TimeSerial(0, 0, 1), "WaitingForRS"
        End If

    Else
        MsgBox "Window not found!"
    End If

End Sub

Might want to add a time limit so it doesn't keep looping forever if the page isn't "ready".


问:
SQS maxNumberOfMessages
Using a Java client application I am querying an SQS queue for messages. The queue has 12,000 messages as setup for testing. I am using openJDK with aws-java-sdk latest (software.amazon.awssdk 2.10.62) pom.xml is shown further down.

The issue I am seeing is that despite setting the maxNumberOfMessages(10) I only ever get 3. I understand that it is a maximum not a guarantee of the number of messages however there is no waver in the number of messages returned. It is always 3.

AWS Documentation:  MaxNumberOfMessages
      The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be
  returned). Valid values: 1 to 10. Default: 1.
      Type: Integer
      Required: No

Consuming Messages Using Short Polling

When you consume messages from a queue using short polling, Amazon SQS
  samples a subset of its servers (based on a weighted random
  distribution) and returns messages from only those servers. Thus, a
  particular ReceiveMessage request might not return all of your
  messages. However, if you have fewer than 1,000 messages in your
  queue, a subsequent request will return your messages. If you keep
  consuming from your queues, Amazon SQS samples all of its servers, and
  you receive all of your messages.

So we have tested two clients in java using both the older aws sdk and the newer one with the same results. Always only 3 messages back.

Interestingly if instead of running the application externally (on my mighty desktop) you run it as an AWS Lambda you get 10 messages. This lambda test was done using JavaScript by a colleague.

So the question remains why do we only ever get 3 messages per request and seemingly within lambda you can get 10.

Given there is a cost per request is the weighted random distribution based on amazon profit =))

SQS Test Method:

```<code>public void SQStart()
{
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create("accessKeyID", "secretKeyID");
    AwsCredentialsProvider creds = StaticCredentialsProvider.create(awsCreds);
    SqsClient sqs = SqsClient.builder().credentialsProvider(creds).region(Region.EU_WEST_1).build();
    GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
            .queueName(QUEUE_NAME)
            .build();
    String queueUrl = sqs.getQueueUrl(getQueueRequest).queueUrl();

    for (int x =1; x < 100; x++) {
        ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .maxNumberOfMessages(10)
                .build();

        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).messages();
        if (messages.size() > 3 ) {
            System.out.println("YEY More than 3 Messages: "+ messages.size());
        }
    }
}
</code>```

POM.XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>SQSTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.10.62</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>

            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sqs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.720</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</project>
</code>```

答: I think this is a similar question.As pointed by Jacob , long polling seems to be the solution to the issue.</p>

Title: SQS maxNumberOfMessages

Body:
Using a Java client application I am querying an SQS queue for messages. The queue has 12,000 messages as setup for testing. I am using openJDK with aws-java-sdk latest (software.amazon.awssdk 2.10.62) pom.xml is shown further down.

The issue I am seeing is that despite setting the maxNumberOfMessages(10) I only ever get 3. I understand that it is a maximum not a guarantee of the number of messages however there is no waver in the number of messages returned. It is always 3.

AWS Documentation:  MaxNumberOfMessages
      The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be
  returned). Valid values: 1 to 10. Default: 1.
      Type: Integer
      Required: No

Consuming Messages Using Short Polling

When you consume messages from a queue using short polling, Amazon SQS
  samples a subset of its servers (based on a weighted random
  distribution) and returns messages from only those servers. Thus, a
  particular ReceiveMessage request might not return all of your
  messages. However, if you have fewer than 1,000 messages in your
  queue, a subsequent request will return your messages. If you keep
  consuming from your queues, Amazon SQS samples all of its servers, and
  you receive all of your messages.

So we have tested two clients in java using both the older aws sdk and the newer one with the same results. Always only 3 messages back.

Interestingly if instead of running the application externally (on my mighty desktop) you run it as an AWS Lambda you get 10 messages. This lambda test was done using JavaScript by a colleague.

So the question remains why do we only ever get 3 messages per request and seemingly within lambda you can get 10.

Given there is a cost per request is the weighted random distribution based on amazon profit =))

SQS Test Method:

public void SQStart()
{
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create("accessKeyID", "secretKeyID");
    AwsCredentialsProvider creds = StaticCredentialsProvider.create(awsCreds);
    SqsClient sqs = SqsClient.builder().credentialsProvider(creds).region(Region.EU_WEST_1).build();
    GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
            .queueName(QUEUE_NAME)
            .build();
    String queueUrl = sqs.getQueueUrl(getQueueRequest).queueUrl();

    for (int x =1; x < 100; x++) {
        ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .maxNumberOfMessages(10)
                .build();

        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).messages();
        if (messages.size() > 3 ) {
            System.out.println("YEY More than 3 Messages: "+ messages.size());
        }
    }
}

POM.XML:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>SQSTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.10.62</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>

            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sqs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.720</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</project>


问:
Create new column that takes the sum of another column values and group by condition in R
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

```<code>`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr
</code>```

Desired output would like something like this:

```<code>`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014
</code>```

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

答:
In dplyr, you usually are using summary functions to get another output. However, with group and ungroup, you can add a summary column.

```<code> newdf <- df %>%
    group_by(Building) %>%
    mutate(PopSum = sum(Population, na.rm=TRUE)) %>%
    ungroup()
</code>```

Body:
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr

Desired output would like something like this:

`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

Body:
In dplyr, you usually are using summary functions to get another output. However, with group and ungroup, you can add a summary column.

 newdf <- df %>%
    group_by(Building) %>%
    mutate(PopSum = sum(Population, na.rm=TRUE)) %>%
    ungroup()


问:
Woocommerce product rating only with stars
I am trying to make the woocommerce product rating only with stars. Therefore I need to remove the currently required fields name, email and comment.

I have accomplished to remove comment with this code

```<code><?php
function rei_preprocess_comment($comment_data) {
    if ($comment_data['comment_content'] == '%dummy-text%') {
        $comment_data['comment_content'] = ''; // replace dummy text.
    }
    return $comment_data;
}
add_filter('preprocess_comment', 'rei_preprocess_comment');
function rei_wp_footer() {
    ?>
    <script>
    jQuery(function($){
        var comment = $('textarea#comment');
        comment.removeAttr('required'); // remove required attribute of textarea.
        $('#commentform').on('submit',function(){
            if (comment.val() == '') {
                comment.css('text-indent','-999px').val('%dummy-text%'); // change to dummy text.
            }
        });
    });
    </script>
    <?php
}
add_action( 'wp_footer', 'rei_wp_footer' );
?>
</code>```

However I am not being able to remove the required name and email field so unregistered user can enter the star product rating.

Please help

答: This is an option in Wordpress go to Settings > Discussion  and look for the required email and name setting. Remove the checkmark and save the settings page.</p>

Body:
I am trying to make the woocommerce product rating only with stars. Therefore I need to remove the currently required fields name, email and comment.

I have accomplished to remove comment with this code

<?php
function rei_preprocess_comment($comment_data) {
    if ($comment_data['comment_content'] == '%dummy-text%') {
        $comment_data['comment_content'] = ''; // replace dummy text.
    }
    return $comment_data;
}
add_filter('preprocess_comment', 'rei_preprocess_comment');
function rei_wp_footer() {
    ?>

    <?php
}
add_action( 'wp_footer', 'rei_wp_footer' );
?>

However I am not being able to remove the required name and email field so unregistered user can enter the star product rating.

Please help


问:
How to stop EditText showing javascript after Android HtmlCompat.fromHtml() creates a Spanned
I have an EditText in my view. I am using HtmlCompat.fromHtml() to show the contents of an email in this EditText so it can be viewed and edited. If the html contains any JavaScript then it is being rendered in the resulting Spanned.

If I have the following (example) code:

```<code>String htmlString = "<html>\n" +
    "\n" +
    "<head>\n" +
    "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
    "    <script type=\"text/javascript\">\n" +
    "        alert(\"This should not appear in the EditText\");\n" +
    "    </script>\n" +
    "</head>\n" +
    "\n" +
    "<body style=\"margin: 0;padding: 0;box-sizing: border-box;-webkit-font-smoothing: antialiased;-webkit-text-size-adjust: none;width: 100% !important;height: 100% !important;line-height: 1.6;margin-top: 0 !important;margin-left: 0 !important;margin-right: 0 !important\" class=\"\">\n" +
    "    <div dir=\"auto\">Technician booked for tomorrow morning\n" +
    "        <br>\n" +
    "        <br>\n" +
    "    </div>\n" +
    "    <div dir=\"auto\">\n" +
    "        <a href=\"http://www.bluemail.me/r?b=15726\"></a>\n" +
    "    </div>\n" +
    "</body>\n" +
    "\n" +
    "</html>";

emailTextView.setText(HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT));
</code>```

then the EditText shows the contents of  I would have expected it to be removed/hidden. But I get:

Is there any way to stop this or is there some other way to have html from an email rendered in an EditText for editing? I know that Gmail can do it on Android, but I can't see how it was done?

答:
In case anyone is interested, the java version of @Cheticamp's answer that I came up with was:</p>

```<code>Html.ImageGetter imageGetter = new PicassoImageGetter(textView);
textView.setText(HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT, imageGetter, new Html.TagHandler() {

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        if (!tag.equals("script")) {
            return;
        }
        if (opening) {
            output.setSpan(new DeleteScriptTagContent(), output.length(), output.length(), Spannable.SPAN_MARK_POINT);
        } else {
            Object[] spans = output.getSpans(0, output.length(), DeleteScriptTagContent.class);
            if (spans.length == 0) {
                return;
            }
            Object lastSpan = spans[spans.length - 1];
            int startIndex = output.getSpanStart(lastSpan);
            int endIndex = output.getSpanEnd(lastSpan);
            if (startIndex == -1 || endIndex == -1) {
                return;
            }
            output.delete(startIndex, endIndex);
        }
    }

    class DeleteScriptTagContent {
    }
}));
textView.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

Body:
I have an EditText in my view. I am using HtmlCompat.fromHtml() to show the contents of an email in this EditText so it can be viewed and edited. If the html contains any JavaScript then it is being rendered in the resulting Spanned.

If I have the following (example) code:

String htmlString = "\n" +
    "\n" +
    "\n" +
    "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
    "    \n" +
    "\n" +
    "\n" +
    "\n" +
    "
Technician booked for tomorrow morning\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "        \n" +
    "
\n" +
    "\n" +
    "\n" +
    "";

emailTextView.setText(HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT));

then the EditText shows the contents of  I would have expected it to be removed/hidden. But I get:

Is there any way to stop this or is there some other way to have html from an email rendered in an EditText for editing? I know that Gmail can do it on Android, but I can't see how it was done?

Body:
In case anyone is interested, the java version of @Cheticamp's answer that I came up with was:

Html.ImageGetter imageGetter = new PicassoImageGetter(textView);
textView.setText(HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT, imageGetter, new Html.TagHandler() {

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        if (!tag.equals("script")) {
            return;
        }
        if (opening) {
            output.setSpan(new DeleteScriptTagContent(), output.length(), output.length(), Spannable.SPAN_MARK_POINT);
        } else {
            Object[] spans = output.getSpans(0, output.length(), DeleteScriptTagContent.class);
            if (spans.length == 0) {
                return;
            }
            Object lastSpan = spans[spans.length - 1];
            int startIndex = output.getSpanStart(lastSpan);
            int endIndex = output.getSpanEnd(lastSpan);
            if (startIndex == -1 || endIndex == -1) {
                return;
            }
            output.delete(startIndex, endIndex);
        }
    }

    class DeleteScriptTagContent {
    }
}));
textView.setMovementMethod(LinkMovementMethod.getInstance());


问:
How do you write a sequence as a vector?
I have a vector "I" which we can take for example to be (0,1,2,3.....) till an unknown length. I want to create a vector such that x^(I-1) so it will be a vector that looks like (0,x,x^2...).
However I do not know how to write this code and I tried (x^I-1) alone doesn't work. </p>

答:
You can use seq(l) to construct a l-length vector from 1 to l as powers. Since you are pursuing a start from 0, so you can use seq(l)-1.

Then, you choose a value of x, and generate the desired vector via

```<code>x**(seq(l)-1)
</code>```

If you have x and l as variables, you can define your custom sequence generator like below

```<code>vgen <- function(x,l)  x**(seq(l)-1)
</code>```

and use it like

```<code>> vgen(3,7)
[1]   1   3   9  27  81 243 729
</code>```

Body:
You can use seq(l) to construct a l-length vector from 1 to l as powers. Since you are pursuing a start from 0, so you can use seq(l)-1.

Then, you choose a value of x, and generate the desired vector via

x**(seq(l)-1)

If you have x and l as variables, you can define your custom sequence generator like below

vgen <- function(x,l)  x**(seq(l)-1)

and use it like

> vgen(3,7)
[1]   1   3   9  27  81 243 729


问:
Post to Facebook wall/feed using AJAX/jQuery
pulling my hair out over this one.

I'm writing a Facebook-connected web app that will ultimately post some arbitrary information to the walls of friends that are selected throughout the process.

I'm in the final stages now and was hoping that posting to the walls would be simple, but I've spent far too long trying to figure this out now so I'm hoping someone can help me.

I'm trying to post using ajax like so:

```<code>$.ajax({
    type: 'POST',
    url: "https://graph.facebook.com/bbeckford/feed",
    data: {message: wallMessage, target_id: friendID, access_token: "<?= $cookie['access_token'] ?>", format: "json"},
    success: function(data) { alert(data); },
    dataType: "JSON"
});
</code>```

But I just keep getting this error: "XMLHttpRequest cannot load https://graph.facebook.com/bbeckford/feed. Origin http://www.secretsantasetup.com is not allowed by Access-Control-Allow-Origin."

I've done searches and one suggestion is to make a php proxy, is that a viable option? How would I go about doing that?

Am I approaching this completely wrong??

Any help would be greatly appreciated,
Thanks,
-Ben

EDIT
I want to do this in the background, ie user has selected 10 friends for example, then on submit the app will loop through each friend and post something on their wall. Is this possible?
Thanks!

EDIT 2
The test console at the bottom of the following page does exactly what I want to do, but there is no source code? - http://developers.facebook.com/docs/reference/rest/stream.publish

答:
I'm not sure where did I heard this, but:

```<code>jQuery.getJSON("https://graph.facebook.com/"+therequestid+"/?callback=?&access_token="+access_token,{},
           function(data, textStatus, jqXHR){
                          //bla-bla
           }
       );
</code>```

Should work, where you need to add "?callback=?" stuff. I do not know why did this work. But, as long as it works, I'll stay happy.

ContentLicense: CC BY-SA 2.5

Body:
pulling my hair out over this one.

I'm writing a Facebook-connected web app that will ultimately post some arbitrary information to the walls of friends that are selected throughout the process.

I'm in the final stages now and was hoping that posting to the walls would be simple, but I've spent far too long trying to figure this out now so I'm hoping someone can help me.

I'm trying to post using ajax like so:

$.ajax({
    type: 'POST',
    url: "https://graph.facebook.com/bbeckford/feed",
    data: {message: wallMessage, target_id: friendID, access_token: "<?= $cookie['access_token'] ?>", format: "json"},
    success: function(data) { alert(data); },
    dataType: "JSON"
});

But I just keep getting this error: "XMLHttpRequest cannot load https://graph.facebook.com/bbeckford/feed. Origin http://www.secretsantasetup.com is not allowed by Access-Control-Allow-Origin."

I've done searches and one suggestion is to make a php proxy, is that a viable option? How would I go about doing that?

Am I approaching this completely wrong??

Any help would be greatly appreciated,
Thanks,
-Ben

EDIT
I want to do this in the background, ie user has selected 10 friends for example, then on submit the app will loop through each friend and post something on their wall. Is this possible?
Thanks!

EDIT 2
The test console at the bottom of the following page does exactly what I want to do, but there is no source code? - http://developers.facebook.com/docs/reference/rest/stream.publish

Body:
I'm not sure where did I heard this, but:

jQuery.getJSON("https://graph.facebook.com/"+therequestid+"/?callback=?&access_token="+access_token,{},
           function(data, textStatus, jqXHR){
                          //bla-bla
           }
       );

Should work, where you need to add "?callback=?" stuff. I do not know why did this work. But, as long as it works, I'll stay happy.