问:
Struggling to iterate over an object with an array of string
Im' trying to iterate over an object with an an array of string in it but I'm struggling to do it

Output of the var_dump of the object I'm trying to iterate:

```<code>object(fooClass)#88(2) {
    ["property1:protected"]=> string(3) "foo"
    ["property2"]=> array(2) {
                    ["foo1"]=> string(4) "foo1"
                    ["foo2"]=> string(4) "foo2"}
}
</code>```

(Edit)But when I try to use an arrayIterator to iterate over the object with this code:

```<code>$obj = new ArrayObject($value);
$it = $obj->getIterator();
echo "iterating over: " . $obj->count() . " values <br />";
while ($it->valid()){
    echo $it->key() . "=" . $it->current() . "<br />" ;
    $it->next();
}
</code>```

I have this output:

```<code>iterating over: 1 values
*property1=foo
</code>```

Edit: What I'm expecting is something like that:

```<code>iterating over 3 values
*property1=foo
*foo1=foo1
*foo2=foo2
</code>```

答:
You need a loop of loop here. Your array has sub array, so you need to loop twice. Your first loop goes through first array and then check if the value is array or not,if it is an array then you need to loop again for inner value.

Example:

```<code>$array = array('property1' => 'foo',
               'property2' => array('foo1', 'foo2')
          );

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    if(is_array($iterator->current())){
        $arrayobject_2 = new ArrayObject($iterator->current());
        $it = $arrayobject_2->getIterator();
        while($it->valid()) {
            echo $it->key() . ' => ' . $it->current() . "\n";
            $it->next();
        }
    } else
        echo $iterator->key() . ' => ' . $iterator->current() . "\n";
   $iterator->next();
}
</code>```

Working link: https://3v4l.org/1eS3Q

Body:
Im' trying to iterate over an object with an an array of string in it but I'm struggling to do it

Output of the var_dump of the object I'm trying to iterate:

object(fooClass)#88(2) {
    ["property1:protected"]=> string(3) "foo"
    ["property2"]=> array(2) {
                    ["foo1"]=> string(4) "foo1"
                    ["foo2"]=> string(4) "foo2"}
}

(Edit)But when I try to use an arrayIterator to iterate over the object with this code:

$obj = new ArrayObject($value);
$it = $obj->getIterator();
echo "iterating over: " . $obj->count() . " values
";
while ($it->valid()){
    echo $it->key() . "=" . $it->current() . "
" ;
    $it->next();
}

I have this output:

iterating over: 1 values
*property1=foo

Edit: What I'm expecting is something like that:

iterating over 3 values
*property1=foo
*foo1=foo1
*foo2=foo2

Body:
You need a loop of loop here. Your array has sub array, so you need to loop twice. Your first loop goes through first array and then check if the value is array or not,if it is an array then you need to loop again for inner value.

Example:

$array = array('property1' => 'foo',
               'property2' => array('foo1', 'foo2')
          );

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    if(is_array($iterator->current())){
        $arrayobject_2 = new ArrayObject($iterator->current());
        $it = $arrayobject_2->getIterator();
        while($it->valid()) {
            echo $it->key() . ' => ' . $it->current() . "\n";
            $it->next();
        }
    } else
        echo $iterator->key() . ' => ' . $iterator->current() . "\n";
   $iterator->next();
}

Working link: https://3v4l.org/1eS3Q


来源: stackexchange

问:
How to get complete memory usage statistics
My spark application is running on remote machine in our internal lab. To analyse the memory consumption of remote application, attached the remote application pid to JProfiler by using the 'attach mode' (with help of jpenable) from my local machine.

After attaching the remote application to JProfiler in local machine, the JProfiler showing only 5% of memory consumption of the remote machine but when we ran the 'top' command on remote Centos machine, the 'top' command showing the 72% of memory consumption. And I am unable to find the whole 72% consumption with JProfiler application.

Please help me to get the whole memory consumption (i.e., 72% of memory usage) statistics by using the JProfiler application.

答:
top shows memory reserved by the JVM, not the actually used heap, so you cannot compare the two values.

In addition, the JVM uses native memory that does not show up in the heap. A Java profiler cannot analyze that memory.

ContentLicense: CC BY-SA 3.0


问:
React Native Fetch does not render response until after clicking screen
So I've been building an app that uses the Fetch API to make a request. Unfortunately, I think the code shown in the Facebook docs are (may be?) incorrect.

Problem

When starting the app, Fetch makes a call to a URL to pull JSON data.

```<code>componentDidMount(){
 return fetch(REQUEST_URL)
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({
      isLoading: false,
      data: JSON.stringify(responseJson)
    })
  })
  .catch((error) => {
    console.error(error);
  });
}
</code>```

This is similar to the code that Facebook docs give as an example.

The problem is that when I start the app, the data doesn't render in the render function.

```<code>render() {

 if (this.state.isLoading) {
   return (
    <View style={{flex: 1, paddingTop: 20}}>
      <ActivityIndicator />
    </View>
  );
 }

var data = this.state.data;
return this.renderData(data);
}
</code>```

At least, it doesn't render until after I click/touch the screen. Once I touch the screen, the data renders. Otherwise, it just stays in a perpetual "loading" state.

Solution?

I remembered that sometime in the past, I had to bind event handlers to their respective controls (this.handleClick = this.handleClick.bind(this), for example)

And that got me thinking: Where is this in the promise request? Where does this point to?

```<code>componentDidMount(){
 return fetch(REQUEST_URL)
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({ <--- **Where are you going?**
      isLoading: false,
      data: JSON.stringify(responseJson)
    })
  })
</code>```

I console.logged "this" within the responseJson promise, and it does point to the component, but I'm not convinced. With it being buried inside of the promise, I don't think the this.setState function is actually able to set the component's State.

So I made a variable before the fetch request.

```<code>const that = this;
return fetch(REQUEST_URL)

.then((response) => response.json())
.then((responseJson) => {

  that.setState({

    isLoading: false,
    data: JSON.stringify(responseJson)
  })
})
</code>```

Now I'm not a software guru. I've been teaching myself this stuff for the last couple of years, so my logic is off half the time.

So if my reasoning is correct or incorrect, please let me know! What I do know is that this is working for me; once the data is fetched, it automatically sets the state and reloads, showing me the JSON data when rendered.

Any thoughts? Am I completely off here? Am I missing anything?

答:
(Posted on behalf of the OP).

Apparently it was due to running the app in debug mode. Running the app with this.setState works just fine when not in debug mode.

Body:
So I've been building an app that uses the Fetch API to make a request. Unfortunately, I think the code shown in the Facebook docs are (may be?) incorrect.

Problem

When starting the app, Fetch makes a call to a URL to pull JSON data.

componentDidMount(){
 return fetch(REQUEST_URL)
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({
      isLoading: false,
      data: JSON.stringify(responseJson)
    })
  })
  .catch((error) => {
    console.error(error);
  });
}

This is similar to the code that Facebook docs give as an example.

The problem is that when I start the app, the data doesn't render in the render function.

render() {

 if (this.state.isLoading) {
   return (
    <View style={{flex: 1, paddingTop: 20}}>
      <ActivityIndicator />
    </View>
  );
 }

var data = this.state.data;
return this.renderData(data);
}

At least, it doesn't render until after I click/touch the screen. Once I touch the screen, the data renders. Otherwise, it just stays in a perpetual "loading" state.

Solution?

I remembered that sometime in the past, I had to bind event handlers to their respective controls (this.handleClick = this.handleClick.bind(this), for example)

And that got me thinking: Where is this in the promise request? Where does this point to?

componentDidMount(){
 return fetch(REQUEST_URL)
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({ <--- **Where are you going?**
      isLoading: false,
      data: JSON.stringify(responseJson)
    })
  })

I console.logged "this" within the responseJson promise, and it does point to the component, but I'm not convinced. With it being buried inside of the promise, I don't think the this.setState function is actually able to set the component's State.

So I made a variable before the fetch request.

const that = this;
return fetch(REQUEST_URL)

.then((response) => response.json())
.then((responseJson) => {

  that.setState({

    isLoading: false,
    data: JSON.stringify(responseJson)
  })
})

Now I'm not a software guru. I've been teaching myself this stuff for the last couple of years, so my logic is off half the time.

So if my reasoning is correct or incorrect, please let me know! What I do know is that this is working for me; once the data is fetched, it automatically sets the state and reloads, showing me the JSON data when rendered.

Any thoughts? Am I completely off here? Am I missing anything?


问:
SQL group by with like condition
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

```<code>reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------
</code>```

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

```<code>reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------
</code>```

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

答:
When you group by one column, you will turn multiple rows into one, other columns in select has to be aggregate functions or subqueries. Which function to use depend on your need. Using MIN() like in example below will give you first result alphabetically if used with string column

