答:
marioosh's answer seems to on the right track. It didn't work for me.
So I found:

Problems connecting via HTTPS/SSL through own Java client

which uses:

```<code>java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
</code>```

Which seems to be necessary with Java 7 and a TLSv1.2 site.

I checked the site with:

```<code>openssl s_client -connect www.st.nmfs.noaa.gov:443
</code>```

using

```<code>openssl version
OpenSSL 1.0.2l  25 May 2017
</code>```

and got the result:

```<code>...
SSL-Session:
   Protocol  : TLSv1.2
   Cipher    : ECDHE-RSA-AES256-GCM-SHA384
...
</code>```

Please note that and older openssl version on my mac did not work and I had to use the macports one.

Body:
Has anyone encountered this error before?  I'm new to SSL, is there anything obviously wrong with my ClientHello that I'm missing?  That exception is thrown with no ServerHello response.  Any advice is appreciated.

*** ClientHello, TLSv1
RandomCookie:  GMT: 1351745496 bytes = { 154, 151, 225, 128, 127, 137, 198, 245, 160, 35, 124, 13, 135, 120, 33, 240, 82, 223, 56, 25, 207, 231, 231, 124, 103, 205, 66, 218 }
Session ID:  {}
Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
***
[write] MD5 and SHA1 hashes:  len = 75
0000: 01 00 00 47 03 01 51 92   00 D8 9A 97 E1 80 7F 89  ...G..Q.........
0010: C6 F5 A0 23 7C 0D 87 78   21 F0 52 DF 38 19 CF E7  ...#...x!.R.8...
0020: E7 7C 67 CD 42 DA 00 00   20 00 04 00 05 00 2F 00  ..g.B... ...../.
0030: 33 00 32 00 0A 00 16 00   13 00 09 00 15 00 12 00  3.2.............
0040: 03 00 08 00 14 00 11 00   FF 01 00                 ...........
xxx, WRITE: TLSv1 Handshake, length = 75
[write] MD5 and SHA1 hashes:  len = 101
0000: 01 03 01 00 3C 00 00 00   20 00 00 04 01 00 80 00  ....<... .......
0010: 00 05 00 00 2F 00 00 33   00 00 32 00 00 0A 07 00  ..../..3..2.....
0020: C0 00 00 16 00 00 13 00   00 09 06 00 40 00 00 15  ............@...
0030: 00 00 12 00 00 03 02 00   80 00 00 08 00 00 14 00  ................
0040: 00 11 00 00 FF 51 92 00   D8 9A 97 E1 80 7F 89 C6  .....Q..........
0050: F5 A0 23 7C 0D 87 78 21   F0 52 DF 38 19 CF E7 E7  ..#...x!.R.8....
0060: 7C 67 CD 42 DA                                     .g.B.
xxx, WRITE: SSLv2 client hello message, length = 101
[Raw write]: length = 103
0000: 80 65 01 03 01 00 3C 00   00 00 20 00 00 04 01 00  .e....<... .....
0010: 80 00 00 05 00 00 2F 00   00 33 00 00 32 00 00 0A  ....../..3..2...
0020: 07 00 C0 00 00 16 00 00   13 00 00 09 06 00 40 00  ..............@.
0030: 00 15 00 00 12 00 00 03   02 00 80 00 00 08 00 00  ................
0040: 14 00 00 11 00 00 FF 51   92 00 D8 9A 97 E1 80 7F  .......Q........
0050: 89 C6 F5 A0 23 7C 0D 87   78 21 F0 52 DF 38 19 CF  ....#...x!.R.8..
0060: E7 E7 7C 67 CD 42 DA                               ...g.B.
[Raw read]: length = 5
0000: 15 03 01 00 02                                     .....
[Raw read]: length = 2
0000: 02 46                                              .F

{http://xml.apache.org/axis/}stackTrace:

javax.net.ssl.SSLException: Received fatal alert: protocol_version
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:136)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1806)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:986)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
at

...

Body:
marioosh's answer seems to on the right track. It didn't work for me.
So I found:

Problems connecting via HTTPS/SSL through own Java client

which uses:

java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");

Which seems to be necessary with Java 7 and a TLSv1.2 site.

I checked the site with:

openssl s_client -connect www.st.nmfs.noaa.gov:443

using

openssl version
OpenSSL 1.0.2l  25 May 2017

and got the result:

...
SSL-Session:
   Protocol  : TLSv1.2
   Cipher    : ECDHE-RSA-AES256-GCM-SHA384
...

Please note that and older openssl version on my mac did not work and I had to use the macports one.


来源: stackexchange

问:
Fill matrix by data from pandas.DataFrame, skip NaN
I want to fill the matrix ref using pd.DataFrame xxx but skip the NaN.

```<code>print xxx
OUT >>
   intensity name  rowtype1  rowtype2
0        100    A         1       4.0
1        200    A         2       NaN
2        300    B         3       5.0
</code>```

Then I fill the matrix by ref[rowtype,col] = intensity where I have 2 rowtype.

```<code>ref = np.zeros(shape=(7,4))
for idx, inte, name, r1, r2 in xxx.itertuples():
    ref[r1,idx] = inte
    ref[r2,idx] = inte # error because of NaN in rowtype2

print ref
</code>```

How can I skip NaN here?
I know one way to use drop.na() but it has to create new dataframe which has rowtype2 and intensity. I would like to have quick simple way, like just jump across NaN with intensity = 200 to next rowtype2 = 5 with intensity = 300.

Additional info:

1) Here is how to create xxx

```<code>prot = ['A','A','B']
calc_m = [1,2,3]
calc_m2 = [4, np.nan,5]
inte = [100,200,300]
xxx = pd.DataFrame({'name' : pd.Series(prot),
                    'rowtype1': pd.Series(calc_m),
                    'rowtype2': pd.Series(calc_m2),
                    'intensity': pd.Series(inte)
                    })
</code>```

答:
I'm not sure I fully understand what behavior you are looking for, but the pandas dropna() command has the "subset" argument... for example, dropping all rows with NaN in the rowtype2 column could be done with

```<code>xxx.dropna(subset=['rowtype2'],inplace=True)
</code>```

That way, you would drop only rows with NaN in the rowtype2 column.

ContentLicense: CC BY-SA 3.0

Body:
I want to fill the matrix ref using pd.DataFrame xxx but skip the NaN.

print xxx
OUT >>
   intensity name  rowtype1  rowtype2
0        100    A         1       4.0
1        200    A         2       NaN
2        300    B         3       5.0

Then I fill the matrix by ref[rowtype,col] = intensity where I have 2 rowtype.

ref = np.zeros(shape=(7,4))
for idx, inte, name, r1, r2 in xxx.itertuples():
    ref[r1,idx] = inte
    ref[r2,idx] = inte # error because of NaN in rowtype2

print ref

How can I skip NaN here?
I know one way to use drop.na() but it has to create new dataframe which has rowtype2 and intensity. I would like to have quick simple way, like just jump across NaN with intensity = 200 to next rowtype2 = 5 with intensity = 300.

Additional info:

1) Here is how to create xxx

prot = ['A','A','B']
calc_m = [1,2,3]
calc_m2 = [4, np.nan,5]
inte = [100,200,300]
xxx = pd.DataFrame({'name' : pd.Series(prot),
                    'rowtype1': pd.Series(calc_m),
                    'rowtype2': pd.Series(calc_m2),
                    'intensity': pd.Series(inte)
                    })

Body:
I'm not sure I fully understand what behavior you are looking for, but the pandas dropna() command has the "subset" argument... for example, dropping all rows with NaN in the rowtype2 column could be done with

xxx.dropna(subset=['rowtype2'],inplace=True)

That way, you would drop only rows with NaN in the rowtype2 column.


问:
how to render a component by string name
I seem to be unable to render components using name strings. I wanted to be able to dynamically generate component name strings which have existing corresponding components that can be rendered.

The array const is going to be populated via JSON data, that's why I need to use string values for identifying the component.

Here is what I'm trying to do:

```<code>import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';

const array = ['Module1', 'Module2', 'Module3'];

{array.map((Module, index) =>
 <Module />
)}
</code>```

Instead of referencing the existing component and rendering it, React is rendering a custom element tag that is all lower case.

NOTE: those components ['Module1', 'Module2', 'Module3'] are created as extends Component

答:
You can put the components in an object and access them using the strings as keys.</p>

```<code>import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';

const array = ['Module1', 'Module2', 'Module3'];

const modules = {
  Module1,
  Module2,
  Module3,
};

{moduleOrderArr.map((key, index) => {
  const Module = modules[key];
  return <Module />;
})}
</code>```

Body:
I seem to be unable to render components using name strings. I wanted to be able to dynamically generate component name strings which have existing corresponding components that can be rendered.

The array const is going to be populated via JSON data, that's why I need to use string values for identifying the component.

Here is what I'm trying to do:

import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';

const array = ['Module1', 'Module2', 'Module3'];

{array.map((Module, index) =>
 <Module />
)}

Instead of referencing the existing component and rendering it, React is rendering a custom element tag that is all lower case.

NOTE: those components ['Module1', 'Module2', 'Module3'] are created as extends Component

Body:
You can put the components in an object and access them using the strings as keys.

import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';

const array = ['Module1', 'Module2', 'Module3'];

const modules = {
  Module1,
  Module2,
  Module3,
};

{moduleOrderArr.map((key, index) => {
  const Module = modules[key];
  return <Module />;
})}


问:
Searching in XML using another XML data
I have those two tables:

Table1:

```<code>IDt1    |    XML
1123         xml
1457         xml
</code>```

Table2:

```<code>ID     |    Name    |    XML
01           A           xml
02           B           xml
</code>```

I want to search in table1 XML and if the data exist, then use the IDt1 and search with it in table2 XML if it exist, then return the ID and Name from table2
here is the XMLs for each table.

Table1 xml:

```<code><t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555/rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>
</code>```

Table2 xml:

```<code><t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>
</code>```

data I want like:

```<code>ID   |   Name
01        a
</code>```

I was able to retrieve the IDs from table 1 that contain what I'm looking for but then I was not able to use these IDs to search in the other xml.
Here is what I have:

```<code>SELECT IDt1 as table1IDs
  FROM [Table1]
  WHERE [XML].exist ('/t/ts/sc/am[contains(., "Name1")]') > 0
</code>```

