问:
dse graph connection timeout from nodejs driver when trying to execute graph queries
I'm playing with the last version of DSE Enterprise. I'm interested in the graph features. I currently have one project running on Titan the open source graph database that inspired DSE Graph, and I'm trying to evaluate DSE Graph as a replacement database, since Titan is missing many administration and operation features.

My problem is the following:

I have a strange behavior while trying to execute graph queries on a datastax cluster using the nodejs driver. The query is working (I can add or delete vertices), but on the client side (nodejs driver) I get always a connection timeout error, after 5 to 7 seconds, like this:

```<code> {
    "statusCode": 200,
    "body": {
        "info": {
            "queriedHost": "xx.xx.xx.xx:9042",
            "triedHosts": {
                "xx.xx.xx.xx:9042": {
                    "message": "Connection timeout",
                    "info": "Cassandra Driver Error"
                }
            },
            "achievedConsistency": 10
        },
        "length": 1,
        "pageState": null
    }
}
</code>```

When I look at datastax studio, my queries are working though. I can see the newly added vertices...

Here is the code used to call dse graph:

```<code>'use strict';

const dse = require('dse-driver');
const dseGraph = require('dse-graph');
const client = new dse.Client({
  contactPoints: ['xx.xx.xx.xx'] ,
  protocolOptions: {port: 9042},
  authProvider: new     dse.auth.DsePlainTextAuthProvider("xxx","xxx"),
  graphOptions: { name: 'test' }
});

module.exports.create = (event, context, callback) => {
  let response = {
    statusCode: 200
  };
  client.executeGraph("graph.addVertex(label,'user','email','c@b');").then(function(users) {
    response.body=users;
    client.shutdown();
    callback(null, response);
  }).catch(function(err) {
    response.statusCode=400;
    response.body=err;
    client.shutdown();
    callback(null, response);
  });
};
</code>```

May be the problem is in my cluster configuration?

Here is my topology:

One cluster

3 datacenters

1 datacenter for the graph, with 2 nodes

1 datacenter for search, with 1 node

1 datacenter for analytics, with 1 node

All settings are defaults ones. I've installed the cluster through OpsCenter, and all my nodes are ec2 instances (m4.xlarge).

Do you have any idea why the queries are working, but I get this strange message in the success callback?

Regards,

Toufic Zayed

答:
thanks to Jorge help, I added this line to log all the events received by the driver:

client.on('log', console.log)

I noticed in the logs that while I called the public address of my EC2 server (since my client is outside my VPC), the node tried to communicate using their private interface between them. And the mix of public and private address caused the problem.

Here is what I did, it solved the problem, but I don't know if it's the right answer.

I modified the cassandra.yaml file on each nodes, and I set the broadcast_rpc_address to the public address of each instance.

Now my queries are working.

The only remaining question is: is there a better way to handle a mix of public and private IP using Cassandra?

Am I doing something wrong by setting the broadcast_rpc_address to the public IP of the EC2 instance?

Body:
I'm playing with the last version of DSE Enterprise. I'm interested in the graph features. I currently have one project running on Titan the open source graph database that inspired DSE Graph, and I'm trying to evaluate DSE Graph as a replacement database, since Titan is missing many administration and operation features.

My problem is the following:

I have a strange behavior while trying to execute graph queries on a datastax cluster using the nodejs driver. The query is working (I can add or delete vertices), but on the client side (nodejs driver) I get always a connection timeout error, after 5 to 7 seconds, like this:

 {
    "statusCode": 200,
    "body": {
        "info": {
            "queriedHost": "xx.xx.xx.xx:9042",
            "triedHosts": {
                "xx.xx.xx.xx:9042": {
                    "message": "Connection timeout",
                    "info": "Cassandra Driver Error"
                }
            },
            "achievedConsistency": 10
        },
        "length": 1,
        "pageState": null
    }
}

When I look at datastax studio, my queries are working though. I can see the newly added vertices...

Here is the code used to call dse graph:

'use strict';

const dse = require('dse-driver');
const dseGraph = require('dse-graph');
const client = new dse.Client({
  contactPoints: ['xx.xx.xx.xx'] ,
  protocolOptions: {port: 9042},
  authProvider: new     dse.auth.DsePlainTextAuthProvider("xxx","xxx"),
  graphOptions: { name: 'test' }
});

module.exports.create = (event, context, callback) => {
  let response = {
    statusCode: 200
  };
  client.executeGraph("graph.addVertex(label,'user','email','c@b');").then(function(users) {
    response.body=users;
    client.shutdown();
    callback(null, response);
  }).catch(function(err) {
    response.statusCode=400;
    response.body=err;
    client.shutdown();
    callback(null, response);
  });
};

May be the problem is in my cluster configuration?

Here is my topology:

One cluster

3 datacenters

1 datacenter for the graph, with 2 nodes

1 datacenter for search, with 1 node

1 datacenter for analytics, with 1 node

All settings are defaults ones. I've installed the cluster through OpsCenter, and all my nodes are ec2 instances (m4.xlarge).

Do you have any idea why the queries are working, but I get this strange message in the success callback?

Regards,

Toufic Zayed


来源: stackexchange

问:
Symfony 3 FOS Rest + JMS Serializer groups
My composer.json (part of it):

```<code>{
    "require": {
        "symfony/symfony": "3.1.*",
        "jms/serializer-bundle": "^1.1",
        "friendsofsymfony/rest-bundle": "^2.1"
    }
}
</code>```

I have some entities which I'd like to return partial data for the list action and complete for the find action. For so, I have these files:

Product.php

```<code><?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
* @ORM\Entity
* @ORM\Table(name="represented")
* @JMS\ExclusionPolicy("ALL")
*/
class Product
{
    /**
    * @var integer
    * @ORM\Column(type="integer", nullable=false, options={"unsigned"=true})
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @var string
    * @ORM\Column(type="string", nullable=false, length=48)
    */
    protected $name;

    /**
    * @var Group
    * @ORM\ManyToOne(targetEntity="Group", inversedBy="products")
    * @ORM\JoinColumn(name="group_id", referencedColumnName="id")
    */
    protected $group;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setGroup(Group $group)
    {
        $this->group = $group;
    }

    public function getGroup()
    {
        return $this->group;
    }
}
</code>```

ProductController.php

```<code><?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;

class ProductController extends FOSRestController
{
    /**
    * @Get("/product", name="list_products")
    */
    public function listAction()
    {
        $products = $this->getDoctrine()
            ->getRepository('AppBundle:Product')
            ->findBy([], [ 'name' => 'ASC' ]);

        $view = $this->view($products);

        return $this->handleView($view);
    }

    /**
    * @Get("/product/{id}", requirements={"id" = "\d+"}, name="get_product")
    */
    public function getAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $product = $em->getRepository('AppBundle:Product')
            ->find($id);

        if ( ! $product) {
            $error = [
                'error' => 'Product not found'
            ];

            $view = $this->view($error, 404);
        } else {
            $view = $this->view($product);
        }

        return $this->handleView($view);
    }
}
</code>```

I would like to be able to not show the group property on the list result. For this I have tried a few of approaches, mainly with groups.

Just use configure the group name for the properties I want to show
on my list with Groups({"List"}) and refer this group on the
controller with @View(serializerGroups={"List"}). But this had no
affect as all properties are visible.

Configure @ExclusionPolicy("all") for the entire entity didn't
work as well.

In addition to ExclusionPolicy, @Expose to all properties I wanted
to show in some or all groups, but that made all properties marked
to be shown.

I also tried some more variants of these, but nothing that change the results.

答:
End of your controller action should not be only:

```<code>return $this->handleView($view);
</code>```

But for getting a group or groups working you need to activate them. On top of the class you need to add FOSRest Context, not JMS context:

```<code>use FOS\RestBundle\Context\Context;
</code>```

and in the controller actions before returning view:

```<code>$view = $this->view($products, 200);
$context = new Context();
$context->setGroups(['list']);
$view->setContext($context);

return $this->handleView($view);
</code>```

This will work for Symfony 3.2 and FOSRest 2.1 and 2.0.

Link for upgrading documentation for FOSRest:
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md

ContentLicense: CC BY-SA 3.0

Body:
My composer.json (part of it):

{
    "require": {
        "symfony/symfony": "3.1.*",
        "jms/serializer-bundle": "^1.1",
        "friendsofsymfony/rest-bundle": "^2.1"
    }
}

I have some entities which I'd like to return partial data for the list action and complete for the find action. For so, I have these files:

Product.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
* @ORM\Entity
* @ORM\Table(name="represented")
* @JMS\ExclusionPolicy("ALL")
*/
class Product
{
    /**
    * @var integer
    * @ORM\Column(type="integer", nullable=false, options={"unsigned"=true})
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @var string
    * @ORM\Column(type="string", nullable=false, length=48)
    */
    protected $name;

    /**
    * @var Group
    * @ORM\ManyToOne(targetEntity="Group", inversedBy="products")
    * @ORM\JoinColumn(name="group_id", referencedColumnName="id")
    */
    protected $group;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setGroup(Group $group)
    {
        $this->group = $group;
    }

    public function getGroup()
    {
        return $this->group;
    }
}

ProductController.php

<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;

class ProductController extends FOSRestController
{
    /**
    * @Get("/product", name="list_products")
    */
    public function listAction()
    {
        $products = $this->getDoctrine()
            ->getRepository('AppBundle:Product')
            ->findBy([], [ 'name' => 'ASC' ]);

        $view = $this->view($products);

        return $this->handleView($view);
    }

    /**
    * @Get("/product/{id}", requirements={"id" = "\d+"}, name="get_product")
    */
    public function getAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $product = $em->getRepository('AppBundle:Product')
            ->find($id);