```<code>SELECT clientID
    , MIN(colA) AS colA
    , MIN(colB) AS colB
    , MIN(colC) AS colC
FROM tableA
WHERE colB LIKE '%test%'
GROUP BY clientID
</code>```

Edit:
here is another solution, not using GROUP BY, but with Common Table Expression using ROW_NUMBER()

```<code>WITH CTE_Source AS
(
  SELECT *
  FROM TableA
  WHERE colB LIKE '%test%'
)
, CTE_Filter AS
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY reference) RN
   FROM CTE_Source
)
SELECT *
FROM CTE_Filter
WHERE RN = 1
</code>```

Title: SQL group by with like condition

Body:
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

Body:
When you group by one column, you will turn multiple rows into one, other columns in select has to be aggregate functions or subqueries. Which function to use depend on your need. Using MIN() like in example below will give you first result alphabetically if used with string column

SELECT clientID
    , MIN(colA) AS colA
    , MIN(colB) AS colB
    , MIN(colC) AS colC
FROM tableA
WHERE colB LIKE '%test%'
GROUP BY clientID

Edit:
here is another solution, not using GROUP BY, but with Common Table Expression using ROW_NUMBER()

WITH CTE_Source AS
(
  SELECT *
  FROM TableA
  WHERE colB LIKE '%test%'
)
, CTE_Filter AS
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY reference) RN
   FROM CTE_Source
)
SELECT *
FROM CTE_Filter
WHERE RN = 1


问:
string.replace() cannot replace char " \" "
I have below json from request post in my MVC model

```<code>"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}
</code>```

I don't know why the json object filled with (\") instead only (") but when I check the value with allert in html, it not content (\")

So I want to replace (/") with (")

```<code>[Authorization()]
[HttpPost()]
public ActionResult Update(VModel vModel)
{
   string JsonArray = (vModel.JsonVar).Replace('\"',' ');
}
</code>```

but result still

```<code>"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}
</code>```

how can?

答:
```<code>class model
{
    public static string jsonVar { get; set; }
}

   public static string ReplaceStringChars(string str)
    {
        string newStr = string.Empty;

        newStr = str.Replace('\"' , ' ');

        return newStr;
    }

    static void Main(string[] args)
    {
        model.jsonVar = "{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}";
        ReplaceStringChars(model.jsonVar);
    }
</code>```

Result:

Body:
I have below json from request post in my MVC model

"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}

I don't know why the json object filled with (\") instead only (") but when I check the value with allert in html, it not content (\")

So I want to replace (/") with (")

[Authorization()]
[HttpPost()]
public ActionResult Update(VModel vModel)
{
   string JsonArray = (vModel.JsonVar).Replace('\"',' ');
}

but result still

"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}

how can?

Body:
class model
{
    public static string jsonVar { get; set; }
}

   public static string ReplaceStringChars(string str)
    {
        string newStr = string.Empty;

        newStr = str.Replace('\"' , ' ');

        return newStr;
    }

    static void Main(string[] args)
    {
        model.jsonVar = "{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}";
        ReplaceStringChars(model.jsonVar);
    }

Result:


问:
MSSQL CLR Trigger problems
So normally I don't get stuck on SQL and I don't give up with ample amounts of my own research. but I have exhausted all thoughts I can and all possibilities that I can think of.

