问:
SqlDataReader inside a loop in vb.NET
I m trying to insert/update multi-records and return the records after change in a table and I m using the following code,

```<code>Using cmd As New SqlCommand("TblRegJoinDynHdlr", con)
    cmd.CommandType = CommandType.StoredProcedure
    Dim Data = PtRegData(0).PartnerData
    For i As Integer = 0 To Data.Count - 1
        cmd.Parameters.Clear()
        If (String.IsNullOrEmpty(Data(i).RecID)) Then
            cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = Convert.ToInt32(Data(i).RecID)
        End If
        If (String.IsNullOrEmpty(Data(i).PtFilenum)) Then
            cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PtFilenum)
        End If
        If (String.IsNullOrEmpty(Data(i).PrtFilenum)) Then
            cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PrtFilenum)
        End If
        cmd.Parameters.Add("@PrtStatus", SqlDbType.Int).Value = (Data(i).PrtStatus)
        con.Open()
        Using sdr As SqlDataReader = cmd.ExecuteReader()
            While sdr.Read()
                Prtdata.Add(New PartnerData() With { _
                 .RecID = sdr("RecID").ToString(), _
                 .PrtFilenum = sdr("PrtFilenum").ToString(), _
                 .PtFilenum = sdr("PtFilenum").ToString(), _
                 .FullName = sdr("FullName").ToString(), _
                 .PrtStatus = sdr("PrtStatus").ToString(), _
                .DOB = sdr("DOB").ToString() _
                })
            End While
        End Using
        con.Close()
    Next

    con.Dispose()
End Using
</code>```

My Problem
If I leave the SqlDataReader inside the loop, all records are updated properly but I get the data as n x 2 and if I leave it outside the loop I get my data but records are not updated/inserted properly
Any help please?

答:
before closing your connection close your reader, that is to say before going to the next round you must close your reader</p>

```<code>    Using cmd As New SqlCommand("TblRegJoinDynHdlr", con)
        cmd.CommandType = CommandType.StoredProcedure
        Dim Data = PtRegData(0).PartnerData
        For i As Integer = 0 To Data.Count - 1
            cmd.Parameters.Clear()
            If (String.IsNullOrEmpty(Data(i).RecID)) Then
                cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = Convert.ToInt32(Data(i).RecID)
            End If
            If (String.IsNullOrEmpty(Data(i).PtFilenum)) Then
                cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PtFilenum)
            End If
            If (String.IsNullOrEmpty(Data(i).PrtFilenum)) Then
                cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PrtFilenum)
            End If
            cmd.Parameters.Add("@PrtStatus", SqlDbType.Int).Value = (Data(i).PrtStatus)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    Prtdata.Add(New PartnerData() With { _
                     .RecID = sdr("RecID").ToString(), _
                     .PrtFilenum = sdr("PrtFilenum").ToString(), _
                     .PtFilenum = sdr("PtFilenum").ToString(), _
                     .FullName = sdr("FullName").ToString(), _
                     .PrtStatus = sdr("PrtStatus").ToString(), _
                    .DOB = sdr("DOB").ToString() _
                    })
                End While
            End Using
    sdr.close() 'This code added
            con.Close()
        Next

    con.Dispose()
End Using
</code>```

Title: SqlDataReader inside a loop in vb.NET

Body:
I m trying to insert/update multi-records and return the records after change in a table and I m using the following code,

Using cmd As New SqlCommand("TblRegJoinDynHdlr", con)
    cmd.CommandType = CommandType.StoredProcedure
    Dim Data = PtRegData(0).PartnerData
    For i As Integer = 0 To Data.Count - 1
        cmd.Parameters.Clear()
        If (String.IsNullOrEmpty(Data(i).RecID)) Then
            cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = Convert.ToInt32(Data(i).RecID)
        End If
        If (String.IsNullOrEmpty(Data(i).PtFilenum)) Then
            cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PtFilenum)
        End If
        If (String.IsNullOrEmpty(Data(i).PrtFilenum)) Then
            cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = DBNull.Value
        Else
            cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PrtFilenum)
        End If
        cmd.Parameters.Add("@PrtStatus", SqlDbType.Int).Value = (Data(i).PrtStatus)
        con.Open()
        Using sdr As SqlDataReader = cmd.ExecuteReader()
            While sdr.Read()
                Prtdata.Add(New PartnerData() With { _
                 .RecID = sdr("RecID").ToString(), _
                 .PrtFilenum = sdr("PrtFilenum").ToString(), _
                 .PtFilenum = sdr("PtFilenum").ToString(), _
                 .FullName = sdr("FullName").ToString(), _
                 .PrtStatus = sdr("PrtStatus").ToString(), _
                .DOB = sdr("DOB").ToString() _
                })
            End While
        End Using
        con.Close()
    Next

    con.Dispose()
End Using

My Problem
If I leave the SqlDataReader inside the loop, all records are updated properly but I get the data as n x 2 and if I leave it outside the loop I get my data but records are not updated/inserted properly
Any help please?

Body:
before closing your connection close your reader, that is to say before going to the next round you must close your reader

    Using cmd As New SqlCommand("TblRegJoinDynHdlr", con)
        cmd.CommandType = CommandType.StoredProcedure
        Dim Data = PtRegData(0).PartnerData
        For i As Integer = 0 To Data.Count - 1
            cmd.Parameters.Clear()
            If (String.IsNullOrEmpty(Data(i).RecID)) Then
                cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@RecID", SqlDbType.Int).Value = Convert.ToInt32(Data(i).RecID)
            End If
            If (String.IsNullOrEmpty(Data(i).PtFilenum)) Then
                cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@ptfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PtFilenum)
            End If
            If (String.IsNullOrEmpty(Data(i).PrtFilenum)) Then
                cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@prfilenum", SqlDbType.Int).Value = Convert.ToInt32(Data(i).PrtFilenum)
            End If
            cmd.Parameters.Add("@PrtStatus", SqlDbType.Int).Value = (Data(i).PrtStatus)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    Prtdata.Add(New PartnerData() With { _
                     .RecID = sdr("RecID").ToString(), _
                     .PrtFilenum = sdr("PrtFilenum").ToString(), _
                     .PtFilenum = sdr("PtFilenum").ToString(), _
                     .FullName = sdr("FullName").ToString(), _
                     .PrtStatus = sdr("PrtStatus").ToString(), _
                    .DOB = sdr("DOB").ToString() _
                    })
                End While
            End Using
    sdr.close() 'This code added
            con.Close()
        Next

    con.Dispose()
End Using


来源: stackexchange

问:
JAXB umarshalling NumberFormatException Not a number: 2.444 at com.sun.xml.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:132)
While unmarhsalling I am getting the below error

java.lang.NumberFormatException
Not a number: 2.444 at com.sun.xml.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:132)

Using JAXB unmarshalling method I am unmarshalling an XML which looks like below

```<code><ProductID itemName="Pen" itemNumber="123-123" effectiveDate="2017-04-10">
  <Amount value="2.444" UOM="g"/>
</ProductID>
</code>```

**in this I am trying to retrieve the value attribute in Amount tag .

While generating JAXB classes from xsd as "value" name conflicts with value  xs:String so I annotated it with below code**

```<code><xs:annotation>
    <xs:appinfo>
        <jxb:property name="valueAttribute"/>
    </xs:appinfo>
</xs:annotation>
</code>```

So in my JAXB Class ,I can see beans in the below format

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "value" })
public static class Amount {
    @XmlValue
    protected String value;
    @XmlAttribute(name = "value")
    protected Byte valueAttribute;
    @XmlAttribute(name = "UOM")
    protected String uom;

    /**
     * Gets the value of the value property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the valueAttribute property.
     *
     * @return possible object is {@link Byte }
     *
     */
    public Byte getValueAttribute() {
        return valueAttribute;
    }

    /**
     * Sets the value of the valueAttribute property.
     *
     * @param value
     *            allowed object is {@link Byte }
     *
     */
    public void setValueAttribute(Byte value) {
        System.out.println("insde set value attribute"+value.byteValue());
        this.valueAttribute = value;
    }

    /**
     * Gets the value of the uom property.
     *
     * @return possible object is {@link String }
     *
     */
</code>```

Any one please help me to resolve this issue
Thanks in advance....

答:
I assume the value attribute of Amount is Byte/integer in your xsd. If it is, it should be a double or float.

Change your declaration  protected Byte valueAttribute; to protected double valueAttribute or protected float valueAttribute;

and in your xsd, it should appear like:

```<code><xs:attribute type="xs:double" name="value">
     <xs:annotation>
          <xs:appinfo>
                <jxb:property name="valueAttribute"/>
          </xs:appinfo>
     </xs:annotation>
</xs:attribute>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
While unmarhsalling I am getting the below error

java.lang.NumberFormatException
Not a number: 2.444 at com.sun.xml.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:132)

Using JAXB unmarshalling method I am unmarshalling an XML which looks like below

<ProductID itemName="Pen" itemNumber="123-123" effectiveDate="2017-04-10">
  <Amount value="2.444" UOM="g"/>
</ProductID>

**in this I am trying to retrieve the value attribute in Amount tag .

While generating JAXB classes from xsd as "value" name conflicts with value  xs:String so I annotated it with below code**

<xs:annotation>
    <xs:appinfo>
        <jxb:property name="valueAttribute"/>
    </xs:appinfo>
</xs:annotation>

So in my JAXB Class ,I can see beans in the below format

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "value" })
public static class Amount {
    @XmlValue
    protected String value;
    @XmlAttribute(name = "value")
    protected Byte valueAttribute;
    @XmlAttribute(name = "UOM")
    protected String uom;

    /**
     * Gets the value of the value property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the valueAttribute property.
     *
     * @return possible object is {@link Byte }
     *
     */
    public Byte getValueAttribute() {
        return valueAttribute;
    }