        if ( ! $product) {
            $error = [
                'error' => 'Product not found'
            ];

            $view = $this->view($error, 404);
        } else {
            $view = $this->view($product);
        }

        return $this->handleView($view);
    }
}

I would like to be able to not show the group property on the list result. For this I have tried a few of approaches, mainly with groups.

Just use configure the group name for the properties I want to show
on my list with Groups({"List"}) and refer this group on the
controller with @View(serializerGroups={"List"}). But this had no
affect as all properties are visible.

Configure @ExclusionPolicy("all") for the entire entity didn't
work as well.

In addition to ExclusionPolicy, @Expose to all properties I wanted
to show in some or all groups, but that made all properties marked
to be shown.

I also tried some more variants of these, but nothing that change the results.

Body:
End of your controller action should not be only:

return $this->handleView($view);

But for getting a group or groups working you need to activate them. On top of the class you need to add FOSRest Context, not JMS context:

use FOS\RestBundle\Context\Context;

and in the controller actions before returning view:

$view = $this->view($products, 200);
$context = new Context();
$context->setGroups(['list']);
$view->setContext($context);

return $this->handleView($view);

This will work for Symfony 3.2 and FOSRest 2.1 and 2.0.

Link for upgrading documentation for FOSRest:
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md


问:
Efficient deserializing of dynamic JSON data into datatable
We are working on a program to fetch slide image data from a group of servers that doesn't have a consistent schema setup (I'm worried it's invalid, but I'm not proficient enough to make that call).  We have no influence over the servers as independent-unrelated researchers.