Situation: programmer built a CLR trigger for me. ( I am SQL Guy, not C# guy). This trigger uses filesystem so a couple things needed to be altered since we didn't bother signing it for now.

So Ran the following on the DB before install

```<code>ALTER DATABASE [DBName] SET TRUSTWORTHY ON;
USE [DBName]
GO

EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO
EXEC sp_changedbowner 'sa'
GO
</code>```

After this. I executed a UI that connects to the Database and installs the trigger. This was working no problem until recently. Then After a couple uninstalls and reinstalls it no longer works.

Now the current code works on his machine in his environment. Install / UnInstall. And if I Turn trustworthy back to off

```<code>ALTER DATABASE [DBName] SET TRUSTWORTHY OFF;
</code>```

It tries to load the assembly and fails. Turn it back on. It supposedly loads the assembly. But the trigger doesn't do anything. For reference. We are both using the same database same user ids (for now sa for testing).

So I guess my question. How do I know it's truely loading the assembly? Why isn't the assembly throwing errors or doing standard things it's supposed to do like creating log files.

For example one of this first tasks to do is to create a log file. It reads data from an XML file that is stored on the server. I put in the log file location abc. So it should error and be like I can't find this location or something. But nothing. So to me, it seems like the assembly is not being loaded at all. Any way to verify the assembly is truly being loaded and executed?

Anything anyone can tell me how to see any errors that might not be showing in output or debug?

答:
So This is completely an error in the C# code. My programmer finally found the error. Nothing was wrong with the SQL Side. I was going Mad. Thanks for anyone who read this. I apologize.

He was reading certain directory locations from wrong locations. and if if directories did not exist he was exiting code. he feels bad I feel relieved. Thanks sorry for bothering.

Title: MSSQL CLR Trigger problems

Body:
So normally I don't get stuck on SQL and I don't give up with ample amounts of my own research. but I have exhausted all thoughts I can and all possibilities that I can think of.

Situation: programmer built a CLR trigger for me. ( I am SQL Guy, not C# guy). This trigger uses filesystem so a couple things needed to be altered since we didn't bother signing it for now.

So Ran the following on the DB before install

ALTER DATABASE [DBName] SET TRUSTWORTHY ON;
USE [DBName]
GO

EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO
EXEC sp_changedbowner 'sa'
GO

After this. I executed a UI that connects to the Database and installs the trigger. This was working no problem until recently. Then After a couple uninstalls and reinstalls it no longer works.

Now the current code works on his machine in his environment. Install / UnInstall. And if I Turn trustworthy back to off

ALTER DATABASE [DBName] SET TRUSTWORTHY OFF;

It tries to load the assembly and fails. Turn it back on. It supposedly loads the assembly. But the trigger doesn't do anything. For reference. We are both using the same database same user ids (for now sa for testing).

So I guess my question. How do I know it's truely loading the assembly? Why isn't the assembly throwing errors or doing standard things it's supposed to do like creating log files.

For example one of this first tasks to do is to create a log file. It reads data from an XML file that is stored on the server. I put in the log file location abc. So it should error and be like I can't find this location or something. But nothing. So to me, it seems like the assembly is not being loaded at all. Any way to verify the assembly is truly being loaded and executed?

Anything anyone can tell me how to see any errors that might not be showing in output or debug?


问:
WCF IPv6 Endpoints
I'm investigating the possibility of using the Peer 2 Peer along with WCF in a Windows app for an EPoS terminal.

The app will sit on a number of PC's in a local network; there will only ever be one instance of the app per PC.

My current thinking is that my app starts up and joins the peer mesh, on joining the mesh it periodically shouts out a 'heartbeat' message which contains its terminal id and IPv6 address.

Any other terminals joining the mesh receive these heartbeats and maintain their own list of terminals in the network.

Actions within the app will require accessing a specific terminal on the network.  The app therefore resolves the terminal id to an ip address and can generate a Uri to access the service via net.tcp

I have published the service endpoint using the link local address

```<code>printingHostRemote = New ServiceHost(printSpooler, New Uri("net.tcp://" & myNetworkAddress & "/" & ServiceNames.PrintingService))
printingHostRemote.AddServiceEndpoint(GetType(IPrintingService), tcpPipeBinding, "net.tcp://" & myNetworkAddress & "/" & ServiceNames.PrintingService)
</code>```

The string to setup the endpoint would be, for example:

"net.tcp://[fe80::250:56ff:fec0:8%4]:5555/GSS-POS/PrintingService"

However, when I try an access this service I get an error saying that the host is unreachable.

TCP error code 10065: A socket operation was attempted to an unreachable host fe80::290:5ff:fe01:6303%4:5555

I realise this is down to my limited knowledge of IPv6 addressing.  What address should I be using for my endpoint (I'm using the link local IPv6 address) ?  Or is my overall concept flawed?

TIA,

Simon

答: I'm actually currently running a client/server(network layer)/database setup I wrote as a business solution and my business partner's on-site internet (Comcast) has him set up in such a way that IPV6 is the only way he can access things inside his lan, and before, only IPV4 outside. I managed to map it to the correct machine address and got IPV6 working on both sides, but what you are describing...is what I was experiencing with a raw IPV6 address. I created a AAAA record for the domain name I use and port forwarded it to the correct machine on the router...if you do that, once it resolves, it will work, but you can't use the hex, you have to use the domain name. Or at least that's how it worked for me. I'd be curious to know why it won't take the hex address.</p>

ContentLicense: CC BY-SA 2.5

Title: WCF IPv6 Endpoints

Body:
I'm investigating the possibility of using the Peer 2 Peer along with WCF in a Windows app for an EPoS terminal.

The app will sit on a number of PC's in a local network; there will only ever be one instance of the app per PC.

My current thinking is that my app starts up and joins the peer mesh, on joining the mesh it periodically shouts out a 'heartbeat' message which contains its terminal id and IPv6 address.

Any other terminals joining the mesh receive these heartbeats and maintain their own list of terminals in the network.

Actions within the app will require accessing a specific terminal on the network.  The app therefore resolves the terminal id to an ip address and can generate a Uri to access the service via net.tcp

I have published the service endpoint using the link local address

printingHostRemote = New ServiceHost(printSpooler, New Uri("net.tcp://" & myNetworkAddress & "/" & ServiceNames.PrintingService))
printingHostRemote.AddServiceEndpoint(GetType(IPrintingService), tcpPipeBinding, "net.tcp://" & myNetworkAddress & "/" & ServiceNames.PrintingService)

The string to setup the endpoint would be, for example:

"net.tcp://[fe80::250:56ff:fec0:8%4]:5555/GSS-POS/PrintingService"

However, when I try an access this service I get an error saying that the host is unreachable.

TCP error code 10065: A socket operation was attempted to an unreachable host fe80::290:5ff:fe01:6303%4:5555

I realise this is down to my limited knowledge of IPv6 addressing.  What address should I be using for my endpoint (I'm using the link local IPv6 address) ?  Or is my overall concept flawed?

TIA,

Simon


问:
how do i send all item id at once through url success.php?id=
As i add some items in the cart i cant change the status in the database from "ADDED TO CART " to "CONFIRMED"

<!DOCTYPE html>

<?php
require 'includes/common.php';

if (!isset($_SESSION['email']))
{
    header('location: index.php');
}
?>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

    <link href="style.css" rel="stylesheet" type="text/css"/>
        <title>Lifestyle Store | Products</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <?php
        include 'includes/header.php';
        ?>
        <?php
        $user_id=$_SESSION['id'];
        //changed from above user_id to $_getc ['user_id']
        $items_query="SELECT items.id,items.name,items.price from items INNER JOIN user_items INNER JOIN users ON items.id=user_items.item_id AND user_items.user_id=users.id WHERE user_items.user_id= $user_id AND user_items.status='Added To Cart'";

        // chaged from select * from user_items inner join items on user_items.item_id=items.id where items.id=$user_id";

        $items_query_result= mysqli_query($con, $items_query) or die(mysqli_error($con));

        ?>

       <?php  if (mysqli_num_rows($items_query_result)==0){ ?>
       <?php echo 'Add something in cart';  }  else  { ?>

                                Item Number
                                Item Name
                                Price
                                Total

                            <?php

                                $total=0;
                                    while ($row= mysqli_fetch_array($items_query_result)) {
                                        $total+=$row['price'];

                                                                                ?>

                                    <?php echo $row['id']  ?> 	   <?php echo $row['name'];   ?> " class='remove_item_link ' style="color:#e53939">Remove  	    Rs. <?php   echo $row['price']; } ?>  	 Rs. <?php echo $total;?>  Confirm Order

                             <?php }?>

             <?php
        include 'includes/footer.php';
        ?>

```

this is the code for a shopping cart

user add some this in the cart

**then when the user goes to the cart the cart displays all the items with their ids, name and the price **

and finally the total price

**i have defined a while loop to sum up the price and to display the id name etc **

now i want to send the item id to the success.php to change the status in the database from "Added To Cart " to "Confirmed"

答:
```<code><tbody>
<?php
    $total=0;
    while ($row= mysqli_fetch_array($items_query_result)) {
        $total+=$row['price'];
        echo "<tr>";
        echo "<td>";
            echo $row['id'];
        echo "</td>";
        echo "<td>";
            echo $row['name'];
        echo '<a href="cart-remove.php?id='.$row['id'].'" class='remove_item_link ' style="color:#e53939">Remove </a>';
        echo "</td>";
        echo "<td>";
            echo "Rs ".$row['price'];
        echo "</td>";
        echo "<td>";
            echo "Rs ".$total;
            echo '<a href="success.php?id=" class='btn btn-primary'>Confirm Order</a>';
        echo "</td>";
        echo"</tr>";
     } ?>
</tbody>
</code>```

try this it will work, I have corrected your iteration closing end. go through it.

Body:
As i add some items in the cart i cant change the status in the database from "ADDED TO CART " to "CONFIRMED"

<!DOCTYPE html>

<?php
require 'includes/common.php';

if (!isset($_SESSION['email']))
{
    header('location: index.php');
}
?>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

    <link href="style.css" rel="stylesheet" type="text/css"/>
        <title>Lifestyle Store | Products</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <?php
        include 'includes/header.php';
        ?>
        <?php
        $user_id=$_SESSION['id'];
        //changed from above user_id to $_getc ['user_id']
        $items_query="SELECT items.id,items.name,items.price from items INNER JOIN user_items INNER JOIN users ON items.id=user_items.item_id AND user_items.user_id=users.id WHERE user_items.user_id= $user_id AND user_items.status='Added To Cart'";

        // chaged from select * from user_items inner join items on user_items.item_id=items.id where items.id=$user_id";

        $items_query_result= mysqli_query($con, $items_query) or die(mysqli_error($con));

        ?>

       <?php  if (mysqli_num_rows($items_query_result)==0){ ?>
       <?php echo 'Add something in cart';  }  else  { ?>

                                Item Number
                                Item Name
                                Price
                                Total

                            <?php

                                $total=0;
                                    while ($row= mysqli_fetch_array($items_query_result)) {
                                        $total+=$row['price'];

                                                                                ?>

                                    <?php echo $row['id']  ?> 	   <?php echo $row['name'];   ?> <a href="cart-remove.php?id=<?php echo $row['id']; ?>" class='remove_item_link ' style="color:#e53939">Remove  	    Rs. <?php   echo $row['price']; } ?>  	 Rs. <?php echo $total;?>  Confirm Order

                             <?php }?>

             <?php
        include 'includes/footer.php';
        ?>

this is the code for a shopping cart

user add some this in the cart

**then when the user goes to the cart the cart displays all the items with their ids, name and the price **

and finally the total price

**i have defined a while loop to sum up the price and to display the id name etc **

now i want to send the item id to the success.php to change the status in the database from "Added To Cart " to "Confirmed"

Body:
<tbody>
<?php
    $total=0;
    while ($row= mysqli_fetch_array($items_query_result)) {
        $total+=$row['price'];
        echo "<tr>";
        echo "<td>";
            echo $row['id'];
        echo "</td>";
        echo "<td>";
            echo $row['name'];
        echo '<a href="cart-remove.php?id='.$row['id'].'" class='remove_item_link ' style="color:#e53939">Remove </a>';
        echo "</td>";
        echo "<td>";
            echo "Rs ".$row['price'];
        echo "</td>";
        echo "<td>";
            echo "Rs ".$total;
            echo '<a href="success.php?id=" class='btn btn-primary'>Confirm Order</a>';
        echo "</td>";
        echo"</tr>";
     } ?>
</tbody>

try this it will work, I have corrected your iteration closing end. go through it.


问:
Passing html into Vue component
At the moment I pass some parameters into a vue component

```<code> <Slider
      :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']"
      :html="['<div>hello</div>', '<div>goodbye</div>']"
    </Slider>
</code>```

The slider is either an 'html' slider or one with images.

This works fine although the html I pass in is going to get a lot more complex, maybe 30 lines and this will be harder to read and manage as params.

Can I pass in an external reference and pull that into the component?

```<code><div v-for="content in html">
    <div class="work-slide">{{ content }}</div>
</div>
</code>```

As you can see the loop in the component is a very simple v-for.

答:
Don't pass HTML using attributes but using Slots:

Suppose we have a component called my-component with the following template:

```<code><div>
  <h2>I'm the child title</h2>
  <slot>
    This will only be displayed if there is no content
    to be distributed.
  </slot>
</div>
</code>```

And a parent that uses the component:

```<code><div>
  <h1>I'm the parent title</h1>
  <my-component>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </my-component>
</div>
</code>```

The rendered result will be:

```<code><div>
  <h1>I'm the parent title</h1>
  <div>
    <h2>I'm the child title</h2>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </div>
</code>```

```<code></div>
</code>```

You can also use Named Slots if you want to pass more than one field containing HTML.

Title: Passing html into Vue component

Body:
At the moment I pass some parameters into a vue component

 <Slider
      :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']"
      :html="['
hello
', '
goodbye
']"
    </Slider>

The slider is either an 'html' slider or one with images.

This works fine although the html I pass in is going to get a lot more complex, maybe 30 lines and this will be harder to read and manage as params.

Can I pass in an external reference and pull that into the component?

{{ content }}

As you can see the loop in the component is a very simple v-for.

Body:
Don't pass HTML using attributes but using Slots:

Suppose we have a component called my-component with the following template:

<div>
  <h2>I'm the child title</h2>
  <slot>
    This will only be displayed if there is no content
    to be distributed.
  </slot>
</div>

And a parent that uses the component:

<div>
  <h1>I'm the parent title</h1>
  <my-component>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </my-component>
</div>

The rendered result will be:

<div>
  <h1>I'm the parent title</h1>
  <div>
    <h2>I'm the child title</h2>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </div>

</div>

You can also use Named Slots if you want to pass more than one field containing HTML.

ContentLicense: CC BY-SA 4.0


问:
Variable Bin Width in Python
so I need just a little bit of help with something I need to do. So I wrote some code which imports excel files form a directory and bins the files into bins of 5, [0,5), [5,10), etc. Nonetheless, everytime there is a number inside the bins the count goes up. Everything works great and it does what I need it to do, yet I was wondering if there was some kind of way that I could vary this bin width as I please, yet I'm having a bit of difficulty doing so. The code is: </p>

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Data/'

for file in os.listdir(datadir):
   if file.endswith('.xlsx'):
   data = pd.read_excel(os.path.join(datadir, file))
   counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+5), 5))
   df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
   plt.title('Data')
   plt.xlabel('Neuron')
   plt.ylabel('# of Spikes')
   plt.show()

   outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
   writer = pd.ExcelWriter(outfile)
   df.to_excel(writer)
   writer.save()
</code>```

<p>So this creates a loop over all the files in the directory and bins them accordingly and exports them as individual, excel files with the results. I am actually pretty new to coding and would sure appreciate some help, any help would actually be greatly appreciated. Anyway, I was thinking of making the bin be a command line parameter which I could use to run the code standalone with a specific value of parameter or some other code could call it with some value based on its results. What would be the best way to go about this, please any help would be greatly appreciated. </p>

答:
The range function takes a step argument (see doc.). The step size will then correspond to the bin width.

Note: if you do not want to plot, but just compute the histogram you also might use numpy.histogramm.

Alternatively, you can define the bin width with the parameters bins (integer number instead of a sequence, n) and range (tuple indicating the bounds, x_min, x_max).

The bin witdth = (x_max - x_min) / n

If you want to fix the bin width you can use a bit of algebra and compute the number of bins given the interval of you input data and the width.
(beware of variations induced by rounding and trunkating with integers)

Title: Variable Bin Width in Python

Body:
so I need just a little bit of help with something I need to do. So I wrote some code which imports excel files form a directory and bins the files into bins of 5, [0,5), [5,10), etc. Nonetheless, everytime there is a number inside the bins the count goes up. Everything works great and it does what I need it to do, yet I was wondering if there was some kind of way that I could vary this bin width as I please, yet I'm having a bit of difficulty doing so. The code is:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Data/'

for file in os.listdir(datadir):
   if file.endswith('.xlsx'):
   data = pd.read_excel(os.path.join(datadir, file))
   counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+5), 5))
   df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
   plt.title('Data')
   plt.xlabel('Neuron')
   plt.ylabel('# of Spikes')
   plt.show()

   outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
   writer = pd.ExcelWriter(outfile)
   df.to_excel(writer)
   writer.save()

So this creates a loop over all the files in the directory and bins them accordingly and exports them as individual, excel files with the results. I am actually pretty new to coding and would sure appreciate some help, any help would actually be greatly appreciated. Anyway, I was thinking of making the bin be a command line parameter which I could use to run the code standalone with a specific value of parameter or some other code could call it with some value based on its results. What would be the best way to go about this, please any help would be greatly appreciated.


问:
using css modules, how can I import classes from a file
I am using css modules for my project, and I have a file positioning.css which has some useful classes that I want to import. e.g. .right, .left

What is the best approach for this using CSS Modules?

At the moment I can see 2 options, but they are not all that great:

composition in the component's style

```<code>.right {
    composes: right from '../styles/positioning.css';
}
</code>```

or

multiple css module imports in the component

```<code>import positioning from '../styles/positioning.css'
import styles from './myComponent.css';
Object.assign(styles, positioning)

class Menu extends Component {

  render() {

    return (
      <div styleName='menu'>
        <div styleName='left'>this is left</div>
        <div styleName='right'>this is right</div>
      </div>
    );
  }
};

export default CSSModules(Menu, styles);
</code>```

答:
I find this one line very helpful with importing:</p>

```<code>@import 'file.css';
</code>```

Body:
I am using css modules for my project, and I have a file positioning.css which has some useful classes that I want to import. e.g. .right, .left

What is the best approach for this using CSS Modules?

At the moment I can see 2 options, but they are not all that great:

composition in the component's style

.right {
    composes: right from '../styles/positioning.css';
}

or

multiple css module imports in the component

import positioning from '../styles/positioning.css'
import styles from './myComponent.css';
Object.assign(styles, positioning)

class Menu extends Component {

  render() {

    return (

this is left

this is right

    );
  }
};

export default CSSModules(Menu, styles);

Body:
I find this one line very helpful with importing:

@import 'file.css';


问:
How to change color in ExpandableRecyclerView
I am using this library but I can't get to a way to change the group background color from white.

EDIT: the xml files as requested in comments:

content_main.xml

the content_main file which include the expandable recyclerview

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</LinearLayout>
</code>```

activity_main.xml

the main activity

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="#64dd17"
    tools:context="ayalma.ir.sample.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>
</code>```

row_drawer.xml

the custom row layout

```<code> <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#ffb74d">
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/carbon_toolbarHeight"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/carbon_padding"
        android:paddingRight="@dimen/carbon_padding" />

    </LinearLayout>
</code>```

答:
Add this line to your

```<code><ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
tools:listitem="@layout/exr_group"
</code>```

And change backgound color

Body:
I am using this library but I can't get to a way to change the group background color from white.

EDIT: the xml files as requested in comments:

content_main.xml

the content_main file which include the expandable recyclerview

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</LinearLayout>

activity_main.xml

the main activity

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="#64dd17"
    tools:context="ayalma.ir.sample.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>

row_drawer.xml

the custom row layout

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#ffb74d">
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/carbon_toolbarHeight"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/carbon_padding"
        android:paddingRight="@dimen/carbon_padding" />

    </LinearLayout>

Body:
Add this line to your

<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
tools:listitem="@layout/exr_group"

And change backgound color


问:
Why is my CalendarExtender getting overlapped when rendered?
I'm working on a .NET web application and I'm using a CalendarExtender control within it to have the user specify a date. For some reason, when I click the icon to display the calendar, the background seems to be transparent.

I'm using the extender on other pages and do not run into this issue.

I'm not sure if it is worth mentioning, but the calendar is nested within a panel that has a rounded corner extender attached to it, as well as the panel below it (where the "From" is overlapping).

Within that panel, I do have a div layout setup to create two columns.

EDIT: The other thing to note here is that the section that has the name and "placeholders" for nickname are all ASP.NET label controls, if that matters.

答:
If those answers does not work properly it might be a problem with hiding overflow. This can be solved using following css:</p>

```<code>.ajax__scroll_none {
    overflow: visible !important;
    z-index: 10000 !important;
}
</code>```

OwnerDisplayName: Dillie-O

LastEditorDisplayName: Dillie-O

Body:
If those answers does not work properly it might be a problem with hiding overflow. This can be solved using following css:

.ajax__scroll_none {
    overflow: visible !important;
    z-index: 10000 !important;
}


问:
Some Quotes and apostrophes don't parse correctly
Okay, first, I'm a noob at android programming.  I have taken some Java, but I'm still learning (aren't we all).
I'm trying to take the source code form here and have it read an RSS feed correctly.  Currently I have 2 problems.  I'll just state the first one and then post another post for the second.

One the RSS feed is displayed on my device, it doesn't include all of the details (description).  When I load the feed through my browser I notice that some of the quotation marks and apostrophes are turned into " and '.  For some reason this stops the parser from correctly parsing it.  Any help would be greatly appreciated.

答:
I found out the cause of the problem.  I had to setup a string buffer in the charcters method.

```<code>public void characters(char ch[] , int start, int length)
{
    if (buffering)
            buf.append(ch, start, length);

}
</code>```

Once I did that, i just assigned the stringbuffer to a string in the "endelement" method when I stored my data.

```<code>public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{

    String content = buf.toString();
    Log.i("RSSReader  ",currentstate +"  " + content + "]");
    switch (currentstate)
    {
        case RSS_TITLE:
                _item.setTitle(content);
                buffering = false;
            currentstate = 0;
            break;
        case RSS_LINK:
                _item.setLink(content);
                buffering = false;
            currentstate = 0;
            break;
        case RSS_DESCRIPTION:
                _item.setDescription(content);
                buffering = false;
            currentstate = 0;
            break;

    }
</code>```

After that everything worked just fine.

Body:
I found out the cause of the problem.  I had to setup a string buffer in the charcters method.

public void characters(char ch[] , int start, int length)
{
    if (buffering)
            buf.append(ch, start, length);

}

Once I did that, i just assigned the stringbuffer to a string in the "endelement" method when I stored my data.

public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{

    String content = buf.toString();
    Log.i("RSSReader  ",currentstate +"  " + content + "]");
    switch (currentstate)
    {
        case RSS_TITLE:
                _item.setTitle(content);
                buffering = false;
            currentstate = 0;
            break;
        case RSS_LINK:
                _item.setLink(content);
                buffering = false;
            currentstate = 0;
            break;
        case RSS_DESCRIPTION:
                _item.setDescription(content);
                buffering = false;
            currentstate = 0;
            break;

    }

After that everything worked just fine.


问:
Encountering parse base error (SAS)
I've been stuck on this the whole day and I hope to get some help from the community. I am still learning SAS so this might be a beginner's question. Please bear with me.

Here I have a code that I am currently working on. I'm running this using eclipse dataserver plugins:

```<code>libname myInput 'D:\_TD5910372542151565380';

proc datasets lib=myInput;
run;

quit;

ods csv files="D:/_TD5910372542151565380/myTest.csv";

proc print data=myInput.inputContainer;
     title "Random";
run;

ods csv close;
</code>```

I am trying to print the content in the inputContainer into a CSV file. Here is the console log that I am getting:

```<code>[MPRINT] Parsing Base DataServer
/* 0001 */  libname myInput 'D:\_TD5910372542151565380';

NOTE: Library myinput assigned successfully
[MPRINT] Parsing Base DataServer
/* 0002 */  proc datasets lib=myInput;
/* 0003 */  run;

-------------------- 10:34: PROC DATASETS --------------------
NOTE: Time taken: 000:00:00.000
[MPRINT] Parsing Base DataServer
/* 0002 */  quit;

[MPRINT] Parsing Base DataServer
/* 0003 */  ods csv files="D:/_TD5910372542151565380/myTest.csv";
/* 0004 */  proc print data=myInput.inputContainer;
/* 0005 */  title "Random";
/* 0006 */  run;

ERROR: Parsing exception - aborting
ERROR: DS-00274 : Could not parse base DataServer code: Encountered " <ALPHANUM> "ods "" at line 3, column 1.
Was expecting one of:
    <EOF>
    ";" ...
    "*" ...
    "data" ...
    "proc" ...
    (and 9 more)
</code>```

I checked the lines a lot of time but I am still not sure if I am missing something. I also browsed a lot of websites to find what can fix this error. Hopefully a second pair of eye can point out what exactly has gone wrong.

Thank you in advance. XD

答:
Haha... I found the solution myself.The way I solved this is as following:

```<code>libname myInput 'D:\_TD5910372542151565380';
proc datasets lib=myInput;
run;

data something;
    set myInput.inputContainer;
run;

proc export data=something
    outfile="D:/Example.csv"
    dbms=csv
    replace;
run;
</code>```

It seems that you have to set the data first to take the obs file. Then, there are no separated semi colons until replace; Which I did wrong in the above. Hope this help anyone out there.

Title: Encountering parse base error (SAS)

Body:
I've been stuck on this the whole day and I hope to get some help from the community. I am still learning SAS so this might be a beginner's question. Please bear with me.

Here I have a code that I am currently working on. I'm running this using eclipse dataserver plugins:

libname myInput 'D:\_TD5910372542151565380';

proc datasets lib=myInput;
run;

quit;

ods csv files="D:/_TD5910372542151565380/myTest.csv";

proc print data=myInput.inputContainer;
     title "Random";
run;

ods csv close;

I am trying to print the content in the inputContainer into a CSV file. Here is the console log that I am getting:

[MPRINT] Parsing Base DataServer
/* 0001 */  libname myInput 'D:\_TD5910372542151565380';

NOTE: Library myinput assigned successfully
[MPRINT] Parsing Base DataServer
/* 0002 */  proc datasets lib=myInput;
/* 0003 */  run;

-------------------- 10:34: PROC DATASETS --------------------
NOTE: Time taken: 000:00:00.000
[MPRINT] Parsing Base DataServer
/* 0002 */  quit;

[MPRINT] Parsing Base DataServer
/* 0003 */  ods csv files="D:/_TD5910372542151565380/myTest.csv";
/* 0004 */  proc print data=myInput.inputContainer;
/* 0005 */  title "Random";
/* 0006 */  run;

ERROR: Parsing exception - aborting
ERROR: DS-00274 : Could not parse base DataServer code: Encountered " <ALPHANUM> "ods "" at line 3, column 1.
Was expecting one of:
    <EOF>
    ";" ...
    "*" ...
    "data" ...
    "proc" ...
    (and 9 more)

I checked the lines a lot of time but I am still not sure if I am missing something. I also browsed a lot of websites to find what can fix this error. Hopefully a second pair of eye can point out what exactly has gone wrong.

Thank you in advance. XD

Body:
Haha... I found the solution myself.The way I solved this is as following:

libname myInput 'D:\_TD5910372542151565380';
proc datasets lib=myInput;
run;

data something;
    set myInput.inputContainer;
run;

proc export data=something
    outfile="D:/Example.csv"
    dbms=csv
    replace;
run;

It seems that you have to set the data first to take the obs file. Then, there are no separated semi colons until replace; Which I did wrong in the above. Hope this help anyone out there.


问:
ng-repeat is Working perfectly with static json But fires exception with dynamic json data
I have a ng-repeat put on a list to display in table.

the script html code is like this :

```<code>`<tr ng-repeat="user in users track by $index" ng-class="{'selected':$index == selectedRow}">
                    <td>
                        {{user.FirstName}}
                    </td>
                    <td>
                        {{user.LastName}}
                    </td>
                    <td>
                        {{user.EmailId}}
                    </td>
                    <td>
                        {{user.ContactNumber}}
                    </td>
                    <td>
                        <button type="button" class="btn btn-warning">
                            <span class="glyphicon glyphicon-pencil"></span>
                        </button>
                        <button type="button" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                    </td>
                </tr>`
</code>```

and in angular script the routing is defined as bellow:

```<code>var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);
</code>```

This part is working absolutely fine.

but when i replace the static json data ie;

```<code> var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
</code>```

with

```<code>$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})
</code>```

it will through this exception :

```<code>`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`
</code>```

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

答: Try JSON.parse instead of JSON.stringify, you're trying to loop over a string (JSON.stringify returns a string). Anyway, if the data is sent back in JSON format just assign the data.

Body:
I have a ng-repeat put on a list to display in table.

the script html code is like this :

`

                        {{user.FirstName}}

                        {{user.LastName}}

                        {{user.EmailId}}

                        {{user.ContactNumber}}

                        <button type="button" class="btn btn-warning">

                        </button>
                        <button type="button" class="btn btn-danger">

                        </button>

`

and in angular script the routing is defined as bellow:

var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);

This part is working absolutely fine.

but when i replace the static json data ie;

 var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];

with

$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})

