问:
XSL: Construct an Array from a Delimited String
I have a string in which data is separated by a delimiter like "|" and is present in a variable.
I would like to create an array in the XSL by dividing the above string based on the delimiter and would like to access the same in the in a for loop.

Please help me in this regard.
Please also let me know if anyone need any more information.

String is "Test1|Test2|Test3|Test4" and would like to get a variable TEMP which would be an array of data from the string and would like to access as TEMP[index].

I have tried to use the tokenize function after the inputs from the forum members to get the values from the string but was not successful. I am not getting the string values in the loop.

```<code><xsl:variable name="temp" xmlns:str="http://exslt.org/strings" select="str:tokenize(normalize-space(' Test1$,$Test2$,$Test3$,$Test4 '),'$,$')"/>
<xsl:for-each xmlns:str="http://exslt.org/strings" select="str:split(normalize-space(' 1$,$2$,$3$,$4$,$5$,$6 '),'$,$')">
    <xsl:variable name="index" select="position()"/>
    <xsl:value-of select="$temp[$index]"/>
</xsl:for-each>
</code>```

Regards,
Lakshman

答:
I try this, I modified the "Dimitre Novatchev" code, and works for me: (please excuse me for my English)

```<code><?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:msxsl="urn:schemas-microsoft-com:xslt"
            exclude-result-prefixes="msxsl">

<xsl:template match="/*">
        <xsl:variable name="_keywords">
            <xsl:call-template name="split-to-values">
                <xsl:with-param name="_text" select="Keywords-comma-separated"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:for-each select="msxsl:node-set($_keywords)/value">
            <xsl:variable name="_keyword" select="."/>
            <!-- ANY CODE -->
        </xsl:for-each>
</xsl:template>

<xsl:template match="text()" name="split-to-values">
    <xsl:param name="_text"/>

    <xsl:if test="string-length($_text)">
        <xsl:variable name="_value" select="substring-before($_text, ',')"/>
        <xsl:variable name="_next" select="substring-after($_text, ',')"/>
        <value>
            <xsl:value-of select="$_value"/>
        </value>

        <xsl:call-template name="split-to-values">
            <xsl:with-param name="_text" select="$_next"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>
</code>```

I hope it helps you

@Bugude ask

I have a string in which data is separated by a delimiter like "|" and
  is present in a variable. I would like to create an array in the XSL
  by dividing the above string based on the delimiter and would like to
  access the same in the in a for loop

Then the string may be:  "alfa,beta,gama,delta"

The delimiter is presented in a variable:

```<code><xsl:variable name="_delimiter">,</xsl:variable>
</code>```

I modified the template as:

```<code><xsl:template match="text()" name="split-to-values">
    <xsl:param name="_text"/>
    <xsl:param name="_delimiter"/>

    <xsl:if test="string-length($_text)">
        <xsl:variable name="_value" select="substring-before($_text, $_delimiter)"/>
        <xsl:variable name="_next" select="substring-after($_text, $_delimiter)"/>
        <value>
            <xsl:value-of select="$_value"/>
        </value>

        <xsl:call-template name="split-to-values">
            <xsl:with-param name="_text" select="$_next"/>
            <xsl:with-param name="_delimiter" select="$_delimiter"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>
</code>```

And we can access to the nodes as similar an array with a for

```<code><xsl:template match="/*">
        <!-- _keyword as set a node -->
        <xsl:variable name="_keywords">
            <xsl:call-template name="split-to-values">
                <xsl:with-param name="_text" select="'alfa,beta,gama,delta'"/>
                <xsl:with-param name="_delimiter" select="$_delimiter"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:for-each select="msxsl:node-set($_keywords)/value">
            <xsl:variable name="_keyword" select="."/>
            <!-- ANY CODE -->
            <xsl:value-of select="$_keyword"/>
        </xsl:for-each>
</xsl:template>
</code>```

Body:
I have a string in which data is separated by a delimiter like "|" and is present in a variable.
I would like to create an array in the XSL by dividing the above string based on the delimiter and would like to access the same in the in a for loop.

Please help me in this regard.
Please also let me know if anyone need any more information.

String is "Test1|Test2|Test3|Test4" and would like to get a variable TEMP which would be an array of data from the string and would like to access as TEMP[index].

I have tried to use the tokenize function after the inputs from the forum members to get the values from the string but was not successful. I am not getting the string values in the loop.

<xsl:variable name="temp" xmlns:str="http://exslt.org/strings" select="str:tokenize(normalize-space(' Test1$,$Test2$,$Test3$,$Test4 '),'$,$')"/>
<xsl:for-each xmlns:str="http://exslt.org/strings" select="str:split(normalize-space(' 1$,$2$,$3$,$4$,$5$,$6 '),'$,$')">
    <xsl:variable name="index" select="position()"/>
    <xsl:value-of select="$temp[$index]"/>
</xsl:for-each>

Regards,
Lakshman

Body:
I try this, I modified the "Dimitre Novatchev" code, and works for me: (please excuse me for my English)

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:msxsl="urn:schemas-microsoft-com:xslt"
            exclude-result-prefixes="msxsl">

<xsl:template match="/*">
        <xsl:variable name="_keywords">
            <xsl:call-template name="split-to-values">
                <xsl:with-param name="_text" select="Keywords-comma-separated"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:for-each select="msxsl:node-set($_keywords)/value">
            <xsl:variable name="_keyword" select="."/>
            <!-- ANY CODE -->
        </xsl:for-each>
</xsl:template>

<xsl:template match="text()" name="split-to-values">
    <xsl:param name="_text"/>

    <xsl:if test="string-length($_text)">
        <xsl:variable name="_value" select="substring-before($_text, ',')"/>
        <xsl:variable name="_next" select="substring-after($_text, ',')"/>
        <value>
            <xsl:value-of select="$_value"/>
        </value>

        <xsl:call-template name="split-to-values">
            <xsl:with-param name="_text" select="$_next"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

I hope it helps you

@Bugude ask

I have a string in which data is separated by a delimiter like "|" and
  is present in a variable. I would like to create an array in the XSL
  by dividing the above string based on the delimiter and would like to
  access the same in the in a for loop

Then the string may be:  "alfa,beta,gama,delta"

The delimiter is presented in a variable:

<xsl:variable name="_delimiter">,</xsl:variable>

I modified the template as:

<xsl:template match="text()" name="split-to-values">
    <xsl:param name="_text"/>
    <xsl:param name="_delimiter"/>

    <xsl:if test="string-length($_text)">
        <xsl:variable name="_value" select="substring-before($_text, $_delimiter)"/>
        <xsl:variable name="_next" select="substring-after($_text, $_delimiter)"/>
        <value>
            <xsl:value-of select="$_value"/>
        </value>

        <xsl:call-template name="split-to-values">
            <xsl:with-param name="_text" select="$_next"/>
            <xsl:with-param name="_delimiter" select="$_delimiter"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

And we can access to the nodes as similar an array with a for

<xsl:template match="/*">
        <!-- _keyword as set a node -->
        <xsl:variable name="_keywords">
            <xsl:call-template name="split-to-values">
                <xsl:with-param name="_text" select="'alfa,beta,gama,delta'"/>
                <xsl:with-param name="_delimiter" select="$_delimiter"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:for-each select="msxsl:node-set($_keywords)/value">
            <xsl:variable name="_keyword" select="."/>
            <!-- ANY CODE -->
            <xsl:value-of select="$_keyword"/>
        </xsl:for-each>
</xsl:template>


来源: stackexchange

问:
Dropdownlist binding in ASP.NET
Let's say I have a dropdownlist with datasource in a page, I can create the dropdownlist and it is automatically fiiled with data in the datasrouce, I don't need to use .bind() method, but why I still see some programmers still use .bind() method in Page_Load? what's the purpose of doing it if ASP.NET automatically does the job for you?</p>

答: You don't need it because you have set it in aspx mark up. But if you specify datasource in code behind then you need to bind it explicitly.