it returns a table of IDs that contain the Name1 now the question how to use the IDs and search with them in the xml of table2 and then return Name and ID of table2
the issue is now I have to use xml.exist [contain table1IDs ] which cannot accept variables

Is there a way to do that?

答:
After several testing I think this does the job

```<code>DECLARE @searchFor NVARCHAR(max)=N'Name1'
SELECT t2.ID as ID, t2.Name as Name
FROM table1 AS t1
JOIN table2 AS t2 ON t2.xml.query(N'/t/ts/d/n').value('.', 'VARCHAR(max)') = CAST(t1.ID as varchar(max))
WHERE t1.xml.exist(N'/t/ts/sc/am[text()[1]=sql:variable("@searchFor")]')=1 order by ID
</code>```

returns

```<code>ID   |   Name
01        a
</code>```

Title: Searching in XML using another XML data

Body:
I have those two tables:

Table1:

IDt1    |    XML
1123         xml
1457         xml

Table2:

ID     |    Name    |    XML
01           A           xml
02           B           xml

I want to search in table1 XML and if the data exist, then use the IDt1 and search with it in table2 XML if it exist, then return the ID and Name from table2
here is the XMLs for each table.

Table1 xml:

<t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555/rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>

Table2 xml:

<t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>

data I want like:

ID   |   Name
01        a

I was able to retrieve the IDs from table 1 that contain what I'm looking for but then I was not able to use these IDs to search in the other xml.
Here is what I have:

SELECT IDt1 as table1IDs
  FROM [Table1]
  WHERE [XML].exist ('/t/ts/sc/am[contains(., "Name1")]') > 0

it returns a table of IDs that contain the Name1 now the question how to use the IDs and search with them in the xml of table2 and then return Name and ID of table2
the issue is now I have to use xml.exist [contain table1IDs ] which cannot accept variables

Is there a way to do that?

Body:
After several testing I think this does the job

DECLARE @searchFor NVARCHAR(max)=N'Name1'
SELECT t2.ID as ID, t2.Name as Name
FROM table1 AS t1
JOIN table2 AS t2 ON t2.xml.query(N'/t/ts/d/n').value('.', 'VARCHAR(max)') = CAST(t1.ID as varchar(max))
WHERE t1.xml.exist(N'/t/ts/sc/am[text()[1]=sql:variable("@searchFor")]')=1 order by ID

returns

ID   |   Name
01        a


问:
SNMP Mib. Are the "qualified" descriptors used in practice
According standard RFC 2578 3.2. IMPORTing Symbols:

```<code>Note that when symbols from "enterprise-specific" information modules
are referenced  (e.g., a descriptor), there is the possibility of
collision.  As such, if different objects with the same descriptor
are IMPORTed, then this ambiguity is resolved by prefixing the
descriptor with the name of the information module and a dot ("."),
i.e.,

    "module.descriptor"

(All descriptors must be unique within any information module.)

Of course, this notation can be used to refer to objects even when
there is no collision when IMPORTing symbols.
</code>```

Everything seems to be clear, but...
i cannot find in standard where it can be used and i cannot find any mib that using "qualified" descriptors.

It seems that no one uses it. Is in real mib "qualified" descriptors used and how it used?

答:
I made up some test cases for my compiler product, so post them here for your reference.

TEST1-MIB module who defines mytest as 9998.

```<code>TEST1-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9998 }

END
</code>```

TEST2-MIB module who defines mytest as 9999.

```<code>TEST2-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9999 }

END
</code>```

Then when TEST3-MIB module tries to import both, we need the prefix to determine which mytest would be used,

```<code>TEST3-MIB DEFINITIONS ::= BEGIN
IMPORTS
    mytest
        FROM TEST1-MIB
    mytest
        FROM TEST2-MIB;

mytest1 OBJECT IDENTIFIER ::= { TEST2-MIB.mytest 9999 }

END
</code>```

Body:
According standard RFC 2578 3.2. IMPORTing Symbols:

Note that when symbols from "enterprise-specific" information modules
are referenced  (e.g., a descriptor), there is the possibility of
collision.  As such, if different objects with the same descriptor
are IMPORTed, then this ambiguity is resolved by prefixing the
descriptor with the name of the information module and a dot ("."),
i.e.,

    "module.descriptor"

(All descriptors must be unique within any information module.)

Of course, this notation can be used to refer to objects even when
there is no collision when IMPORTing symbols.

Everything seems to be clear, but...
i cannot find in standard where it can be used and i cannot find any mib that using "qualified" descriptors.

It seems that no one uses it. Is in real mib "qualified" descriptors used and how it used?

Body:
I made up some test cases for my compiler product, so post them here for your reference.

TEST1-MIB module who defines mytest as 9998.

TEST1-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9998 }

END

TEST2-MIB module who defines mytest as 9999.

TEST2-MIB DEFINITIONS ::= BEGIN
IMPORTS
    enterprises
        FROM SNMPv2-SMI;

mytest OBJECT IDENTIFIER ::= { enterprises 9999 }

END

Then when TEST3-MIB module tries to import both, we need the prefix to determine which mytest would be used,

TEST3-MIB DEFINITIONS ::= BEGIN
IMPORTS
    mytest
        FROM TEST1-MIB
    mytest
        FROM TEST2-MIB;

mytest1 OBJECT IDENTIFIER ::= { TEST2-MIB.mytest 9999 }

END


问:
Swift String array with arithmetic operators addition operation
I'm fetching value from RealmDB which is in string format. However this string contains values in arithmetic format like below

```<code>let values = ["1/2","1/3","2/3","3/5","1/7"]
</code>```

Now my problem is that I've to return the addition value of whole array. I'm unable to convert it to Double value because the string itself contain arithmetic operator. How to perform addition on above array of string?

I've tried to use NSExpreesion to do the mathematical operation but it's giving nil value.

```<code>let expn = NSExpression(format:"1/3")
print(expn.expressionValue(with: nil, context: nil))
</code>```

答:
You can use a single flatMap on your array to convert the fractional Strings to Doubles. You just have to separate the String into two parts by using String.componenets(separatedBy:), then try converting the String parts into numbers and if that succeeds, do the division.

The "" default value is used during the conversion to Int to make sure your app doesn't crash even if some of the values in the array are not proper fractions.

```<code>let fractionStrings = ["1/2","1/3","2/3","3/5","1/7"]
let fractions = fractionStrings.flatMap({ fractionString -> Double? in
    let numbers = fractionString.components(separatedBy: "/")
    if let nominator = Int(numbers.first ?? ""), let denominator = Int(numbers.last ?? "") {
        return Double(nominator)/Double(denominator)
    } else {
        return nil
    }
})
print(fractions)
</code>```

Output:

[0.5, 0.3333333333333333, 0.6666666666666666, 0.6, 0.1428571428571428]

Body:
I'm fetching value from RealmDB which is in string format. However this string contains values in arithmetic format like below

let values = ["1/2","1/3","2/3","3/5","1/7"]

Now my problem is that I've to return the addition value of whole array. I'm unable to convert it to Double value because the string itself contain arithmetic operator. How to perform addition on above array of string?

I've tried to use NSExpreesion to do the mathematical operation but it's giving nil value.

let expn = NSExpression(format:"1/3")
print(expn.expressionValue(with: nil, context: nil))

Body:
You can use a single flatMap on your array to convert the fractional Strings to Doubles. You just have to separate the String into two parts by using String.componenets(separatedBy:), then try converting the String parts into numbers and if that succeeds, do the division.

The "" default value is used during the conversion to Int to make sure your app doesn't crash even if some of the values in the array are not proper fractions.

let fractionStrings = ["1/2","1/3","2/3","3/5","1/7"]
let fractions = fractionStrings.flatMap({ fractionString -> Double? in
    let numbers = fractionString.components(separatedBy: "/")
    if let nominator = Int(numbers.first ?? ""), let denominator = Int(numbers.last ?? "") {
        return Double(nominator)/Double(denominator)
    } else {
        return nil
    }
})
print(fractions)

Output:

[0.5, 0.3333333333333333, 0.6666666666666666, 0.6, 0.1428571428571428]