it will through this exception :

`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?


问:
OOP - manage a unique identifier in a collection
I'm developing a shopping cart in php following OOP and DDD.
I've got a ShoppingCart class acting as collection for different types of CartItem instances (Type1ProductItem, Type2ProductItem, etc..), all implementing a CartItemInterface.

What about the best way to manage the unique identifier to be used as key in the ShoppingCart's internal collection?

My current solution is a "getPrimaryKey()" method in CartItemInterface  returning a unique identifier based on type and id:

ShoppingCart:

```<code>public function add(CartItemInterface $CartItem) {
    $this->items[$CartItem->getPrimaryKey()] = $CartItem;
}
public function remove(CartItemInterface $CartItem) {
    unset($this->items[$CartItem->getPrimaryKey()]);
}
</code>```

resulting in:

```<code>ShoppingCart->add($CartItem);
ShoppingCart->doSomething($CartItem);
</code>```

But in this way I've got to create a CartItem before every action on the cart (add, remove, update..), depending on uri's parameters, and then pass it to the relevant method of ShoppingCart:

```<code>// type and id coming as parameters
switch ($type) {
    case 1 : $CartItem = new Type1ProductItem($id); break;
    case 2 : $CartItem = new Type2ProductItem($id); break;
    ....
}
ShoppingCart->doSomething($CartItem);
</code>```

This is not a great problem as I can use a factory to avoid duplicated logic, but will it be a more feasible solution if the unique identifier (UID) was created outside the CartItem instances and passed to ShoppingCart the first time an item is added?

```<code>ShoppingCart->add($UID, CartItemInterface $CartItem);
 ShoppingCart->doSomething($UID); // no need of CartItem instance here