    /**
     * Sets the value of the valueAttribute property.
     *
     * @param value
     *            allowed object is {@link Byte }
     *
     */
    public void setValueAttribute(Byte value) {
        System.out.println("insde set value attribute"+value.byteValue());
        this.valueAttribute = value;
    }

    /**
     * Gets the value of the uom property.
     *
     * @return possible object is {@link String }
     *
     */

Any one please help me to resolve this issue
Thanks in advance....

Body:
I assume the value attribute of Amount is Byte/integer in your xsd. If it is, it should be a double or float.

Change your declaration  protected Byte valueAttribute; to protected double valueAttribute or protected float valueAttribute;

and in your xsd, it should appear like:

<xs:attribute type="xs:double" name="value">
     <xs:annotation>
          <xs:appinfo>
                <jxb:property name="valueAttribute"/>
          </xs:appinfo>
     </xs:annotation>
</xs:attribute>


问:
scons "import os" is not importing my OS environment variable?
I'm testing the behavior of scons on MAC, I tried "import os" to construct from environment variable, like this:

```<code>$cat SConstruct
import os
env=Environment(ENV=os.environ)
kkk=env['MY']
</code>```

Then I tried to run it, seems still the environment variable is not imported by "env=Environment(ENV=os.environ)" statement

```<code>$export MY='haha'
$/usr/local/bin/scons
scons: Reading SConscript files ...
KeyError: 'MY':
  File "/Users/my/SConstruct", line 3:
    kkk=env['MY']
  File "/usr/local/Cellar/scons/2.5.1/libexec/scons-local/SCons/Environment.py", line 410:
    return self._dict[key]
</code>```

I'm using scons version:

```<code>$/usr/local/bin/scons -v
SCons by Steven Knight et al.:
    script: v2.5.1.rel_2.5.1:3735:9dc6cee5c168[MODIFIED], 2016/11/03 14:02:02, by bdbaddog on mongodog
    engine: v2.5.1.rel_2.5.1:3735:9dc6cee5c168[MODIFIED], 2016/11/03 14:02:02, by bdbaddog on mongodog
    engine path: ['/usr/local/Cellar/scons/2.5.1/libexec/scons-local/SCons']
Copyright (c) 2001 - 2016 The SCons Foundation
</code>```

Where did I get wrong, how to fix it?

答:
Try:

```<code>import os
env=Environment(ENV=os.environ)
my_env_value=env['ENV']['MY']
</code>```

The environment presented to commands run by SCons is env['ENV'], and not env itself.

Body:
I'm testing the behavior of scons on MAC, I tried "import os" to construct from environment variable, like this:

$cat SConstruct
import os
env=Environment(ENV=os.environ)
kkk=env['MY']

Then I tried to run it, seems still the environment variable is not imported by "env=Environment(ENV=os.environ)" statement

$export MY='haha'
$/usr/local/bin/scons
scons: Reading SConscript files ...
KeyError: 'MY':
  File "/Users/my/SConstruct", line 3:
    kkk=env['MY']
  File "/usr/local/Cellar/scons/2.5.1/libexec/scons-local/SCons/Environment.py", line 410:
    return self._dict[key]

I'm using scons version:

$/usr/local/bin/scons -v
SCons by Steven Knight et al.:
    script: v2.5.1.rel_2.5.1:3735:9dc6cee5c168[MODIFIED], 2016/11/03 14:02:02, by bdbaddog on mongodog
    engine: v2.5.1.rel_2.5.1:3735:9dc6cee5c168[MODIFIED], 2016/11/03 14:02:02, by bdbaddog on mongodog
    engine path: ['/usr/local/Cellar/scons/2.5.1/libexec/scons-local/SCons']
Copyright (c) 2001 - 2016 The SCons Foundation

Where did I get wrong, how to fix it?

Body:
Try:

import os
env=Environment(ENV=os.environ)
my_env_value=env['ENV']['MY']

The environment presented to commands run by SCons is env['ENV'], and not env itself.


问:
set layout to resize the control in java designed using netbeans
I am designing the swing JFrame form using NetBeans . I am not sure about the layout setting in JFrame form .When we change the resolution of the windows the forms are not adjusted automatically

but i want the forms and control designed on forms should be re
  sized automatically.   How is it possible

答:
For any component that you want to add layout below images will guide you:

You need to choose layout that fit to your requirements.

Also you can customize the layout, to do that:

Also you can do it manualy or you can change the properties from Customize code.

To do that like the above image right click on the component and go to customie code(Cannot do it for JFrame).


问:
Selenium WebDriver typing very slow in text field on IE browser
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

```<code>element.sendKeys("string");
</code>```

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?

答: Instead of WebEelement.send.keys, I used Actions object with sendKeys method. This worked like a charm.</p>

Body:
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

element.sendKeys("string");

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?


问:
Anyone know much about lua tables,classes, and functions?
I was just wondering why this returned Mexico not England? I've been trying to separate x1 to x6 by their properties, like continent, but I haven't made much progress.</p>

```<code>world = {continent = "", country = ""}

function world:new (o,continent,country)
   o = o or {}
   setmetatable(o, self)
   self.__index = self
   self.continent= continent or ""
   self.country = country or "";
   return o
end

x1 = world:new(nil,"Europe","England")
x2 = world:new(nil,"Europe","France")
x3 = world:new(nil,"Africa","Algeria")
x4 = world:new(nil,"Africa","Nigera")
x5 = world:new(nil,"America","United States")
x6 = world:new(nil,"America","Mexico")

list_1 = {x1,x2,x3,x4,x5,x6}

print(list_1[1].country)
</code>```

答:
In the context of new, self is the metatable, and o is the object. Setting attributes on self overwrites the previous values. So, change

```<code>self.continent= continent or ""
self.country = country or ""
</code>```

to

```<code>o.continent= continent or ""
o.country = country or ""
</code>```

Body:
I was just wondering why this returned Mexico not England? I've been trying to separate x1 to x6 by their properties, like continent, but I haven't made much progress.

world = {continent = "", country = ""}

function world:new (o,continent,country)
   o = o or {}
   setmetatable(o, self)
   self.__index = self
   self.continent= continent or ""
   self.country = country or "";
   return o
end

x1 = world:new(nil,"Europe","England")
x2 = world:new(nil,"Europe","France")
x3 = world:new(nil,"Africa","Algeria")
x4 = world:new(nil,"Africa","Nigera")
x5 = world:new(nil,"America","United States")
x6 = world:new(nil,"America","Mexico")

list_1 = {x1,x2,x3,x4,x5,x6}

print(list_1[1].country)

Body:
In the context of new, self is the metatable, and o is the object. Setting attributes on self overwrites the previous values. So, change

self.continent= continent or ""
self.country = country or ""

to

o.continent= continent or ""
o.country = country or ""


问:
Mapping points in a map
I try to show country data in a map using points in the map. Here the dataframe:

```<code>> dput(countries)
structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
</code>```

The code from here:

```<code> library(maps)
 library(ggplot2)
 base_world <- map_data("world")
 map_data_coloured <-
     base_world +
     geom_point(data=countries,
                aes(x=Longitude, y=Latitude, colour=Value), size=5, alpha=I(0.7))
</code>```

But I receive this error:

```<code>Error in as.vector(x, mode) :
  cannot coerce type 'environment' to vector of type 'any'
</code>```

答:
you need to pass the geom_polygon argument to map your base_world object

```<code>ggplot() +
   geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
   geom_point(data=countries, aes(x=Longitude, y=Latitude, colour=Value), size=5, alpha=I(0.7))
</code>```

Title: Mapping points in a map

Body:
I try to show country data in a map using points in the map. Here the dataframe:

> dput(countries)
structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))

The code from here:

 library(maps)
 library(ggplot2)
 base_world <- map_data("world")
 map_data_coloured <-
     base_world +
     geom_point(data=countries,
                aes(x=Longitude, y=Latitude, colour=Value), size=5, alpha=I(0.7))

But I receive this error:

Error in as.vector(x, mode) :
  cannot coerce type 'environment' to vector of type 'any'

Body:
you need to pass the geom_polygon argument to map your base_world object

ggplot() +
   geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
   geom_point(data=countries, aes(x=Longitude, y=Latitude, colour=Value), size=5, alpha=I(0.7))


问:
where is to take some calculation in codeigniter?
I want some table that value on database already calculated but in database not calculated.

My controller code...

```<code>public function data2()
{
    $data['row']=$this->std->getdata2();
    $this->load->view('konversi',$data);
}
</code>```

My model code...

```<code>public function getdata2()
{
    $query=$this->db->get('tb_data');
    return $query->result();
}
</code>```

My view code...

```<code><?php
    $i=1;

    foreach ($row as $r)
    {
        $pendidikans = 'pendidikan';
        $fpendidikans = $pendidikans * 100;

        echo "    <td>";
        echo "    $r->lulusan</td>";

        echo "    <td>";
        echo number_format((float)$r->$fpendidikans, 2, '.', '2' );
        echo "</td>";

        echo "    </tr>";

        $i++;
    }
?>
</code>```

答:
I am not sure about this(I think,this is what you are trying)
view </p>

```<code>    <?php

            $i=1;
                foreach ($row as $r) {
// if pendidikan is columnname
    $pendidikans = $r->pendidikan;
    $fpendidikans=$pendidikans*100;

?>
                     <td><?php echo $r->lulusan; ?></td>

                    <td><?php echo number_format((float)$fpendidikans, 2,'.' ,'2' ); ?></td>

                    </tr>
    <?php
                          $i++;
                }

            ?>
</code>```

Body:
I want some table that value on database already calculated but in database not calculated.

My controller code...

public function data2()
{
    $data['row']=$this->std->getdata2();
    $this->load->view('konversi',$data);
}

My model code...

public function getdata2()
{
    $query=$this->db->get('tb_data');
    return $query->result();
}

My view code...