问:
Add user-defined color box in a UITableView
How would I go about creating a small box with a color previously defined by the user, in a UITableView?  Something similar to what the "Things" app has.  (http://culturedcode.com/styles_2.5/images-things-iphone/tt-screenshot-sortedbyduedate.png)

Thanks!

答:
That looks like a custom table cell View. You can create one of these views programmatically
or you may design one in interface builder. You will need a view controller for this custom cell view and then when you providing the table view with table cell views through its delegate function you just instantiate a new custom view and return that.

Edit:

Heres a link to a tutorial...
Custom Table Cell View Tutorial

ContentLicense: CC BY-SA 2.5


问:
electron ipc renderer to main process - euro sign (€) becomes 'Ôé¼'
I have some encoding troubles with a string I am sending from the ipcRenderer to ipcMain within the electron framework.

Renderer process:

```<code>let test: String = "abc€123";
console.log(test); // prints "abc€123"
electron.ipcRenderer.send('testMessage', test);
</code>```

Main process:

```<code>ipcMain.on('testMessage', (event, arg) => {
    console.log(arg); // prints "abcÔé¼123"
});
</code>```

Why is the main process printing the string as "abcÔé¼123"?
The value gets saved into a database and gets saved as garbage and not the actuall € sign.

Edit: console.log("€") in the main process also shows up 'Ôé¼' in the console

答:
The problem actually was not the encoding. Turned out to be the datatype i used to save it into sql db.

I use the node-mssql and had to change the datatype to NVarChar:

```<code>request.input('test', db.sql.NVarChar, "€");
</code>```

Body:
I have some encoding troubles with a string I am sending from the ipcRenderer to ipcMain within the electron framework.

Renderer process:

let test: String = "abc€123";
console.log(test); // prints "abc€123"
electron.ipcRenderer.send('testMessage', test);

Main process:

ipcMain.on('testMessage', (event, arg) => {
    console.log(arg); // prints "abcÔé¼123"
});

Why is the main process printing the string as "abcÔé¼123"?
The value gets saved into a database and gets saved as garbage and not the actuall € sign.

Edit: console.log("€") in the main process also shows up 'Ôé¼' in the console

Body:
The problem actually was not the encoding. Turned out to be the datatype i used to save it into sql db.

I use the node-mssql and had to change the datatype to NVarChar:

request.input('test', db.sql.NVarChar, "€");


问:
SqlPlus (Oracle) Spool Formatting Issue
I have scheduled a shell script which is outputting the following email. I want to remove the unwanted/additional duplicated text which is being printed using the dual table below to give a heading to my SQL select output.

How can I do it?

Following is the spool SQL script. After the script execution is done (/home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out) file is added to the email body and sent to recipients.

Can you guide which set parameter command is missing OR which one is extra or unnecessary below?

This is shell script file code.

```<code>sqlplus user/pass@pgwdb @/home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.sql
sleep 5
/bin/mail -s "MFS PGW Fraud Alerts (Day)" -r “test-email-1@email-domain.com” "test-email-2@email-domain.com" < /home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out
</code>```

PGW_ALERTS.sql   Code

```<code>set echo off;
set feedback off ;
set verify off ;
set serveroutput off;
set heading on;
set trimspool on;
set headsep off;
set PAGESIZE 60;
set LINESIZE 400;
SET WRAP OFF;
SET COLSEP '    ';
set numw 20;

SPOOL /home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out append;

select '======  Transactions with count > 2 from same MSISDN  ======' from dual;

SELECT '"'
  || MOBILENUMBER
  || '"' MSISDN,
  AMOUNT/100 AMOUNT,
  DECODE(TXNTYPEID,'6','MW', '0') TXN_TYPE,
  MERCHANTCODE,
  COUNT (*) COUNT
FROM TBL_TXN_LOG
WHERE TXNTYPEID ='6'
AND AMOUNT     <=10000
AND TXNDATETIME>= SYSDATE -1
AND STATUS      ='xxxx'
GROUP BY '"'
  || MOBILENUMBER
  || '"', AMOUNT/100, DECODE(TXNTYPEID,'6','MW', '0'), MERCHANTCODE
HAVING COUNT (*) > 2
UNION ALL
SELECT '"'
  || MOBILENUMBER
  || '"' MSISDN ,
  AMOUNT/100 AMOUNT,
  DECODE(TXNTYPEID,'164', 'Card', '0') TXN_TYPE,
  MERCHANTCODE,
  COUNT (*) COUNT
FROM TBL_TXN_LOG
WHERE TXNTYPEID ='164'
AND AMOUNT     >=2500000
AND TXNDATETIME>= SYSDATE - 1
AND STATUS      ='xxxx'
GROUP BY MOBILENUMBER,
  AMOUNT,
  DECODE(TXNTYPEID,'164','Card', '0') ,
  MERCHANTCODE
HAVING COUNT (*) > 1
;

SPOOL OFF;

SET DEFINE ON
SET SERVEROUTPUT OFF
quit
</code>```

The email which recipient is getting.,

-----Original Message----- From: destination.email@emaildomain.com Sent: Friday, December 8, 2017 7:36 PM To:
destination.email@emaildomain.com Subject: MFS PGW Fraud Alerts (4
Hourly)

***> '======TRANSACTIONSWITHAMOUNT<100FORMW&>25000======'

--------------------------------------------------------------***

======  Transactions with Amount < 100 for MW & > 25000 ======

MSISDN                                  AMOUNT    TXN_    MERCHANTCODE
COUNT
----------------------    --------------------    ----    ------------------------------    -------------------- "924008482888"                               70    MW      00342386                                             1
"924008345433"                               20    MW      002218387

1

I want to remove these extra lines

'======TRANSACTIONSWITHAMOUNT<100FORMW&>25000======'

答:
Change your query a bit, use an alias for your heading, and turn off/on heading as shown:

```<code>set heading off
select '======  Transactions with count > 2 from same MSISDN  ======' as info from dual;

select '```' from dual;
set heading on
-- rest of your query
set heading off
select '```' from dual;
</code>```

That should do the trick if the message is being sent in HTML format.

ContentLicense: CC BY-SA 4.0

Title: SqlPlus (Oracle) Spool Formatting Issue

Body:
I have scheduled a shell script which is outputting the following email. I want to remove the unwanted/additional duplicated text which is being printed using the dual table below to give a heading to my SQL select output.

How can I do it?

Following is the spool SQL script. After the script execution is done (/home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out) file is added to the email body and sent to recipients.

Can you guide which set parameter command is missing OR which one is extra or unnecessary below?

This is shell script file code.

sqlplus user/pass@pgwdb @/home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.sql
sleep 5
/bin/mail -s "MFS PGW Fraud Alerts (Day)" -r “test-email-1@email-domain.com” "test-email-2@email-domain.com" < /home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out

PGW_ALERTS.sql   Code

set echo off;
set feedback off ;
set verify off ;
set serveroutput off;
set heading on;
set trimspool on;
set headsep off;
set PAGESIZE 60;
set LINESIZE 400;
SET WRAP OFF;
SET COLSEP '    ';
set numw 20;

SPOOL /home/oracle/MFS_ALERT/PGW_ALERTS_FRAUDS/PGW_ALERTS.out append;

select '======  Transactions with count > 2 from same MSISDN  ======' from dual;

SELECT '"'
  || MOBILENUMBER
  || '"' MSISDN,
  AMOUNT/100 AMOUNT,
  DECODE(TXNTYPEID,'6','MW', '0') TXN_TYPE,
  MERCHANTCODE,
  COUNT (*) COUNT
FROM TBL_TXN_LOG
WHERE TXNTYPEID ='6'
AND AMOUNT     <=10000
AND TXNDATETIME>= SYSDATE -1
AND STATUS      ='xxxx'
GROUP BY '"'
  || MOBILENUMBER
  || '"', AMOUNT/100, DECODE(TXNTYPEID,'6','MW', '0'), MERCHANTCODE
HAVING COUNT (*) > 2
UNION ALL
SELECT '"'
  || MOBILENUMBER
  || '"' MSISDN ,
  AMOUNT/100 AMOUNT,
  DECODE(TXNTYPEID,'164', 'Card', '0') TXN_TYPE,
  MERCHANTCODE,
  COUNT (*) COUNT
FROM TBL_TXN_LOG
WHERE TXNTYPEID ='164'
AND AMOUNT     >=2500000
AND TXNDATETIME>= SYSDATE - 1
AND STATUS      ='xxxx'
GROUP BY MOBILENUMBER,
  AMOUNT,
  DECODE(TXNTYPEID,'164','Card', '0') ,
  MERCHANTCODE
HAVING COUNT (*) > 1
;

SPOOL OFF;

SET DEFINE ON
SET SERVEROUTPUT OFF
quit

The email which recipient is getting.,

-----Original Message----- From: destination.email@emaildomain.com Sent: Friday, December 8, 2017 7:36 PM To:
destination.email@emaildomain.com Subject: MFS PGW Fraud Alerts (4
Hourly)

***> '======TRANSACTIONSWITHAMOUNT<100FORMW&>25000======'

--------------------------------------------------------------***

======  Transactions with Amount < 100 for MW & > 25000 ======

MSISDN                                  AMOUNT    TXN_    MERCHANTCODE
COUNT
----------------------    --------------------    ----    ------------------------------    -------------------- "924008482888"                               70    MW      00342386                                             1
"924008345433"                               20    MW      002218387

1

I want to remove these extra lines

'======TRANSACTIONSWITHAMOUNT<100FORMW&>25000======'

Body:
Change your query a bit, use an alias for your heading, and turn off/on heading as shown:

set heading off
select '======  Transactions with count > 2 from same MSISDN  ======' as info from dual;

select '<pre>' from dual;
set heading on
-- rest of your query
set heading off
select '</pre>' from dual;

That should do the trick if the message is being sent in HTML format.


问:
Is this reallocation method correct
My code works but my question is if this dynamic allocation is correct. It's works well and all is ok but I'm not so sure it is correct.</p>

```<code>        StudentDynamic* pStudents = NULL;
        char auxfirstName[255], auxlastName[255];
        float auxGrade;
        FILE* pFile = fopen("InitialDB.txt", "r");
        if (pFile == NULL)
        {
            printf("Could not open file or is empty! Exiting...");
            exit(2);
        }
        int i = 0;
        pStudents = (StudentDynamic*)malloc(sizeof(StudentDynamic) * 1);
        while (!feof(pFile))
        {
            fscanf(pFile, "%s", auxfirstName);
            pStudents[i].firstName = (char*)malloc(strlen(auxfirstName) + 1);
            strcpy(pStudents[i].firstName, auxfirstName);

            fscanf(pFile, "%s", auxlastName);
            pStudents[i].lastName = (char*)malloc(strlen(auxlastName) + 1);
            strcpy(pStudents[i].lastName, auxlastName);

            fscanf(pFile, "%f", &auxGrade);
            pStudents[i].grade = auxGrade;

            i++;
            pStudents = (StudentDynamic*)realloc(pStudents, sizeof(StudentDynamic) * (i + 1));
        }
        nStudents = i;
        fclose(pFile);
</code>```

答:
```<code>temp_pStudents  = realloc(pStudents , sizeof(StudentDynamic) * (i + 1));
if (!temp_pStudents)
    // error
pStudents  = temp_pStudents ;
</code>```

Ideally this would be something like this. Otherwise in case of error you have a memory leak. Also this saves you from derefrencing the null pointer.

Again other things include

casting malloc which is not necessary.

And using constructs with while(!feof(file)). Don't use it. Check the discussion posted in comment.

Title: Is this reallocation method correct

Body:
My code works but my question is if this dynamic allocation is correct. It's works well and all is ok but I'm not so sure it is correct.

        StudentDynamic* pStudents = NULL;
        char auxfirstName[255], auxlastName[255];
        float auxGrade;
        FILE* pFile = fopen("InitialDB.txt", "r");
        if (pFile == NULL)
        {
            printf("Could not open file or is empty! Exiting...");
            exit(2);
        }
        int i = 0;
        pStudents = (StudentDynamic*)malloc(sizeof(StudentDynamic) * 1);
        while (!feof(pFile))
        {
            fscanf(pFile, "%s", auxfirstName);
            pStudents[i].firstName = (char*)malloc(strlen(auxfirstName) + 1);
            strcpy(pStudents[i].firstName, auxfirstName);

            fscanf(pFile, "%s", auxlastName);
            pStudents[i].lastName = (char*)malloc(strlen(auxlastName) + 1);
            strcpy(pStudents[i].lastName, auxlastName);

            fscanf(pFile, "%f", &auxGrade);
            pStudents[i].grade = auxGrade;

            i++;
            pStudents = (StudentDynamic*)realloc(pStudents, sizeof(StudentDynamic) * (i + 1));
        }
        nStudents = i;
        fclose(pFile);

Body:
temp_pStudents  = realloc(pStudents , sizeof(StudentDynamic) * (i + 1));
if (!temp_pStudents)
    // error
pStudents  = temp_pStudents ;

Ideally this would be something like this. Otherwise in case of error you have a memory leak. Also this saves you from derefrencing the null pointer.

Again other things include

casting malloc which is not necessary.

And using constructs with while(!feof(file)). Don't use it. Check the discussion posted in comment.


问:
Transitioned SQL database from Azure VM to Azure SQL database - size of new db is significantly smaller?
I have a database of approximately 70GB in size residing on SQL Server 2016 Enterprise on an Azure VM.  We decided to move this to an Azure SQL Database.

I accomplished the move via the "Deploy to Azure SQL Database"  (right-click on the database and it's under Tasks).  This wizard seemed very complete and ran a battery of tests, followed by doing the deployment step-by-very-detailed-step.  The full process took about 3 hours, but it finished with all steps marked as success.

The issue is the size of the resulting Azure SQL database is only showing as 31GB??  Is this possible?  Is there a possibility that there were 40gb worth of extraneous/temporary/unneeded data that the transition process recognized as unnecessary?  As you can imagine, I'm very hesitant to take down the original database and start using the new one given this difference in size.

答: It could be that you had fragmented indexes and moving them from one place to another allowed for a rebuild eliminating wasted space. It could be that you just had a database that was set to 70gb but only had 31gb of data. The size of your backups should give you an indication of the actual size of the data in your system. Run counts on the tables to ensure that both data sets match.</p>


问:
unit testing ef datamodel
I'm working on a personal c# project in my spare time. Before this projected I haven't really done any unit testing, but I that it was time to learn so I read a couple of tutorials/blogs and installed NUnit and Testdriven.Net in VS2010 and I think I got the basics covered now.

My project uses a data model, which I created using EF4. I've also created a repository to retrieve the data and now I want to test that repository. How should I test it? Can I somehow avoid making calls to the database everytime I want to test a method in the Repository?

cheers

答:
You can also use mocking frameworks to create "fake" versions of your repositories.  Moq is one I use very often.  Essentially, you write code to fake return values of your repositories based on configuration...

```<code>var mock = new Mock<YourObject>();
mock.Setup(m => m.DoSomething().Returns(true));
var result = mock.Object.DoSomething();
Assert.IsTrue(result);
</code>```

Here's a good tutorial on getting started with Moq by Stephen Walther.

Title: unit testing ef datamodel

Body:
You can also use mocking frameworks to create "fake" versions of your repositories.  Moq is one I use very often.  Essentially, you write code to fake return values of your repositories based on configuration...

var mock = new Mock<YourObject>();
mock.Setup(m => m.DoSomething().Returns(true));
var result = mock.Object.DoSomething();
Assert.IsTrue(result);

Here's a good tutorial on getting started with Moq by Stephen Walther.


问:
jQuery looping checkboxes
I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.

When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.

The HTML looks like this:

```<code><input type="checkbox" id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
</code>```

There are about 40 of these checkboxes. What I'm looking for is a string like:

"pdfam_711131, pdfam_711341"

I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.

```<code>$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););
</code>```

答:
A simple way is to use .map() to make an array of the IDs, then use .toArray().join(", ") to get your string.

var s = $('input:checkbox[id^="pdfam_"]:checked')
  .map(function(i, el) { return el.id })
  .toArray()
  .join(", ");

console.log(s);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br /></code>```