The data was entered manually (for the most part), through a large series of forms (n>50), with inconsistent fields (data goes back to the 90's).  Here is an example of a response:

```<code>{
"form12873": [

    {
        "id": "9202075838",
        "timestamp": "2015-06-25 10:24:51",
        "user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit\/600.6.3 (KHTML, like Gecko) Version\/8.0.6 Safari\/600.6.3",
        "remote_addr": "[Re.dact.ed]",
        "processed": "1",
        "data": {
            "33885124": {
                "field": "33885124",
                "value": "CDat Lab",
                "flat_value": "CDat Lab",
                "label": "Completed by:",
                "type": "select"
            },

            ''**Several more fields as above**''...

            "33884660": {
                "field": "33884660",
                "value": {
                    "slideX": "2456123",
                    "slideY": "456632",
                    "label": "K-20150322148",
                    "approved": "1",
                    "score": "30144"
                },
                "flat_value": "slideX = 2456123\nslideY = 456632\nlabel = K-20150322148\napproved = 1\nscore = 30144",
                "label": "Slide Stats:",
                "type": "slidestats"
            },

            ''**Some of the fields are as above...

            "31970564": {
                "field": "31970564",
                "value": [
                    "System",
                    "Crated",
                    "Mirax",
                    "NanoZoomer",
                    "ThinPrep",
                    "Aperio",
                    "Intellisite"

                ],
                "flat_value": "System\nCrated\nMirax\nNanoZoomer\nThinPrep\nAperio\nIntellisite",
                "label": "System Information",
                "type": "checkbox"
            },

            ''**Some of the values are Arrays...

            "33883781": {
                "field": "33883781",
                "selection": "Retain",
                "label": "4. Retain\/Remove\/Review",
                "type": "selectdrop"
            },

            ''**Some of the fields don't have the same children

            "52792890": {
                "field": "52792890",
                "image": "'A really large byte[], removed for ease of reading'",
                "type": "image"
            }

            ''**Somewhere near the end of each response is the actual image...
        }
    },

    {
        "id": "33884681",
            ''**Then it continues on as above until the end:
    }
], "total": 170, "pages": 5, "pretty_id": "478125624983" }
</code>```

In the past when I've been able to model/class for the structure of the JSON, I've known how to handle it (make a data class with field, value, etc defined).

Trying solutions like:

```<code>var result = JsonConvert.DeserializeObject<List<Dictionary<string,
                            Dictionary<string, string>>>>(content);
</code>```

Always led to array errors or cast issues (even if direct casts were added).  I am able to get the actual first array using:

```<code>    Public Shared Function Tabulate(json As String) As DataTable
    Dim jsonLinq = Newtonsoft.Json.Linq.JObject.Parse(json)

    ' Find the first array using Linq

    Dim srcArray = jsonLinq.Descendants().Where(Function(d) TypeOf d Is JArray).First()
    Dim trgArray = New Newtonsoft.Json.Linq.JArray()
    For Each row As JObject In srcArray.Children(Of JObject)()
        Dim cleanRow = New JObject()
        For Each column As JProperty In row.Properties()
            ' Only include JValue types
            If TypeOf column.Value Is JValue Then
                cleanRow.Add(column.Name, column.Value)
            End If
        Next

        trgArray.Add(cleanRow)
    Next

    Return JsonConvert.DeserializeObject(Of DataTable)(trgArray.ToString())
End Function
</code>```

My end goal is also to get to a data table, and looping/the image byte have me concerned about trying to regressively go down to further children.  My attempts to then deserialize using the first array have then come up nill.

If there is a quick way to handle this, I'd love the solution.  If the problem is that I'm trying to handle crap JSON, I'd love a reference to where the current standard is being broken (so I can at least try to get the other institution to change their servers).  That said, I'll probably have to deal with it anyway, even if it is loops.

*Note: The project was started in VB.net, so we've kept it that way, but I may decide to port to C# anyway.  Code in either would be great.

Below is an unmarked example of the Json that should be usable for testing.  My end goal is to flatten this into a datatable:

```<code>{
"form12873": [
    {
        "id": "9202075838",
        "timestamp": "2015-06-25 10:24:51",
        "user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit\/600.6.3 (KHTML, like Gecko) Version\/8.0.6 Safari\/600.6.3",
        "remote_addr": "[Re.dact.ed]",
        "processed": "1",
        "data": {
            "33885124": {
                "field": "33885124",
                "value": "CDat Lab",
                "flat_value": "CDat Lab",
                "label": "Completed by:",
                "type": "select"
            },
            "33884660": {
                "field": "33884660",
                "value": {
                    "slideX": "2456123",
                    "slideY": "456632",
                    "label": "K-20150322148",
                    "approved": "1",
                    "score": "30144"
                },
                "flat_value": "slideX = 2456123\nslideY = 456632\nlabel = K-20150322148\napproved = 1\nscore = 30144",
                "label": "Slide Stats:",
                "type": "slidestats"
            },
            "31970564": {
                "field": "31970564",
                "value": [
                    "System",
                    "Crated",
                    "Mirax",
                    "NanoZoomer",
                    "ThinPrep",
                    "Aperio",
                    "Intellisite"
                ],
                "flat_value": "System\nCrated\nMirax\nNanoZoomer\nThinPrep\nAperio\nIntellisite",
                "label": "System Information",
                "type": "checkbox"
            },

            "33883781": {
                "field": "33883781",
                "selection": "Retain",
                "label": "4. Retain\/Remove\/Review",
                "type": "select"
            }
        }
    }
], "total": 170, "pages": 5, "pretty_id": "478125624983" }
</code>```

答:
The ugly contraption below is able to do (roughly) what you want. Feed you json source string as parameter to DeserializeToDataTable and collect the result datatable. It worked on your sample. I can't guarantee it will work in the rest of your data. The purpose here is to provide a working start kit which you can study, understand, debug and adapt to suit your needs.

Private Function DeserializeToDataTable(ByVal jsource As String)
    Dim JRootObject = JObject.Parse(jsource)
    Dim Children = JRootObject.SelectTokens("$..data.*").ToArray
    Dim Records = Children.OfType(Of JObject).ToArray
    Dim dicList As New List(Of Dictionary(Of String, Object))
    For Each rec In Records
        dicList.Add(DeserializeToDictionary(rec))
    Next
    Dim fieldnames = dicList.SelectMany(Function(d) d.Keys).Distinct.ToArray
    Dim dt As New DataTable
    For Each fieldname In fieldnames
        dt.Columns.Add(fieldname, GetType(Object))
    Next
    Dim row As DataRow
    For Each dic In dicList
        row = dt.NewRow
        For Each kvp In dic
            row.SetField(kvp.Key, kvp.Value)
        Next
        dt.Rows.Add(row)
    Next
    Return dt
End Function

Private Function DeserializeToDictionary(ByVal json_object As JObject) As Dictionary(Of String, Object)
    Dim dic = New Dictionary(Of String, Object)
    For Each field In json_object.Properties
        Select Case field.Value.Type
            Case JTokenType.Array
                Dim subobject = New JObject
                Dim item = 0
                For Each token In field.Value
                    subobject("item" & item) = token
                    item += 1
                Next
                Dim subdic = DeserializeToDictionary(subobject)
                For Each kvp In subdic
                    dic(kvp.Key) = kvp.Value
                Next
            Case JTokenType.Boolean
                dic(field.Name) = field.Value.ToObject(Of Boolean)
            Case JTokenType.Bytes
                dic(field.Name) = field.Value.ToObject(Of Byte())
            Case JTokenType.Date
                dic(field.Name) = field.Value.ToObject(Of Date)
            Case JTokenType.Float
                dic(field.Name) = field.Value.ToObject(Of Double)
            Case JTokenType.Guid
                dic(field.Name) = field.Value.ToObject(Of Guid)
            Case JTokenType.Integer
                dic(field.Name) = field.Value.ToObject(Of Integer)
            Case JTokenType.Object
                Dim subdic = DeserializeToDictionary(field.Value)
                For Each kvp In subdic
                    dic(kvp.Key) = kvp.Value
                Next
            Case JTokenType.String
                Try
                    dic(field.Name) = field.Value.ToObject(Of String)
                Catch ex As Exception
                    dic(field.Name) = field.Value.ToObject(Of Object)
                End Try
            Case JTokenType.TimeSpan
                dic(field.Name) = field.Value.ToObject(Of TimeSpan)
            Case Else
                dic(field.Name) = field.Value.ToString
        End Select
    Next
    Return dic
End Function
```

<p><strong>You must be aware of this when using code above:</strong></p>

<ol>
<li><p>It uses recursion to flatten a multi-branch structure. So,</p>

```{
    "A":"aaaa",
    "B":"bbbb",
    "C":{
            "D":"dddd",
            "E":"eeee",
            "F":"ffff"
        }
    }
}
```

<p>will become </p>

```A   |B   |D   |E   |F
----+----+----+----+----
aaaa|bbbb|dddd|eeee|ffff
```</li>
<li><p>The way I did assumes there won't be duplications when flattening; should there be those, it will preserve just the last. So,</p>

```{
    "A":"aaaa",
    "B":"bbbb",
    "C":{
            "D":"d1d1",
            "E":"e1e1",
            "F":"f1f1"
        },
    "G":{
            "D":"d2d2",
            "E":"e2e2",
            "F":"f2f2"
        }
    }
}
```

<p>will become </p>

```A   |B   |D   |E   |F
----+----+----+----+----
aaaa|bbbb|d2d2|e2e2|f2f2
```

which is an obvious flawed, buggy behavior, which will require a more sophisticated approach that I leave for you to build on my scratch.

Body:
We are working on a program to fetch slide image data from a group of servers that doesn't have a consistent schema setup (I'm worried it's invalid, but I'm not proficient enough to make that call).  We have no influence over the servers as independent-unrelated researchers.

The data was entered manually (for the most part), through a large series of forms (n>50), with inconsistent fields (data goes back to the 90's).  Here is an example of a response:

{
"form12873": [

    {
        "id": "9202075838",
        "timestamp": "2015-06-25 10:24:51",
        "user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit\/600.6.3 (KHTML, like Gecko) Version\/8.0.6 Safari\/600.6.3",
        "remote_addr": "[Re.dact.ed]",
        "processed": "1",
        "data": {
            "33885124": {
                "field": "33885124",
                "value": "CDat Lab",
                "flat_value": "CDat Lab",
                "label": "Completed by:",
                "type": "select"
            },

            ''**Several more fields as above**''...

            "33884660": {
                "field": "33884660",
                "value": {
                    "slideX": "2456123",
                    "slideY": "456632",
                    "label": "K-20150322148",
                    "approved": "1",
                    "score": "30144"
                },
                "flat_value": "slideX = 2456123\nslideY = 456632\nlabel = K-20150322148\napproved = 1\nscore = 30144",
                "label": "Slide Stats:",
                "type": "slidestats"
            },

            ''**Some of the fields are as above...

            "31970564": {
                "field": "31970564",
                "value": [
                    "System",
                    "Crated",
                    "Mirax",
                    "NanoZoomer",
                    "ThinPrep",
                    "Aperio",
                    "Intellisite"

                ],
                "flat_value": "System\nCrated\nMirax\nNanoZoomer\nThinPrep\nAperio\nIntellisite",
                "label": "System Information",
                "type": "checkbox"
            },

            ''**Some of the values are Arrays...

            "33883781": {
                "field": "33883781",
                "selection": "Retain",
                "label": "4. Retain\/Remove\/Review",
                "type": "selectdrop"
            },

            ''**Some of the fields don't have the same children

            "52792890": {
                "field": "52792890",
                "image": "'A really large byte[], removed for ease of reading'",
                "type": "image"
            }

            ''**Somewhere near the end of each response is the actual image...
        }
    },

    {
        "id": "33884681",
            ''**Then it continues on as above until the end:
    }
], "total": 170, "pages": 5, "pretty_id": "478125624983" }

In the past when I've been able to model/class for the structure of the JSON, I've known how to handle it (make a data class with field, value, etc defined).

Trying solutions like:

var result = JsonConvert.DeserializeObject<List<Dictionary<string,
                            Dictionary<string, string>>>>(content);

Always led to array errors or cast issues (even if direct casts were added).  I am able to get the actual first array using:

    Public Shared Function Tabulate(json As String) As DataTable
    Dim jsonLinq = Newtonsoft.Json.Linq.JObject.Parse(json)

    ' Find the first array using Linq

    Dim srcArray = jsonLinq.Descendants().Where(Function(d) TypeOf d Is JArray).First()
    Dim trgArray = New Newtonsoft.Json.Linq.JArray()
    For Each row As JObject In srcArray.Children(Of JObject)()
        Dim cleanRow = New JObject()
        For Each column As JProperty In row.Properties()
            ' Only include JValue types
            If TypeOf column.Value Is JValue Then
                cleanRow.Add(column.Name, column.Value)
            End If
        Next

        trgArray.Add(cleanRow)
    Next

    Return JsonConvert.DeserializeObject(Of DataTable)(trgArray.ToString())
End Function

My end goal is also to get to a data table, and looping/the image byte have me concerned about trying to regressively go down to further children.  My attempts to then deserialize using the first array have then come up nill.

If there is a quick way to handle this, I'd love the solution.  If the problem is that I'm trying to handle crap JSON, I'd love a reference to where the current standard is being broken (so I can at least try to get the other institution to change their servers).  That said, I'll probably have to deal with it anyway, even if it is loops.

*Note: The project was started in VB.net, so we've kept it that way, but I may decide to port to C# anyway.  Code in either would be great.

Below is an unmarked example of the Json that should be usable for testing.  My end goal is to flatten this into a datatable:

{
"form12873": [
    {
        "id": "9202075838",
        "timestamp": "2015-06-25 10:24:51",
        "user_agent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit\/600.6.3 (KHTML, like Gecko) Version\/8.0.6 Safari\/600.6.3",
        "remote_addr": "[Re.dact.ed]",
        "processed": "1",
        "data": {
            "33885124": {
                "field": "33885124",
                "value": "CDat Lab",
                "flat_value": "CDat Lab",
                "label": "Completed by:",
                "type": "select"
            },
            "33884660": {
                "field": "33884660",
                "value": {
                    "slideX": "2456123",
                    "slideY": "456632",
                    "label": "K-20150322148",
                    "approved": "1",
                    "score": "30144"
                },
                "flat_value": "slideX = 2456123\nslideY = 456632\nlabel = K-20150322148\napproved = 1\nscore = 30144",
                "label": "Slide Stats:",
                "type": "slidestats"
            },
            "31970564": {
                "field": "31970564",
                "value": [
                    "System",
                    "Crated",
                    "Mirax",
                    "NanoZoomer",
                    "ThinPrep",
                    "Aperio",
                    "Intellisite"
                ],
                "flat_value": "System\nCrated\nMirax\nNanoZoomer\nThinPrep\nAperio\nIntellisite",
                "label": "System Information",
                "type": "checkbox"
            },

            "33883781": {
                "field": "33883781",
                "selection": "Retain",
                "label": "4. Retain\/Remove\/Review",
                "type": "select"
            }
        }
    }
], "total": 170, "pages": 5, "pretty_id": "478125624983" }

Body:
The ugly contraption below is able to do (roughly) what you want. Feed you json source string as parameter to DeserializeToDataTable and collect the result datatable. It worked on your sample. I can't guarantee it will work in the rest of your data. The purpose here is to provide a working start kit which you can study, understand, debug and adapt to suit your needs.

Private Function DeserializeToDataTable(ByVal jsource As String)
    Dim JRootObject = JObject.Parse(jsource)
    Dim Children = JRootObject.SelectTokens("$..data.*").ToArray
    Dim Records = Children.OfType(Of JObject).ToArray
    Dim dicList As New List(Of Dictionary(Of String, Object))
    For Each rec In Records
        dicList.Add(DeserializeToDictionary(rec))
    Next
    Dim fieldnames = dicList.SelectMany(Function(d) d.Keys).Distinct.ToArray
    Dim dt As New DataTable
    For Each fieldname In fieldnames
        dt.Columns.Add(fieldname, GetType(Object))
    Next
    Dim row As DataRow
    For Each dic In dicList
        row = dt.NewRow
        For Each kvp In dic
            row.SetField(kvp.Key, kvp.Value)
        Next
        dt.Rows.Add(row)
    Next
    Return dt
End Function

Private Function DeserializeToDictionary(ByVal json_object As JObject) As Dictionary(Of String, Object)
    Dim dic = New Dictionary(Of String, Object)
    For Each field In json_object.Properties
        Select Case field.Value.Type
            Case JTokenType.Array
                Dim subobject = New JObject
                Dim item = 0
                For Each token In field.Value
                    subobject("item" & item) = token
                    item += 1
                Next
                Dim subdic = DeserializeToDictionary(subobject)
                For Each kvp In subdic
                    dic(kvp.Key) = kvp.Value
                Next
            Case JTokenType.Boolean
                dic(field.Name) = field.Value.ToObject(Of Boolean)
            Case JTokenType.Bytes
                dic(field.Name) = field.Value.ToObject(Of Byte())
            Case JTokenType.Date
                dic(field.Name) = field.Value.ToObject(Of Date)
            Case JTokenType.Float
                dic(field.Name) = field.Value.ToObject(Of Double)
            Case JTokenType.Guid
                dic(field.Name) = field.Value.ToObject(Of Guid)
            Case JTokenType.Integer
                dic(field.Name) = field.Value.ToObject(Of Integer)
            Case JTokenType.Object
                Dim subdic = DeserializeToDictionary(field.Value)
                For Each kvp In subdic
                    dic(kvp.Key) = kvp.Value
                Next
            Case JTokenType.String
                Try
                    dic(field.Name) = field.Value.ToObject(Of String)
                Catch ex As Exception
                    dic(field.Name) = field.Value.ToObject(Of Object)
                End Try
            Case JTokenType.TimeSpan
                dic(field.Name) = field.Value.ToObject(Of TimeSpan)
            Case Else
                dic(field.Name) = field.Value.ToString
        End Select
    Next
    Return dic
End Function

You must be aware of this when using code above:

It uses recursion to flatten a multi-branch structure. So,

{
    "A":"aaaa",
    "B":"bbbb",
    "C":{
            "D":"dddd",
            "E":"eeee",
            "F":"ffff"
        }
    }
}

will become

A   |B   |D   |E   |F
----+----+----+----+----
aaaa|bbbb|dddd|eeee|ffff

The way I did assumes there won't be duplications when flattening; should there be those, it will preserve just the last. So,

{
    "A":"aaaa",
    "B":"bbbb",
    "C":{
            "D":"d1d1",
            "E":"e1e1",
            "F":"f1f1"
        },
    "G":{
            "D":"d2d2",
            "E":"e2e2",
            "F":"f2f2"
        }
    }
}

will become

A   |B   |D   |E   |F
----+----+----+----+----
aaaa|bbbb|d2d2|e2e2|f2f2

which is an obvious flawed, buggy behavior, which will require a more sophisticated approach that I leave for you to build on my scratch.


问:
Add Global Secondary Index to an existing table in DynamoDB using aws cli
I can notseem to find an example on how to add Global Secondary Index to an existing table in DynamoDB using the aws cli.

This is what i know so far from the docs

Any pointers would be appreciated

答:
Here is the update-table document.

Example:

```<code>aws dynamodb update-table --table-name <tableName> --global-secondary-index-updates file://gsi-command.json
</code>```

Create a JSON file based with either update, create or delete action:-

Keep one of the action (update, create or delete) from below sample JSON and update the attribute definitions accordingly

```<code>[
  {
    "Update": {
      "IndexName": "string",
      "ProvisionedThroughput": {
        "ReadCapacityUnits": long,
        "WriteCapacityUnits": long
      }
    },
    "Create": {
      "IndexName": "string",
      "KeySchema": [
        {
          "AttributeName": "string",
          "KeyType": "HASH"|"RANGE"
        }
        ...
      ],
      "Projection": {
        "ProjectionType": "ALL"|"KEYS_ONLY"|"INCLUDE",
        "NonKeyAttributes": ["string", ...]
      },
      "ProvisionedThroughput": {
        "ReadCapacityUnits": long,
        "WriteCapacityUnits": long
      }
    },
    "Delete": {
      "IndexName": "string"
    }
  }
  ...
]
</code>```

Body:
Here is the update-table document.

Example:

aws dynamodb update-table --table-name <tableName> --global-secondary-index-updates file://gsi-command.json

Create a JSON file based with either update, create or delete action:-

Keep one of the action (update, create or delete) from below sample JSON and update the attribute definitions accordingly

[
  {
    "Update": {
      "IndexName": "string",
      "ProvisionedThroughput": {
        "ReadCapacityUnits": long,
        "WriteCapacityUnits": long
      }
    },
    "Create": {
      "IndexName": "string",
      "KeySchema": [
        {
          "AttributeName": "string",
          "KeyType": "HASH"|"RANGE"
        }
        ...
      ],
      "Projection": {
        "ProjectionType": "ALL"|"KEYS_ONLY"|"INCLUDE",
        "NonKeyAttributes": ["string", ...]
      },
      "ProvisionedThroughput": {
        "ReadCapacityUnits": long,
        "WriteCapacityUnits": long
      }
    },
    "Delete": {
      "IndexName": "string"
    }
  }
  ...
]


问:
RegularExpressionValidator for more than just AlphaNumerics
I have a RegularExpressionValidator with:

```<code>ValidationExpression="^(a-zA-Z0-9 '-]+$"
</code>```

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

```<code>ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"
</code>```

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

答:
try this. put the opening [ in and move the - to the end.

^[a-zA-Z0-9 '_&,().-]+$

BTW: . has no specific reference in character classes neither do most aside from your language's regex expression delimiter from the code itself.

ContentLicense: CC BY-SA 2.5

Body:
I have a RegularExpressionValidator with:

ValidationExpression="^(a-zA-Z0-9 '-]+$"

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.


问:
How to use group_by variable as an exclusion value with dplyr?
Let's say I have the following data frame:

```<code>(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10
</code>```

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

```<code># A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21
</code>```

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

```<code>x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))
</code>```

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

答:
@67342343's solution seems like the way to go here. If you have more complex overlapping/excluded groups, then maybe something like the following would be helpful:

```<code>library(tidyverse)