<?php
    $i=1;

    foreach ($row as $r)
    {
        $pendidikans = 'pendidikan';
        $fpendidikans = $pendidikans * 100;

        echo "    ";
        echo "    $r->lulusan	";

        echo "    ";
        echo number_format((float)$r->$fpendidikans, 2, '.', '2' );
        echo "	";

        echo "
";

        $i++;
    }
?>

Body:
I am not sure about this(I think,this is what you are trying)
view

    <?php

            $i=1;
                foreach ($row as $r) {
// if pendidikan is columnname
    $pendidikans = $r->pendidikan;
    $fpendidikans=$pendidikans*100;

?>
                     <td><?php echo $r->lulusan; ?></td>

                    <td><?php echo number_format((float)$fpendidikans, 2,'.' ,'2' ); ?></td>

                    </tr>
    <?php
                          $i++;
                }

            ?>


问:
How to access this json data 'id' inside data 'Message' in the php script below?
The variable $res returning this response below

```<code>   {"Status":"Success","Message":{"Id":"9235948e-5469-450e-8aaf-551772da9c6a"}}
</code>```

How do i access this id inside message?

```<code>$res = $leadsquared->create_lead($data);
print_r($res);
</code>```

答:
Try this :

```<code>$result = json_decode($res,true);<br/>
$id = $result['Message']['Id']
</code>```

Body:
The variable $res returning this response below

   {"Status":"Success","Message":{"Id":"9235948e-5469-450e-8aaf-551772da9c6a"}}

How do i access this id inside message?

$res = $leadsquared->create_lead($data);
print_r($res);

Body:
Try this :

$result = json_decode($res,true);<br/>
$id = $result['Message']['Id']


问:
How to make progress bar with dotted lines?
Maybe you've already seen such a progress bar? Share links for example. Are there any ideas how to do it? Thank you!
Image progress bar </p>

答:
If you want a simple progress bar you can use HTML5's <progress> element (https://developer.mozilla.org/en/docs/Web/HTML/Element/progress)  which seems to be supported quite well: http://caniuse.com/#feat=progress

You could then apply custom style on it so that you can see little dots when the progress increases.


问:
Get rid of warnings in List<GenericClass<T>>.toArray()
Another one of those how do I do toArray() with no warnings questions, but it's different from most of the ones posted here.

How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?

The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there's no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?

Thank you

```<code><T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}
</code>```

答:
You can add an @SuppressWarnings("unchecked") annotation. This does not change the method signature and allows you to do "unsafe" things without generating a warning. Your code is genuinely safe, so it's OK to suppress the warning. Note that, per @Affe's answer, Bad Things may happen after you return, but you can certainly implement your method correctly.

The Java Collections framework does this kind of stuff internally so it's not just a hack. Well, it is a hack, but it's an OK hack. Well, it's not that OK, but it works. Kinda.

ContentLicense: CC BY-SA 2.5

Body:
Another one of those how do I do toArray() with no warnings questions, but it's different from most of the ones posted here.

How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?

The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there's no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?

Thank you

<T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
    return list.toArray(new GenericClass[0]);
}


问:
File naming convention for JSP
Is there an industry-standard naming convention for JSP files?

I have come across three conventions from different sources:

All lowercase  (thisismyfile.jsp)

Camel case with the first letter lowercase (thisIsMyFile.jsp)

Camel case with the first letter uppercase (ThisIsMyFile.jsp)

答:
According to IBM, jsp file should be named all lowercase and separate by underscore ("_") characters.

Eg: orderline_search_bydate.jsp

Title: File naming convention for JSP


答:
Like this:

```<code>$res = '{"Status":"Success","Message":{"Id":"9235948e-5469-450e-8aaf-551772da9c6a"}}';
$resArr = json_decode($res, true); // true is needed to make the output array associative.
print_r($resArr['Message']['Id']);
</code>```

Use json_decode() to turn the json string into a php array.

Title: How to access this json data 'id' inside data 'Message' in the php script below?

Body:
Like this:

$res = '{"Status":"Success","Message":{"Id":"9235948e-5469-450e-8aaf-551772da9c6a"}}';
$resArr = json_decode($res, true); // true is needed to make the output array associative.
print_r($resArr['Message']['Id']);

Use json_decode() to turn the json string into a php array.


问:
Counting spaces, tabs and new lines using while ( cin >> )
Im having trouble with my programm that should count every symbol in a string that the user sent to the stream. It counts consonants, vowels, 'ff', 'fl', 'fi' and '\t', '\n' and ' '. The problem is that the programm works pretty good, but still doesnt count spaces, tabs and new lines. I've tried to use noskipws manipulator but it doesnt read anything untill the first word.

Here it is:

```<code>int aCnt=0, eCnt=0, iCnt=0, oCnt=0, uCnt=0,
consonantCnt=0;

int ffCnt = 0, flCnt = 0, fiCnt = 0;

int spaceCnt = 0, newlCnt = 0, tabCnt = 0;

char *check = new char[100];

while ( cin >> check ) {

for ( int ix = 0; ix < strlen(check); ++ix ) {

 switch ( check[ix] ) {
    case 'a': case 'A':
      ++aCnt;
      break;
    case 'e': case 'E':
      ++eCnt;
      break;
    case 'i': case 'I':
      ++iCnt;
      break;
    case 'o': case 'O':
      ++oCnt;
      break;
    case 'u': case 'U':
      ++uCnt;
      break;
    case ' ':
      ++spaceCnt;
      break;
    case '\t':
      ++tabCnt;
      break;
    case '\n':
      ++newlCnt;
      break;
    default:
      if ( isalpha( check[ix] ) )
          ++consonantCnt;
      break;
}

  if ( check[ix] == 'f' ) {
    ++ix;
       switch ( check[ix] ) {
           case 'f':
              ++consonantCnt;
              ++ffCnt;
              break;
            case 'i':
              ++fiCnt;
              ++iCnt;
              break;
            case 'l':
              ++consonantCnt;
              ++flCnt;
              break;
            case 'I':
              ++iCnt;
              break;
            case 'a': case 'A':
              ++aCnt;
              break;
            case 'e': case 'E':
              ++eCnt;
              break;
            case 'o': case 'O':
              ++oCnt;
              break;
            case 'u': case 'U':
              ++uCnt;
              break;
            case ' ':
              ++spaceCnt;
              break;
            case '\t':
              ++tabCnt;
              break;
            case '\n':
              ++newlCnt;
              break;

            default:
               if ( isalpha( check[ix] ) )
               ++consonantCnt;
               break;
      }
    }
  }
}

delete [] check;

cout << "Встретилась a: \t" << aCnt << '\n'
<< "Встретилась e: \t" << eCnt << '\n'
<< "Встретилась i: \t" << iCnt << '\n'
<< "Встретилась o: \t" << oCnt << '\n'
<< "Встретилась u: \t" << uCnt << '\n'
<< "Встретилось согласных: \t" << consonantCnt << '\n'
<< "Встретилось fl: \t" << flCnt << '\n'
<< "Встретилось fi: \t" << fiCnt << '\n'
<< "Встретилось ff: \t" << ffCnt << '\n'
<< "Встретилось символов табуляции: \t" << ffCnt << '\n'
<< "Встретилось символов пробела: \t" << ffCnt << '\n'
<< "Встретилось символов новой строки: \t" << ffCnt << '\n'
<< '\n';
</code>```

答:
```<code>int tabCount = 0, spaceCount = 0, newlineCount = -1;
while(std::getline(std::cin, line)){ //getline reads in a line to a string tokenized by \d by default
    newlineCount++; //every time there's a new loop, theres a new newline.
    for(auto c : line) {
        if(c == '\t')
            tabCount++;
        else if(c == ' ')
            spaceCount++;
    }
}
</code>```

You can use this basic format to read in strings line by line from std::cin or any other input stream. std::getline will automatically tokenize by '\n' so you can start your newline count from -1 (assuming you get at least one line) and loop over your string and count any character you want.

Body:
Im having trouble with my programm that should count every symbol in a string that the user sent to the stream. It counts consonants, vowels, 'ff', 'fl', 'fi' and '\t', '\n' and ' '. The problem is that the programm works pretty good, but still doesnt count spaces, tabs and new lines. I've tried to use noskipws manipulator but it doesnt read anything untill the first word.

Here it is:

int aCnt=0, eCnt=0, iCnt=0, oCnt=0, uCnt=0,
consonantCnt=0;

int ffCnt = 0, flCnt = 0, fiCnt = 0;

int spaceCnt = 0, newlCnt = 0, tabCnt = 0;

char *check = new char[100];

while ( cin >> check ) {

for ( int ix = 0; ix < strlen(check); ++ix ) {

 switch ( check[ix] ) {
    case 'a': case 'A':
      ++aCnt;
      break;
    case 'e': case 'E':
      ++eCnt;
      break;
    case 'i': case 'I':
      ++iCnt;
      break;
    case 'o': case 'O':
      ++oCnt;
      break;
    case 'u': case 'U':
      ++uCnt;
      break;
    case ' ':
      ++spaceCnt;
      break;
    case '\t':
      ++tabCnt;
      break;
    case '\n':
      ++newlCnt;
      break;
    default:
      if ( isalpha( check[ix] ) )
          ++consonantCnt;
      break;
}

  if ( check[ix] == 'f' ) {
    ++ix;
       switch ( check[ix] ) {
           case 'f':
              ++consonantCnt;
              ++ffCnt;
              break;
            case 'i':
              ++fiCnt;
              ++iCnt;
              break;
            case 'l':
              ++consonantCnt;
              ++flCnt;
              break;
            case 'I':
              ++iCnt;
              break;
            case 'a': case 'A':
              ++aCnt;
              break;
            case 'e': case 'E':
              ++eCnt;
              break;
            case 'o': case 'O':
              ++oCnt;
              break;
            case 'u': case 'U':
              ++uCnt;
              break;
            case ' ':
              ++spaceCnt;
              break;
            case '\t':
              ++tabCnt;
              break;
            case '\n':
              ++newlCnt;
              break;

            default:
               if ( isalpha( check[ix] ) )
               ++consonantCnt;
               break;
      }
    }
  }
}