</code>```

I'm not sure if it's good that the uid is managed outside the CartItem instances.
What do you think?
What the pros and the cons of the solutions?
Thank you very much.

答:
In general it is not recommended to pass mutable objects to an Aggregate's instance because of the risk of mutating the Aggregate outside its own methods. You can pass objects but they have to be immutable, like Value objects.

In your case, if CartItemInterface are mutable objects then that is not a good thing. You have to make them immutable (so Value objects) or to not pass them but pass their properties instead (and those properties must also be immutable), like this:

```<code>public function addItemToCart($productId, $productType, $quantity, $price)
</code>```

Then, if you need to do something on a cart item, for example to change the quantity, then pass the cart item identifier to the ShoppingCart (the Aggregate) method. That identifier would come from the ShoppingCart Aggregate itself, when you display the cart items to the user and must not necessarily be a GUID or otherwise globally unique thing, it must be unique only inside the Aggregate, so even a zero based index would suffice. In this way, the Aggregate decides itself how to identify its cart items, the Aggregate is in charge, the Aggregate is the authority when it comes to its own cart items and the Aggregate can change this at any time without "asking" permission from other parts of the system. For example, if you need to remove an item from the cart you do like this:

```<code>public function remove($cartItemIndex) {
    unset($this->items[cartItemIndex]);
}
</code>```

Because you said (in comments) that you need some behavior inside the cart items I recommend to make them value objects (so immutable) and then you can pass them around as you need (i.e. when displaying the cart to the user without the need to make an additional local DTO class).

Body:
I'm developing a shopping cart in php following OOP and DDD.
I've got a ShoppingCart class acting as collection for different types of CartItem instances (Type1ProductItem, Type2ProductItem, etc..), all implementing a CartItemInterface.

What about the best way to manage the unique identifier to be used as key in the ShoppingCart's internal collection?

My current solution is a "getPrimaryKey()" method in CartItemInterface  returning a unique identifier based on type and id:

ShoppingCart:

public function add(CartItemInterface $CartItem) {
    $this->items[$CartItem->getPrimaryKey()] = $CartItem;
}
public function remove(CartItemInterface $CartItem) {
    unset($this->items[$CartItem->getPrimaryKey()]);
}

resulting in:

ShoppingCart->add($CartItem);
ShoppingCart->doSomething($CartItem);

But in this way I've got to create a CartItem before every action on the cart (add, remove, update..), depending on uri's parameters, and then pass it to the relevant method of ShoppingCart:

// type and id coming as parameters
switch ($type) {
    case 1 : $CartItem = new Type1ProductItem($id); break;
    case 2 : $CartItem = new Type2ProductItem($id); break;
    ....
}
ShoppingCart->doSomething($CartItem);

This is not a great problem as I can use a factory to avoid duplicated logic, but will it be a more feasible solution if the unique identifier (UID) was created outside the CartItem instances and passed to ShoppingCart the first time an item is added?

ShoppingCart->add($UID, CartItemInterface $CartItem);
 ShoppingCart->doSomething($UID); // no need of CartItem instance here

I'm not sure if it's good that the uid is managed outside the CartItem instances.
What do you think?
What the pros and the cons of the solutions?
Thank you very much.

Body:
In general it is not recommended to pass mutable objects to an Aggregate's instance because of the risk of mutating the Aggregate outside its own methods. You can pass objects but they have to be immutable, like Value objects.

In your case, if CartItemInterface are mutable objects then that is not a good thing. You have to make them immutable (so Value objects) or to not pass them but pass their properties instead (and those properties must also be immutable), like this:

public function addItemToCart($productId, $productType, $quantity, $price)

Then, if you need to do something on a cart item, for example to change the quantity, then pass the cart item identifier to the ShoppingCart (the Aggregate) method. That identifier would come from the ShoppingCart Aggregate itself, when you display the cart items to the user and must not necessarily be a GUID or otherwise globally unique thing, it must be unique only inside the Aggregate, so even a zero based index would suffice. In this way, the Aggregate decides itself how to identify its cart items, the Aggregate is in charge, the Aggregate is the authority when it comes to its own cart items and the Aggregate can change this at any time without "asking" permission from other parts of the system. For example, if you need to remove an item from the cart you do like this:

public function remove($cartItemIndex) {
    unset($this->items[cartItemIndex]);
}

Because you said (in comments) that you need some behavior inside the cart items I recommend to make them value objects (so immutable) and then you can pass them around as you need (i.e. when displaying the cart to the user without the need to make an additional local DTO class).


问:
Need to change date format in angular 2
Currently using Date() gives it in format

```<code>Wed Jul 05 2017 15:14:53 GMT+0530 (India Standard Time)
</code>```

i want to change it so that I get it in this format (want GMT time not IST)

```<code>Jul 5 15:14:53 2017 GMT
</code>```

I also want to know how I can get the time say 2 years from now.

EDIT:

I have fixed the format but now having problems in setting it up to gmt time instead of ist fixed it by :

```<code>let d = new Date();
let month = d.toLocaleString("en-us", { month: "short" });
let datestring = month + " " + d.getDate() + " " + (d.getHours()) + ":" + (d.getMinutes())+ ":" +d.getSeconds() + " " + (d.getFullYear()+2) + " GMT";
</code>```

but naturally that does not actauly show the gmt, its just IST so now trying to fix that.

答:
you can manipulate date in angular like that. does this help!

```<code>  const date = new Date();
           const year = date.getFullYear();
           const month = date.getMonth();
           const day = date.getDay();
           console.log(year);
           console.log(year + 2);
           date.setFullYear(year + 2, month, day);
           console.log(date);
           console.log(date.toLocaleString());