Title: jQuery looping checkboxes

Body:
I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.

When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.

The HTML looks like this:

<input type="checkbox" id="pdfam_711131" />
Temporary Staff

<input type="checkbox" id="pdfam_711341" />
Other Contractors

There are about 40 of these checkboxes. What I'm looking for is a string like:

"pdfam_711131, pdfam_711341"

I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.

$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););

Body:
A simple way is to use .map() to make an array of the IDs, then use .toArray().join(", ") to get your string.

var s = $('input:checkbox[id^="pdfam_"]:checked')
  .map(function(i, el) { return el.id })
  .toArray()
  .join(", ");

console.log(s);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />


问:
How do I create an event listener on a property in every instance of a class?
I have 5 objects (ie instances of a class), and I need to set an event listener on the "im" property, that runs the function "squash()".

I attempted to use this.im.click(squash()) in the class, but that did not work.  How can I create the event listener?

```<code>let divs = $(".flies");
divs.each(function(i){
  let img = $("<img/>");
  img.attr({
    "id": i,
    "src": "http://clipart-library.com/images/8iznoLG8T.png"});
  $(this).append(img)
});

class Fly {
  constructor(div, im, alive){
    this.div = div;
    this.im = im;
    this.alive = true;
  }
  squash(){
    this.alive= false;
    this.element.css("visibility", "hidden");
    }
  }

let fly1 = new Fly($('#fly1'), $('#0'), true);
let fly2 = new Fly($('#fly2'), $('#1'), true);
let fly3 = new Fly($('#fly3'), $('#2'), true);
let fly4 = new Fly($('#fly4'), $('#3'), true);
let fly5 = new Fly($('#fly5'), $('#4'), true);
</code>```

答:
Use im.click(this.squash.bind(this));

class Fly {
  constructor(div, im, alive){
    this.div = div;
    this.im = im;
    this.alive = true;
    this.init()
  }

  init(){
    this.im.click(this.squash.bind(this));
  }

  squash(){
    this.alive= false;
    // wasn't sure what `element` is supposed to be, used `div` instead
    this.div.css("visibility", "hidden");
    }
  }

let fly1 = new Fly($('#fly1'), $('#0'), true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="0">Click to hide content</button>

<div id="fly1">Content 1</div></code>```

Body:
I have 5 objects (ie instances of a class), and I need to set an event listener on the "im" property, that runs the function "squash()".

I attempted to use this.im.click(squash()) in the class, but that did not work.  How can I create the event listener?

let divs = $(".flies");
divs.each(function(i){
  let img = $("");
  img.attr({
    "id": i,
    "src": "http://clipart-library.com/images/8iznoLG8T.png"});
  $(this).append(img)
});

class Fly {
  constructor(div, im, alive){
    this.div = div;
    this.im = im;
    this.alive = true;
  }
  squash(){
    this.alive= false;
    this.element.css("visibility", "hidden");
    }
  }

let fly1 = new Fly($('#fly1'), $('#0'), true);
let fly2 = new Fly($('#fly2'), $('#1'), true);
let fly3 = new Fly($('#fly3'), $('#2'), true);
let fly4 = new Fly($('#fly4'), $('#3'), true);
let fly5 = new Fly($('#fly5'), $('#4'), true);

Body:
Use im.click(this.squash.bind(this));

class Fly {
  constructor(div, im, alive){
    this.div = div;
    this.im = im;
    this.alive = true;
    this.init()
  }

  init(){
    this.im.click(this.squash.bind(this));
  }

  squash(){
    this.alive= false;
    // wasn't sure what `element` is supposed to be, used `div` instead
    this.div.css("visibility", "hidden");
    }
  }

let fly1 = new Fly($('#fly1'), $('#0'), true);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="0">Click to hide content</button>

<div id="fly1">Content 1</div>


问:
How to get an object from a List<typeObject> in a DropDownlistFor?
As a beginner in c#/asp.net/mvc, I can't find how to get an object from a Html.DropDownList in the View.
Here is my ViewModel :

```<code>public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public Something TheSomethingToGet {get;set;} // The object I want to get
}
</code>```

The "Something" object is for example :

```<code>public class Something {
   public int Id {get;set;}
   public string Name {get;set;}
   public int AnotherProperty {get;set;}
}
</code>```

I populate my List<> in the controller :

```<code>public ActionResult Index () {
   MyViewModel mvm=new MyViewModel();
   mvm.ListOfSomething=(my code to populate the List);
   return View(vm);
}
</code>```

The View is here :

```<code>@model Project.ViewModels.MyViewModel
@Html.LabelFor(m => m.ListOfSomething)
@Html.DropDownListFor(m => m.ListOfSomething, new SelectList(Model.ListOfSomething, "id", "name"), "-")<br/>
</code>```

And eventually, the [HttpPost] Index of the controller :

```<code>[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    /* Here, how could I get the "Something" object that
       was selected in the dropdownlist and can be identified
       by the "id" property ?
    */

}
</code>```

I'm totally wrong ?
Thanks

答:
According to my understanding the DropDownListFor works with primitive types for example int, string, what you need to do is have the SelectedId property in the ViewModel and post that, then in controller using that Id you will have to pull the selected item from the collection in your view model in controller.

You can try it like:

```<code>public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public int SelectedItem {get;set;}
}
</code>```

and now in your view, you would have to do:

```<code>@Html.DropDownListFor(m => m.SelectedItem, new SelectList(Model.ListOfSomething, "id", "name"), "-")
</code>```

and then in your action method:

```<code>[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    // use mvm.SelectedItem id to get the selected complete object from repository
}
</code>```

Hopefully it will help.

Body:
As a beginner in c#/asp.net/mvc, I can't find how to get an object from a Html.DropDownList in the View.
Here is my ViewModel :

public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public Something TheSomethingToGet {get;set;} // The object I want to get
}

The "Something" object is for example :

public class Something {
   public int Id {get;set;}
   public string Name {get;set;}
   public int AnotherProperty {get;set;}
}

I populate my List<> in the controller :

public ActionResult Index () {
   MyViewModel mvm=new MyViewModel();
   mvm.ListOfSomething=(my code to populate the List);
   return View(vm);
}

The View is here :

@model Project.ViewModels.MyViewModel
@Html.LabelFor(m => m.ListOfSomething)
@Html.DropDownListFor(m => m.ListOfSomething, new SelectList(Model.ListOfSomething, "id", "name"), "-")

And eventually, the [HttpPost] Index of the controller :

[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    /* Here, how could I get the "Something" object that
       was selected in the dropdownlist and can be identified
       by the "id" property ?
    */

}

I'm totally wrong ?
Thanks

Body:
According to my understanding the DropDownListFor works with primitive types for example int, string, what you need to do is have the SelectedId property in the ViewModel and post that, then in controller using that Id you will have to pull the selected item from the collection in your view model in controller.

You can try it like:

public class MyViewModel {
   public List<Something> ListOfSomething {get;set;} // A list of Somethings
   public int SelectedItem {get;set;}
}

and now in your view, you would have to do:

@Html.DropDownListFor(m => m.SelectedItem, new SelectList(Model.ListOfSomething, "id", "name"), "-")

and then in your action method:

[HttpPost]
public ActionResult Index(MyViewModel mvm) {
    // use mvm.SelectedItem id to get the selected complete object from repository
}

Hopefully it will help.


问:
Best Practice for a Linux Desktop App to ensure it has Hardware Access Permissions?
We are a hardware vendor and want to provide support for linux.
This means we want to provide a (user space) shared library that can be used by our customers applications without struggling with the lowlevel protocol.

Our Hardware is accessed via USB/HID and thus our library need to get access to /dev/hidrawX.

But to get access to this device (or other kind of hardware devices) it seems that we need to modify the system by adding permissions to the udev system (see
Get access to USB device on Linux (libusb-1.0)?).

Is this really best practice? If so, where should I do this? In the .deb/.rpm/... installer of the customers application? What about FlatPak or similar concepts?

答: Udev is standard and best practice. Every linux distribution has udev rules files typically for ex in case of ubuntu it is found in /etc/udev/rules.d folder. You need to create a udev rule file and write MODE="0666" rule to it. Take a look at this example for how to write udev rule.</p>


问:
Why VS Code always try to generate a new jsconfig.json file
There is a relatively large project which has typescript and javascript files mixed together. I've already generate a tsconfig.json and it works pretty well.

The problem is, everytime I use VS Code to open this project, the editor always try to generate a jsconfig.json for me, even I create a jsconfig.json manually, the editor still try to create a new one.

I also try with another project, of course a new and smaller one, no problem like above, this is very confusing, what's the cause behind the scene?

答: After some investigation, this problem is caused by an extension called ember-cli for vscode, just disable it if you suffered a lot. Also, I've already file an issue, hope it gives us an option in the near future.


问:
Append URL param value into html
To extract that user name from URL into html

Sample url

```<code>something.com?editors=username
</code>```

Html code

```<code><P id="demo"><p>
</code>```

JS:-

```<code>document.getElementById("demo").innerHTML =
"Welcome " + get_editor() + " to my website";