delete [] check;

cout << "Встретилась a: \t" << aCnt << '\n'
<< "Встретилась e: \t" << eCnt << '\n'
<< "Встретилась i: \t" << iCnt << '\n'
<< "Встретилась o: \t" << oCnt << '\n'
<< "Встретилась u: \t" << uCnt << '\n'
<< "Встретилось согласных: \t" << consonantCnt << '\n'
<< "Встретилось fl: \t" << flCnt << '\n'
<< "Встретилось fi: \t" << fiCnt << '\n'
<< "Встретилось ff: \t" << ffCnt << '\n'
<< "Встретилось символов табуляции: \t" << ffCnt << '\n'
<< "Встретилось символов пробела: \t" << ffCnt << '\n'
<< "Встретилось символов новой строки: \t" << ffCnt << '\n'
<< '\n';

Body:
int tabCount = 0, spaceCount = 0, newlineCount = -1;
while(std::getline(std::cin, line)){ //getline reads in a line to a string tokenized by \d by default
    newlineCount++; //every time there's a new loop, theres a new newline.
    for(auto c : line) {
        if(c == '\t')
            tabCount++;
        else if(c == ' ')
            spaceCount++;
    }
}

You can use this basic format to read in strings line by line from std::cin or any other input stream. std::getline will automatically tokenize by '\n' so you can start your newline count from -1 (assuming you get at least one line) and loop over your string and count any character you want.


问:
UTF-8 String decoding in Python
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

```<code>    utf8_encode ("Köln") //result: KÃ¶ln
</code>```

From the Python side I tried the decode function:

```<code>    "KÃ¶ln".decode("utf-8", "strict")
</code>```

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?

答: In cases like this you should add #-*- coding: UTF-8 -*- in the first line of your .py file.

Title: UTF-8 String decoding in Python

Body:
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

    utf8_encode ("Köln") //result: KÃ¶ln

From the Python side I tried the decode function:

    "KÃ¶ln".decode("utf-8", "strict")

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?


问:
Special characters in my javascript variables keep showing up as �, how do i prevent this?
I have a javascript script which is calling a php page to supply an ajax form with suggestions. The suggestions are returned fine by the php page, but for some reason, when i set the responsetext of the javascript object request as an element in my HTML page, all the special characters (ie. á or ã) show up as this question mark. Is there a function II must run on the response text of the request to make sure these are read properly?

Thanks.

答:
If you are not serving your HTML pages as UTF-8, the browser will guess an encoding, typically a single-byte Windows codepage depending on the user's locale.

But this doesn't happen for AJAX. With XMLHttpRequest, unless you specifically state an encoding in the Content-Type: ...; charset= parameter, the browser will treat it as UTF-8. That means if you are actually serving Windows code page 1252 (Western European) content, you will get an invalid UTF-8 sequence and consequent question mark.

You don't want to be using a non-UTF-8 encoding! Make sure you are using UTF-8 throughout your application. Serve all your pages with Content-Type: text/html; charset=utf-8, store your data in UTF-8 tables, use mysql_set_charset() to choose UTF-8, etc.

In any case consider passing AJAX responses using JSON. The function json_encode() will create a JSON string that uses JavaScript escape sequences for non-ASCII characters, which avoids any problem of encoding mismatch. Also this is easier to extend to add functionality than returning raw HTML.


答:
In Python3, all text is in unicode. So I would recommend, on your PHP side, converting the string to unicode (outputting as u'K\xf6ln'). After you've done this, you can convert it back to (sort of) it's original form in Python, however, the mutated vowel will be destroyed.

```<code>import unicodedata

unicodetext = u'K\xf6ln'
output = unicodedata.normalize('NFKD', unicodetext).encode('ascii', 'ignore')
</code>```

This will output a lonesome Koln, without the rather pretty mutation. From my research, I can't find any way around this, but please, anybody who finds a more apt solution please comment

Title: UTF-8 String decoding in Python

Body:
In Python3, all text is in unicode. So I would recommend, on your PHP side, converting the string to unicode (outputting as u'K\xf6ln'). After you've done this, you can convert it back to (sort of) it's original form in Python, however, the mutated vowel will be destroyed.

import unicodedata

unicodetext = u'K\xf6ln'
output = unicodedata.normalize('NFKD', unicodetext).encode('ascii', 'ignore')

This will output a lonesome Koln, without the rather pretty mutation. From my research, I can't find any way around this, but please, anybody who finds a more apt solution please comment


问:
How does this way of accessing character in C-String work?
This question was asked in a recent exam where the candidate had to find the output for the following code:

```<code>#include<stdio.h>
#include<string.h>
int main()
{
    char * c = "GATECSIT2017";
    char *p = c;
    printf("%d", (int)strlen(c+2[p]-6[p]-1));
    return 0;
}
</code>```

I started coding in C++ , so I wasn't an expert in C-Strings. After messing around with code, I understood how it worked, but one thing wasn't clear to me, which was this way of accessing a char from the char* string.

My question is, how 2[p] gets the character at index 2?
Does it  resolve into *(p+2) or is there something else going on? Also, is there any documentation or any article that could explain this behavior?

答:
For any array or pointer a and index i, the expression a[i] is equal to *(a + i).

Because of the commutative property of + the expression *(a + i) is equal to *(i + a), which according to the first equality is equal to i[a], i.e. switching place of the index and pointer/array.

So in your case the expression 2[p] is equal to *(2 + p) which is equal to *(p + 2) which is equal to p[2].

Using e.g. 2[p] is only for (bad) obfuscation so please don't use it anywhere.

Body:
This question was asked in a recent exam where the candidate had to find the output for the following code:

#include<stdio.h>
#include<string.h>
int main()
{
    char * c = "GATECSIT2017";
    char *p = c;
    printf("%d", (int)strlen(c+2[p]-6[p]-1));
    return 0;
}

I started coding in C++ , so I wasn't an expert in C-Strings. After messing around with code, I understood how it worked, but one thing wasn't clear to me, which was this way of accessing a char from the char* string.

My question is, how 2[p] gets the character at index 2?
Does it  resolve into *(p+2) or is there something else going on? Also, is there any documentation or any article that could explain this behavior?


问:
After Deleting Row, Unable to Reload UITableView Data from NSObject File
When Pressing delete button it deletes selected Object from WebServer Datasource but unable to reload TableView,