ContentLicense: CC BY-SA 3.0

Title: Dropdownlist binding in ASP.NET


问:
Web API resulting in Memory Usage 99%, Didn't drop down
I am using MVC 4 & have created a Standalone Utility application which sends data after every 30 minutes to the cloud database.

I can notice on the cloud server CPU Memory Usage goes up to 99% & i have to restart the IIS when this happens. There is no dropping of the Memory when ti reaches above 90%.

Is there some thing that i can change in my code? Or How to handle this?

Following is the Code :-
API Calling Method :-

```<code>List<IEnumerable<Logs>> listOfLists = new List<IEnumerable<Logs>>();
                            for (int i = 0; i < lst.Count(); i += 50)
                            {
                                listOfLists.Add(lst.Skip(i).Take(50));
                            }
                            int count = 0;
                            foreach (var data in listOfLists)
                            {
                                count = count + data.Count();
                                string url = UrlLink + "/api/SaveEmployee?Schema=" + Schema;
                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                request.Timeout = 20000000; request.Proxy = null; request.KeepAlive = true;
                                request.KeepAlive = true;
                                request.ContentType = "application/json; charset=utf-8";
                                request.Accept = "application/json, text/javascript, *"; request.Proxy = null;
                                request.Method = "Post";
                                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                                {
                                    streamWriter.Write(JsonConvert.SerializeObject(data));
                                    streamWriter.Flush();
                                }
                                try
                                {
                                    using (WebResponse response = request.GetResponse())
                                    {
                                        Stream stream = response.GetResponseStream();
                                        var rawJson = new StreamReader(stream).ReadToEnd();
                                        lst = (JsonConvert.DeserializeObject<List<Logs>>(rawJson));

                                                using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
                                                using (StreamWriter sw = new StreamWriter(fs))
                                                {
                                                    sw.WriteLine(data.Count());
                                                }
                                    }
                                }
                                catch (Exception ee)
                                {

                                }
                                finally
                                {
                                    request.Abort();
                                }
}
</code>```

API Method :-

```<code>[AcceptVerbs("GET", "POST")]
        public void SaveEmployee(string Schema)
        {
            using (var ctx = new ApplicationDbContext(Schema))
            {
                ctx.Configuration.AutoDetectChangesEnabled = false;
                var d1 = Request.Content.ReadAsStreamAsync().Result;
                var rawJson = new StreamReader(d1).ReadToEnd();
            }
         }
</code>```

答:
var rawJson = new StreamReader(d1).ReadToEnd();

According to your API Method, I found you don't release the StreamReader resource. I guess this is the reason why your CPU memory is 99%.

StreamReader, StreamWriter, BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferably with a using statement.

So I suggest you could change the webapi method as below:

```<code>       ctx.Configuration.AutoDetectChangesEnabled = false;
       var d1 = Request.Content.ReadAsStreamAsync().Result;
       using (StreamReader sr = new StreamReader(d1))
                {
                    string rawJson = sr.ReadToEnd();
                    //....Then you could return the response
                }
</code>```

Body:
I am using MVC 4 & have created a Standalone Utility application which sends data after every 30 minutes to the cloud database.

I can notice on the cloud server CPU Memory Usage goes up to 99% & i have to restart the IIS when this happens. There is no dropping of the Memory when ti reaches above 90%.

Is there some thing that i can change in my code? Or How to handle this?

Following is the Code :-
API Calling Method :-

List<IEnumerable<Logs>> listOfLists = new List<IEnumerable<Logs>>();
                            for (int i = 0; i < lst.Count(); i += 50)
                            {
                                listOfLists.Add(lst.Skip(i).Take(50));
                            }
                            int count = 0;
                            foreach (var data in listOfLists)
                            {
                                count = count + data.Count();
                                string url = UrlLink + "/api/SaveEmployee?Schema=" + Schema;
                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                                request.Timeout = 20000000; request.Proxy = null; request.KeepAlive = true;
                                request.KeepAlive = true;
                                request.ContentType = "application/json; charset=utf-8";
                                request.Accept = "application/json, text/javascript, *"; request.Proxy = null;
                                request.Method = "Post";
                                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                                {
                                    streamWriter.Write(JsonConvert.SerializeObject(data));
                                    streamWriter.Flush();
                                }
                                try
                                {
                                    using (WebResponse response = request.GetResponse())
                                    {
                                        Stream stream = response.GetResponseStream();
                                        var rawJson = new StreamReader(stream).ReadToEnd();
                                        lst = (JsonConvert.DeserializeObject<List<Logs>>(rawJson));

                                                using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
                                                using (StreamWriter sw = new StreamWriter(fs))
                                                {
                                                    sw.WriteLine(data.Count());
                                                }
                                    }
                                }
                                catch (Exception ee)
                                {

                                }
                                finally
                                {
                                    request.Abort();
                                }
}

API Method :-

[AcceptVerbs("GET", "POST")]
        public void SaveEmployee(string Schema)
        {
            using (var ctx = new ApplicationDbContext(Schema))
            {
                ctx.Configuration.AutoDetectChangesEnabled = false;
                var d1 = Request.Content.ReadAsStreamAsync().Result;
                var rawJson = new StreamReader(d1).ReadToEnd();
            }
         }

Body:
var rawJson = new StreamReader(d1).ReadToEnd();

According to your API Method, I found you don't release the StreamReader resource. I guess this is the reason why your CPU memory is 99%.

StreamReader, StreamWriter, BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferably with a using statement.

So I suggest you could change the webapi method as below:

       ctx.Configuration.AutoDetectChangesEnabled = false;
       var d1 = Request.Content.ReadAsStreamAsync().Result;
       using (StreamReader sr = new StreamReader(d1))
                {
                    string rawJson = sr.ReadToEnd();
                    //....Then you could return the response
                }


答:
Test Code:

```<code>import pandas as pd
df = pd.DataFrame([[1, 1.0, 2.3], [2, 3.4, 2.0]],
                  columns=["Sample_ID", "NaX", "NaU"])\
    .set_index('Sample_ID')

s = pd.DataFrame([['NaX', 0.2], ['NaU', 0.1]],
                   columns=['Sample_ID', 'Blank'])\
    .set_index('Sample_ID').Blank

print(df)
print(s)
print(df-s)
</code>```

Result:

```<code>           NaX  NaU
Sample_ID
1          1.0  2.3
2          3.4  2.0

Sample_ID
NaX    0.2
NaU    0.1
Name: Blank, dtype: float64

           NaX  NaU
Sample_ID
1          0.8  2.2
2          3.2  1.9
</code>```

Title: Subtract Dataframe using data in series

Body:
I have a pandas.DataFrame with multiple columns of data

Example Dataframe:

Sample_ID, NaX, NaU
1,         1.0, 2.3
2,         3.4, 2.0

Data Series:

Sample_ID: Blank
NaX        0.2
NaU        0.1

Is there a way to subtract the DataFrame with values in the Series?

The end result I am looking for is as follows:
Example Dataframe blank corrected:

Sample_ID, NaX, NaU
1,         0.8, 2.2
2,         3.2, 1.9

Thanks.

Larger Data Series:

Sample_ID,572,,
NaX,3073.333333,,
NaU,126.666667,,
MgX,3081.666667,,
MgU,69.333333,,
AlX,5275.333333,,
AlU,48.333333,,
SiX,554966.6667,,
SiU,366.666667,,
PX,294.866667,,
PU,3.333333,,
SX,0,,
SU,0,,
ClX,153.033333,,
ClU,1.266667,,
ArX,NaN,,
ArU,NaN,,
KX,684.666667,,
KU,13.666667,,
CaX,6771.333333,,
CaU,33.666667,,
ScX,43,,
ScU,12,,
TiX,75.433333,,
TiU,4.166667,,
VX,12.533333,,
VU,3.633333,,
CrX,74.6,,
CrU,3.033333,,
MnX,35.6,,
,...,,
AgX,0,,
AgU,0,,
CdX,0,,
CdU,0,,
SnX,0,,
SnU,0,,
SbX,0,,
SbU,0,,
TeX,0,,
TeU,0,,
IX,0,,
IU,0,,
CsX,0,,
CsU,0,,
BaX,0,,
BaU,0,,
LaX,0,,
LaU,0,,
CeX,0,,
CeU,0,,
SmX,0,,
SmU,0,,
WX,0,,
WU,0,,
HgX,0,,
HgU,0,,
PbX,0,,
PbU,0,,
BiX,0,,
BiU,0,,
Length:,"87,",dtype:,float64