function get_editor() {
  var url = new URL( window.location.href );
  var params = new URLSearchParams(url.search);
  return params.get('editors');
}
</code>```

答:
I know that I am late, but from Czeran's answer, I created this JS function that will append and go to the URL:

```<code>    function urlAppend(value){
        var current_location = window.location.href;
        current_location += "/" + value;
        window.location.href = current_location;
    }
</code>```

This allows for a more dynamic URL append

Hope this helps!

Title: Append URL param value into html

Body:
To extract that user name from URL into html

Sample url

something.com?editors=username

Html code

JS:-

document.getElementById("demo").innerHTML =
"Welcome " + get_editor() + " to my website";

function get_editor() {
  var url = new URL( window.location.href );
  var params = new URLSearchParams(url.search);
  return params.get('editors');
}

Body:
I know that I am late, but from Czeran's answer, I created this JS function that will append and go to the URL:

    function urlAppend(value){
        var current_location = window.location.href;
        current_location += "/" + value;
        window.location.href = current_location;
    }

This allows for a more dynamic URL append

Hope this helps!


问:
Test if Button Text has changed
I have a button whose text changes based on certain criteria. I want to test this functionality with XCUITest but I can't seem to be able to access the text on the button.

I have tried

```<code>button.staticTexts
button.value
button.title
elementsQuery.buttons["My Button"] //This uses the accessibility label
</code>```

How can I access the text?

答:
I know this is old but try this:

```<code>let app = XCUIApplication();
let buttonText = app.otherElements["My Button"].staticTexts;
</code>```

If this doesn't work let me know. Currently working on iOS XCUITests myself

Title: Test if Button Text has changed

Body:
I have a button whose text changes based on certain criteria. I want to test this functionality with XCUITest but I can't seem to be able to access the text on the button.

I have tried

button.staticTexts
button.value
button.title
elementsQuery.buttons["My Button"] //This uses the accessibility label

How can I access the text?

Body:
I know this is old but try this:

let app = XCUIApplication();
let buttonText = app.otherElements["My Button"].staticTexts;

If this doesn't work let me know. Currently working on iOS XCUITests myself


问:
When you program in as3, do you usually use classes?
I want other programmers' opinions on this.  When you program in as3, do you usually use classes?  Why?</p>

答:
ActionScript is an object-oriented programming language, so it is recommended that classes are used to provide modularity to your code freeing up actions and functions in the main timeline. So it should not really be a question whether or not to use classes.

Try reading up on The Lost ActionScript Weekend to give you a crash course on what modularity means in AS3, especially the first section on "Building an airplane"

airplane in flight

   - group of interoperating parts based on a set of blueprints

  program running

  - group of interoperating objects, based on a set of classes


问:
How to get list of json strings from sinlgle line multi json string in scala
I am trying to get list of json string from given string having multiple json strings separated by ",".

For example
    val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"

```<code>expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]
</code>```

答:
You should replace the json separator with a string or character that is not repeated in the whole string and use that special separator to be used with split method to get you your required output. Here I have used -

```<code>jsonString.replace("},{", "}-{").split("-")
</code>```

You should have output as

```<code>res0: Array[String] = Array({"a":"b"}, {"c":"d", "e":"f"})
</code>```

One step further, calling toList method would get you to the final dataType you require

```<code>jsonString.replace("},{", "}-{").split("-").toList  //res0: List[String] = List({"a":"b"}, {"c":"d", "e":"f"})
</code>```

Body:
I am trying to get list of json string from given string having multiple json strings separated by ",".

For example
    val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"

expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]

Body:
You should replace the json separator with a string or character that is not repeated in the whole string and use that special separator to be used with split method to get you your required output. Here I have used -

jsonString.replace("},{", "}-{").split("-")

You should have output as

res0: Array[String] = Array({"a":"b"}, {"c":"d", "e":"f"})

One step further, calling toList method would get you to the final dataType you require

jsonString.replace("},{", "}-{").split("-").toList  //res0: List[String] = List({"a":"b"}, {"c":"d", "e":"f"})


问:
Calculating proportion by year using dplyr
I'm attempting to calculate the frequency a variable (in this case country) shows up in any given year. For example:

```<code>name <- c('AJ Griffin','Steve Bacon','Kevin Potatoe','Jose Hernandez','Kent Brockman',
                  'Sal Fasno','Kirk Kelly','Wes United','Livan Domingo','Mike Fast')

country <- c('USA', 'USA', 'Canada', 'Dominican Republic', 'Panama', 'Dominican Republic', 'Canada', 'USA', 'Dominican Republic', 'Mexico')

year <- c('2016', '2016', '2016', '2016', '2016', '2015', '2015', '2015', '2015', '2015')

country_analysis <-data.frame(name, country, year)
</code>```

When I use the following code I get the proportion of countries for the entire dataset, but I would like to pare this down even further to specific years.

```<code>P <- country_analysis %>%
  group_by(country) %>%
  summarise(n=n())%>%
  mutate(freq = round(n / sum(n), 1))
</code>```

Ideally the end result would have country, year, frequency column (i.e. 2016, USA, 0.4). Any input would be appreciated.

答:
First collapse by year and country, then by just year. For example</p>

```<code>country_analysis %>%
  group_by(year, country) %>%
  summarize(count=n()) %>%
  mutate(proportion=count/sum(count))

#     year            country count proportion
#   <fctr>             <fctr> <int>      <dbl>
# 1   2015             Canada     1        0.2
# 2   2015 Dominican Republic     2        0.4
# 3   2015             Mexico     1        0.2
# 4   2015                USA     1        0.2
# 5   2016             Canada     1        0.2
# 6   2016 Dominican Republic     1        0.2
# 7   2016             Panama     1        0.2
# 8   2016                USA     2        0.4
</code>```

Body:
I'm attempting to calculate the frequency a variable (in this case country) shows up in any given year. For example:

name <- c('AJ Griffin','Steve Bacon','Kevin Potatoe','Jose Hernandez','Kent Brockman',
                  'Sal Fasno','Kirk Kelly','Wes United','Livan Domingo','Mike Fast')

country <- c('USA', 'USA', 'Canada', 'Dominican Republic', 'Panama', 'Dominican Republic', 'Canada', 'USA', 'Dominican Republic', 'Mexico')

year <- c('2016', '2016', '2016', '2016', '2016', '2015', '2015', '2015', '2015', '2015')

country_analysis <-data.frame(name, country, year)

When I use the following code I get the proportion of countries for the entire dataset, but I would like to pare this down even further to specific years.

P <- country_analysis %>%
  group_by(country) %>%
  summarise(n=n())%>%
  mutate(freq = round(n / sum(n), 1))

Ideally the end result would have country, year, frequency column (i.e. 2016, USA, 0.4). Any input would be appreciated.

Body:
First collapse by year and country, then by just year. For example

country_analysis %>%
  group_by(year, country) %>%
  summarize(count=n()) %>%
  mutate(proportion=count/sum(count))

#     year            country count proportion
#   <fctr>             <fctr> <int>      <dbl>
# 1   2015             Canada     1        0.2
# 2   2015 Dominican Republic     2        0.4
# 3   2015             Mexico     1        0.2
# 4   2015                USA     1        0.2
# 5   2016             Canada     1        0.2
# 6   2016 Dominican Republic     1        0.2
# 7   2016             Panama     1        0.2
# 8   2016                USA     2        0.4


问:
For loop - how to?
I am trying to run the following code in Android but there seems to be some problem with the for loop. The code builds without any build error but when I try access the second element of the array station_id it gives a runtime error. If I try to access station_id[0], then there is no error at all. I was not sure if the for loop actually loops over and stores the data in every element of the array. Therefore I tried printing the value of i to check if the for loop runs 187 times. However, 'i' is printed only once in the logcat of Android studio. I could not figure out where it goes wrong. Your suggestions would be of great help. Below is my code.

```<code>public class LoadDataOnce {
    private String Url_get_data;
    private String result_fullData;
    private JSONArray fullData;
    // GetData - class that sends http get request and fetches data
    private GetData getfullData;
    private String [] station_id;
    private String []  station_coordinates;
    private int total_num_of_stations;

public LoadDataOnce() {
    Url_get_data = "http://fluggs.wupperverband.de/sos2/api/v1/timeseries/";
    result_fullData = null;
    fullData = null;
    getfullData = new GetData();
    station_id = new String[187];
    station_coordinates = new String[187];
    total_num_of_stations = 0;
}

public String[] getStation_id() {

    return station_id;

}

public String [] getStation_coordinates() {
    return station_coordinates;
}

public int getTotal_num_of_stations() {
    return total_num_of_stations;
}

public void loadData () {

    try {
        result_fullData = getfullData.execute(Url_get_data).get();

        try {
            fullData = new JSONArray(result_fullData);
            total_num_of_stations = fullData.length();
            //station_id =  new String [total_num_of_stations];
            station_coordinates = new String[total_num_of_stations];
            for (int i = 0; i < 187; i++){
                station_id[i] = fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
                System.out.println(i);
                station_coordinates[i] = fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

}
</code>```

Exception that I get while testing in Android 7.0 phone.

```<code>    java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.charu.droidar_wupperverband/system.ArActivity}:
    java.lang.IllegalArgumentException: width and height must be > 0
    at
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:969)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:948)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:915)
    at util.IO.loadBitmapFromView(IO.java:158)
    at util.IO.loadBitmapFromView(IO.java:140)
    at gl.GLFactory.newTextObject(GLFactory.java:611)
    at com.example.charu.droidar_wupperverband.WupperAugment._b_addWorldsToRenderer(WupperAugment.java:106)
    at system.Setup.run(Setup.java:254)
    at system.ArActivity.runSetup(ArActivity.java:61)
    at system.ArActivity.onCreate(ArActivity.java:38)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
    ... 9 more

 <Debug Infos>
 OS Version: 3.18.14-12365438 (G930FXXU1DQJ8)
 OS API Level: 24
 Device: herolte
 Model (and Product): SM-G930F (heroltexx)
 Manufacturer: samsung
 Other TAGS: release-keys
 screenWidth: 1080
 screenHeigth: 1920
 Keyboard available: false
 Trackball available: false
 SD Card state: mounted