dat = data_frame(v1 = rep(letters[1:5], 3), v2 = 1:(5*3))

c(combn(unique(dat$v1),2, simplify=FALSE),
  combn(unique(dat$v1),3, simplify=FALSE)) %>%
  map_df(~ dat %>%
           group_by(v1) %>%
           summarise(v2 = sum(v2)) %>%
           filter(v1 %in% .x) %>%
           ungroup %>%
           summarise(groups = paste(.x,collapse=","),
                     sum = sum(v2)))
</code>```

```<code>   groups   sum
1     a,b    39
2     a,c    42
3     a,d    45
4     a,e    48
5     b,c    45
...
18  b,c,e    75
19  b,d,e    78
20  c,d,e    81
</code>```

Body:
Let's say I have the following data frame:

(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

# A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

Body:
@67342343's solution seems like the way to go here. If you have more complex overlapping/excluded groups, then maybe something like the following would be helpful:

library(tidyverse)

dat = data_frame(v1 = rep(letters[1:5], 3), v2 = 1:(5*3))

c(combn(unique(dat$v1),2, simplify=FALSE),
  combn(unique(dat$v1),3, simplify=FALSE)) %>%
  map_df(~ dat %>%
           group_by(v1) %>%
           summarise(v2 = sum(v2)) %>%
           filter(v1 %in% .x) %>%
           ungroup %>%
           summarise(groups = paste(.x,collapse=","),
                     sum = sum(v2)))

   groups   sum
1     a,b    39
2     a,c    42
3     a,d    45
4     a,e    48
5     b,c    45
...
18  b,c,e    75
19  b,d,e    78
20  c,d,e    81


问:
Sklearn predict function
I am using sklearn's Linear Regression ML model in Python to predict. The predict function returns an array with a lot of floating point numbers, (which is correct) but I don't quite understand what the floating point numbers represent. Is it possible to map them back?

For context, I am trying to predict sales of a product (label) from stocks available. The predict function returns a large array of floating point numbers. How do I know what each floating point number represents?

For instance, the array is like [11.5, 12.0, 6.1,..]. It seems 6.1 is the sales qty but with what stock quantity is it associated with?

答: i'th output is prediction for i'th input. Whatever you passed to .predict is a collection of objects, and the ordering of predictions is the same as the ordering of data passed in.</p>

Title: Sklearn predict function


问:
Using a regex to extract a substring
I have the following string:

```<code><cfset foo="Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam    Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124    Course Date/Time: February 03, 2017">
</code>```

I want to use a regex to extract only the list of students which is:

```<code>Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam
</code>```

If I use replace, I have to use many replace to make it happen. I think it would work with one regex, but I am not good with regular expressions. Can anybody help and guide?

答:
Please pay no attention to the insult someone made in the comments. That's not what SO is for.

Anywho, there are a number of ColdFusion string functions that make your job easier. Here's what I did. This is assuming certain parts of your string will always be the same.

May not be super efficient, but it will help detail step by step what we're doing, and gives you precise control.

```<code><cfset StringVar = "Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124 Course Date/Time: February 03, 2017">

<!---Set total length of string --->
<cfset LengthIndent = len(StringVar)>

<!---Trim off the Students: part--->
<cfset StringVar = Right(StringVar,LengthIndent-9)>

<!---Trim up to the Course Location: part--->
<cfset StringVar = SpanExcluding(StringVar, ":")>

<!---Set total length of REMAINING string --->
<cfset LengthIndent = len(StringVar)>

<!---Trim off the Course Location: part--->
<cfset StringVar = LEFT(StringVar,LengthIndent-15)>

<!---Outputting this will give you ONLY names of students--->
<cfoutput>#StringVar#</cfoutput>
</code>```

Title: Using a regex to extract a substring

Body:
I have the following string:

<cfset foo="Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam    Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124    Course Date/Time: February 03, 2017">

I want to use a regex to extract only the list of students which is:

Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam

If I use replace, I have to use many replace to make it happen. I think it would work with one regex, but I am not good with regular expressions. Can anybody help and guide?

Body:
Please pay no attention to the insult someone made in the comments. That's not what SO is for.

Anywho, there are a number of ColdFusion string functions that make your job easier. Here's what I did. This is assuming certain parts of your string will always be the same.

May not be super efficient, but it will help detail step by step what we're doing, and gives you precise control.

<cfset StringVar = "Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124 Course Date/Time: February 03, 2017">

<!---Set total length of string --->
<cfset LengthIndent = len(StringVar)>

<!---Trim off the Students: part--->
<cfset StringVar = Right(StringVar,LengthIndent-9)>

<!---Trim up to the Course Location: part--->
<cfset StringVar = SpanExcluding(StringVar, ":")>

<!---Set total length of REMAINING string --->
<cfset LengthIndent = len(StringVar)>

<!---Trim off the Course Location: part--->
<cfset StringVar = LEFT(StringVar,LengthIndent-15)>

<!---Outputting this will give you ONLY names of students--->
<cfoutput>#StringVar#</cfoutput>


答:
A small function without using dplyr:</p>

```<code>dat  <- data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10)