</code>```

output:

Title: Need to change date format in angular 2

Body:
Currently using Date() gives it in format

Wed Jul 05 2017 15:14:53 GMT+0530 (India Standard Time)

i want to change it so that I get it in this format (want GMT time not IST)

Jul 5 15:14:53 2017 GMT

I also want to know how I can get the time say 2 years from now.

EDIT:

I have fixed the format but now having problems in setting it up to gmt time instead of ist fixed it by :

let d = new Date();
let month = d.toLocaleString("en-us", { month: "short" });
let datestring = month + " " + d.getDate() + " " + (d.getHours()) + ":" + (d.getMinutes())+ ":" +d.getSeconds() + " " + (d.getFullYear()+2) + " GMT";

but naturally that does not actauly show the gmt, its just IST so now trying to fix that.

Body:
you can manipulate date in angular like that. does this help!

  const date = new Date();
           const year = date.getFullYear();
           const month = date.getMonth();
           const day = date.getDay();
           console.log(year);
           console.log(year + 2);
           date.setFullYear(year + 2, month, day);
           console.log(date);
           console.log(date.toLocaleString());

output:


问:
Split data from a text file 8 times to put in CSV in individual rows
I need to read some data from a text file and generate the CSV.

I am using this PowerShell script to get the data

```<code>$PAGE = Get-Content .\DATA.txt | ForEach-Object {
     New-Object PSObject -Property @{
         FIELD1 = [regex]::Matches($_, '^[^\:]*[^\.txt:]').Value
         FIELD2 = [regex]::Match($_, 'DATA').Value
         FIELD3 = [regex]::Match($_, 'DATA\s(.+)').Value
         FIELD4  = [regex]::Match($_, 'DATA\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s')
     }
}

$PAGE | Select-Object FIELD1, FIELD2, FIELD3, FIELD4 |
    Export-Csv DATA.csv -NoTypeInformation