</code>```

答:
I figured out what the problem is..

"the third statement of the for loop has turned out to be wrong"!! and hence the loop has been broken the very first time and did not run for the rest of the times. The error is that the data fetched and the format in which I tried to store it has been different..The request returns an array which I tried storing in a String.  Sorry for the inconvenience.

Title: For loop - how to?

Body:
I am trying to run the following code in Android but there seems to be some problem with the for loop. The code builds without any build error but when I try access the second element of the array station_id it gives a runtime error. If I try to access station_id[0], then there is no error at all. I was not sure if the for loop actually loops over and stores the data in every element of the array. Therefore I tried printing the value of i to check if the for loop runs 187 times. However, 'i' is printed only once in the logcat of Android studio. I could not figure out where it goes wrong. Your suggestions would be of great help. Below is my code.

public class LoadDataOnce {
    private String Url_get_data;
    private String result_fullData;
    private JSONArray fullData;
    // GetData - class that sends http get request and fetches data
    private GetData getfullData;
    private String [] station_id;
    private String []  station_coordinates;
    private int total_num_of_stations;

public LoadDataOnce() {
    Url_get_data = "http://fluggs.wupperverband.de/sos2/api/v1/timeseries/";
    result_fullData = null;
    fullData = null;
    getfullData = new GetData();
    station_id = new String[187];
    station_coordinates = new String[187];
    total_num_of_stations = 0;
}

public String[] getStation_id() {

    return station_id;

}

public String [] getStation_coordinates() {
    return station_coordinates;
}

public int getTotal_num_of_stations() {
    return total_num_of_stations;
}

public void loadData () {

    try {
        result_fullData = getfullData.execute(Url_get_data).get();

        try {
            fullData = new JSONArray(result_fullData);
            total_num_of_stations = fullData.length();
            //station_id =  new String [total_num_of_stations];
            station_coordinates = new String[total_num_of_stations];
            for (int i = 0; i < 187; i++){
                station_id[i] = fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
                System.out.println(i);
                station_coordinates[i] = fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

}

Exception that I get while testing in Android 7.0 phone.

    java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.charu.droidar_wupperverband/system.ArActivity}:
    java.lang.IllegalArgumentException: width and height must be > 0
    at
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:969)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:948)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:915)
    at util.IO.loadBitmapFromView(IO.java:158)
    at util.IO.loadBitmapFromView(IO.java:140)
    at gl.GLFactory.newTextObject(GLFactory.java:611)
    at com.example.charu.droidar_wupperverband.WupperAugment._b_addWorldsToRenderer(WupperAugment.java:106)
    at system.Setup.run(Setup.java:254)
    at system.ArActivity.runSetup(ArActivity.java:61)
    at system.ArActivity.onCreate(ArActivity.java:38)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
    ... 9 more

 <Debug Infos>
 OS Version: 3.18.14-12365438 (G930FXXU1DQJ8)
 OS API Level: 24
 Device: herolte
 Model (and Product): SM-G930F (heroltexx)
 Manufacturer: samsung
 Other TAGS: release-keys
 screenWidth: 1080
 screenHeigth: 1920
 Keyboard available: false
 Trackball available: false
 SD Card state: mounted


问:
How do you enable customers use their openid on your website, just like stackoverflow?
I want customers to use their openId on my site. I googled for this but didn't find any good tutorial. I use PHP and MySQL.

There is one at Plaxo. But it says we should download something from JanRain.com.

I saw the openId module of Drupal. It doesn't want anything to be downloaded.

Can anyone tell me what to do exactly?

答:
Drupal's OpenID module started off using the JanRain library in 4.7.x, which is the most commonly used implementation of OpenID in PHP.

You don't have to download a library in Drupal because it's already built into Drupal core.

OwnerDisplayName: iSattar

OwnerDisplayName: ceejayoz


问:
Cannot bind text field to selected item in JTable in NetBeans
I am trying to use NetBeans to bind a JTextField to the selected element of a JTable.

The JTable gets its data from an AbstractTableModel subclass which returns Cow objects.  At present, each Cow object is displayed as a String through its toString method.

I am trying to bind the text property of the JTextField to the name property of the Cow object which is selected in the JTable.

I bound the text property of the JTextField in NetBeans to:

flowTable[${selectedElement.name}]

This produces the following line of generated code:

```<code>org.jdesktop.beansbinding.Binding binding =
  org.jdesktop.beansbinding.Bindings.createAutoBinding(
    org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
    cowTable,
    org.jdesktop.beansbinding.ELProperty.create("${selectedElement.name}"),
    cowNameTextField,
    org.jdesktop.beansbinding.BeanProperty.create("text"));</code>```

The bound value of the text field is always null.

What am I doing wrong?

答: Does your Cow class support adding a PropertyChangeListener? I did not use the beans binding support from NetBeans that often, but I remember you needed it. Anyway, a little more code could help with finding out whats going wrong.

Body:
I am trying to use NetBeans to bind a JTextField to the selected element of a JTable.

The JTable gets its data from an AbstractTableModel subclass which returns Cow objects.  At present, each Cow object is displayed as a String through its toString method.

I am trying to bind the text property of the JTextField to the name property of the Cow object which is selected in the JTable.

I bound the text property of the JTextField in NetBeans to:

flowTable[${selectedElement.name}]

This produces the following line of generated code:

org.jdesktop.beansbinding.Binding binding =
  org.jdesktop.beansbinding.Bindings.createAutoBinding(
    org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
    cowTable,
    org.jdesktop.beansbinding.ELProperty.create("${selectedElement.name}"),
    cowNameTextField,
    org.jdesktop.beansbinding.BeanProperty.create("text"));

The bound value of the text field is always null.

What am I doing wrong?


问:
How to adjust bootstrap carousel arrows height?
This happened when I changed the height of the .well class:

I tried to modify the height for the controls, the .carousel-inner and also the height of the carousel itself. All of these still yield the same results. I figure if I was able to change the background color of the carousel-control, I would be able to modify the height on the same elements. May I know which class to can be modified to change this?

```<code>          <a class="left carousel-control" href="#text-carousel" data-slide="prev" style="background: #f8f8f8 !important">
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a class="right carousel-control" href="#text-carousel" data-slide="next" style="background: #f8f8f8 !important">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
</code>```

答:
I think these are the selectors you are trying to find:

```<code>.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
    width: 200px;
    height: 200px;
}

.carousel-control .glyphicon-chevron-left:before,
.carousel-control .glyphicon-chevron-right:before {
    font-size: 200px;
}
</code>```

So fitted into a Bootstrap 3 environment (as based on OP's markup this is BS 3, not 4) here is the example on Codepen.

Body:
I think these are the selectors you are trying to find:

.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
    width: 200px;
    height: 200px;
}

.carousel-control .glyphicon-chevron-left:before,
.carousel-control .glyphicon-chevron-right:before {
    font-size: 200px;
}

So fitted into a Bootstrap 3 environment (as based on OP's markup this is BS 3, not 4) here is the example on Codepen.


问:
How to reload the View in MVVM?
```<code><Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Margin" Value="5" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid
                    Grid.IsSharedSizeScope ="False"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Center"
                    ScrollViewer.CanContentScroll="True"
                    ScrollViewer.HorizontalScrollBarVisibility="Visible">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid Grid.Row="0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <RadioButton
                            Name="RadioButton"
                            Grid.Column="0"
                            Margin="16"
                            VerticalAlignment="Center"
                            IsChecked="False" />
                        <TextBlock
                            Grid.Column="1"
                            HorizontalAlignment="Left"
                            VerticalAlignment="Center"
                            FontFamily="{StaticResource RRWFont}"
                            FontSize="{Binding FontSize, ElementName=TextBlock}"
                            Foreground="{StaticResource DarkGrey}"
                            Text="{Binding Path=Content.Name}"
                            TextAlignment="Left"
                            TextWrapping="Wrap" />
                    </Grid>
                    <Image
                        Grid.Row="1"
                        Width="auto"
                        Height="auto"
                        Source="{Binding Path=Content.File}" />
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter TargetName="RadioButton" Property="IsChecked" Value="True" />
                    </Trigger>
                    <Trigger SourceName="RadioButton" Property="IsChecked" Value="True">
                        <Setter Property="IsSelected" Value="True" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