test_func<-function(df){
      a<-sum(df[df$v1 != "a",][,2])
      b<-sum(df[df$v1 != "b",][,2])
      c<-sum(df[df$v1 != "c",][,2])
      out<-rbind(a,b,c)
      return(out)
}

test_func(dat)

  [,1]
a   49
b   40
c   21
</code>```

Title: How to use group_by variable as an exclusion value with dplyr?

Body:
A small function without using dplyr:

dat  <- data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10)

test_func<-function(df){
      a<-sum(df[df$v1 != "a",][,2])
      b<-sum(df[df$v1 != "b",][,2])
      c<-sum(df[df$v1 != "c",][,2])
      out<-rbind(a,b,c)
      return(out)
}

test_func(dat)

  [,1]
a   49
b   40
c   21


问:
tuProlog - using multiple files with consult - can't get engine to load additional files with consult(otherFile.pl)
Edit: Clarity - the main .pl file loads, it's all the subfiles that it has been told to load which don't load. (all the consult('subfile.pl').)

I have a Java project that uses tuProlog. It calls a theory as:

```<code>Theory theory = new Theory(":-consult('main.pl').");
        engine.setTheory(theory);
</code>```

This is as per the manual.
file.pl exists in the same folder as other prolog files.
Inside of main.pl, I have further

```<code>consult('otherfile.pl').
</code>```

statements to load additional files (several).

The folder structure is:

```<code>src/main.pl
src/Prolog_Files/otherfile.pl (multiple)
src/main/java/JavaStuff
</code>```

I can't get the engine to load the theories that I've told it to consult inside of the main file.pl

I have tried: giving it absolute path instead of just filename.

moving files around.

I'm wondering if there is something about usage of tuProlog I'm not understanding?

The theory works when loaded with:

```<code>Theory theory = new Theory(new FileInputStream(url_of_file)).
</code>```

However, this is causing me issues when building the jar, as it can't find the file location.

Am I attempting to load the file correctly? Are my consults inside of the main .pl file correct?

Could someone please post an example of how this should be done if not? The manual doesn't elaborate very much on this topic.

Thanks

答:
The manual is slightly outdated in parts - it says to use consult/1, whereas elsewhere it states that consult/1 is deprecated, whereas include/1 is the replacement.

Secondly, when using 2p.jar, it reads Prolog files from the Project root as its root. When creating a jar, 2p.jar cannot be inside of the project jar. They should be in relative folders, and 2p.jar reads Prolog files with the location of 2p.jar as root. It doesn't seem that it can read inside of project jar.

Hopefully that's clear enough!

Body:
Edit: Clarity - the main .pl file loads, it's all the subfiles that it has been told to load which don't load. (all the consult('subfile.pl').)

I have a Java project that uses tuProlog. It calls a theory as:

Theory theory = new Theory(":-consult('main.pl').");
        engine.setTheory(theory);

This is as per the manual.
file.pl exists in the same folder as other prolog files.
Inside of main.pl, I have further

consult('otherfile.pl').

statements to load additional files (several).

The folder structure is:

src/main.pl
src/Prolog_Files/otherfile.pl (multiple)
src/main/java/JavaStuff

I can't get the engine to load the theories that I've told it to consult inside of the main file.pl

I have tried: giving it absolute path instead of just filename.

moving files around.

I'm wondering if there is something about usage of tuProlog I'm not understanding?

The theory works when loaded with:

Theory theory = new Theory(new FileInputStream(url_of_file)).

However, this is causing me issues when building the jar, as it can't find the file location.

Am I attempting to load the file correctly? Are my consults inside of the main .pl file correct?

Could someone please post an example of how this should be done if not? The manual doesn't elaborate very much on this topic.

Thanks


问:
Chrome: Changing Select Value with jQuery is not working correctly
This code worked in IE, FF, and Safari (windows7).

It is not working in Chrome however.

Basically, I am trying to make some changes on page load (Magento product page).  I change the selected option (of a hidden select dropdown), then when they hover over the Add to Cart button, I make sure that an option was selected.

Code below:

```<code>$j('select#attribute76').val( $j('a'+hash).attr('index') ).change();
alert($j('select#attribute76').val()); // shows correctly w/ all browsers
</code>```

... then later on ...

```<code> $j('#addtocartbutton').hover(function(){
      //alert($j('select#attribute76 option:selected').val());// empty in Chrome!
      if ($j('select#attribute76').val()=='')// empty in Chrome!
           $j('.infoOptionsColors a:first').click();
     });
</code>```

What is happening is that Chrome is selecting the option that I am asking it to, but it reverts back somehow...  perhaps there is another call that is overriding it..

答:
If you know $j('select#attribute76').val() produces a value why not use that always instead of the longer $j('select#attribute76 option:selected').val() which doesn't work?

Edit:

I understand better. The value of a select can be an array since a select can also be a multiselect. When comparing with an empty string ('') most browsers make the shortcut of treating all empty values as equal, whether it is 0, NULL or array with no items. I believe you might have better luck with

```<code>if (!$j('select#attribute76').val())
</code>```

or by casting the returned value to a string

```<code>if (String($j('select#attribute76').val())=='')
</code>```

Body:
This code worked in IE, FF, and Safari (windows7).

It is not working in Chrome however.

Basically, I am trying to make some changes on page load (Magento product page).  I change the selected option (of a hidden select dropdown), then when they hover over the Add to Cart button, I make sure that an option was selected.

Code below:

$j('select#attribute76').val( $j('a'+hash).attr('index') ).change();
alert($j('select#attribute76').val()); // shows correctly w/ all browsers

... then later on ...

 $j('#addtocartbutton').hover(function(){
      //alert($j('select#attribute76 option:selected').val());// empty in Chrome!
      if ($j('select#attribute76').val()=='')// empty in Chrome!
           $j('.infoOptionsColors a:first').click();
     });

What is happening is that Chrome is selecting the option that I am asking it to, but it reverts back somehow...  perhaps there is another call that is overriding it..

Body:
If you know $j('select#attribute76').val() produces a value why not use that always instead of the longer $j('select#attribute76 option:selected').val() which doesn't work?

Edit:

I understand better. The value of a select can be an array since a select can also be a multiselect. When comparing with an empty string ('') most browsers make the shortcut of treating all empty values as equal, whether it is 0, NULL or array with no items. I believe you might have better luck with

if (!$j('select#attribute76').val())

or by casting the returned value to a string

if (String($j('select#attribute76').val())=='')


问:
Karp reduction from PARTITION to SUBSET SUM
PARTITION: Given a set of positive integers A={a_1,...,a_n} does there exist a subset of A with sum equal to the sum of it's complement?

SUBSET SUM: Given a set of positive integers A={a_1,...,a_n} and another positive integer B, does there exist a subset of A such that it's sum is equal to B?

I was trying to prove that if PARTITION is NP-complete then SUBSET SUM is also NP-complete, by reducing PART to SSUM.

My solution was: let A={a1,...,an} be a set of positive integers. Then if A when fed into PART gives the solution I={k1,...,km} (where k_i are the indices of the members of the solution subset), then we construct A'={a1,...an,S} where S is the sum of {a_k1,a_k2,...,a_km}. A' is a solution to SSUM.

My problem with this is that this goes only one way, meaning that we can't show that given A' then A is a solution to PART. Is this a problem? and how could i modify the proof to cover it?

答:
Partition to SubsetSum is actually easier than what you've done here.

If Partition is Satisfied that means that there are some subsets P1 and P2 such that sum(P1) = sum(P2) correct? Because sum(P1) + sum(P2) = Sum(A), which means that sum(P1) = sum(P2) = (1/2)sum(A)

We don't even need to construct an A' for subset sum. Just set A' = A and the target sum = (1/2)sum(A). It should be clear that this is the exact same problem as Partition with almost no abstraction.

In other words Partition is always just subset sum where target sum = (1/2)sum(A)

ContentLicense: CC BY-SA 4.0


问:
How to get formatted console message in Google Chrome's developer tools?
Today I were surprised of getting a formatted console message while surfing on Facebook.

I have no need to use formatted console messages but I am wondering how to get formatted console messages? Just a chrome feature?

I'm using Google Chrome on my Macbook.

答:
```<code>console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
</code>```

https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css

Body:
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css


问:
Python return statement error " 'return' outside function"
When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

```<code>while True:
    return False
</code>```

I get the following error

```<code>SyntaxError: 'return' outside function
</code>```

I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

答: As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

Body:
When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

I get the following error

SyntaxError: 'return' outside function

I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!


问:
Cannot find module 'sails'
I am trying to run a sails application with Webstorm 7.0.3.
this appear when i try to run the server in the console log:

module.js:340
    throw err;
          ^
Error: Cannot find module 'sails'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (C:\Users**\projects\WebstormProjects**\app.js:2:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain [as _onTimeout] (module.js:497:10)

Process finished with exit code 8

i installed sails globaly. i know that this is dont work because it cant find the sails module in the project's local 'node_modules' directory. if ill install again 'sails' localy it will work. but i dont want to...

Is there a way to make it work with sails global install? thanks!

答:
If your applications relies on Sails, you should have it in your dependencies in package.json as well as installed locally.

If you don't like the way that npm creates a copy of each module locally, use yarn and tell it to symlink the cached version.

Title: Cannot find module 'sails'


问:
sed in backtick expansion, with xargs, not substituting the input string
```<code>echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`
</code>```

Expected output:

```<code>where are you
</code>```

actual output:

```<code>who are you
</code>```

Note - this is not actual use case but an example test case.

答:
The order of expansion has to be slightly modified:

```<code>echo "who are you" | echo "`sed "s/who/where/"`" | xargs -I@ echo "@"
</code>```