Larger DataFrame:

Sample_ID,NaX,NaU,MgX,MgU,AlX,AlU,SiX,SiU,PX,PU,...,SmX,SmU,WX,WU,HgX,HgU,PbX,PbU,BiX,BiU
6,332,9470,230,2680,110,6257,55,372700,300,1836,...,0,0,0,0,0,0,297,10,0,0
7,332_Repeat,8940,230,2690,110,6199,55,383500,300,1754,...,0,0,0,0,0,0,215,11,0,0
8,346,10470,260,2500,120,7004,56,253300,200,2586,...,0,0,0,0,0,0,676,13,0,0
9,347,2740,160,1530,79,4799,51,521200,300,530.8,...,0,0,0,0,0,0,107.3,8.8,0,0
10,348,5260,190,1749,91,5506,53,448400,300,1143,...,0,0,0,0,0,0,211,10,0,0
11,348_Repeat,5510,190,1795,91,5486,53,447600,300,1138,...,0,0,0,0,0,0,174,10,0,0
17,427,0,0,3484,75,5093,48,529000,300,560,...,0,0,0,0,0,0,0,0,0,0
18,427_Repeat,0,0,3598,76,5096,48,529900,300,557.8,...,0,0,0,0,0,0,0,0,0,0
19,428,3410,140,5602,86,7590,56,562600,300,794.2,...,0,0,0,0,0,0,8.3,7.3,0,0
20,429,0,0,3977,78,5107,49,530300,300,594.6,...,0,0,0,0,0,0,0,0,0,0
21,430,3530,140,5626,88,7944,57,559800,300,899,...,0,0,0,0,0,0,3.8,3.8,0,0
22,447,139200,300,0,0,2473,27,135200,100,432.2,...,0,0,0,0,0,0,0,0,0,0
23,447_Repeat,138900,300,0,0,2504,26,135400,100,440.3,...,0,0,0,0,0,0,0,0,0,0
24,448,141900,400,0,0,1829,26,73970,60,419.7,...,0,0,0,0,0,0,0,0,0,0
25,449,169700,400,0,0,2034,26,40150,40,420.5,...,0,0,0,0,0,0,0,0,0,0
26,567,168400,600,9460,200,1894,52,20560,40,1474,...,0,0,0,0,0,0,1.2,1.2,0,0
27,568,169300,600,3230,190,1455,51,11370,30,1414,...,0,0,0,0,0,0,6.9,6.9,0,0
28,568_Repeat,169400,600,3200,190,1462,51,11340,30,1406,...,0,0,0,0,0,0,5.3,5.3,0,0
35,7320,174700,500,3470,110,8720,48,129100,100,452.7,...,0,0,0,0,0,0,19,8.2,0,0
36,7323,176500,500,0,0,4928,51,71390,80,572.8,...,0,0,0,0,0,0,17.2,8.1,0,0
37,7326,56390,220,26440,110,24600,60,320900,200,242.1,...,0,0,0,0,0,0,22.3,7.8,0,0

Series and Frame as images:

Body:
Test Code:

import pandas as pd
df = pd.DataFrame([[1, 1.0, 2.3], [2, 3.4, 2.0]],
                  columns=["Sample_ID", "NaX", "NaU"])\
    .set_index('Sample_ID')

s = pd.DataFrame([['NaX', 0.2], ['NaU', 0.1]],
                   columns=['Sample_ID', 'Blank'])\
    .set_index('Sample_ID').Blank

print(df)
print(s)
print(df-s)

Result:

           NaX  NaU
Sample_ID
1          1.0  2.3
2          3.4  2.0

Sample_ID
NaX    0.2
NaU    0.1
Name: Blank, dtype: float64

           NaX  NaU
Sample_ID
1          0.8  2.2
2          3.2  1.9


问:
How to let only certain people test interal itunes connect testing
So this seems rather dumb I have to ask seeing as it's all over the itunes connect page. But my question is rather simple. I want to release a test flight version out but only allow certain people access to it. We need to test things on our dev server but don't want ALL of our testers using the dev server (they would get confused). When I go to Test Flight --> iOS --> (click on version) --> There's a Groups tab. And it lists the groups for this build to test on... okay. That's fine. Except there's no way to delete a group. I just want to submit a built to test flight and just allow certain people access to it. Is this possible?

UPDATE

Screenshot of what im talking about

答:
Create a group for those specific users, and add their emails to the group. Make sure the group is selected in the left sidebar, by default it will show the list of users you just added...

But above the list you can choose the builds tab. Tap that and you will see this...

Tap the + sign and choose the build that you want to share with this group of users. If this is the first time you have shared this version of the app it may have to be approved for Beta testing by Apple.


问:
How to apply z-index to a content of div to display in above pseudo elements
I have created one table and to the last column of the table, I have added pseudo elements. That last column contains an image. That image is getting clipped due to pseudo elements. I tried adding z-index to that image, but it's not working. HTML code:

```<code><table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
     <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
  </tr>
   <tr>
    <td>Eve</td>
    <td>Jackson</td>
     <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
  </tr>
</table>
</code>```

CSS code:

```<code>td:nth-child(3):before {
    content: '';
    width: 100%;
    display: block;
    border-top: 8px solid white;
    position: absolute;
    z-index: 1;
}
</code>```

I have regenerated the issue in following pluker:
http://plnkr.co/edit/oTGWJrAFk5esgnwTOvKE?p=preview

How to avoid an image from getting clipped?
Thank you in advance.

答:
Please refer following css just by removing z-index

```<code>td:nth-child(3)::before {
    border-top: 8px solid white;
    content: "";
    display: block;
    position: unset; //use either unset or relative
    width: 100%;
}
</code>```

This will just solve your issue
Thanks,

Body:
I have created one table and to the last column of the table, I have added pseudo elements. That last column contains an image. That image is getting clipped due to pseudo elements. I tried adding z-index to that image, but it's not working. HTML code:

    Jill
    Smith

    Eve
    Jackson

    Eve
    Jackson

CSS code:

td:nth-child(3):before {
    content: '';
    width: 100%;
    display: block;
    border-top: 8px solid white;
    position: absolute;
    z-index: 1;
}

I have regenerated the issue in following pluker:
http://plnkr.co/edit/oTGWJrAFk5esgnwTOvKE?p=preview

How to avoid an image from getting clipped?
Thank you in advance.

Body:
Please refer following css just by removing z-index

td:nth-child(3)::before {
    border-top: 8px solid white;
    content: "";
    display: block;
    position: unset; //use either unset or relative
    width: 100%;
}

This will just solve your issue
Thanks,


问:
Azure Service Fabric SDK 2.6.210 Missing Stateless Web API Template on Visual Studio 2017?
I installed the latest 2.6.210 SDK / 5.6.210 Runtime for Service Fabric on my development PC using Visual Studio 2017 and now when I choose to create a new Cloud solution the "Stateless Web API" template is gone.  I've also noticed that the "Stateless ASP.NET Core" template is no longer marked as "Pending".

I believe I can manually create the boilerplate to host a Web API service using Owin and .NET Framework using the "Stateless Service" template but why did they remove the much simpler "Stateless Web API" template that did all that for you?

I can't find any documentation from Microsoft explaining why this template would be missing.