</code>```

The regex can be tested here. Sample input:

```
file1.txt: DATA 46546 TEST1 EUIRWY 283746827 2 1 3 3
file2.txt: DATA 96873 TEST2 KJH-ASKDJH 928374 0 0 0 0
```

The output of the above script on the given data is coming as this:

```
FIELD1 | FIELD2 | FIELD3                                     | FIELD4
file1  | DATA   | DATA 46546 TEST1 EUIRWY 283746827 2 1 3 3  | FIELD4
file2  | DATA   | DATA 96873 TEST2 KJH-ASKDJH 928374 0 0 0 0 | FIELD4
```

But the intended output is this.

```
FIELD1 | FIELD2 | FIELD3 | FIELD4
file1  | DATA   | D1     | 46546
file1  | DATA   | D2     | TEST1
file1  | DATA   | D3     | EUIRWY
file1  | DATA   | D4     | 283746827
file1  | DATA   | D5     | 2
file1  | DATA   | D6     | 1
file1  | DATA   | D7     | 3
file1  | DATA   | D8     | 3
file2  | DATA   | D1     | 96873
................................
................................
..............and so no 8 times
```

Basically Field4 will always have 8 strings or digits FIELD1 should be the name of the file 8 times FIELD2 will also appear 8 times that too 'DATA' and FIELD3 will always follow this sequence D1....D8. The same is to be repeated for every line in DATA.TXT file. So in sample I have taken 2 lines as file1.txt and file2.txt.

I am unable to think of how should I proceed. As I want to use the similar approach in the script because it's part of my main script and for uniformity I want to use this approach if possible.

答:
I would do the match in a Where-Object filter and construct the desired objects in a for loop nested inside the ForEach-Object:

```<code>$re = '^(.*?\.txt):\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$'
$PAGE = Get-Content .\DATA.txt | Where-Object {
    $_ -match $re
} | ForEach-Object {
    for ($i=3; $i -lt $matches.Count; $i++) {
        New-Object PSObject -Property @{
            FIELD1 = $matches[1]
            FIELD2 = $matches[2]
            FIELD3 = "D$($i-2))"
            FIELD4 = $matches[$i]
        }
    }
}
</code>```

Body:
I need to read some data from a text file and generate the CSV.

I am using this PowerShell script to get the data

$PAGE = Get-Content .\DATA.txt | ForEach-Object {
     New-Object PSObject -Property @{
         FIELD1 = [regex]::Matches($_, '^[^\:]*[^\.txt:]').Value
         FIELD2 = [regex]::Match($_, 'DATA').Value
         FIELD3 = [regex]::Match($_, 'DATA\s(.+)').Value
         FIELD4  = [regex]::Match($_, 'DATA\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s(\S*)\s')
     }
}

$PAGE | Select-Object FIELD1, FIELD2, FIELD3, FIELD4 |
    Export-Csv DATA.csv -NoTypeInformation

The regex can be tested here. Sample input:

file1.txt: DATA 46546 TEST1 EUIRWY 283746827 2 1 3 3
file2.txt: DATA 96873 TEST2 KJH-ASKDJH 928374 0 0 0 0

The output of the above script on the given data is coming as this:

FIELD1 | FIELD2 | FIELD3                                     | FIELD4
file1  | DATA   | DATA 46546 TEST1 EUIRWY 283746827 2 1 3 3  | FIELD4
file2  | DATA   | DATA 96873 TEST2 KJH-ASKDJH 928374 0 0 0 0 | FIELD4

But the intended output is this.

FIELD1 | FIELD2 | FIELD3 | FIELD4
file1  | DATA   | D1     | 46546
file1  | DATA   | D2     | TEST1
file1  | DATA   | D3     | EUIRWY
file1  | DATA   | D4     | 283746827
file1  | DATA   | D5     | 2
file1  | DATA   | D6     | 1
file1  | DATA   | D7     | 3
file1  | DATA   | D8     | 3
file2  | DATA   | D1     | 96873
................................
................................
..............and so no 8 times

Basically Field4 will always have 8 strings or digits FIELD1 should be the name of the file 8 times FIELD2 will also appear 8 times that too 'DATA' and FIELD3 will always follow this sequence D1....D8. The same is to be repeated for every line in DATA.TXT file. So in sample I have taken 2 lines as file1.txt and file2.txt.

I am unable to think of how should I proceed. As I want to use the similar approach in the script because it's part of my main script and for uniformity I want to use this approach if possible.

Body:
I would do the match in a Where-Object filter and construct the desired objects in a for loop nested inside the ForEach-Object:

$re = '^(.*?\.txt):\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$'
$PAGE = Get-Content .\DATA.txt | Where-Object {
    $_ -match $re
} | ForEach-Object {
    for ($i=3; $i -lt $matches.Count; $i++) {
        New-Object PSObject -Property @{
            FIELD1 = $matches[1]
            FIELD2 = $matches[2]
            FIELD3 = "D$($i-2))"
            FIELD4 = $matches[$i]
        }
    }
}


问:
Parameter declaration in Procedure Prototype and Interface in RPG
I am trying to understand the way parameter variables are declared in Procedure Prototype (PR) and Procedure Interface (PI) in an RPG program. Why is it that the parameter variables need to be defined in both the PR and PI? Declaring it both places is necessary but why the need to redefine? </p>

答:
You do not need a Dcl-Pr for procedures within the same module. You only need a prototype for procedures which are either

within a different module within the program

in a service program which you are trying to reference


问:
The purpose of SQL's EXISTS and NOT EXISTS
Every now and then I see these being used, but it never seems to be anything that can't be performed as equally well, if not better, by using a normal join or subquery.

I see them as being misleading (they're arguably harder to accurately visualize compared to conventional joins and subqueries), often misunderstood (e.g. using SELECT * will behave the same as SELECT 1 in the EXISTS/NOT EXISTS subquery), and from my limited experience, slower to execute.

Can someone describe and/or provide me an example where they are best suited or where there is no option other than to use them?  Note that since their execution and performance are likely platform dependent, I'm particularly interested in their use in MySQL.

答:
Every now and then I see these being used, but it never seems to be anything that can't be performed as equally well, if not better, by using a normal join or subquery.

This article (though SQL Server related):

IN vs. JOIN vs. EXISTS

may be of interest to you.

In a nutshell, JOIN is a set operation, while EXISTS is a predicate.

In other words, these queries:

```<code>SELECT  *
FROM    a
JOIN    b
ON      some_condition(a, b)
</code>```

vs.

```<code>SELECT  *
FROM    a
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    b
        WHERE   some_condition(a, b)
        )
</code>```

are not the same: the former can return more than one record from a, while the latter cannot.

Their counterparts, NOT EXISTS vs. LEFT JOIN / IS NULL, are the same logically but not performance-wise.

In fact, the former may be more efficient in SQL Server:

NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server

Body:
Every now and then I see these being used, but it never seems to be anything that can't be performed as equally well, if not better, by using a normal join or subquery.

This article (though SQL Server related):

IN vs. JOIN vs. EXISTS

may be of interest to you.

In a nutshell, JOIN is a set operation, while EXISTS is a predicate.

In other words, these queries:

SELECT  *
FROM    a
JOIN    b
ON      some_condition(a, b)

vs.

SELECT  *
FROM    a
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    b
        WHERE   some_condition(a, b)
        )

are not the same: the former can return more than one record from a, while the latter cannot.

Their counterparts, NOT EXISTS vs. LEFT JOIN / IS NULL, are the same logically but not performance-wise.

In fact, the former may be more efficient in SQL Server:

NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server


答:
We can use mget to create a list of matrices

```<code>lst <- mget(ls(pattern = "F5\\.Titers"))
names(lst) <- sub("F5.Titers.", "", names(lst))
</code>```

Title: Stack matrices with different number of rows in R

Body:
Sorry if too naive but I cannot find a simple answer. I have two matrices:

> F5.Titers.reticulata1
         3d    6d    12d     18d     24d
 [1,]  6.34 15.64 256.37 1025.82 1025.34
 [2,] 12.35 28.64 198.64 1658.41  970.00
 [3,] 10.22 13.52 364.35  896.64 1236.69
 [4,]  8.34  7.68 298.78 1536.17 1532.44
 [5,]  6.16 28.64 345.11 1223.35  899.31
 [6,]  7.37  6.45 287.46  956.33 2025.35

> F5.Titers.tankan1
         3d    6d    12d     18d     24d
 [1,]  6.35 15.34 315.36 1425.36 1102.13
 [2,] 15.34 20.15 485.35  996.35  969.97
 [3,] 10.21 25.55 263.35  568.36 1045.09

And you like to have a stacked one:

> Joint.matrix.hurray

[[reticulata1]]

         3d    6d    12d     18d     24d
 [1,]  6.34 15.64 256.37 1025.82 1025.34
 [2,] 12.35 28.64 198.64 1658.41  970.00
 [3,] 10.22 13.52 364.35  896.64 1236.69
 [4,]  8.34  7.68 298.78 1536.17 1532.44
 [5,]  6.16 28.64 345.11 1223.35  899.31
 [6,]  7.37  6.45 287.46  956.33 2025.35

 [[tankan1]]
         3d    6d    12d     18d     24d
 [1,]  6.35 15.34 315.36 1425.36 1102.13
 [2,] 15.34 20.15 485.35  996.35  969.97
 [3,] 10.21 25.55 263.35  568.36 1045.09

Please note they have different numbers of rows but same number of cols. I'd like to have them stacked, if possible keeping numbers as numeric and the names.  Thanks

Body:
We can use mget to create a list of matrices

lst <- mget(ls(pattern = "F5\\.Titers"))
names(lst) <- sub("F5.Titers.", "", names(lst))


问:
Count the records with the same difference of two date columns Rails
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

```<code>start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07
</code>```

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

答:
You can do like this

Example:

```<code>Model.all.each do |d|
    date = (d.end_date - d.start_date).to_i

    Model.where.not(id: d.id).each do |diff|
    date_diff = (diff.end_date - diff.start_date).to_i

         if (date==date_diff)
            puts date
         end
    end