Here is my code, Please advice that how to accomplish this or to let
  me know where I am doing this wrong.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    Records * RecordsObject;

    RecordsObject = [recordsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = RecordsObject.recordsMname;
    cell.detailTextLabel.text= RecordsObject.recordsImei;

    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [detailButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    detailButton.frame = CGRectMake(WidthCalculation - 45, 0.0f, 50.0f, 45.0f);
    [cell addSubview:detailButton];
    [detailButton addTarget:self
                     action:@selector(detailsButton:)
           forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:detailButton];
    [detailButton setTag:indexPath.row];

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
    deleteButton.frame = CGRectMake(WidthCalculation - 75, 0.0f, 50.0f, 45.0f);
    [cell addSubview:deleteButton];
    [deleteButton addTarget:self
                       action:@selector(delButton:event:)
             forControlEvents:UIControlEventTouchUpInside];
     [cell.contentView addSubview:deleteButton];

    // Configure the cell...

    return cell;
}
</code>```

Delete Button Functionality

```<code>- (IBAction)delButton: (UIButton*)button event:(UIEvent*)event
{
    UIButton *delButton = button;
    NSLog(@"FaceBook Button is sharing %li row's Image", (long)delButton.tag);

    NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:
                              [[[event touchesForView:button] anyObject]
                               locationInView:self.tableView]];

    Records *object = self.recordsArray[delButton.tag];
    NSLog(@"selected Object %@", object);
    NSString *id = object.recordsId;
    NSMutableString * postString = [NSMutableString stringWithString:kdeleteURL];
    [postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, id]];
    [postString setString:[postString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];

    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];

    [request setHTTPMethod:@"POST"];

    postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    [self.recordsArray removeObjectAtIndex:indexPath.row];

            [self.tableView reloadData];

}
</code>```

Please do let me know if you require more information such is as code for object file or data retrieval code snippet for retrieving data from server side.

答:
```<code>NSIndexPath *index = [[NSIndexPath alloc] init];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    Records * RecordsObject;

    RecordsObject = [recordsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = RecordsObject.recordsMname;
    cell.detailTextLabel.text= RecordsObject.recordsImei;

    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [detailButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    detailButton.frame = CGRectMake(WidthCalculation - 45, 0.0f, 50.0f, 45.0f);
    [cell addSubview:detailButton];
    [detailButton addTarget:self
                     action:@selector(detailsButton:)
           forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:detailButton];
    [detailButton setTag:indexPath.row];

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
    deleteButton.frame = CGRectMake(WidthCalculation - 75, 0.0f, 50.0f, 45.0f);
    deleteButton.tag = indexPath.row
    [cell addSubview:deleteButton];
    [deleteButton addTarget:self
                       action:@selector(delButton:event:)
             forControlEvents:UIControlEventTouchUpInside];
     [cell.contentView addSubview:deleteButton];

    // Configure the cell...

    return cell;
}

- (IBAction)delButton: (UIButton*)button event:(UIEvent*)event
{
    UIButton *delButton = button;
    NSLog(@"FaceBook Button is sharing %li row's Image", (long)delButton.tag);

    NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:
                              [[[event touchesForView:button] anyObject]
                               locationInView:self.tableView]];

    Records *object = self.recordsArray[delButton.tag];
    NSLog(@"selected Object %@", object);
    NSString *id = object.recordsId;
    NSMutableString * postString = [NSMutableString stringWithString:kdeleteURL];
    [postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, id]];
    [postString setString:[postString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];

    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];

    [request setHTTPMethod:@"POST"];

    postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    index = indexPath
}
</code>```

If you get success response then delete row and object from array.

```<code>-(void)serviceResponce() {
   [self.recordsArray removeObjectAtIndex:indexPath.row];
   [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: index] withRowAnimation:UITableViewRowAnimationNone];
}
</code>```

Body:
When Pressing delete button it deletes selected Object from WebServer Datasource but unable to reload TableView,

Here is my code, Please advice that how to accomplish this or to let
  me know where I am doing this wrong.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    Records * RecordsObject;

    RecordsObject = [recordsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = RecordsObject.recordsMname;
    cell.detailTextLabel.text= RecordsObject.recordsImei;

    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [detailButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    detailButton.frame = CGRectMake(WidthCalculation - 45, 0.0f, 50.0f, 45.0f);
    [cell addSubview:detailButton];
    [detailButton addTarget:self
                     action:@selector(detailsButton:)
           forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:detailButton];
    [detailButton setTag:indexPath.row];

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
    deleteButton.frame = CGRectMake(WidthCalculation - 75, 0.0f, 50.0f, 45.0f);
    [cell addSubview:deleteButton];
    [deleteButton addTarget:self
                       action:@selector(delButton:event:)
             forControlEvents:UIControlEventTouchUpInside];
     [cell.contentView addSubview:deleteButton];

    // Configure the cell...

    return cell;
}

Delete Button Functionality

- (IBAction)delButton: (UIButton*)button event:(UIEvent*)event
{
    UIButton *delButton = button;
    NSLog(@"FaceBook Button is sharing %li row's Image", (long)delButton.tag);

    NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:
                              [[[event touchesForView:button] anyObject]
                               locationInView:self.tableView]];

    Records *object = self.recordsArray[delButton.tag];
    NSLog(@"selected Object %@", object);
    NSString *id = object.recordsId;
    NSMutableString * postString = [NSMutableString stringWithString:kdeleteURL];
    [postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, id]];
    [postString setString:[postString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];

    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];

    [request setHTTPMethod:@"POST"];

    postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    [self.recordsArray removeObjectAtIndex:indexPath.row];

            [self.tableView reloadData];

}

Please do let me know if you require more information such is as code for object file or data retrieval code snippet for retrieving data from server side.

Body:
NSIndexPath *index = [[NSIndexPath alloc] init];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];

    Records * RecordsObject;

    RecordsObject = [recordsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = RecordsObject.recordsMname;
    cell.detailTextLabel.text= RecordsObject.recordsImei;

    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [detailButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    detailButton.frame = CGRectMake(WidthCalculation - 45, 0.0f, 50.0f, 45.0f);
    [cell addSubview:detailButton];
    [detailButton addTarget:self
                     action:@selector(detailsButton:)
           forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:detailButton];
    [detailButton setTag:indexPath.row];

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
    deleteButton.frame = CGRectMake(WidthCalculation - 75, 0.0f, 50.0f, 45.0f);
    deleteButton.tag = indexPath.row
    [cell addSubview:deleteButton];
    [deleteButton addTarget:self
                       action:@selector(delButton:event:)
             forControlEvents:UIControlEventTouchUpInside];
     [cell.contentView addSubview:deleteButton];

    // Configure the cell...

    return cell;
}

- (IBAction)delButton: (UIButton*)button event:(UIEvent*)event
{
    UIButton *delButton = button;
    NSLog(@"FaceBook Button is sharing %li row's Image", (long)delButton.tag);

    NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:
                              [[[event touchesForView:button] anyObject]
                               locationInView:self.tableView]];

    Records *object = self.recordsArray[delButton.tag];
    NSLog(@"selected Object %@", object);
    NSString *id = object.recordsId;
    NSMutableString * postString = [NSMutableString stringWithString:kdeleteURL];
    [postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, id]];
    [postString setString:[postString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];

    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];

    [request setHTTPMethod:@"POST"];

    postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    index = indexPath
}

If you get success response then delete row and object from array.

-(void)serviceResponce() {
   [self.recordsArray removeObjectAtIndex:indexPath.row];
   [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: index] withRowAnimation:UITableViewRowAnimationNone];
}


问:
MySQL JOIN tables with COUNT values

I have the following tables in my database.I only listed the important columns which can be used for joining.

I need to get the following output

Currently I'm using two seperate queries for each COUNT value

For assigned licenses

```<code>select
    products.id,products.name,COUNT(assigned_licenses.id)
from
    deployment_users
inner join
    assigned_licenses
on
    deployment_users.id = assigned_licenses.deployment_user_id
inner join
    products
on
    assigned_licenses.id = products.id
and
    deployment_users.customer_id = 10
group by
    assigned_licenses.id
;
</code>```

For total licenses

```<code>select
    products.id,products.name,COUNT(total_licenses.id)
from
    customers
inner join
    total_licenses
on
    customers.iccode = licenses.iccode
inner join
    products
on
    total_licenses.id = products.id
and
    customers.id = 10
group by
    total_licenses.id
;
</code>```

Since there are more than a 1,000 products that need to be listed,I want to combine them into a single query.How can I do that?

答:
Your specification leaves some room for interpretation (e.g. can a user have assigned licenses without total licenses? if yes my query will fail.) but I would go with this.

```<code>SELECT
    products.id,
    products.name,
    Count(Distinct total_licenses.id) As CountTotalLicenses,
    Count(Distinct assigned_liceses.deployment_users_id) As CountAssignedLicenses
FROM products
    LEFT JOIN total_licenses ON total_licenses.products_id = products.id
    LEFT JOIN customers ON customers.iccode = total_licenses.customers_iccode
    LEFT JOIN assigned_licenses ON assigned_liceses.total_licenses_id = total_licenses.id
WHERE
    customers.id = 10
GROUP BY
    products.id,
    products.name
</code>```

For the future it would be awesome if you could paste code as code and not as an image. People cannot simple copy paste snippets of your code and have to type everything again...

Title: MySQL JOIN tables with COUNT values

Body:
I have the following tables in my database.I only listed the important columns which can be used for joining.

I need to get the following output

Currently I'm using two seperate queries for each COUNT value

For assigned licenses

select
    products.id,products.name,COUNT(assigned_licenses.id)
from
    deployment_users
inner join
    assigned_licenses
on
    deployment_users.id = assigned_licenses.deployment_user_id
inner join
    products
on
    assigned_licenses.id = products.id
and
    deployment_users.customer_id = 10
group by
    assigned_licenses.id
;

For total licenses

select
    products.id,products.name,COUNT(total_licenses.id)
from
    customers
inner join
    total_licenses
on
    customers.iccode = licenses.iccode
inner join
    products
on
    total_licenses.id = products.id
and
    customers.id = 10
group by
    total_licenses.id
;

Since there are more than a 1,000 products that need to be listed,I want to combine them into a single query.How can I do that?

Body:
Your specification leaves some room for interpretation (e.g. can a user have assigned licenses without total licenses? if yes my query will fail.) but I would go with this.

SELECT
    products.id,
    products.name,
    Count(Distinct total_licenses.id) As CountTotalLicenses,
    Count(Distinct assigned_liceses.deployment_users_id) As CountAssignedLicenses
FROM products
    LEFT JOIN total_licenses ON total_licenses.products_id = products.id
    LEFT JOIN customers ON customers.iccode = total_licenses.customers_iccode
    LEFT JOIN assigned_licenses ON assigned_liceses.total_licenses_id = total_licenses.id
WHERE
    customers.id = 10
GROUP BY
    products.id,
    products.name

For the future it would be awesome if you could paste code as code and not as an image. People cannot simple copy paste snippets of your code and have to type everything again...


问:
Android Material Stepper - How to create ListView in Fragment?
I am new to android Programming as well as Java, and right now I am making an app that requires a wizard. So, I am using a stepper library called Android Material Stepper by Stepstone.
In this wizard I have 3 step. the first step (First Fragment) contains an editText where the user fill in some text with certain pattern.  The text then passed to the second step (Second Fragment), where in this step the editText is split and convert to an array and display it to the end user as a ListView. Now here is the problem, I can't figure out how to do so.
This my second Fragment Code.

```<code>public class FragmentStep2 extends Fragment implements BlockingStep{TextView stepContent;
private DataManager dataManager;
onProceedListener onProceedListener;
private String passedData;

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    // TODO: Implement this method
    if(context instanceof onProceedListener | context instanceof DataManager) {
        onProceedListener = (onProceedListener) context;
        dataManager = (DataManager) context;
    } else {
        throw new IllegalStateException("Activity must implement OnProceedListener");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.quick_lfl_step2, container, false);
    return v;
}