Is Microsoft trying to get people to avoid using the .NET Framework in Service Fabric for Web API services because .NET Core ASP is no longer in preview?

Is it just a bug and if so how do I get that template back?

Thanks in advance for any assistance you can give me.

答:
The OWIN based template was only available self-hosted web framework for .NET until ASP.NET Core and .NET Core tooling in Visual Studio 2017 was release in General Availability.

Since Service Fabric cannot use IIS for hosting web services, we recommend using ASP.NET Core and provide templates in Visual Studio which integrates Service Fabric Reliable Services and ASP.NET Core Templates for MVC and Web API.

Remember you can still build your ASP.NET Core services with .NET Framework as the target and use all of .NET Framework from an ASP.NET Core Service.

Visual Studio tooling still supports the OWIN based services, and they can still run in Service Fabric.

See also here: Using WebListener or OWIN as API Gateway for azure service fabric and here for info for ASP.NET support in Service Fabric https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication-aspnetcore


问:
Selenium element not visible?
I Have a problem on Selenium in click event

```<code>WebElement btn = driver.findElement(By.xpath("//form[@name=\"addMemberForm\"]/div[14]/div/button"));
System.out.print(btn);
</code>```

the result of the print

[[ChromeDriver: chrome on LINUX (0f787065444f6b2cddf2c6ff5e6c056d)] ->
  xpath: //form[@name="addMemberForm"]/div[14]/div/button]

and when triggered with btn.click() event error says element not visible

org.openqa.selenium.ElementNotVisibleException: element not visible
    (Session info: chrome=52.0.2743.82)
    (Driver info: chromedriver=2.23.409687 (c46e862757edc04c06b1bd88724d15a5807b84d1),platform=Linux 4.2.0-42-generic x86_64) (WARNING: The server did not provide any stacktrace information)
  Command duration or timeout: 11 milliseconds
  Build info: version: 'unknown', revision: '2aa21c1', time: '2016-08-02 14:59:43 -0700'
  System info: host: 'kyben-All-Series', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.2.0-42-generic', java.version: '1.8.0_101'
  Driver info: org.openqa.selenium.chrome.ChromeDriver
  Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.23.409687 (c46e862757edc04c06b1bd88724d15a5807b84d1), userDataDir=/tmp/.org.chromium.Chromium.8Xt3v7}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=52.0.2743.82, platform=LINUX, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
  Session ID: 0f787065444f6b2cddf2c6ff5e6c056d
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:683)
      at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:319)
      at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:85)
      at testCase.teamMemberNew2.chngPassLogout(teamMemberNew2.java:127)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
      at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
      at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
      at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
      at org.testng.TestRunner.privateRun(TestRunner.java:774)
      at org.testng.TestRunner.run(TestRunner.java:624)
      at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
      at org.testng.SuiteRunner.run(SuiteRunner.java:261)
      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
      at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
      at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
      at org.testng.TestNG.run(TestNG.java:1048)
      at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
      at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
      at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)

答:
Sometimes the error message "element not visible" means you object may not be placed in your current browser window view. You may need to scroll the browser to in order to locate your object before you click.
If that is the case, you may need to scroll your browser to center your object before you click. You can add the following code before button click.

```<code>JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(false);", btn);
</code>```

Note that "btn" is your WebElement object.
The above code works in my Firefox browser. But I saw some other answers suggests to set scrollIntoView(true);. You may try both and see which one works better.

Title: Selenium element not visible?

Body:
I Have a problem on Selenium in click event

WebElement btn = driver.findElement(By.xpath("//form[@name=\"addMemberForm\"]/div[14]/div/button"));
System.out.print(btn);

the result of the print

[[ChromeDriver: chrome on LINUX (0f787065444f6b2cddf2c6ff5e6c056d)] ->
  xpath: //form[@name="addMemberForm"]/div[14]/div/button]

and when triggered with btn.click() event error says element not visible

org.openqa.selenium.ElementNotVisibleException: element not visible
    (Session info: chrome=52.0.2743.82)
    (Driver info: chromedriver=2.23.409687 (c46e862757edc04c06b1bd88724d15a5807b84d1),platform=Linux 4.2.0-42-generic x86_64) (WARNING: The server did not provide any stacktrace information)
  Command duration or timeout: 11 milliseconds
  Build info: version: 'unknown', revision: '2aa21c1', time: '2016-08-02 14:59:43 -0700'
  System info: host: 'kyben-All-Series', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.2.0-42-generic', java.version: '1.8.0_101'
  Driver info: org.openqa.selenium.chrome.ChromeDriver
  Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.23.409687 (c46e862757edc04c06b1bd88724d15a5807b84d1), userDataDir=/tmp/.org.chromium.Chromium.8Xt3v7}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=52.0.2743.82, platform=LINUX, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
  Session ID: 0f787065444f6b2cddf2c6ff5e6c056d
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:683)
      at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:319)
      at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:85)
      at testCase.teamMemberNew2.chngPassLogout(teamMemberNew2.java:127)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
      at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
      at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
      at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
      at org.testng.TestRunner.privateRun(TestRunner.java:774)
      at org.testng.TestRunner.run(TestRunner.java:624)
      at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
      at org.testng.SuiteRunner.run(SuiteRunner.java:261)
      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
      at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
      at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
      at org.testng.TestNG.run(TestNG.java:1048)
      at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
      at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
      at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)

Body:
Sometimes the error message "element not visible" means you object may not be placed in your current browser window view. You may need to scroll the browser to in order to locate your object before you click.
If that is the case, you may need to scroll your browser to center your object before you click. You can add the following code before button click.

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView(false);", btn);

Note that "btn" is your WebElement object.
The above code works in my Firefox browser. But I saw some other answers suggests to set scrollIntoView(true);. You may try both and see which one works better.


问:
Reference parent class of method when `this` seems to been reset
I'm using react google charts and am trying to use the chartEvents method to hook into the selection event.

This works:

```<code>const ChartClass = React.createClass({
  getInitialState () {
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  chartEvents: [
    {
      eventName: 'select',
      callback: function (Chart) {
         this.handleShowModal()
      }
    }
  ],
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})
</code>```

However within that callback I would like to call some other methods

```<code>this.handleOpenModal(ChartObj) // TypeError: this.handleOpenModal is not a function
this.sthElse()
</code>```

because within this callback this is being set to event itself

```<code>console.log(this) //object {eventName: "select", callback: function}
</code>```

Is there any way to reference the parent class so I can use its methods? I don't think I can simply place the function outside of the class because it needs to use this.setState

答:
React.createClass components did auto-bind all their methods, so you need to do nothing but declare the callback as a method - or just use handleShowModal directly:

```<code>const ChartClass = React.createClass({
  getInitialState() {
    return {
      showModal: false
    }
  },
  handleShowModal(Chart) {
    this.setState((prev, props) => {
      return {
        showModal: true
      }
    })
  },
  render() {
    return (
      <Chart
        chartEvents={[
          {
            eventName: 'select',
            callback: this.handleShowModal
          }
        ]}
        data={this.props.data}
      />
    )
  }
})
</code>```

Of course, given you are using ES6 anyway, you probably should just switch to class syntax.

A (probably considered hacky) alternative would be to create the chartEvents with the bound callback in the getInitialState method:

```<code>const ChartClass = React.createClass({
  getInitialState() {
    this.chartEvents = [
      {
        eventName: 'select',
        callback: (Chart) => { // use arrow functions
          this.handleShowModal()
        } // or .bind(this) or whatever here
      }
    ];
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})
</code>```

Body:
I'm using react google charts and am trying to use the chartEvents method to hook into the selection event.

This works:

const ChartClass = React.createClass({
  getInitialState () {
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  chartEvents: [
    {
      eventName: 'select',
      callback: function (Chart) {
         this.handleShowModal()
      }
    }
  ],
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})

However within that callback I would like to call some other methods

this.handleOpenModal(ChartObj) // TypeError: this.handleOpenModal is not a function
this.sthElse()

because within this callback this is being set to event itself

console.log(this) //object {eventName: "select", callback: function}

Is there any way to reference the parent class so I can use its methods? I don't think I can simply place the function outside of the class because it needs to use this.setState

Body:
React.createClass components did auto-bind all their methods, so you need to do nothing but declare the callback as a method - or just use handleShowModal directly:

const ChartClass = React.createClass({
  getInitialState() {
    return {
      showModal: false
    }
  },
  handleShowModal(Chart) {
    this.setState((prev, props) => {
      return {
        showModal: true
      }
    })
  },
  render() {
    return (
      <Chart
        chartEvents={[
          {
            eventName: 'select',
            callback: this.handleShowModal
          }
        ]}
        data={this.props.data}
      />
    )
  }
})

Of course, given you are using ES6 anyway, you probably should just switch to class syntax.

A (probably considered hacky) alternative would be to create the chartEvents with the bound callback in the getInitialState method:

const ChartClass = React.createClass({
  getInitialState() {
    this.chartEvents = [
      {
        eventName: 'select',
        callback: (Chart) => { // use arrow functions
          this.handleShowModal()
        } // or .bind(this) or whatever here
      }
    ];
    return {
      showModal: false
    }
  },
  handleShowModal () {
    this.setState((prev, props) => {
       return {
         showModal: true
       }
    })
  },
  render () {
    return (
      <Chart
        chartEvents={this.chartEvents}
        data={this.props.data}
      />
    )
  }
})


问:
JavaScript round number to first two digits?
I'm trying to round a number up to the first two digits.

```<code>14300 -> 15000
1430  -> 1500
143   -> 150
14    -> 14
</code>```

I have figured out this much:

```<code>var n = 14300;
n = parseFloat(Math.ceil(n).toPrecision(2));
console.log(n);
</code>```

It returns 14000, but I want to round it up. Math.ceil only works to the next integer.
http://jsfiddle.net/cruTY/

Note: I know I can divide n to make it a decimal, but I want this function to work for all numbers without having to manually insert /1000 or /1000000.

答:
My answer is more universal than other ones, because you can change the values around easily. This function will ceil to any index of the number you need. If its to third or second, just change the dig to corresponding number:

function ceil(num, ind){
    let str = Math.floor(num)+"",
        arr = new Array(str.length).fill("0");
        arr[ind - 1] = "1";
    let divider = arr.join("");

    return Math.ceil(num/divider) * divider;
}

let number = 14300, //which number to be ceiled
    dig = 2; //to which index we ceil

document.body.textContent = ceil( number, dig );```

Body:
I'm trying to round a number up to the first two digits.

14300 -> 15000
1430  -> 1500
143   -> 150
14    -> 14

I have figured out this much:

var n = 14300;
n = parseFloat(Math.ceil(n).toPrecision(2));
console.log(n);

It returns 14000, but I want to round it up. Math.ceil only works to the next integer.
http://jsfiddle.net/cruTY/

Note: I know I can divide n to make it a decimal, but I want this function to work for all numbers without having to manually insert /1000 or /1000000.


问:
New Line in Gmail App for iOS using URL Scheme
We are working on an iOS app and we happen to be using the Gmail app's URL Scheme to compose a new email for the user. We figured out most of it, however we are having some trouble adding new lines in the body of the email. So far our URL looks like this:

googlegmail://co?from=username@example.com&to=helpdesk@example.com&subject=TITLE&body=What%20ever%20they%20include%20for%20the%20body

We have already tried using %0D%0A, as well as a few other options, however none of those seem to work. Is there any way to add a new line through the URL or is that just not possible?

答:
I have only used this scheme once before and I didn't need the ability to create new lines, but after taking a look at it, I'm as stumped as you are. My guess is that this isn't possible using this method. It seems to me that it only focuses on putting spaces between words.

One thing I would recommend looking into is the Gmail API for iOS. You will most likely have much more luck with this and there's also the upside of having more control over your messages. You can easily install it with CocoaPods and it doesn't take long to set up at all.


问:
Cast/convert array of bytes to address
So I have an address where an offset for a vftable is located. it is stored in the assembly as bytes. ex: 03 c3 bd 0c

I want to get the bytes, and convert them little endian style to an address.

```<code>byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];
</code>```

so the output of the example would be 0x0cbdc303.

how can I correctly code this?

答:
So you have a little-endian device and want to convert 4 little-endian byte to a single 4-byte-number. This can easily be done this way:  </p>

```<code>uint32_t myNumber = *((uint32_t *)addr);
</code>```

Title: Cast/convert array of bytes to address

Body:
So I have an address where an offset for a vftable is located. it is stored in the assembly as bytes. ex: 03 c3 bd 0c

I want to get the bytes, and convert them little endian style to an address.

byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];

so the output of the example would be 0x0cbdc303.

how can I correctly code this?

Body:
So you have a little-endian device and want to convert 4 little-endian byte to a single 4-byte-number. This can easily be done this way:

uint32_t myNumber = *((uint32_t *)addr);


问:
C# DLL (Class Library) functions called from Go Language
Hello Go Lang and C# gurus,

Good day.
I would like to ask if anyone of you have tried calling a C# DLL functions (Class Library type) from a Go program?

I have made some initial research and saw these articles:

```<code>- https://github.com/golang/go/wiki/WindowsDLLs
- https://stackoverflow.com/questions/27849137/golang-call-windows-dll-functions
</code>```

But these are DLLs created out from C Win32 implementations.
I tried searching for C# DLL loaded into Go program all of them will tell you that you need to have a C++/C (Win32) wrapper before you can call it on a Go program.

Plus, the links above will tell you that Go is expecting a "C" declaration I think (which is of type __declspec) or the likes (e.g. WINAPI).

Is there a way in this case where we can completely skip the C/C++ wrapper and directly call the C# DLL functions in Go?

Your enlightening ideas and inputs will be greatly appreciated =)!

Thanks

答:
Option 1 Turn your .NET DLL into a COM component like this, then you can invoke it from golang following the steps in your first link. Remember this option is for windows only.

Option 2 Wrap the DLL within a simple C# console application, and invoke the application in golang using os/exec. Your final program is still cross-platform if your C# DLL is cross-platform.

Both options need a basic knowledge of C#, either creating COM components, or writing a console application to invoke the DLL. IMO the latter is easier.

Body:
Hello Go Lang and C# gurus,

Good day.
I would like to ask if anyone of you have tried calling a C# DLL functions (Class Library type) from a Go program?

I have made some initial research and saw these articles:

- https://github.com/golang/go/wiki/WindowsDLLs
- https://stackoverflow.com/questions/27849137/golang-call-windows-dll-functions

But these are DLLs created out from C Win32 implementations.
I tried searching for C# DLL loaded into Go program all of them will tell you that you need to have a C++/C (Win32) wrapper before you can call it on a Go program.

Plus, the links above will tell you that Go is expecting a "C" declaration I think (which is of type __declspec) or the likes (e.g. WINAPI).

Is there a way in this case where we can completely skip the C/C++ wrapper and directly call the C# DLL functions in Go?

Your enlightening ideas and inputs will be greatly appreciated =)!

Thanks


问:
Wait until all processes notified after EventWaitHandle.Set()
I do in one process:

```<code>_eventWaitHandle.Set();
_eventWaitHandle.Reset();
</code>```

In another process:

```<code>_eventWaitHandle.WaitOne();
Console.WriteLine("Hello");
</code>```

But never get notified (no console output).
It seem that Set in asynchronous.

How can I wait until all waiters were signaled before doing Reset()?

I create wait handle (NAMED inter process wait handle):

```<code>    internal static EventWaitHandle OpenExistingOrCreateEventWaitHandle(string name)
    {
        try
        {
            return EventWaitHandle.OpenExisting(name);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            return new EventWaitHandle(false, EventResetMode.ManualReset, name);
        }
    }