XAML (ListBox)

```<code>   <ListBox
        Grid.Column="1"
        HorizontalAlignment="Center"
        Background="{x:Null}"
        BorderBrush="{x:Null}"
        ItemContainerStyle="{StaticResource ListBoxItemStyle}"
        ItemsSource="{Binding Path=AnswersVariants}"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        SelectedItem="{Binding Path=SelectAnswer, Mode=TwoWay}"
        SelectionMode="Single">

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Loaded="ListBoxWrapPanel_Loaded"
                    Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</code>```

C#

```<code>private void ListBoxWrapPanel_Loaded(object sender, RoutedEventArgs e)
{
    if (!(sender is WrapPanel panel))
        return;
    if (panel.Children.Count == 0)
        return;

    var max = (from FrameworkElement panelChild in panel.Children
            select panelChild.ActualWidth + panelChild.Margin.Left + panelChild.Margin.Right)
        .Concat(new double[] { 0 }).Max();
    panel.ItemWidth = max;
}
</code>```

I have this ContentControl: (class names have been changed)

```<code>*XAML:*
ContentControl
            Content="{Binding CurrentContent}"
 I change the CurrentContent like this:

CurrentContent = new ContentOne();
CurrentContent = new ContentTwo();
</code>```

INotifyPropertyChanged, etc. for MVVM is created and it all works
correctly.

There is such a problem. When one CurrentContent changes to another,
but of the same class, the View does not change, it only changes the
data.

Those.

```<code>CurrentContent = new ContentOne(); //1
---over time
CurrentContent = new ContentOne(); //2
</code>```

In the second case, View remains the same.

This causes a problem, because in View there is a ListBox, ItemPanel
which represents WrapPanel. For all WP children, the heights and
widths are the same and are set during the initialization of the View
by finding the greatest widths and heights. When the ViewModel
changes, but View does not change, the following can happen:

View for *1:

View for *2:

You will not be able to recalculate altitudes and widths, because they
are considered when they are not already set for WrapPanel, and in the
case of * 2 they are already set.

P.S. In this case everything works correctly:

```<code>CurrentContent = new ContentOne();
---over time
CurrentContent = new ContentTwo();
---over time
CurrentContent = new ContentOne();
</code>```

答: Instead of WrapPanel, you need to use UniformGrid.</p>

Title: How to reload the View in MVVM?

Body:
XAML (ListBox)

   <ListBox
        Grid.Column="1"
        HorizontalAlignment="Center"
        Background="{x:Null}"
        BorderBrush="{x:Null}"
        ItemContainerStyle="{StaticResource ListBoxItemStyle}"
        ItemsSource="{Binding Path=AnswersVariants}"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        SelectedItem="{Binding Path=SelectAnswer, Mode=TwoWay}"
        SelectionMode="Single">

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Loaded="ListBoxWrapPanel_Loaded"
                    Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

C#

private void ListBoxWrapPanel_Loaded(object sender, RoutedEventArgs e)
{
    if (!(sender is WrapPanel panel))
        return;
    if (panel.Children.Count == 0)
        return;

    var max = (from FrameworkElement panelChild in panel.Children
            select panelChild.ActualWidth + panelChild.Margin.Left + panelChild.Margin.Right)
        .Concat(new double[] { 0 }).Max();
    panel.ItemWidth = max;
}

I have this ContentControl: (class names have been changed)

*XAML:*
ContentControl
            Content="{Binding CurrentContent}"
 I change the CurrentContent like this:

CurrentContent = new ContentOne();
CurrentContent = new ContentTwo();

INotifyPropertyChanged, etc. for MVVM is created and it all works
correctly.

There is such a problem. When one CurrentContent changes to another,
but of the same class, the View does not change, it only changes the
data.

Those.

CurrentContent = new ContentOne(); //1
---over time
CurrentContent = new ContentOne(); //2

In the second case, View remains the same.

This causes a problem, because in View there is a ListBox, ItemPanel
which represents WrapPanel. For all WP children, the heights and
widths are the same and are set during the initialization of the View
by finding the greatest widths and heights. When the ViewModel
changes, but View does not change, the following can happen:

View for *1:

View for *2:

You will not be able to recalculate altitudes and widths, because they
are considered when they are not already set for WrapPanel, and in the
case of * 2 they are already set.

P.S. In this case everything works correctly:

CurrentContent = new ContentOne();
---over time
CurrentContent = new ContentTwo();
---over time
CurrentContent = new ContentOne();


问:
php email image not display in gmail

I want to display image in email that send from php. In yahoo the image was display but in gmail the image is missing.

This is the code for display image

```<code> <a href="{{ url:site }}user/active/{{ id }}/{{ code }}"><img alt="" data-pyroimage="true" src="{{ url:site }}image/sample.png" style="width:66%;" /></a>
</code>```

This is the image url after i inspect in gmail

```<code><a href="http://ipaddress/user/active/123456/123cp00a42c9b78514000c53f8294e5ec0d0aasgd" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&q=http://ipaddress/users/activate/123456/123cp00a42c9b78514000c53f8294e5ec0d0aasgd&source=gmail&ust=1233456567575&usg=AFQjCNGTV3UZZ4wSgFSsx_rcn7-mh3UUxw"><img alt="" src="https://ci5.googleusercontent.com/proxy/KaJG60d7WUoIwstJlDYAp8vLq1SSpmWyOZlrgZtUJMtHoBCEr863637_4tdJaibPlgJy7jnzXHs5RGv8C3g=s0-d-e1-ft#http://ipaddress/image/sample.png" style="width:66%" class="CToWUd"></a>
</code>```

答:
I would suggest using the img plugin function to reveal a physical file location. If that's an image in the public directory something like this might work:

```<code>{{ img('public::image/sample.png').url }}
</code>```

Then you can bet that Google will treat it much like a native image source.

Title: php email image not display in gmail

Body:
I want to display image in email that send from php. In yahoo the image was display but in gmail the image is missing.

This is the code for display image

This is the image url after i inspect in gmail

Body:
I would suggest using the img plugin function to reveal a physical file location. If that's an image in the public directory something like this might work:

{{ img('public::image/sample.png').url }}

Then you can bet that Google will treat it much like a native image source.


问:
Delete Specific getstream feed
I want to delete getstream feed (Single complete stream like TIMELINE:200) by using nodejs client

```<code>const timeline = client.feed('TIMELINE', '200');
timeline.delete(); // this line throws error
</code>```

TypeError: timeline_200.feed.delete is not a function

答:
We don't currently have an API endpoint or SDK method to delete a feed.

Generally it's not an issue - hypothetically, let's say a user (who has some feeds) deletes/deactivates their account from your app. Whenever that user returns to your app, they won't be able to log in, but you also won't be making the requests to retrieve their feed server-side. That feed (and the associated activities) still exist somewhere, but you just won't access them from your application.

Hopefully this helps!

Title: Delete Specific getstream feed

Body:
I want to delete getstream feed (Single complete stream like TIMELINE:200) by using nodejs client

const timeline = client.feed('TIMELINE', '200');
timeline.delete(); // this line throws error

TypeError: timeline_200.feed.delete is not a function


问:
3 toggle sort of table column
I have a table of food and calories. I found snippets to allow me to sort the calorie column ASC and DESC. But what I would like to do is to have it also go back to the original display on the third click. So on page load, the table is in a certain order. On the first click, it sorts the table in ascending order by the values in the calorie column, on the second click it sorts in descending order. How would I go about, on the third click, to have it go back to the original order?
Here is the snippet I found, thanks to SO:

```<code>const sortTable = (f,n) => {
    var rows = $('.meal-foods-table tbody tr').get();
    rows.sort((a, b) => {

        var A = getVal(a);
        var B = getVal(b);
        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm) {
        var v = $(elm).children('td').eq(2).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, (index, row) => {
        $('.meal-foods-table').children('tbody').append(row);
    });
}

const sortHeaders = () => {
    var f_nm = 1;

    $("#cal").on('click', 'button.sort-cal', () => {
        f_nm *= -1;
        var n = $(this).prevAll().length;
        sortTable(f_nm,n);
    });
}
</code>```

This is the HTML for the table:

```<code><table class="meal-foods-table">
    <thead>
      <tr>
        <th class="hidden"></th>
        <th id='name'>Name</th>
        <th id='cal' class='cal-header'><button class='sort-cal'>Calories</button></th>
      </tr>
    </thead>
    <tbody class="meal-foods-body">
    </tbody>
  </table>
</code>```

The table is populated dynamically, here is t he code for that part:

```<code>const prependMealFood = (food) => {
  $(`<tr id=${food.id}>
    <td><input id='food-${food.id}' type="checkbox"></td>
      <td class='food-name' contenteditable='true'>${food.name}</td>
      <td class='food-calories' contenteditable='true'>${food.calories}</td>
      </tr>`).prependTo('tbody.meal-foods-body')
}
</code>```

Thanks for the help :D

答:
You are destructively sorting. You are grabbing the list from the HTML, sorting it, and then pasting it back into the same place you grabbed it from. If you want to get back to the original sort order, you must keep a copy of the original list. </p>

```<code>var originalRows = $('.meal-foods-table tbody tr').get();
const sortTable = (f,n) => {
    var rows;
    if(f == 0) {
        $.each(originalRows, (index, row) => {
            $('.meal-foods-table').children('tbody').append(row);
        });
        return;
    }
    rows = [].concat(originalRows);
    rows.sort((a, b) => {

        var A = getVal(a);
        var B = getVal(b);
        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm) {
        var v = $(elm).children('td').eq(2).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, (index, row) => {
        $('.meal-foods-table').children('tbody').append(row);
    });
}
const sortHeaders = () => {
    var f_nm = -1;

    $("#cal").on('click', 'button.sort-cal', () => {
        var n = $(this).prevAll().length;
        switch(f_nm) {
          case 0:
            f_nm = -1;
            break;
          case -1:
            f_nm = 1;
          default:
            f_nm = 0;
        }
        sortTable(f_nm,n);
    });
}
</code>```

Title: 3 toggle sort of table column