@Override
public void onSelected()
{
    // TODO: Implement this method
    passedData = dataManager.getData();
    String[] arrayLfl = passedData.split("@");
    ListAdapter adapter = new ArrayAdapter<String>(getActivity(), R.layout.quick_lfl_row, R.id.absenLflList, arrayLfl);
    ListView listView = (ListView) getView().findViewById(R.id.list_lfl);
    listView.setAdapter(adapter);
}}
</code>```

here is a logcat

06-03 19:53:03.925 I/ActivityManager(802): Displayed
  tk.divabyan.ig/.activity.DefaultTabsActivity: +188ms (total
  +35m19s326ms) 06-03 19:53:10.246 E/AndroidRuntime(2162): Process: tk.divabyan.ig, PID: 2162 06-03 19:53:10.246 E/AndroidRuntime(2162):
    at
  tk.divabyan.ig.activity.QuickLfl.FragmentStep2.onSelected(FragmentStep2.java:76)
  06-03 19:53:10.246 E/AndroidRuntime(2162):    at
  tk.divabyan.ig.activity.FragmentStep1.onNextClicked(FragmentStep1.java:68)

答: Turns out the problem is because I give a wrong resource id to the list adapter.</p>

Body:
I am new to android Programming as well as Java, and right now I am making an app that requires a wizard. So, I am using a stepper library called Android Material Stepper by Stepstone.
In this wizard I have 3 step. the first step (First Fragment) contains an editText where the user fill in some text with certain pattern.  The text then passed to the second step (Second Fragment), where in this step the editText is split and convert to an array and display it to the end user as a ListView. Now here is the problem, I can't figure out how to do so.
This my second Fragment Code.

public class FragmentStep2 extends Fragment implements BlockingStep{TextView stepContent;
private DataManager dataManager;
onProceedListener onProceedListener;
private String passedData;

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    // TODO: Implement this method
    if(context instanceof onProceedListener | context instanceof DataManager) {
        onProceedListener = (onProceedListener) context;
        dataManager = (DataManager) context;
    } else {
        throw new IllegalStateException("Activity must implement OnProceedListener");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.quick_lfl_step2, container, false);
    return v;
}

@Override
public void onSelected()
{
    // TODO: Implement this method
    passedData = dataManager.getData();
    String[] arrayLfl = passedData.split("@");
    ListAdapter adapter = new ArrayAdapter<String>(getActivity(), R.layout.quick_lfl_row, R.id.absenLflList, arrayLfl);
    ListView listView = (ListView) getView().findViewById(R.id.list_lfl);
    listView.setAdapter(adapter);
}}

here is a logcat

06-03 19:53:03.925 I/ActivityManager(802): Displayed
  tk.divabyan.ig/.activity.DefaultTabsActivity: +188ms (total
  +35m19s326ms) 06-03 19:53:10.246 E/AndroidRuntime(2162): Process: tk.divabyan.ig, PID: 2162 06-03 19:53:10.246 E/AndroidRuntime(2162):
    at
  tk.divabyan.ig.activity.QuickLfl.FragmentStep2.onSelected(FragmentStep2.java:76)
  06-03 19:53:10.246 E/AndroidRuntime(2162):    at
  tk.divabyan.ig.activity.FragmentStep1.onNextClicked(FragmentStep1.java:68)


问:
merge 2 vectors using STL algorithm
I've 2 vectors, namely deals_all and deals_new of FXDeal, where FxDeal is a class

```<code>struct FxDeal
{
    int deal_id_; // primary key
    string ccy_pair_;
    double amount_;
}
</code>```

Both vectors are sorted by the primary key field deal_id_.

How could I merge deals_new into deals_all so that

new deals in deals_new are copied or appended to deals_all, and

deals in deals_all that appear also in deal_new (by primary key
deal_id_), will have field ccy_pair_ and amount_ updated

I'm using c++11.

答:
You can use std::set_union. (this assumes the vectors are sorted using a comparison function called compare_by_id, which does what the name implies).

```<code>std::vector<FxDeal> merged_deals;
std::set_union(deals_new.begin(), deals_new.end(),
    deals_all.begin(), deals_all.end(),
    std::back_inserter(merged_deals),
    compare_by_id);

deals_all = std::move(merged_deals);
</code>```

Be sure you pass deals_new as the first range, because that will be the one which is copied over in cases of duplicate ids.

Title: merge 2 vectors using STL algorithm

Body:
I've 2 vectors, namely deals_all and deals_new of FXDeal, where FxDeal is a class

struct FxDeal
{
    int deal_id_; // primary key
    string ccy_pair_;
    double amount_;
}

Both vectors are sorted by the primary key field deal_id_.

How could I merge deals_new into deals_all so that

new deals in deals_new are copied or appended to deals_all, and

deals in deals_all that appear also in deal_new (by primary key
deal_id_), will have field ccy_pair_ and amount_ updated

I'm using c++11.

Body:
You can use std::set_union. (this assumes the vectors are sorted using a comparison function called compare_by_id, which does what the name implies).

std::vector<FxDeal> merged_deals;
std::set_union(deals_new.begin(), deals_new.end(),
    deals_all.begin(), deals_all.end(),
    std::back_inserter(merged_deals),
    compare_by_id);

deals_all = std::move(merged_deals);

Be sure you pass deals_new as the first range, because that will be the one which is copied over in cases of duplicate ids.


问:
How can I select a specific tag in two different HTML structure?
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}</code>```

HTML1:

    sth
    something
    link

HTML2:

    something

sth

```
</div>
</div>
</p>

<p>Ok, let me explain. I want two things happen when the user clicks on <code>.myclass</code> element: <em>(as you see, <code>.myclass</code> element is different in two HTML structures)</em></p>

<ul>
<li><p>Setting a pale gray color to the background of <code>li</code>.</p></li>
<li><p>Printing the <code>href</code> value of the link in the console.</p></li>
</ul>

<p>My current code works correctly for the first HTML structure <em>(but not for the second one)</em>. </p>

<hr>

<p><strong>Note:</strong> For the second one, jQuery code should look like this:</p>

``` $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})
```

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

答:
You can use .is() to test where current element is anchor and keep using .closest() to target LI element.

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

```<code>$(document).on('click', '.myclass', function(e) {
    e.preventDefault(e);
    var url;
    if ($(this).is('a')) {
        url = $(this).attr('href');
    } else {
        url = $(this).find('a').attr('href');
    }
    console.log(url);

    $(this).closest('li').css('background-color', '#f1f1f1');
});
</code>```

$(document).on('click', '.myclass', function(e) {
  e.preventDefault(e);
  var url;
  if ($(this).is('a')) {
    url = $(this).attr('href');
  } else {
    url = $(this).find('a').attr('href');
  }
  console.log(url);

  $(this).closest('li').css('background-color', '#f1f1f1');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  border: 1px solid gray;
}

a {
  display: block;
}

.myclass {
  cursor: pointer;
}</code>```

HTML1:

    sth
    something
    link

 HTML2:

      something

sth