</code>```

UPDATE

For now I have one "solution"

```<code>_eventWaitHandle.Set();
Thread.Sleep(10);
_eventWaitHandle.Reset();
</code>```

Second possible - to have many handles for each process. But this code should work in any office application add-in or standalone app. So names should be generated some how and discovered.

Third - to use WCF p2p(netPeerTcpBinding) or named pipes with UdpDiscoveryEndpoint- but these use "IP" so can have some security issues when deployed to end users?

答: Use EventResetMode.Manual and store your EventWaitHandle in a static.  Consumers should read the handle from this static.  Whenever you are about to call Set(), first create a new EventWaitHandle and store it in that static.  The next time a consumer wants a handle he will get the new one, which is clear.</p>

Body:
I do in one process:

_eventWaitHandle.Set();
_eventWaitHandle.Reset();

In another process:

_eventWaitHandle.WaitOne();
Console.WriteLine("Hello");

But never get notified (no console output).
It seem that Set in asynchronous.

How can I wait until all waiters were signaled before doing Reset()?

I create wait handle (NAMED inter process wait handle):

    internal static EventWaitHandle OpenExistingOrCreateEventWaitHandle(string name)
    {
        try
        {
            return EventWaitHandle.OpenExisting(name);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            return new EventWaitHandle(false, EventResetMode.ManualReset, name);
        }
    }

UPDATE

For now I have one "solution"

_eventWaitHandle.Set();
Thread.Sleep(10);
_eventWaitHandle.Reset();

Second possible - to have many handles for each process. But this code should work in any office application add-in or standalone app. So names should be generated some how and discovered.

Third - to use WCF p2p(netPeerTcpBinding) or named pipes with UdpDiscoveryEndpoint- but these use "IP" so can have some security issues when deployed to end users?


问:
My C# function will not work
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.</p>

```<code>namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}
</code>```

答:
Change the method declaration to

```<code> public static int AddNumbers(int number1, int number2)
</code>```

Or create an instance of Program class in main method and then access the add numbers method.

```<code> namespace FunctionPractice
 {
      class Program
      {
         public int AddNumbers(int number1, int number2)
         {
             int result = number1 + number2;
             return result;
         }

         static void Main(string[] args)
         {
             Console.WriteLine("Enter 2 numbers: ");
             int firstNumber = Convert.ToInt16(Console.ReadLine());
             int secondNumber = Convert.ToInt16(Console.ReadLine());

            Program program = new Program();

            int result = program.AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}
</code>```

Title: My C# function will not work

Body:
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.

namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}

Body:
Change the method declaration to

 public static int AddNumbers(int number1, int number2)

Or create an instance of Program class in main method and then access the add numbers method.

 namespace FunctionPractice
 {
      class Program
      {
         public int AddNumbers(int number1, int number2)
         {
             int result = number1 + number2;
             return result;
         }

         static void Main(string[] args)
         {
             Console.WriteLine("Enter 2 numbers: ");
             int firstNumber = Convert.ToInt16(Console.ReadLine());
             int secondNumber = Convert.ToInt16(Console.ReadLine());

            Program program = new Program();

            int result = program.AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}


问:
android how to recycle image before loading a new one
I have a out of memory problem here in which i have full screen images being displayed. I want to show images in full screen and I have two buttons to cycle through them to the left or to the right. How can i have the past images be recycled before showing the next to prevent the out of memory exception? or is there an even better way to do so?

here is my class in which i view the image.

```<code>public class ImageViewActivity extends Activity
{
private Button btnHome;
private Button btnBack;
private ImageButton btnLeft;
private ImageButton btnRight;
ImageView imageView;
RelativeLayout layout;

int height;
int width;

Bitmap bitmap;
String[] imagesPath;
int position;

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageview_activity);

    btnHome = (Button) findViewById(R.id.btnHome);
    btnBack = (Button) findViewById(R.id.btnBack);
    btnLeft = (ImageButton) findViewById(R.id.leftArrow);
    btnRight = (ImageButton) findViewById(R.id.rightArrow);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;

    imagesPath = getIntent().getStringExtra("IMAGES").split("\\|");
    position = getIntent().getIntExtra("POSITION", 0);

    bitmap = BitmapFactory.decodeFile(imagesPath[position]);

    imageView = (ImageView)findViewById(R.id.displayImage);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

    btnLeft.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 0)
                position = 5;
            else
                position--;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnRight.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 5)
                position = 0;
            else
                position++;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnHome.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), MainMenuActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    imageView.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            ImageView view = (ImageView) v;
            dumpEvent(event);

            // Handle touch events here...
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    start.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(mid, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        // ...
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - start.x, event.getY()
                                - start.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                        }
                    }
                    break;
            }

            view.setImageMatrix(matrix);
            return true;
        }
    });

}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float)Math.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}
</code>```

thank you for any input and if you need any additional information please feel free to ask!

答:
I would either scale down the image or consider using the Picasso image loading library: http://square.github.io/picasso/

It is also really simply to use and prevents a lot Out of Memory Exceptions.

```<code>Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
</code>```

Body:
I have a out of memory problem here in which i have full screen images being displayed. I want to show images in full screen and I have two buttons to cycle through them to the left or to the right. How can i have the past images be recycled before showing the next to prevent the out of memory exception? or is there an even better way to do so?

here is my class in which i view the image.

public class ImageViewActivity extends Activity
{
private Button btnHome;
private Button btnBack;
private ImageButton btnLeft;
private ImageButton btnRight;
ImageView imageView;
RelativeLayout layout;

int height;
int width;

Bitmap bitmap;
String[] imagesPath;
int position;

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageview_activity);

    btnHome = (Button) findViewById(R.id.btnHome);
    btnBack = (Button) findViewById(R.id.btnBack);
    btnLeft = (ImageButton) findViewById(R.id.leftArrow);
    btnRight = (ImageButton) findViewById(R.id.rightArrow);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;

    imagesPath = getIntent().getStringExtra("IMAGES").split("\\|");
    position = getIntent().getIntExtra("POSITION", 0);

    bitmap = BitmapFactory.decodeFile(imagesPath[position]);

    imageView = (ImageView)findViewById(R.id.displayImage);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

    btnLeft.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 0)
                position = 5;
            else
                position--;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnRight.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 5)
                position = 0;
            else
                position++;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnHome.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), MainMenuActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    imageView.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            ImageView view = (ImageView) v;
            dumpEvent(event);

            // Handle touch events here...
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    start.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(mid, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        // ...
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - start.x, event.getY()
                                - start.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                        }
                    }
                    break;
            }

            view.setImageMatrix(matrix);
            return true;
        }
    });

}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float)Math.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}

thank you for any input and if you need any additional information please feel free to ask!

Body:
I would either scale down the image or consider using the Picasso image loading library: http://square.github.io/picasso/

It is also really simply to use and prevents a lot Out of Memory Exceptions.

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);


问:
How to create a simple pagination/carousel in divs HTML Angular 2
Hi I have an *ngFor in my template and it creates n number of divs.

```<code><div *ngFor="let item of widgets" class="page-content widget-item">
  <div>{{content}} </div>
</div>
</code>```

How can I add a simple pagination on my div's guys? So that my first page will have 10 divs and on click on a button, the page slides and shows the rest of the divs? Any idea? Thanks in advance.

答:
You need to create a service like this :

```<code>import * as _ from 'underscore';

export class PagerService {
getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10)
{
    // calculate total pages
    let totalPages = Math.ceil(totalItems / pageSize);

    let startPage: number, endPage: number;
    if (totalPages <= 10) {
        // less than 10 total pages so show all
        startPage = 1;
        endPage = totalPages;
    } else {
        // more than 10 total pages so calculate start and end pages
        if (currentPage <= 6) {
            startPage = 1;
            endPage = 10;
        } else if (currentPage + 4 >= totalPages) {
            startPage = totalPages - 9;
            endPage = totalPages;
        } else {
            startPage = currentPage - 5;
            endPage = currentPage + 4;
        }
    }

    // calculate start and end item indexes
    let startIndex = (currentPage - 1) * pageSize;
    let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

    // create an array of pages to ng-repeat in the pager control
    let pages = _.range(startPage, endPage + 1);

    // return object with all pager properties required by the view
    return {
        totalItems: totalItems,
        currentPage: currentPage,
        pageSize: pageSize,
        totalPages: totalPages,
        startPage: startPage,
        endPage: endPage,
        startIndex: startIndex,
        endIndex: endIndex,
        pages: pages
    };
   }
}
</code>```

And change your component like below :

```<code>import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