In your example the command substitution happens before the commands will be started by the shell:

```<code>echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`
</code>```

command substitution does this:

```<code>echo @ | sed "s/who/where/"
</code>```

The result is "@" as sed just prints out the input.
Next step is:

```<code>echo "who are you" | xargs -i@ echo @
</code>```

xargs substitutes @ with the standard input "who are you" and build and run this command:

```<code>echo "who are you"
</code>```

So finaly you get the output:

```<code>who are you
</code>```

Body:
echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`

Expected output:

where are you

actual output:

who are you

Note - this is not actual use case but an example test case.

Body:
The order of expansion has to be slightly modified:

echo "who are you" | echo "`sed "s/who/where/"`" | xargs -I@ echo "@"

In your example the command substitution happens before the commands will be started by the shell:

echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`

command substitution does this:

echo @ | sed "s/who/where/"

The result is "@" as sed just prints out the input.
Next step is:

echo "who are you" | xargs -i@ echo @

xargs substitutes @ with the standard input "who are you" and build and run this command:

echo "who are you"

So finaly you get the output:

who are you


问:
sql left join clarification
I have two tables.

I need all records from table A except where there is a match in table B, then take table B's matching value

So if table A has a match with table B, then I need to exclude that value from the results (i.e take all records from table A and replace records from table A with the matching value from table B).

from my understanding I left joined the two tables on the matching column and then added a where clause to exclude the null values but I'm not sure if that is correct.

data:

```<code>tableA (col1 =ID, col2 =value)
1, 5
2, 3
3, 7

tableB (col1 =ID, col2 =value)
4, 6
2, 9

expected result:

5

9

7
</code>```

This is the closest I've gotten but I'm not sure if it's correct:

```<code>select * from tableA tblA
left join tableB tblB
on tblA.matchingColumn = tblB.matchingColumn
where tblB.matchingColumn is null
</code>```

答:
This will return all the rows in TABLEA. If there are any matching value in TABLEB then it will be used as VALUE.

```<code>SELECT TBLA.ID
    , COALESCE(TBLB.VALUE, TBLA.VALUE) VALUE
FROM TABLEA TBLA
    LEFT JOIN TABLEB TBLB
        ON TBLA.ID = TBLB.ID;
</code>```

UPDATE - SQLFiddle for this thread

Title: sql left join clarification

Body:
I have two tables.

I need all records from table A except where there is a match in table B, then take table B's matching value

So if table A has a match with table B, then I need to exclude that value from the results (i.e take all records from table A and replace records from table A with the matching value from table B).

from my understanding I left joined the two tables on the matching column and then added a where clause to exclude the null values but I'm not sure if that is correct.

data:

tableA (col1 =ID, col2 =value)
1, 5
2, 3
3, 7

tableB (col1 =ID, col2 =value)
4, 6
2, 9

expected result:

5

9

7

This is the closest I've gotten but I'm not sure if it's correct:

select * from tableA tblA
left join tableB tblB
on tblA.matchingColumn = tblB.matchingColumn
where tblB.matchingColumn is null

Body:
This will return all the rows in TABLEA. If there are any matching value in TABLEB then it will be used as VALUE.

SELECT TBLA.ID
    , COALESCE(TBLB.VALUE, TBLA.VALUE) VALUE
FROM TABLEA TBLA
    LEFT JOIN TABLEB TBLB
        ON TBLA.ID = TBLB.ID;

UPDATE - SQLFiddle for this thread


问:
SQL Display the TID and Total Number of Items Sold
Q:Display the TID and the total number of items (of all products) sold within the transaction for all sales transactions whose total number of items (of all products sold within the transaction is greater than five.

I've tried multiple times, but what I end up doing is adding together the individual purchases rather than the item purchases combined.

答:
You are supposed to compute the sum per TID and then use the having clause to filter those products having sold more than 5 items:

```<code>select TID, sum(NoOfItems) from soldvia group by TID having sum(NoOfItems) > 5;
</code>```

Body:
You are supposed to compute the sum per TID and then use the having clause to filter those products having sold more than 5 items:

select TID, sum(NoOfItems) from soldvia group by TID having sum(NoOfItems) > 5;


问:
Non cryptographic hashing in Java using unsigned integers
I am looking for a hashing function that can be used for non cryptographic purposes in Java. The challenge is that most of the hashing functions return signed integer values (-,0,+) that cannot be used as identifier in every context (for example negative integers cannot be used in URLs). One solution to this problem is that I come up with is to use a 32 bit signed int and convert it to a 32 bit unsigned int and store it in a long. This works pretty well. However, 32 bit random information makes hash collisions too frequent in our setup. One way of solving this is to use a 64 bit hashing function (same SipHash works fine) and convert that signed integer to unsigned by shifting one to the right and having 0 in the MSB position. I was trying to achieve that with the Java >> operator but the results does not make sense.

```<code>//Using Guava
private final static HashFunction hashFunction = Hashing.sipHash24();

    private static int getRandomInt() {
        return hashFunction.newHasher().putLong(rnd.nextLong()).hash().asInt();
    }

    private static long getRandomLong(){
        return hashFunction.newHasher().putLong(rnd.nextLong()).hash().asLong();
    }
</code>```

Bitshifting:

```<code> System.out.println(Long.toBinaryString(-2147483648L >> 1));
 1111111111111111111111111111111111000000000000000000000000000000
</code>```

What am I missing and how could I have a 62 bit unsigned integer hash value stored in a 64 bit int (long) in Java?

UPDATE1:

After doing some research I finally found a way to correctly display the effect of >>> on a Long value:

```<code>        System.out.println(
          String.format("%64s", Long.toBinaryString(-2147483648L))
            .replace(' ', '0'));
        System.out.println(
          String.format("%64s", Long.toBinaryString(-2147483648L >>> 1))
            .replace(' ', '0'));

        1111111111111111111111111111111110000000000000000000000000000000
        0111111111111111111111111111111111000000000000000000000000000000
</code>```

答:
a >> b

shifts a to the right by b bits. On the left it repeats the bit that was already there (sign extending!).
Examples:

101010 >> 1 = 110101

010101 >> 1 = 001010

a >>> b

also shifts a to the right by b bits, but doesn't sign extend. It always adds in zeros on the left:

101010 >>> 1 = 010101

010101 >>> 1 = 001010

Body:
I am looking for a hashing function that can be used for non cryptographic purposes in Java. The challenge is that most of the hashing functions return signed integer values (-,0,+) that cannot be used as identifier in every context (for example negative integers cannot be used in URLs). One solution to this problem is that I come up with is to use a 32 bit signed int and convert it to a 32 bit unsigned int and store it in a long. This works pretty well. However, 32 bit random information makes hash collisions too frequent in our setup. One way of solving this is to use a 64 bit hashing function (same SipHash works fine) and convert that signed integer to unsigned by shifting one to the right and having 0 in the MSB position. I was trying to achieve that with the Java >> operator but the results does not make sense.

//Using Guava
private final static HashFunction hashFunction = Hashing.sipHash24();

    private static int getRandomInt() {
        return hashFunction.newHasher().putLong(rnd.nextLong()).hash().asInt();
    }

    private static long getRandomLong(){
        return hashFunction.newHasher().putLong(rnd.nextLong()).hash().asLong();
    }

Bitshifting:

 System.out.println(Long.toBinaryString(-2147483648L >> 1));
 1111111111111111111111111111111111000000000000000000000000000000

What am I missing and how could I have a 62 bit unsigned integer hash value stored in a 64 bit int (long) in Java?

UPDATE1:

After doing some research I finally found a way to correctly display the effect of >>> on a Long value:

        System.out.println(
          String.format("%64s", Long.toBinaryString(-2147483648L))
            .replace(' ', '0'));
        System.out.println(
          String.format("%64s", Long.toBinaryString(-2147483648L >>> 1))
            .replace(' ', '0'));

        1111111111111111111111111111111110000000000000000000000000000000
        0111111111111111111111111111111111000000000000000000000000000000


问:
Is there another tool out there for building oracle reports other then oracle reports builder?
I cant stand oracle reports builder. Its constantly crashing and sucking in general. Copying and pasting stuff only sometimes works. Elements visualy look selected after you unselect them. AARRRRRRRRGGHHHHHHHHHHHH!!! I need another tool. Are their any alternatives for designing the report jsps? </p>

答: Use SQL and understand your data model and plug it into an excel spreadsheet using ODBC?</p>


问:
Application Installation Failed (Android Studio) ; device not found

There's no problem with running a emulator on the Android studio.

when i run the app in mobile, "Application installation failed" dialog came.

答: For me this problem was resolved by using a different usb cable to connect the phone to the computer.</p>


问:
Copy column widths using resize and copy
I have the following code that looks to the original worksheet on row 80 of each column and if it has the text "True" it copies that column to the destination worksheet.  It then loops and goes through all of the columns.  It works perfect, except I can not figure out how to copy the column widths. - Jordan</p>

```<code>'Called from AddWorksheet
Sub CopyFinal(orgSheet As Worksheet, destSheet As Worksheet)

Dim j As Integer '**Why is j an Integer and others are Long?
Dim lastColumn As Long
Dim benRow As Long

j = 2
lastColumn = 2
'Counts the number of benefits on each sheet.  Assumes that they will not go past row 40
benRow = WorksheetFunction.CountA(orgSheet.Range("B3:B40"))

Application.ScreenUpdating = False

Do Until IsEmpty(orgSheet.Cells(3, j))
    If orgSheet.Cells(80, j) = True Then
        orgSheet.Cells(3, j).Resize(benRow).Copy destSheet.Cells(3, lastColumn) '**Need to paste column widths
    End If
    j = j + 1
    lastColumn = destSheet.UsedRange.Columns(destSheet.UsedRange.Columns.Count).Column + 1