```
</div>
</div>
</p>

<hr>

<p>However It would be cleaner to use separate event handler</p>

```$(document).on('click', 'a.myclass', function(e){
  var url = $(this).attr('href');
})
$(document).on('click', 'li.myclass', function(e){
  var url = $(this).find('a').attr('href');
})
```

Body:
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})

li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}

HTML1:

    sth
    something
    link

HTML2:

    something

sth

Ok, let me explain. I want two things happen when the user clicks on .myclass element: (as you see, .myclass element is different in two HTML structures)

Setting a pale gray color to the background of li.

Printing the href value of the link in the console.

My current code works correctly for the first HTML structure (but not for the second one).

Note: For the second one, jQuery code should look like this:

 $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

Body:
You can use .is() to test where current element is anchor and keep using .closest() to target LI element.

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

$(document).on('click', '.myclass', function(e) {
    e.preventDefault(e);
    var url;
    if ($(this).is('a')) {
        url = $(this).attr('href');
    } else {
        url = $(this).find('a').attr('href');
    }
    console.log(url);

    $(this).closest('li').css('background-color', '#f1f1f1');
});

$(document).on('click', '.myclass', function(e) {
  e.preventDefault(e);
  var url;
  if ($(this).is('a')) {
    url = $(this).attr('href');
  } else {
    url = $(this).find('a').attr('href');
  }
  console.log(url);

  $(this).closest('li').css('background-color', '#f1f1f1');
})

li {
  border: 1px solid gray;
}

a {
  display: block;
}

.myclass {
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML1:

<ul>
  <li>
    <a href="#">sth</a>
    <span>something</span>
    <a class="myclass" href="./my/path">link</a>
  </li>
</ul>

<hr /> HTML2:

<ul>
  <li class="myclass">
    <a href="./my/path">
      <span>something</span>
    </a>
    <div>sth</div>
  </li>
</ul>

However It would be cleaner to use separate event handler

$(document).on('click', 'a.myclass', function(e){
  var url = $(this).attr('href');
})
$(document).on('click', 'li.myclass', function(e){
  var url = $(this).find('a').attr('href');
})


问:
How to exclude text between two curly brackets with regex?
I am new to regular expressions, I have a text like this:

test{{this should not be selected and the curly brackets too}} but
  this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets.

and I want this result

"test"

and

"but this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets."

This is my expression I used:

```<code>$p = '/[a-zA-Z0-9#\' ]+(?![^{{]*}})/';
</code>```

But this excludes the single curly brackets.

I want to know how to include the single curly brackets with the text and exclude only text between two curly brackets

And please can you give me some good documentation about regex expression? I want to learn more about this.

答:
Input (I doubled the string for effect):

```<code>$string = 'test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.';
</code>```

Method #1 preg_split():

```<code>var_export(preg_split('/{{[^}]*}}/', $string, 0, PREG_SPLIT_NO_EMPTY));
// Added the fourth param in case the input started/ended with a double curly substring.
</code>```

Method #2 preg_match_all():

```<code>var_export(preg_match_all('/(?<=}{2}|^)(?!{{2}).*?(?={{2}|$)/s', $string, $out) ? $out[0] : []);
</code>```

Output (either way):

```<code>array (
  0 => 'test',
  1 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test',
  2 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.',
)
</code>```

preg_split() treats the double curly wrapped substrings as "delimiters" and splits the full string on them.

The preg_match_all() method pattern...
Pattern Demo  This uses a positive lookbehind and a positive lookahead both of which hunt for double curlies or start/end of string.  It uses a negative lookahead in the middle to avoid matching unwanted double-curly strings at the start of a new line.  Finally the s modifier at the end of the pattern will allow . to match newline characters.

Body:
I am new to regular expressions, I have a text like this:

test{{this should not be selected and the curly brackets too}} but
  this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets.

and I want this result

"test"

and

"but this one { or } should be selected.  So I want to exclude all text
  between an opening and closing curly brackets."

This is my expression I used:

$p = '/[a-zA-Z0-9#\' ]+(?![^{{]*}})/';

But this excludes the single curly brackets.

I want to know how to include the single curly brackets with the text and exclude only text between two curly brackets

And please can you give me some good documentation about regex expression? I want to learn more about this.

Body:
Input (I doubled the string for effect):

$string = 'test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.';

Method #1 preg_split():

var_export(preg_split('/{{[^}]*}}/', $string, 0, PREG_SPLIT_NO_EMPTY));
// Added the fourth param in case the input started/ended with a double curly substring.

Method #2 preg_match_all():

var_export(preg_match_all('/(?<=}{2}|^)(?!{{2}).*?(?={{2}|$)/s', $string, $out) ? $out[0] : []);

Output (either way):

array (
  0 => 'test',
  1 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test',
  2 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.',
)

preg_split() treats the double curly wrapped substrings as "delimiters" and splits the full string on them.

The preg_match_all() method pattern...
Pattern Demo  This uses a positive lookbehind and a positive lookahead both of which hunt for double curlies or start/end of string.  It uses a negative lookahead in the middle to avoid matching unwanted double-curly strings at the start of a new line.  Finally the s modifier at the end of the pattern will allow . to match newline characters.

ContentLicense: CC BY-SA 4.0


问:
Can we say this is an IIFE ?!?- In Javascript
As you know in Javascript, it's very common to use the following expression as an IIFE (Immediately Invoked Function Expression) :

```<code>(function(){
  //code ...
})();
</code>```

I'm wondering if we can say that the following expression is an IIFE (when no return value needed):

```<code>new function(){
 //code ...
}
</code>```

Or

```<code>new function(global){
  //code..
}(this);
</code>```

Even though it's an object . Thanks .

Answer :

[ Thanks to @le_m , @vol7ron and @Bergi , here is the short answer ]
Can we say that he following expression is an IIFE (Immediately Invoked Function Expression) ?

```<code>new function(){
 //code ...
}
</code>```

Or

```<code>new function(global){
  //code..
}(this);
</code>```

The answer is NO.
And what's that ?
It's just an unnamed object with an anonymous constructor, so we're not talking about functions here (plain and simple).

答:
Yes it is an Immediately Invoked Function Expression (IIFE), though this pattern is not generally used.

From MDN Docs:

IIFE (Immediately Invoked Function Expression) is a JavaScript
  function that runs as soon as it is defined.

```<code>new function(){
 //code ...
}
</code>```

So according to the definition, your example is a Javascript function and runs the definition immediately.

From Wikipedia:

An immediately-invoked function expressio is a JavaScript programming language idiom which produces a
  lexical scope using JavaScript's function scoping. Immediately-invoked
  function expressions can be used to avoid variable hoisting from
  within blocks, protect against polluting the global environment and
  simultaneously allow public access to methods while retaining privacy
  for variables defined within the function.

In the mentioned example, the pattern does provide a lexical scope to the variables in the definition and encapsulates the methods and definitions from global environment.

Body:
As you know in Javascript, it's very common to use the following expression as an IIFE (Immediately Invoked Function Expression) :

(function(){
  //code ...
})();

I'm wondering if we can say that the following expression is an IIFE (when no return value needed):

new function(){
 //code ...
}

Or

new function(global){
  //code..
}(this);

Even though it's an object . Thanks .

Answer :

[ Thanks to @le_m , @vol7ron and @Bergi , here is the short answer ]
Can we say that he following expression is an IIFE (Immediately Invoked Function Expression) ?

new function(){
 //code ...
}

Or

new function(global){
  //code..
}(this);

The answer is NO.
And what's that ?
It's just an unnamed object with an anonymous constructor, so we're not talking about functions here (plain and simple).

Body:
Yes it is an Immediately Invoked Function Expression (IIFE), though this pattern is not generally used.

From MDN Docs:

IIFE (Immediately Invoked Function Expression) is a JavaScript
  function that runs as soon as it is defined.

new function(){
 //code ...
}

So according to the definition, your example is a Javascript function and runs the definition immediately.

From Wikipedia:

An immediately-invoked function expressio is a JavaScript programming language idiom which produces a
  lexical scope using JavaScript's function scoping. Immediately-invoked
  function expressions can be used to avoid variable hoisting from
  within blocks, protect against polluting the global environment and
  simultaneously allow public access to methods while retaining privacy
  for variables defined within the function.

In the mentioned example, the pattern does provide a lexical scope to the variables in the definition and encapsulates the methods and definitions from global environment.


问:
String concatenation maintaining destination length
I have a basic server-client program that I'm writing in C and I am stuck with an issue regarding strings and concatenation.
Basically I have some strings (in the example below just 2) that I have to put into a buffer which size is determined by:

```<code>  total # of registered people * 33
</code>```

Both the strings in the example have a length which is much less than the length of the buffer. I want to obtain something like this after the concatenation:

```<code>            [0]            [32]
people_list=Mark           Amy\0;
</code>```

where Mark(which is inserted secondly) is right at the start of the buffer (people_list) and Amy is 32 characters away from the start of Mark (I hope I've made myself clear).

This is because the client code was given to me and I cannot modify it. The client code takes the buffer and reads the first element, then jumps of 32 chars and reads again.
The output I get from the printf of the client is this:

```<code>connected to server
Registered people:
 Mark
</code>```

while I'd like this:

```<code>connected to server
Registered people:
 Mark
 Amy
</code>```

The communication is implemented through sockets, which I have already checked, but if you wish to suggest some changes I would appreciate that.

Server code:

```<code>#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#define LENGTH 32

struct person {
    char name[LENGTH+1];
    struct person *next;
    struct person *prev;

};
struct person *p_head = NULL;

void addPerson(char* name_p){
    struct person *new = (struct person*) malloc(sizeof(struct person));
    strcpy(new->name, name_p);
    new->name[LENGTH]='\0';
    new->next=p_head;
    new->prev=NULL;
    p_head=new;

}

int main(){

    int fd_ser;
    int fd_c;
    int N=100;
    char buf[N];
    int times=0;
    char* path="tmp/sock";

    struct sockaddr_un sa;

    unlink(path);
    sa.sun_family=AF_UNIX;
    strncpy(sa.sun_path,(char*) path, sizeof(sa.sun_path));

    if((fd_ser=socket(AF_UNIX,SOCK_STREAM,0))<0){   //socket
        perror((const char*) (size_t) errno);
        exit(EXIT_FAILURE);
    }

    if ( bind(fd_ser,(struct sockaddr *)&sa, sizeof(sa))<0){
        perror("bind\n");
    }

    listen(fd_ser,10);  //listen

    struct sockaddr_un addr;
    int addr_size= sizeof(struct sockaddr_un);

    fd_c=0;
    while( (fd_c=accept(fd_ser,(struct sockaddr*) &addr, (socklen_t*)&addr_size))<0){
        printf("waiting for connections...\n");
        sleep(2);
    }

    //initialize list of people
    char* Amy="Amy";
    char* Mark="Mark";

    addPerson(Amy);
    addPerson(Mark);

    //now concat the name strings in a buffer to be sent to the client

    char* people_list;
    unsigned int list_len;
    int value;

    struct person* ptr=(struct person*) malloc(sizeof(struct person));
    ptr=p_head;
    int offset=0;
    int i=0;

    while(ptr!=NULL){
        i++;
        people_list=realloc(people_list,i*LENGTH); //every single name has to be LENGTH characters
        strcpy(&people_list[offset],ptr->name);
        ptr=ptr->next;
        offset=offset+LENGTH;
    }
    people_list[i*LENGTH]='\0';
    list_len=(i*LENGTH)+1;

    value=write(fd_c, &(list_len), sizeof(unsigned int));
    if(value==-1){
        perror("write length");
        return -1;
    }

    int toWrite=list_len;
    char *toRead=people_list;
    while(toWrite>0){
        value=write(fd_c, toRead, toWrite);
        if(value==-1){
            perror("write data");
            return -1;
        }
        toWrite=toWrite-value;
        toRead=toRead+value;
        if(toRead<=people_list + list_len) break;
    }

    close(fd_c);
    close(fd_ser);

    return 0;
}
</code>```

Client code:

```<code>#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <errno.h>
#define MAX_LENGTH 2048
#define LENGTH 32