import * as _ from 'underscore';

import { PagerService } from './_services/index'

@Component({
  moduleId: module.id,
   selector: 'app',
   templateUrl: 'app.component.html'
 })

export class AppComponent implements OnInit {
constructor(private http: Http, private pagerService: PagerService) { }

// array of all items to be paged
private allItems: any[];

// pager object
pager: any = {};

// paged items
pagedItems: any[];

ngOnInit() {
    // get dummy data
    this.http.get('./dummy-data.json')
        .map((response: Response) => response.json())
        .subscribe(data => {
            // set items to json response
            this.allItems = data;

            // initialize to page 1
            this.setPage(1);
        });
}

setPage(page: number) {
    if (page < 1 || page > this.pager.totalPages) {
        return;
    }

    // get pager object from service
    this.pager = this.pagerService.getPager(this.allItems.length, page);

    // get current page of items
    this.pagedItems = this.allItems.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
}
</code>```

and your HTML should be something like this :

```<code><div>
<div class="container">
    <div class="text-center">
        <h1>Angular 2 - Pagination Example with logic like Google</h1>

        <!-- items being paged -->
        <div *ngFor="let item of pagedItems">{{item.name}}</div>

        <!-- pager -->
        <ul *ngIf="pager.pages && pager.pages.length" class="pagination">
            <li [ngClass]="{disabled:pager.currentPage === 1}">
                <a (click)="setPage(1)">First</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === 1}">
                <a (click)="setPage(pager.currentPage - 1)">Previous</a>
            </li>
            <li *ngFor="let page of pager.pages" [ngClass]="{active:pager.currentPage === page}">
                <a (click)="setPage(page)">{{page}}</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
                <a (click)="setPage(pager.currentPage + 1)">Next</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
                <a (click)="setPage(pager.totalPages)">Last</a>
            </li>
        </ul>
    </div>
</div>
</div>
</code>```

you can see an example here :

https://plnkr.co/edit/vPXf2U?p=preview

Body:
Hi I have an *ngFor in my template and it creates n number of divs.

{{content}}

How can I add a simple pagination on my div's guys? So that my first page will have 10 divs and on click on a button, the page slides and shows the rest of the divs? Any idea? Thanks in advance.

Body:
You need to create a service like this :

import * as _ from 'underscore';

export class PagerService {
getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10)
{
    // calculate total pages
    let totalPages = Math.ceil(totalItems / pageSize);

    let startPage: number, endPage: number;
    if (totalPages <= 10) {
        // less than 10 total pages so show all
        startPage = 1;
        endPage = totalPages;
    } else {
        // more than 10 total pages so calculate start and end pages
        if (currentPage <= 6) {
            startPage = 1;
            endPage = 10;
        } else if (currentPage + 4 >= totalPages) {
            startPage = totalPages - 9;
            endPage = totalPages;
        } else {
            startPage = currentPage - 5;
            endPage = currentPage + 4;
        }
    }

    // calculate start and end item indexes
    let startIndex = (currentPage - 1) * pageSize;
    let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

    // create an array of pages to ng-repeat in the pager control
    let pages = _.range(startPage, endPage + 1);

    // return object with all pager properties required by the view
    return {
        totalItems: totalItems,
        currentPage: currentPage,
        pageSize: pageSize,
        totalPages: totalPages,
        startPage: startPage,
        endPage: endPage,
        startIndex: startIndex,
        endIndex: endIndex,
        pages: pages
    };
   }
}

And change your component like below :

import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

import * as _ from 'underscore';

import { PagerService } from './_services/index'

@Component({
  moduleId: module.id,
   selector: 'app',
   templateUrl: 'app.component.html'
 })

export class AppComponent implements OnInit {
constructor(private http: Http, private pagerService: PagerService) { }

// array of all items to be paged
private allItems: any[];

// pager object
pager: any = {};

// paged items
pagedItems: any[];

ngOnInit() {
    // get dummy data
    this.http.get('./dummy-data.json')
        .map((response: Response) => response.json())
        .subscribe(data => {
            // set items to json response
            this.allItems = data;

            // initialize to page 1
            this.setPage(1);
        });
}

setPage(page: number) {
    if (page < 1 || page > this.pager.totalPages) {
        return;
    }

    // get pager object from service
    this.pager = this.pagerService.getPager(this.allItems.length, page);

    // get current page of items
    this.pagedItems = this.allItems.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
}

and your HTML should be something like this :

<div>
<div class="container">
    <div class="text-center">
        <h1>Angular 2 - Pagination Example with logic like Google</h1>

        <!-- items being paged -->
        <div *ngFor="let item of pagedItems">{{item.name}}</div>

        <!-- pager -->
        <ul *ngIf="pager.pages && pager.pages.length" class="pagination">
            <li [ngClass]="{disabled:pager.currentPage === 1}">
                <a (click)="setPage(1)">First</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === 1}">
                <a (click)="setPage(pager.currentPage - 1)">Previous</a>
            </li>
            <li *ngFor="let page of pager.pages" [ngClass]="{active:pager.currentPage === page}">
                <a (click)="setPage(page)">{{page}}</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
                <a (click)="setPage(pager.currentPage + 1)">Next</a>
            </li>
            <li [ngClass]="{disabled:pager.currentPage === pager.totalPages}">
                <a (click)="setPage(pager.totalPages)">Last</a>
            </li>
        </ul>
    </div>
</div>
</div>

you can see an example here :

https://plnkr.co/edit/vPXf2U?p=preview


问:
Is it possible to turn off the canonical hostname URL Rewrite rule from the codebehind?
I was wondering it is possible to turn off the canonical hostname URL Rewrite rule from the URL Rewrite 2.0 IIS 7.5 Module.

I'm locally developing on a IIS 7.5. The setting of this URL Rewrite rule is set in the web.config.

This is how I deploy: I'm using Webdeploy to publish my web application. The new web.config transforms, which was introduced with VS 2010, is no option for me, because it is bugged: VS 2010 configuration transformation produces unwanted white space during deployment and will not be fixed until the release of VS2010 SP1. I'm also not using web deployment projects anymore, because Webdeploy does not seem working with web deployment projects. As a result, I manually switch on the rewrite rule in the web.config before deploying.

If I now want to locally debug something, I manually need to turn off the rule.

Is there a solution like this pseudo-code?

```<code>if(Properties.Settings.TurnOffCanonicalHostNameWithLocalHost)
{
  URLRewriteModule["CanonicalHostName"].Enabled = false;
}
</code>```

答:
```<code> <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I was wondering it is possible to turn off the canonical hostname URL Rewrite rule from the URL Rewrite 2.0 IIS 7.5 Module.

I'm locally developing on a IIS 7.5. The setting of this URL Rewrite rule is set in the web.config.

This is how I deploy: I'm using Webdeploy to publish my web application. The new web.config transforms, which was introduced with VS 2010, is no option for me, because it is bugged: VS 2010 configuration transformation produces unwanted white space during deployment and will not be fixed until the release of VS2010 SP1. I'm also not using web deployment projects anymore, because Webdeploy does not seem working with web deployment projects. As a result, I manually switch on the rewrite rule in the web.config before deploying.

If I now want to locally debug something, I manually need to turn off the rule.

Is there a solution like this pseudo-code?