Loop

Application.ScreenUpdating = True
End Sub
</code>```

答:
```<code>Do Until IsEmpty(orgSheet.Cells(3, j))
    If orgSheet.Cells(80, j) = True Then
        orgSheet.Cells(3, j).Resize(benRow).Copy
        With destSheet.Cells(3, lastColumn)
            .Paste
            .PasteSpecial Paste:=xlPasteColumnWidths
        End With
    End If
    j = j + 1
    lastColumn = destSheet.UsedRange.Columns(destSheet.UsedRange.Columns.Count).Column + 1
Loop
</code>```

Body:
I have the following code that looks to the original worksheet on row 80 of each column and if it has the text "True" it copies that column to the destination worksheet.  It then loops and goes through all of the columns.  It works perfect, except I can not figure out how to copy the column widths. - Jordan

'Called from AddWorksheet
Sub CopyFinal(orgSheet As Worksheet, destSheet As Worksheet)

Dim j As Integer '**Why is j an Integer and others are Long?
Dim lastColumn As Long
Dim benRow As Long

j = 2
lastColumn = 2
'Counts the number of benefits on each sheet.  Assumes that they will not go past row 40
benRow = WorksheetFunction.CountA(orgSheet.Range("B3:B40"))

Application.ScreenUpdating = False

Do Until IsEmpty(orgSheet.Cells(3, j))
    If orgSheet.Cells(80, j) = True Then
        orgSheet.Cells(3, j).Resize(benRow).Copy destSheet.Cells(3, lastColumn) '**Need to paste column widths
    End If
    j = j + 1
    lastColumn = destSheet.UsedRange.Columns(destSheet.UsedRange.Columns.Count).Column + 1
Loop

Application.ScreenUpdating = True
End Sub


问:
Uploading Image from Android to Node
I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.

Here is my server code

```<code>app.post('/upload', function(req, res) {
    var base64Data = req.rawBody;
    fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
        if(err) console.log(err);
        else {
            console.log("file Succesfully written ");
            cloudinary.uploader.upload("test.jpg", function (image) {
                if(image !== undefined) {

                     res.json({link: image.secure_url}).end();
                     console.log("url = " , image.secure_url);
                 //   fs.unlink(ImageFile);
                } else console.log.error("Error uploading to Cloudinary, ", image);
            });
        }
    });
});
</code>```

Here is my front end code I use to convert my bitmap to an encoded Base64 String.

```<code>final String encodedString = ImageBase64.encode(fileArray.get(i));
</code>```

Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.

```<code>/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
                                                                          AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
</code>```

However on my backend it is displayed as this

```<code>2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
</code>```

答:
```<code>InputStream imageStream;
                try {
                    imageStream = getContentResolver().openInputStream(uri);//uri is the image URI
                    Bitmap bm = BitmapFactory.decodeStream(imageStream);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
                    byte[] byteArray = baos.toByteArray();
                    String encodedImage = Base64.encodeToString(byteArray,Base64.NO_WRAP);//encodedImage is your image string

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
</code>```

Title: Uploading Image from Android to Node

Body:
I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.

Here is my server code

app.post('/upload', function(req, res) {
    var base64Data = req.rawBody;
    fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
        if(err) console.log(err);
        else {
            console.log("file Succesfully written ");
            cloudinary.uploader.upload("test.jpg", function (image) {
                if(image !== undefined) {

                     res.json({link: image.secure_url}).end();
                     console.log("url = " , image.secure_url);
                 //   fs.unlink(ImageFile);
                } else console.log.error("Error uploading to Cloudinary, ", image);
            });
        }
    });
});

Here is my front end code I use to convert my bitmap to an encoded Base64 String.

final String encodedString = ImageBase64.encode(fileArray.get(i));

Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                          AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
                                                                          AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA

However on my backend it is displayed as this

2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ


问:
Android Studio Error,
When I launch an Android Studio Project I get this Error

```<code>Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings
</code>```

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

答: you need to change the path in the picture to the C:\Program Files (x86)\Java\jre1.8.0_101

Title: Android Studio Error,

Body:
When I launch an Android Studio Project I get this Error

Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap


问:
Swift Console input not case sensitive
i just started learning Swift3. For the beginning i write a console program for converting units. I have a console input stream

```<code>let typ = readLine()
</code>```

and of cause i get the exact same string back but i use this in a if statement. Now my Problem i don't want to check it case sensitive i only want the plain string.
This is the if construct i use:

```<code>if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}
</code>```

Thank you :D

答:
Simply lowercase the input before comparing it. Also, a switch statement can greatly clean up the if/if else/else ladder.

```<code>guard let input = readLine() else {
    fatalError("No input recieved")
}

switch input.lowercased() {
    case unitA: print("foo")
    case unitB: print("super foo")
    default: print("Invalid input :/")
}
</code>```

Title: Swift Console input not case sensitive

Body:
i just started learning Swift3. For the beginning i write a console program for converting units. I have a console input stream

let typ = readLine()

and of cause i get the exact same string back but i use this in a if statement. Now my Problem i don't want to check it case sensitive i only want the plain string.
This is the if construct i use:

if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}

Thank you :D

Body:
Simply lowercase the input before comparing it. Also, a switch statement can greatly clean up the if/if else/else ladder.

guard let input = readLine() else {
    fatalError("No input recieved")
}

switch input.lowercased() {
    case unitA: print("foo")
    case unitB: print("super foo")
    default: print("Invalid input :/")
}


问:
C++: Why does this constexpr template function cause an internal error in VS2017?(In gcc is ok)
This code compiles fine in GCC, but it causes an internal error in Visual Studio 2017 compiler. What is wrong in my code? Or it is an compiler issue? I`ve heard that VS doesnt use two phase name lookup and this can cause problems in some cases.

```<code>template <typename T>
constexpr auto doSomeSum(const T* a, const T* b) {
    if (a > b)return 0;
    auto sum = 0;
    while (a != b)
        sum += *(a++);
    return sum;
}

int main()
{
    constexpr int arr[] = { 1,2,3,4,5,6,7,0b1000,9,10 };
    constexpr float second[] = { 1,2,3,4,5,6,7,8,9,10 };
    constexpr auto a = doSomeSum<int>(arr, arr+10);
    constexpr auto b = doSomeSum<float>(second,second+10); //works if I comment this line
    return 0;
}
</code>```

答:
The issue (which also occurs with MSVC 2015) appears to be that it deduces both the return type and sum's type as int, then has an aneurysm whenever T is a different type.  I'm not sure about 2017, but 2015 emits this warning before it implodes:

main.cpp(6): warning C4244: '+=': conversion from 'const float' to 'int', possible loss of data

  main.cpp(15): note: see reference to function template instantiation 'int doSomeSum(const T *,const T *)' being compiled
          with

```<code>    [
        T=float
    ]
</code>```

Where line 6 is:

```<code>    sum += *(a++);
</code>```

Therefore, it sees *(a++) as const float, but sum as int; this is because sum is initialised with 0, an integer literal.  We can easily fix this, however, by instead initialising it with T{0}, tying sum's type to the template parameter.  As this will cause return type deduction to determine two conflicting types (int for 0, T for sum), we must also change the first line to return T{0}.  And thus, the end result is:

```<code>template <typename T>
constexpr auto doSomeSum(const T* a, const T* b) {
    if (a > b)return T{0};
    auto sum = T{0};
    while (a != b)
        sum += *(a++);
    return sum;
}
</code>```

Tested with Compiler Explorer and RiSE4Fun's MSVC 2015 online environment (note that the latter doesn't provide any facility to link to individual sessions).  Testing the original code with GCC and Clang demonstrates that both have the same issue, with Clang also emitting an error due to it.

Body:
This code compiles fine in GCC, but it causes an internal error in Visual Studio 2017 compiler. What is wrong in my code? Or it is an compiler issue? I`ve heard that VS doesnt use two phase name lookup and this can cause problems in some cases.

template <typename T>
constexpr auto doSomeSum(const T* a, const T* b) {
    if (a > b)return 0;
    auto sum = 0;
    while (a != b)
        sum += *(a++);
    return sum;
}

int main()
{
    constexpr int arr[] = { 1,2,3,4,5,6,7,0b1000,9,10 };
    constexpr float second[] = { 1,2,3,4,5,6,7,8,9,10 };
    constexpr auto a = doSomeSum<int>(arr, arr+10);
    constexpr auto b = doSomeSum<float>(second,second+10); //works if I comment this line
    return 0;
}

Body:
The issue (which also occurs with MSVC 2015) appears to be that it deduces both the return type and sum's type as int, then has an aneurysm whenever T is a different type.  I'm not sure about 2017, but 2015 emits this warning before it implodes:

main.cpp(6): warning C4244: '+=': conversion from 'const float' to 'int', possible loss of data

  main.cpp(15): note: see reference to function template instantiation 'int doSomeSum(const T *,const T *)' being compiled
          with

    [
        T=float
    ]

Where line 6 is:

    sum += *(a++);

Therefore, it sees *(a++) as const float, but sum as int; this is because sum is initialised with 0, an integer literal.  We can easily fix this, however, by instead initialising it with T{0}, tying sum's type to the template parameter.  As this will cause return type deduction to determine two conflicting types (int for 0, T for sum), we must also change the first line to return T{0}.  And thus, the end result is:

template <typename T>
constexpr auto doSomeSum(const T* a, const T* b) {
    if (a > b)return T{0};
    auto sum = T{0};
    while (a != b)
        sum += *(a++);
    return sum;
}

Tested with Compiler Explorer and RiSE4Fun's MSVC 2015 online environment (note that the latter doesn't provide any facility to link to individual sessions).  Testing the original code with GCC and Clang demonstrates that both have the same issue, with Clang also emitting an error due to it.


问:
Get int user input in java using delimiters and hasNext?
```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.useDelimiter(", "); // using delimiter ", "

    int i = 1;
    while(in.hasNextInt()){
        i = in.nextInt();
        System.out.println(i);
    }
}
</code>```

I am trying to get the input from console, but this code is
not printing last integer
How can I solve this problem. I don't want to use split and save the result in an array.

答:
You will need to use a regex pattern.

```<code>in.useDelimiter(",?\\s");
</code>```

OR, if it is not necessarily seperated by both spaces and commas (e.g. 1, 4,5465, 5):

```<code>in.useDelimiter("[,\\s]+"); // this is more permissive
</code>```

Body:
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.useDelimiter(", "); // using delimiter ", "

    int i = 1;
    while(in.hasNextInt()){
        i = in.nextInt();
        System.out.println(i);
    }
}

I am trying to get the input from console, but this code is
not printing last integer
How can I solve this problem. I don't want to use split and save the result in an array.

Body:
You will need to use a regex pattern.

in.useDelimiter(",?\\s");

OR, if it is not necessarily seperated by both spaces and commas (e.g. 1, 4,5465, 5):

in.useDelimiter("[,\\s]+"); // this is more permissive


问:
DjangoAdmin: Accesing the parent instance within an Inline admin
I have a Django admin class which declares an inlines iterable. Something like:

```<code>@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    ...
    ...
    inlines = [CategoryModifiersInline,]
    ...
    ...