int main(){

    int fd_cli;
    char* path="tmp/sock";
    struct sockaddr_un sa;
    sa.sun_family=AF_UNIX;
    strncpy(sa.sun_path,(char*) path, sizeof(sa.sun_path));

    if( (fd_cli = socket(AF_UNIX, SOCK_STREAM, 0))==-1){
        perror((const char*) (size_t) errno);
        return -1;
    }

    while( (connect(fd_cli,(struct sockaddr*)&sa, sizeof(struct sockaddr_un))) == -1 ) {
        if ( errno == ENOENT ) { sleep(1); }
        else perror("connect:");
        errno=0;
        sleep(1);
    }

    printf("connected to server\n");

    int value;

    unsigned int len_data;

    value=read(fd_cli,&(len_data),sizeof(unsigned int));
    if(value==-1){
        perror("read length");
        return -1;
    }
    char* buffer=malloc(len_data*sizeof(char));

    int toRead=len_data;
    char *toWrite=buffer;
    while(toRead>0){
        value=read(fd_cli, toWrite, toRead);
        if(value==-1){
            perror("read buffer");
            return -1;
        }
        toRead=toRead-value;
        toWrite=toWrite+value;
        if(toWrite<=buffer + len_data) break;
    }

    int people_n = len_data / (LENGTH+1);
    assert(people_n > 0); //proceeds only if there is at least one person registered

    printf("Registered people:\n");

    for(int i=0,p=0;i<people_n; ++i, p+=(LENGTH+1)) {
        printf(" %s\n", &buffer[p]);
    }

    close(fd_cli);

    return 0;

}
</code>```

I really hope I've explained the problem clearly! Thank you for your help!

答:
It's printing only the first user (Mark) because of this line:

```<code>int people_n = len_data / (LENGTH+1);
</code>```

In this example, len_data = 65, LENGTH = 32. So when you are adding 1 to LENGTH, it will return 1 (65/33 = 1.96 => you get 1). Then it only prints the first user.

Consider using Valgrind. It will help you checking the use of the memory.

Body:
I have a basic server-client program that I'm writing in C and I am stuck with an issue regarding strings and concatenation.
Basically I have some strings (in the example below just 2) that I have to put into a buffer which size is determined by:

  total # of registered people * 33

Both the strings in the example have a length which is much less than the length of the buffer. I want to obtain something like this after the concatenation:

            [0]            [32]
people_list=Mark           Amy\0;

where Mark(which is inserted secondly) is right at the start of the buffer (people_list) and Amy is 32 characters away from the start of Mark (I hope I've made myself clear).

This is because the client code was given to me and I cannot modify it. The client code takes the buffer and reads the first element, then jumps of 32 chars and reads again.
The output I get from the printf of the client is this:

connected to server
Registered people:
 Mark

while I'd like this:

connected to server
Registered people:
 Mark
 Amy

The communication is implemented through sockets, which I have already checked, but if you wish to suggest some changes I would appreciate that.

Server code:

#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#define LENGTH 32

struct person {
    char name[LENGTH+1];
    struct person *next;
    struct person *prev;

};
struct person *p_head = NULL;

void addPerson(char* name_p){
    struct person *new = (struct person*) malloc(sizeof(struct person));
    strcpy(new->name, name_p);
    new->name[LENGTH]='\0';
    new->next=p_head;
    new->prev=NULL;
    p_head=new;

}

int main(){

    int fd_ser;
    int fd_c;
    int N=100;
    char buf[N];
    int times=0;
    char* path="tmp/sock";

    struct sockaddr_un sa;

    unlink(path);
    sa.sun_family=AF_UNIX;
    strncpy(sa.sun_path,(char*) path, sizeof(sa.sun_path));

    if((fd_ser=socket(AF_UNIX,SOCK_STREAM,0))<0){   //socket
        perror((const char*) (size_t) errno);
        exit(EXIT_FAILURE);
    }

    if ( bind(fd_ser,(struct sockaddr *)&sa, sizeof(sa))<0){
        perror("bind\n");
    }

    listen(fd_ser,10);  //listen

    struct sockaddr_un addr;
    int addr_size= sizeof(struct sockaddr_un);

    fd_c=0;
    while( (fd_c=accept(fd_ser,(struct sockaddr*) &addr, (socklen_t*)&addr_size))<0){
        printf("waiting for connections...\n");
        sleep(2);
    }

    //initialize list of people
    char* Amy="Amy";
    char* Mark="Mark";

    addPerson(Amy);
    addPerson(Mark);

    //now concat the name strings in a buffer to be sent to the client

    char* people_list;
    unsigned int list_len;
    int value;

    struct person* ptr=(struct person*) malloc(sizeof(struct person));
    ptr=p_head;
    int offset=0;
    int i=0;

    while(ptr!=NULL){
        i++;
        people_list=realloc(people_list,i*LENGTH); //every single name has to be LENGTH characters
        strcpy(&people_list[offset],ptr->name);
        ptr=ptr->next;
        offset=offset+LENGTH;
    }
    people_list[i*LENGTH]='\0';
    list_len=(i*LENGTH)+1;

    value=write(fd_c, &(list_len), sizeof(unsigned int));
    if(value==-1){
        perror("write length");
        return -1;
    }

    int toWrite=list_len;
    char *toRead=people_list;
    while(toWrite>0){
        value=write(fd_c, toRead, toWrite);
        if(value==-1){
            perror("write data");
            return -1;
        }
        toWrite=toWrite-value;
        toRead=toRead+value;
        if(toRead<=people_list + list_len) break;
    }

    close(fd_c);
    close(fd_ser);

    return 0;
}

Client code:

#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <errno.h>
#define MAX_LENGTH 2048
#define LENGTH 32

int main(){

    int fd_cli;
    char* path="tmp/sock";
    struct sockaddr_un sa;
    sa.sun_family=AF_UNIX;
    strncpy(sa.sun_path,(char*) path, sizeof(sa.sun_path));

    if( (fd_cli = socket(AF_UNIX, SOCK_STREAM, 0))==-1){
        perror((const char*) (size_t) errno);
        return -1;
    }

    while( (connect(fd_cli,(struct sockaddr*)&sa, sizeof(struct sockaddr_un))) == -1 ) {
        if ( errno == ENOENT ) { sleep(1); }
        else perror("connect:");
        errno=0;
        sleep(1);
    }

    printf("connected to server\n");

    int value;

    unsigned int len_data;

    value=read(fd_cli,&(len_data),sizeof(unsigned int));
    if(value==-1){
        perror("read length");
        return -1;
    }
    char* buffer=malloc(len_data*sizeof(char));

    int toRead=len_data;
    char *toWrite=buffer;
    while(toRead>0){
        value=read(fd_cli, toWrite, toRead);
        if(value==-1){
            perror("read buffer");
            return -1;
        }
        toRead=toRead-value;
        toWrite=toWrite+value;
        if(toWrite<=buffer + len_data) break;
    }

    int people_n = len_data / (LENGTH+1);
    assert(people_n > 0); //proceeds only if there is at least one person registered

    printf("Registered people:\n");

    for(int i=0,p=0;i<people_n; ++i, p+=(LENGTH+1)) {
        printf(" %s\n", &buffer[p]);
    }

    close(fd_cli);

    return 0;

}

I really hope I've explained the problem clearly! Thank you for your help!

Body:
It's printing only the first user (Mark) because of this line:

int people_n = len_data / (LENGTH+1);

In this example, len_data = 65, LENGTH = 32. So when you are adding 1 to LENGTH, it will return 1 (65/33 = 1.96 => you get 1). Then it only prints the first user.

Consider using Valgrind. It will help you checking the use of the memory.


问:
How to change h1 tittle when clicked/make the section centered
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

```<code><Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
</code>```

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

答:
Is this what you are looking for?

$(document).on("click", "h1", function() {
  $(this).css("text-align", "center");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p, h1 {
  text-align: left;
}</code>```

 Title

 First section: Original version.
```

Body:
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

 Title

 First section: Original version.

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

Body:
Is this what you are looking for?

$(document).on("click", "h1", function() {
  $(this).css("text-align", "center");
})

p, h1 {
  text-align: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 title="When this is clicked, the section changes"> Title </h1>
<p id="first" title="When this is clicked, the title is centered"> First section: Original version. </p>


问:
How to load resource from a relative path in a nodejs module?
In one of my NodeJS modules I need to access a file that is part of the module in an own folder (for unit tests). It tried __dirname in the calling file with a relative path to that resource file. This works when running from within vscode, but not whe executing npm test in a terminal. In that case the constructed path is one level off. How can that be?

I have to add that I'm using typescript for coding and Mocha for unit tests.

Simply logging __filename helps a bit here. It shows that under vscode the executing file is the transpiled JS file, while under Mocha it's the typescript source file. I run:

```<code>mocha --compilers ts:ts-node/register,tsx:ts-node/register
</code>```

for my tests. Any idea how to overcome this and ensure the correct path is used (other than testing if __filename ends with .ts)?

答:
Ok, turns out to be simple. Instead of running mocha with ts code let it use the transpiled code. Only requires a transpilation run before testing:</p>

```<code>  "scripts": {
    "prepublish": "tsc",
    "install": "tsc",
    "test": "tsc && mocha out/test"
  },
</code>```

Body:
In one of my NodeJS modules I need to access a file that is part of the module in an own folder (for unit tests). It tried __dirname in the calling file with a relative path to that resource file. This works when running from within vscode, but not whe executing npm test in a terminal. In that case the constructed path is one level off. How can that be?

I have to add that I'm using typescript for coding and Mocha for unit tests.

Simply logging __filename helps a bit here. It shows that under vscode the executing file is the transpiled JS file, while under Mocha it's the typescript source file. I run:

mocha --compilers ts:ts-node/register,tsx:ts-node/register

for my tests. Any idea how to overcome this and ensure the correct path is used (other than testing if __filename ends with .ts)?

Body:
Ok, turns out to be simple. Instead of running mocha with ts code let it use the transpiled code. Only requires a transpilation run before testing:

  "scripts": {
    "prepublish": "tsc",
    "install": "tsc",
    "test": "tsc && mocha out/test"
  },


问:
gulp.series() not function when running multiple tasks
I am trying to run multiple gulp tasks one after another in synchronised fashion

but i got the following error

TypeError: gulp.series is not a function

Code

```<code>gulp.task('default',function () {
    gulp.watch('resources/assets/js/components/*.js', function() {
        gulp.series('scripts','compress');
    });
})
</code>```

答:
If you want to use gulp.series and gulp.parallel you need gulp 4.0.

To get 4.+ which is technically in beta but has been around for a long time, use gulp v4

npm i gulp@4.0.0-alpha.2
```
<p><strong>Update 13 July 2020</strong></p>
<p>Gulp v4 was released December 2018</p>
<pre class="lang-sh prettyprint-override"><code>npm i gulp@4.0.0 --save-dev
</code>```

Body:
I am trying to run multiple gulp tasks one after another in synchronised fashion

but i got the following error

TypeError: gulp.series is not a function

Code

gulp.task('default',function () {
    gulp.watch('resources/assets/js/components/*.js', function() {
        gulp.series('scripts','compress');
    });
})

Body:
If you want to use gulp.series and gulp.parallel you need gulp 4.0.

To get 4.+ which is technically in beta but has been around for a long time, use gulp v4

npm i gulp@4.0.0-alpha.2

Update 13 July 2020

Gulp v4 was released December 2018

npm i gulp@4.0.0 --save-dev