end
</code>```

Output depends on your end_date and start_date date format. I assume format like this "2017-06-15 10:00:12"

Body:
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

Body:
You can do like this

Example:

Model.all.each do |d|
    date = (d.end_date - d.start_date).to_i

    Model.where.not(id: d.id).each do |diff|
    date_diff = (diff.end_date - diff.start_date).to_i

         if (date==date_diff)
            puts date
         end
    end
end

Output depends on your end_date and start_date date format. I assume format like this "2017-06-15 10:00:12"


问:
SQL group by with like condition
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

```<code>reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------
</code>```

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

```<code>reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------
</code>```

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

答:
Simply use:-

```<code>group by  clientID,colA,colB,colC
</code>```

instead of

```<code>group by  clientID
</code>```

Demo:-

```<code>Create table testTable (clientID int , colA varchar(10), colB varchar(10), colC varchar(10))
go
insert into testTable values
(1,'test1','test2','test3'),
(1,'test1','ball2','test3'),
(2,'test1','ball2','test3'),
(2,'test1','ball2','test3'),
(3,'test1','test2','test3'),
(4,'test1','test2','test3'),
(4,'test1','test2','test3'),
(5,'test1','ball2','test3')

select * from testTable
where colB LIKE '%test%'
group by  clientID,colA,colB,colC
</code>```

Output:-

```<code>clientID    colA    colB    colC
  1        test1    test2   test3
  3        test1    test2   test3
  4        test1    test2   test3
</code>```

Title: SQL group by with like condition

Body:
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

Body:
Simply use:-

group by  clientID,colA,colB,colC

instead of

group by  clientID

Demo:-

Create table testTable (clientID int , colA varchar(10), colB varchar(10), colC varchar(10))
go
insert into testTable values
(1,'test1','test2','test3'),
(1,'test1','ball2','test3'),
(2,'test1','ball2','test3'),
(2,'test1','ball2','test3'),
(3,'test1','test2','test3'),
(4,'test1','test2','test3'),
(4,'test1','test2','test3'),
(5,'test1','ball2','test3')

select * from testTable
where colB LIKE '%test%'
group by  clientID,colA,colB,colC

Output:-

clientID    colA    colB    colC
  1        test1    test2   test3
  3        test1    test2   test3
  4        test1    test2   test3


问:
nodejs callback async calls maximum limit
I'm new new to nodejs and want to have some clarity about the callstack. What my application does is read messages from SQS and upload asynchronously to different datasources like dynamo,  mysql,stream etc... The problem here is using multiple workers we can receive in parallel 20/30 msgs at a time and will do async calls to upload.Since the operation is slower to upload and receive the callback, I doubt the event queue in nodejs will be filled with async calls while I make all upload async calls in a short time. So, I have two questions

What is the maximum capacity of event loop and how many async calls can lie in event loop at once.

How to control the concurrency and get the details of load and calculate wait time needed for next upload async call.

ps: Assuming I can read 80000 msgs in 10 mins, I can't make 80000 parallel async upload IO calls and queue them in nodejs event loop. Please help me understand this.

答:
I don't know what is the maximum number of tasks in progress as far as the event loop is concerned, but what you can do is, you can control the number of tasks in progress with modules like Async (if you're using traditional callbacks), Q or Bluebird (if you're using promises) or with some combination of promise libraries if you're using ES8 async/await.

See:

http://caolan.github.io/async/

http://documentup.com/kriskowal/q/

http://bluebirdjs.com/

Especially see things like parallelLimit etc:

http://caolan.github.io/async/docs.html#parallelLimit

Now, for the event loop limits. You can test it with a code like this:

```<code>const n = 1000000;
let s = 0;
for (let i = 0; i < n; i++) {
  setTimeout(() => {
    s++;
    if (i >= n - 1) {
      console.log(s);
    }
  });
}
</code>```

You can see that having millions of things on the event loop is not a problem so the event loop itself is unlikely to be a bottleneck in your case. I would be more concerned with your OS limit of open sockets or your server limit of concurrent requests that it can handle.

For that reason I would recommend to use one of the way to limit the number of concurrent requests that I have described above.

Body:
I don't know what is the maximum number of tasks in progress as far as the event loop is concerned, but what you can do is, you can control the number of tasks in progress with modules like Async (if you're using traditional callbacks), Q or Bluebird (if you're using promises) or with some combination of promise libraries if you're using ES8 async/await.

See:

http://caolan.github.io/async/

http://documentup.com/kriskowal/q/

http://bluebirdjs.com/

Especially see things like parallelLimit etc:

http://caolan.github.io/async/docs.html#parallelLimit

Now, for the event loop limits. You can test it with a code like this:

const n = 1000000;
let s = 0;
for (let i = 0; i < n; i++) {
  setTimeout(() => {
    s++;
    if (i >= n - 1) {
      console.log(s);
    }
  });
}

You can see that having millions of things on the event loop is not a problem so the event loop itself is unlikely to be a bottleneck in your case. I would be more concerned with your OS limit of open sockets or your server limit of concurrent requests that it can handle.

For that reason I would recommend to use one of the way to limit the number of concurrent requests that I have described above.


问:
Cordova - Multiple dex files define (annotation)
I'm working on a project with ionic. After I installed the Facebook Plugin I'm not able to build the project for android anymore!

The command

```<code>ionic build android
</code>```

gives me this error message

```<code>UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
</code>```

I'm reading a lot of tutorials/answers about this error and it seems to be related to the use of the Facebook Plugin with the Push Notification Plugin.

It's two days I'm trying a lot of different solutions, but none of those is working :(

Here are some information about my configuration:

```<code>plugin com.phonegap.plugins.PushPlugin version 2.5.0
plugin com.phonegap.plugins.facebookconnect version 0.11.0 (installed with the local repository, as indicated on github)
cordova version 5.0
ionic version 1.6.3
</code>```

It looks like this problem is related to the "support-annotations" library loaded several times. Buy I really don't know how this is possible and where I can check it.

Can you help me? Do you have any idea of how to make this working?
Is there a ionic/cordova configuration file where I can check the dependencies?

Thanks a lot in advance.

答:
We had the same problem with Google Analytics plugin with One Signal plugin and finally it was resolved by installing the plugins in different order;

first install Google Analytics

and then One Signal plugin, if you install in reverse order you will get that error.

This was our config:

Cordova CLI: 7.0.1

Ionic Framework Version: 3.3.0

Ionic CLI Version: 2.2.1

Ionic App Lib Version: 2.2.0

Cheers!

Body:
I'm working on a project with ionic. After I installed the Facebook Plugin I'm not able to build the project for android anymore!

The command

ionic build android

gives me this error message

UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;

I'm reading a lot of tutorials/answers about this error and it seems to be related to the use of the Facebook Plugin with the Push Notification Plugin.

It's two days I'm trying a lot of different solutions, but none of those is working :(

Here are some information about my configuration:

plugin com.phonegap.plugins.PushPlugin version 2.5.0
plugin com.phonegap.plugins.facebookconnect version 0.11.0 (installed with the local repository, as indicated on github)
cordova version 5.0
ionic version 1.6.3

It looks like this problem is related to the "support-annotations" library loaded several times. Buy I really don't know how this is possible and where I can check it.

Can you help me? Do you have any idea of how to make this working?
Is there a ionic/cordova configuration file where I can check the dependencies?

Thanks a lot in advance.


问:
Array function with number at position returning zero
I am new to javascript and was trying this code below.

This code was working properly but seems now its only returning -1.

Array.prototype.nthIndexOf = function (element,location) {
    var index = -1;
    for(var i=0; i< this.length; i++) {
        if(element === this[i] && !--location) {
            index = i;
            break;
        }
    }
    return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);
console.log(position); // position is -1 all the time```

答:
You got to use parseInt() for converting values you are getting from prompt to number as you are getting string value from prompt input.

Please read this page :- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt

and this too :- difference between parseInt() and parseFloat()

Array.prototype.nthIndexOf = function (element,location) {
    var index = -1;
    for(var i=0; i< this.length; i++) {
        if(element === this[i] && !--location) {
            index = i;
            break;
        }
    }
    return index;
}

var findNumber = parseInt(prompt("Please enter number to be found"));
var positionAt = parseInt(prompt("Please enter position"));

// The type of operator will tell you type of object you are getting
// Remove parseInt above and check console log you will get string for findNumber type
console.log(typeof findNumber);

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);

if(position !== -1) {
    console.log(findNumber + " located at " + position);
}else {
    console.log("Occurrence " + positionAt + " of number " + findNumber + " not found");
}```