Body:
I have a table of food and calories. I found snippets to allow me to sort the calorie column ASC and DESC. But what I would like to do is to have it also go back to the original display on the third click. So on page load, the table is in a certain order. On the first click, it sorts the table in ascending order by the values in the calorie column, on the second click it sorts in descending order. How would I go about, on the third click, to have it go back to the original order?
Here is the snippet I found, thanks to SO:

const sortTable = (f,n) => {
    var rows = $('.meal-foods-table tbody tr').get();
    rows.sort((a, b) => {

        var A = getVal(a);
        var B = getVal(b);
        if(A  B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm) {
        var v = $(elm).children('td').eq(2).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, (index, row) => {
        $('.meal-foods-table').children('tbody').append(row);
    });
}

const sortHeaders = () => {
    var f_nm = 1;

    $("#cal").on('click', 'button.sort-cal', () => {
        f_nm *= -1;
        var n = $(this).prevAll().length;
        sortTable(f_nm,n);
    });
}

This is the HTML for the table:

        Name
        <button class='sort-cal'>Calories</button>

The table is populated dynamically, here is t he code for that part:

const prependMealFood = (food) => {
  $(`

    <input id='food-${food.id}' type="checkbox">
      ${food.name}
      ${food.calories}

`).prependTo('tbody.meal-foods-body')
}

Thanks for the help :D

Body:
You are destructively sorting. You are grabbing the list from the HTML, sorting it, and then pasting it back into the same place you grabbed it from. If you want to get back to the original sort order, you must keep a copy of the original list.

var originalRows = $('.meal-foods-table tbody tr').get();
const sortTable = (f,n) => {
    var rows;
    if(f == 0) {
        $.each(originalRows, (index, row) => {
            $('.meal-foods-table').children('tbody').append(row);
        });
        return;
    }
    rows = [].concat(originalRows);
    rows.sort((a, b) => {

        var A = getVal(a);
        var B = getVal(b);
        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm) {
        var v = $(elm).children('td').eq(2).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, (index, row) => {
        $('.meal-foods-table').children('tbody').append(row);
    });
}
const sortHeaders = () => {
    var f_nm = -1;

    $("#cal").on('click', 'button.sort-cal', () => {
        var n = $(this).prevAll().length;
        switch(f_nm) {
          case 0:
            f_nm = -1;
            break;
          case -1:
            f_nm = 1;
          default:
            f_nm = 0;
        }
        sortTable(f_nm,n);
    });
}


问:
Display Image in a Data Table from a local path in R Shiny
I am trying to display the Image in a Data Table from a local path. Please note the local path is different from www folder and in real scenario, I can not move the images from the prescribed path to www folder. Strange thing is that it is working from www location and but not from the prescribed path. Looking for any tips to resolve this.

Here is the code:

```<code>library(shiny)
library(shinyBS)
library(DT)

flag <- data.frame(image=c('<img src="C:/Users/string/100x100/100x100_bigimg.jpg"></img>'))

ui <- shinyUI(pageWithSidebar(
headerPanel("renderImage example"),
sidebarPanel(
actionButton("go","Go")
),
mainPanel(
bsModal("modalExample", "Image", "go", size =    "large",imageOutput("myImage")),

DT::dataTableOutput("dt")

)
))

server <- shinyServer(function(input, output, session) {

output$dt <- DT::renderDataTable({
DT::datatable(flag,escape = FALSE )
})

observeEvent(input$go,{
output$myImage <- renderImage({
# Return a list containing the filename
return(list(src = "C:/Users/string/100x100/100x100_bigimg.jpg",
     contentType = 'image/png',
     width = 550,
     height = 400,
     alt = "This is alternate text"))
}, deleteFile = FALSE)

})

})

shinyApp(ui,server)
</code>```

Also, from prescribed path renderImage part is working perfectly but in data table part image is not getting displayed.

答:
This can be achieved using addResourcePath - Applicable to Windows as well as Shiny web Server.It adds directory of static resource. https://shiny.rstudio.com/reference/shiny/latest/addResourcePath.html

Here is the working example:

ui.R

```<code>library(shiny)
library(shinydashboard)
library(shinyBS)
library(DT)

dashboardPage(
dashboardHeader(title = span(tagList(icon("image"), "Example"))),
dashboardSidebar(),
dashboardBody(

div(style="display:inline-block",uiOutput("infoButton")),

DT::dataTableOutput("table2")

 )
)
</code>```

Server.R

```<code>addResourcePath("Images","D/HDImages") # Images are located outside shiny App

LeafNames <- c('Leaf1.jpg','Leaf2.jpg','Leaf3.jpg','Leaf4.jpg','Leaf5.jpg','Leaf6.jpg','Leaf7.jpg','Leaf8.jpg','Leaf9.jpg','Leaf10.jpg')
LeafTable <- data.frame(LeafNames)
LeafTable<- within(LeafTable, thumbnail <- paste0("<img
src='","Images/",LeafTable$LeafNames,"' height='50'></img>"))

function(input, output) {

output$table2<-DT::renderDataTable({

responseDataFilter2 <- LeafTable[,c(2,1)]

displayableData<-DT::datatable(data = as.data.frame(responseDataFilter2, stringAsFactors = FALSE, row.names = NULL),

                               escape=FALSE,selection="single",rownames=FALSE,colnames=c(" ","Name"),

                               callback = JS("table.on('dblclick.dt', 'td', function() {
                                             var row=table.cell(this).index().row;
                                             Shiny.onInputChange('rows_home',[row, Math.random()])});
                                             table.on('click.dt', 'td', function() {
                                             var k=table.cell(this).index().row;
                                             if(table.rows('.selected').indexes().toArray()!= '' && table.rows('.selected').indexes().toArray() == k){k=-1;}
                                             Shiny.onInputChange('rows_up_home',[k, Math.random()]);
                                             Shiny.onInputChange('row_path', table.rows(this).data().toArray());
                                             });"),

                               options = list(

                                 paging=FALSE,searching = FALSE,ordering=FALSE,scrollY = 750,scrollCollapse=TRUE,server = TRUE

                               ))

})

output$infoButton = renderUI({
s = input$table2_rows_selected # Row number of selected row
if (length(s)!= 0) {
  tagList(
    actionButton("info", "",icon("info-circle"),style="color:rgb(57,156,8);border-color:rgb(255,255,255)"),

    # Information Dialog Box
    bsModal("ObjectInfo", LeafTable[s,c(1)], "info", size = "large", # Enables Pop up Screen

            img(src= paste0("Images/",LeafTable[s,c(1)]),width='800',height='600')

    )
  )

}
})

}
</code>```

Body:
I am trying to display the Image in a Data Table from a local path. Please note the local path is different from www folder and in real scenario, I can not move the images from the prescribed path to www folder. Strange thing is that it is working from www location and but not from the prescribed path. Looking for any tips to resolve this.

Here is the code:

library(shiny)
library(shinyBS)
library(DT)

flag <- data.frame(image=c(''))

ui <- shinyUI(pageWithSidebar(
headerPanel("renderImage example"),
sidebarPanel(
actionButton("go","Go")
),
mainPanel(
bsModal("modalExample", "Image", "go", size =    "large",imageOutput("myImage")),

DT::dataTableOutput("dt")

)
))

server <- shinyServer(function(input, output, session) {

output$dt <- DT::renderDataTable({
DT::datatable(flag,escape = FALSE )
})

observeEvent(input$go,{
output$myImage <- renderImage({
# Return a list containing the filename
return(list(src = "C:/Users/string/100x100/100x100_bigimg.jpg",
     contentType = 'image/png',
     width = 550,
     height = 400,
     alt = "This is alternate text"))
}, deleteFile = FALSE)

})

})

shinyApp(ui,server)

Also, from prescribed path renderImage part is working perfectly but in data table part image is not getting displayed.

Body:
This can be achieved using addResourcePath - Applicable to Windows as well as Shiny web Server.It adds directory of static resource. https://shiny.rstudio.com/reference/shiny/latest/addResourcePath.html

Here is the working example:

ui.R

library(shiny)
library(shinydashboard)
library(shinyBS)
library(DT)

dashboardPage(
dashboardHeader(title = span(tagList(icon("image"), "Example"))),
dashboardSidebar(),
dashboardBody(

div(style="display:inline-block",uiOutput("infoButton")),

DT::dataTableOutput("table2")

 )
)

Server.R

addResourcePath("Images","D/HDImages") # Images are located outside shiny App

LeafNames <- c('Leaf1.jpg','Leaf2.jpg','Leaf3.jpg','Leaf4.jpg','Leaf5.jpg','Leaf6.jpg','Leaf7.jpg','Leaf8.jpg','Leaf9.jpg','Leaf10.jpg')
LeafTable <- data.frame(LeafNames)
LeafTable<- within(LeafTable, thumbnail <- paste0("<img
src='","Images/",LeafTable$LeafNames,"' height='50'></img>"))

function(input, output) {

output$table2<-DT::renderDataTable({

responseDataFilter2 <- LeafTable[,c(2,1)]

displayableData<-DT::datatable(data = as.data.frame(responseDataFilter2, stringAsFactors = FALSE, row.names = NULL),

                               escape=FALSE,selection="single",rownames=FALSE,colnames=c(" ","Name"),

                               callback = JS("table.on('dblclick.dt', 'td', function() {
                                             var row=table.cell(this).index().row;
                                             Shiny.onInputChange('rows_home',[row, Math.random()])});
                                             table.on('click.dt', 'td', function() {
                                             var k=table.cell(this).index().row;
                                             if(table.rows('.selected').indexes().toArray()!= '' && table.rows('.selected').indexes().toArray() == k){k=-1;}
                                             Shiny.onInputChange('rows_up_home',[k, Math.random()]);
                                             Shiny.onInputChange('row_path', table.rows(this).data().toArray());
                                             });"),

                               options = list(

                                 paging=FALSE,searching = FALSE,ordering=FALSE,scrollY = 750,scrollCollapse=TRUE,server = TRUE

                               ))

})

output$infoButton = renderUI({
s = input$table2_rows_selected # Row number of selected row
if (length(s)!= 0) {
  tagList(
    actionButton("info", "",icon("info-circle"),style="color:rgb(57,156,8);border-color:rgb(255,255,255)"),

    # Information Dialog Box
    bsModal("ObjectInfo", LeafTable[s,c(1)], "info", size = "large", # Enables Pop up Screen

            img(src= paste0("Images/",LeafTable[s,c(1)]),width='800',height='600')

    )
  )

}
})

}