if(Properties.Settings.TurnOffCanonicalHostNameWithLocalHost)
{
  URLRewriteModule["CanonicalHostName"].Enabled = false;
}


问:
Install private dependencies via NPM
According to documentation, we can use git repositories as NPM dependencies:

Git urls can be of the form:

```<code>git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish
</code>```

The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master.

That's fine and works like a charm, for public repositories. For private repositories (e.g. from GitHub), I tried this:

```<code>{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
      "builder": "git+ssh://github.com/IonicaBizau/myprivatemodule.git"
  },
  "author": "",
  "license": "ISC"
}
</code>```

When I do npm install, I get the following output:

```<code>$ npm i
npm WARN package.json test@1.0.0 No description
npm WARN package.json test@1.0.0 No repository field.
npm WARN package.json test@1.0.0 No README data
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Cloning into bare repository '/home/....'...
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Permission denied (publickey).
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git fatal: Could not read from remote repository.
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Please make sure you have the correct access rights
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git and the repository exists.
npm ERR! Error: Command failed: Cloning into bare repository '/home/...'...
npm ERR! Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
</code>```

This error appears only for private repositories.

I have the access to this repository and doing git clone ... works, via SSH.

What's the solution for this issue?

答:
I had been using the Node.js prompt and a Babun prompt which have been working fine for me.  I got this error with "npm install" on a new repository.  When I used the Git Shell from GitHub it worked fine.

I had already setup my SSH keys and did not have this issue with any other npm installs I did.

Title: Install private dependencies via NPM

Body:
According to documentation, we can use git repositories as NPM dependencies:

Git urls can be of the form:

git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish

The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master.

That's fine and works like a charm, for public repositories. For private repositories (e.g. from GitHub), I tried this:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
      "builder": "git+ssh://github.com/IonicaBizau/myprivatemodule.git"
  },
  "author": "",
  "license": "ISC"
}

When I do npm install, I get the following output:

$ npm i
npm WARN package.json test@1.0.0 No description
npm WARN package.json test@1.0.0 No repository field.
npm WARN package.json test@1.0.0 No README data
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Cloning into bare repository '/home/....'...
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Permission denied (publickey).
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git fatal: Could not read from remote repository.
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git Please make sure you have the correct access rights
npm ERR! git clone ssh://github.com/IonicaBizau/myprivatemodule.git and the repository exists.
npm ERR! Error: Command failed: Cloning into bare repository '/home/...'...
npm ERR! Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

This error appears only for private repositories.

I have the access to this repository and doing git clone ... works, via SSH.

What's the solution for this issue?


问:
How to position HTML bordered box in the centre
I am trying to place a fully responsive text box in the centre of the page inside of an image. I haven't had any trouble placing the text box on the image but for some reason I am having trouble centring the box. I have tried reviewed and looked over multiple tutorials and stack overflow answers but nothing has been helpful. I have tried both width: 50% and margins but neither have worked. Attached below is my code. Again, I am fully aware that there are multiple answers to this question but none seem to work. Thanks a lot for the help it is highly appreciated!

Orillia, Ontario

        Welcome to Orillia!

```

Again, thank you very much!

答:
Just use flex-box ;)

More info: link

Orillia, Ontario

        Welcome to Orillia!

```

Body:
I am trying to place a fully responsive text box in the centre of the page inside of an image. I haven't had any trouble placing the text box on the image but for some reason I am having trouble centring the box. I have tried reviewed and looked over multiple tutorials and stack overflow answers but nothing has been helpful. I have tried both width: 50% and margins but neither have worked. Attached below is my code. Again, I am fully aware that there are multiple answers to this question but none seem to work. Thanks a lot for the help it is highly appreciated!

Orillia, Ontario

        Welcome to Orillia!

Again, thank you very much!

Body:
Just use flex-box ;)

More info: link

<html>
<head>
<style>

.back {
    min-width: 100%;
}

.title {
    font-size: 90px;
    color: white;
    font-family: 'Oswald', sans-serif;
    text-align: center;
    margin-top: -483px;
}

.square {
    position: relative;
    width: 50%;
    background-color: white;
    border: 8px solid #686868;
    height: 100px;
    text-align: center;
    margin-top: 225px;
}

.square:after {
    content: "";
    display: block;
    padding-bottom: 100%;
}

.content {
    position: absolute;
    width: 100%;
    height: 100%;

   display:flex;
   justify-content: center;
   flex-direction: column
}

</style>
</head>

<body>

<img src="orilliaback.jpg" class="back" height=500 />

<div class="title">Orillia, Ontario</div>

<div class="square">
    <div class="content">
        Welcome to Orillia!
    </div>
</div>

</body>

</html>


问:
Which PHP version is currently running 5.2.15 or 5.3.4?

           i often read official PHP website website.

on 9 Dec,2010 headlines was   PHP 5.2.15 Released! and

on 10 Dec,2010 headlines was  PHP 5.3.4 Released!

i m really confused that what means of two different headlines??
i think version order are may b wrong or what is this??please explain PHP GURU

please tell me what should i said when interviewer ask which version of php we works currently??

ONE MORE THING

so which version we need to use for safeside, is that 5.3.x or 5.2.x???

答:
You should use 5.3. 5.2 in "security fixes only" maintenance mode and the recent release is probably the last one for 5.2 series. That means unless there's an outrageous gaping security hole discovered there will be no releases on 5.2 anymore and no bugfixes or improvements. 5.3 is the current maintained version of PHP. It is better than 5.2 in any respect, use it please :)

5.2 is maintained because some people are slow or reluctant to move to more recent version ("if it works, don't touch it"). However, the answer to the question "what is the current PHP version" is "5.3.4" (at least for today). 5.3 will probably the current version for at least couple of years, then it'd be either 5.4 or maybe 6.

Oh, and the last but not least - all 5.2.x versions are binary and code compatible (i.e. you should not expect any issues upgrading), so are 5.3.x, but between 5.2 and 5.3 there are binary incompatibilities and may be source incompatibilities too, see upgrading guide.


答:
Use position: relative; z-index: 2 on the image to stack on top of the pseudo element, which is z-index: 1. You could also remove the z-index from the pseudo element, and just add position: relative to the img, if the z-index on the pseudo element isn't necessary for some other reason.

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

        Jill
        Smith

        Eve
        Jackson

        Eve
        Jackson

```

Title: How to apply z-index to a content of div to display in above pseudo elements

Body:
I have created one table and to the last column of the table, I have added pseudo elements. That last column contains an image. That image is getting clipped due to pseudo elements. I tried adding z-index to that image, but it's not working. HTML code:

    Jill
    Smith

    Eve
    Jackson

    Eve
    Jackson

CSS code:

td:nth-child(3):before {
    content: '';
    width: 100%;
    display: block;
    border-top: 8px solid white;
    position: absolute;
    z-index: 1;
}

I have regenerated the issue in following pluker:
http://plnkr.co/edit/oTGWJrAFk5esgnwTOvKE?p=preview

How to avoid an image from getting clipped?
Thank you in advance.

Body:
Use position: relative; z-index: 2 on the image to stack on top of the pseudo element, which is z-index: 1. You could also remove the z-index from the pseudo element, and just add position: relative to the img, if the z-index on the pseudo element isn't necessary for some other reason.

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <style>
    td:nth-child(3):before {
    content: '';
    width: 100%;
    display: block;
    border-top: 8px solid white;
    position: absolute;
    z-index: 1;
    }
    td img { position: relative; z-index: 2;}
    </style>
  </head>

  <body>
    <table style="width:100%">
      <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
      </tr>
      <tr>
        <td>Eve</td>
        <td>Jackson</td>
         <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
      </tr>
       <tr>
        <td>Eve</td>
        <td>Jackson</td>
         <td><img src='https://t4.ftcdn.net/jpg/01/22/05/05/160_F_122050525_sPpYBGxcms3Wpz6tJNnv23Xq7dq60RXi.jpg' height='25'></td>
      </tr>
    </table>
  </body>

</html>