</code>```

Then I have an Inline admin class like this:

```<code>class CategoryModifiersInline(admin.TabularInline):

    model = Category.modifiers.through
    fk_name = 'category'
    extra = 1

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        qs = Product.objects.filter(is_modifier=True).filter(active=True)
        kwargs['queryset'] = qs
        return super(CategoryModifiersInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
</code>```

Where I filter the queryset for the foreign key based on some business requirement.

This inline is only showed to the user in the change view, that means, when an object of the class Category is created and the user wants to add modifiers to it, never in the add view.

What I want to do, is filtering the foreign key by one of the attributes of the Category model, I mean, I want to access the parent object from the formfield_for_foreignkey method.

Does anyone know a way to achieve that?

答:
Well I found a similar question here in StackOverflow, and used the method described there to solve it.

It uses the parent_model attribute from inlines, and the resolve method from django.core.urlresolvers to get the instance based in the url.

Here's the code:

```<code>    def get_object(self, request):
        resolved = resolve(request.path_info)
        if resolved.args:
             return self.parent_model.objects.get(pk=resolved.args[0])
        return None
</code>```

Then I would call the get_object method inside of my formfield_from_foreignkey method to get the instance of the object I want to use as a filter.

Hope it helps!

Body:
I have a Django admin class which declares an inlines iterable. Something like:

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    ...
    ...
    inlines = [CategoryModifiersInline,]
    ...
    ...

Then I have an Inline admin class like this:

class CategoryModifiersInline(admin.TabularInline):

    model = Category.modifiers.through
    fk_name = 'category'
    extra = 1

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        qs = Product.objects.filter(is_modifier=True).filter(active=True)
        kwargs['queryset'] = qs
        return super(CategoryModifiersInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

Where I filter the queryset for the foreign key based on some business requirement.

This inline is only showed to the user in the change view, that means, when an object of the class Category is created and the user wants to add modifiers to it, never in the add view.

What I want to do, is filtering the foreign key by one of the attributes of the Category model, I mean, I want to access the parent object from the formfield_for_foreignkey method.

Does anyone know a way to achieve that?

Body:
Well I found a similar question here in StackOverflow, and used the method described there to solve it.

It uses the parent_model attribute from inlines, and the resolve method from django.core.urlresolvers to get the instance based in the url.

Here's the code:

    def get_object(self, request):
        resolved = resolve(request.path_info)
        if resolved.args:
             return self.parent_model.objects.get(pk=resolved.args[0])
        return None

Then I would call the get_object method inside of my formfield_from_foreignkey method to get the instance of the object I want to use as a filter.

Hope it helps!


问:
simple dynamic allocation question
What is the difference between this:-

```<code>width = new int;
</code>```

And this:-

```<code>int width;
</code>```

i.e. of what use is the dynamic allocation in the first code?

答:
The first one allocates space for the integer on heap and allocates space to hold the pointer on stack. It also initializes width to 0. Space allocated on heap has to be de-allocated by the programmer (extra burden). This space on heap can be accessed from anywhere as long as pointer to it is available and the memory is not freed.

Second declaration just allocates space on stack and is freed automatically when the variable goes out of scope. The value of width is garbage.

Title: simple dynamic allocation question

Body:
What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?


问:
Mapbox GL JS: zoom to filtered polygon?
I am using Mapbox GL JS to display a polygon layer. I would to allow the user to choose a name from a dropdown, and then highlight and zoom to the matching polygon.

I already know how to highlight the matching polygon using map.setFilter, but I don't know how to zoom to the bounds of the matching polygon. This is my current code:

```<code>map.addLayer({
    'id': 'polygon_hover',
    'source': 'mysource',
    'source-layer': 'mylayer',
    'type': 'fill',
    'paint': {
        'fill-color': 'red',
        "fill-opacity": 0.6
    },
    "filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
    // get details of name from select event
    map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
    // Get bounds of filtered polygon somehow?
    // var bounds = ??;
    // map.fitBounds(bounds);
});
</code>```

I have examined the Mapbox example of zooming to bounds, but it assumes that you already know what the bounds are.

Is there any way it's possible to get the bounds of the polygon matching a map filter in Mapbox?

答:
I found a solution to your problem. Leaflet has a polygon Class which takes an Array of polygon coordinates and has a function called getBounds() that returns south west and north east bounds. However, Leaflet doesn't follow the convention of LngLat, its format is LatLng. Therefore, you have to switch it. I took an example out from Mapbox Show drawn polygon area, and added exactly what you're looking for.

```<code>var polygon = data.features[0].geometry.coordinates;
var fit = new L.Polygon(polygon).getBounds();
var southWest = new mapboxgl.LngLat(fit['_southWest']['lat'], fit['_southWest']['lng']);
var northEast = new mapboxgl.LngLat(fit['_northEast']['lat'], fit['_northEast']['lng']);
var center = new mapboxgl.LngLatBounds(southWest, northEast).getCenter();
// map.flyTo({center: center, zoom: 10});
map.fitBounds(new mapboxgl.LngLatBounds(southWest, northEast));
</code>```

Title: Mapbox GL JS: zoom to filtered polygon?

Body:
I am using Mapbox GL JS to display a polygon layer. I would to allow the user to choose a name from a dropdown, and then highlight and zoom to the matching polygon.

I already know how to highlight the matching polygon using map.setFilter, but I don't know how to zoom to the bounds of the matching polygon. This is my current code:

map.addLayer({
    'id': 'polygon_hover',
    'source': 'mysource',
    'source-layer': 'mylayer',
    'type': 'fill',
    'paint': {
        'fill-color': 'red',
        "fill-opacity": 0.6
    },
    "filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
    // get details of name from select event
    map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
    // Get bounds of filtered polygon somehow?
    // var bounds = ??;
    // map.fitBounds(bounds);
});

I have examined the Mapbox example of zooming to bounds, but it assumes that you already know what the bounds are.

Is there any way it's possible to get the bounds of the polygon matching a map filter in Mapbox?

Body:
I found a solution to your problem. Leaflet has a polygon Class which takes an Array of polygon coordinates and has a function called getBounds() that returns south west and north east bounds. However, Leaflet doesn't follow the convention of LngLat, its format is LatLng. Therefore, you have to switch it. I took an example out from Mapbox Show drawn polygon area, and added exactly what you're looking for.

var polygon = data.features[0].geometry.coordinates;
var fit = new L.Polygon(polygon).getBounds();
var southWest = new mapboxgl.LngLat(fit['_southWest']['lat'], fit['_southWest']['lng']);
var northEast = new mapboxgl.LngLat(fit['_northEast']['lat'], fit['_northEast']['lng']);
var center = new mapboxgl.LngLatBounds(southWest, northEast).getCenter();
// map.flyTo({center: center, zoom: 10});
map.fitBounds(new mapboxgl.LngLatBounds(southWest, northEast));


问:
Include font from resource folder
I am trying to have a label in my WPF-Window that has a special font that is probably not installed on all computers.

This is currently my xaml-code for the label:

```<code><Label x:Name="ping" Content="00" FontFamily="pack://application:,,,/resources/#visitor" HorizontalAlignment="Left" Margin="165,10,0,0" VerticalAlignment="Top"/>
</code>```

And here is my project hierarchy:

But why doesn't the font appear in the application/on the label?

答:
Sorry to drag up an old thread, but I found the solution to this. While the font filename is visitor1, FontFamily doesn't look for this and instead looks for the font name. Open the font file and you'll see the name is actually "Visitor TT1 BRK". Use this in your code and it will work:</p>

```<code>FontFamily="CustomFonts\#Visitor TT1 BRK"
</code>```

Title: Include font from resource folder

Body:
I am trying to have a label in my WPF-Window that has a special font that is probably not installed on all computers.

This is currently my xaml-code for the label:

And here is my project hierarchy:

But why doesn't the font appear in the application/on the label?

Body:
Sorry to drag up an old thread, but I found the solution to this. While the font filename is visitor1, FontFamily doesn't look for this and instead looks for the font name. Open the font file and you'll see the name is actually "Visitor TT1 BRK". Use this in your code and it will work:

FontFamily="CustomFonts\#Visitor TT1 BRK"