问:
Incorrect serialization with symfony serializer
I am trying to serialize my Entity to json using symfony/serializer.
I want to get something like

```<code>  {
    "id" : "string",
    "name" : "name here",
    "admin": "admin_id"
  }
</code>```

But I always end up with complete tree - resulting json contains all related entities with their relationships. I believe that it must be trivial task with symfony/serializer and obviously doing something wrong, but what?

CarbonNormalizer simply returns string representation of nesbot/carbon object.

Here is my controller:

```<code>    $data=$this->em->getRepository('Cpa:Cpa')->findAll();
    $encoder = new JsonEncoder();
    $normalizer = new GetSetMethodNormalizer();//object -same
    $dateTimeNormalizer = new CarbonNormalizer();
    $normalizer->setCircularReferenceHandler(function ($object) {
        return $object->getId();
    });
    $this->serializer = new Serializer([$dateTimeNormalizer, $normalizer], [$encoder]);

    $data = $this->serializer->serialize($data, 'json', ['groups' => ['show'], 'enable_max_depth' => true]);
    return new JsonResponse($data, $code, [], true);
</code>```

And my entity:

```<code><?php

namespace Domain\Cpa\Models;

use Domain\Offer\Models\CpaOffer;
use Domain\User\Models\User;
use Ramsey\Uuid\Uuid;

class Cpa
{
/** @var  string */
private $id;

/** @var  string */
private $name;

/** @var  User */
private $admin;

/** @var  CpaOffer[] */
private $offers;

/**
 * Cpa constructor.
 * @param string $name
 * @param User $admin
 */
public function __construct($name, User $admin)
{
    $this->id = Uuid::uuid4()->toString();
    $this->name = $name;
    $this->admin = $admin;
    $this->offers = [];
}

/**
 * @return string
 */
public function getId(): string
{
    return $this->id;
}

/**
 * @return string
 */
public function getName(): string
{
    return $this->name;
}

/**
 * @return User
 */
public function getAdmin(): User
{
    return $this->admin;
}

/**
 * @return CpaOffer[]
 */
public function getOffers()//: array
{
    return $this->offers;
}
</code>```

}

serialization.yml

```<code>Domain\Cpa\Models\Cpa:
 attributes:
   id:
    groups: ['show']
   name:
    groups: ['show']
   admin:
    groups: ['show']
</code>```

答:
To use groups, you need to initialize the ClassMetadataFactory too:

```<code>// Don't forget to add the new use statements
// ...
$normalizer = new GetSetMethodNormalizer(
  new ClassMetadataFactory(
    new YamlFileLoader('/the/path/to/yourfile.yaml')
  )
);
// ...
</code>```

You must also fix the indentation of your YAML file:

```<code>'Domain\Cpa\Models\Cpa':
  attributes:
    id:
      groups: ['show']
    name:
      groups: ['show']
    admin:
      groups: ['show']
</code>```

Body:
I am trying to serialize my Entity to json using symfony/serializer.
I want to get something like

  {
    "id" : "string",
    "name" : "name here",
    "admin": "admin_id"
  }

But I always end up with complete tree - resulting json contains all related entities with their relationships. I believe that it must be trivial task with symfony/serializer and obviously doing something wrong, but what?

CarbonNormalizer simply returns string representation of nesbot/carbon object.

Here is my controller:

    $data=$this->em->getRepository('Cpa:Cpa')->findAll();
    $encoder = new JsonEncoder();
    $normalizer = new GetSetMethodNormalizer();//object -same
    $dateTimeNormalizer = new CarbonNormalizer();
    $normalizer->setCircularReferenceHandler(function ($object) {
        return $object->getId();
    });
    $this->serializer = new Serializer([$dateTimeNormalizer, $normalizer], [$encoder]);

    $data = $this->serializer->serialize($data, 'json', ['groups' => ['show'], 'enable_max_depth' => true]);
    return new JsonResponse($data, $code, [], true);

And my entity:

<?php

namespace Domain\Cpa\Models;

use Domain\Offer\Models\CpaOffer;
use Domain\User\Models\User;
use Ramsey\Uuid\Uuid;

class Cpa
{
/** @var  string */
private $id;

/** @var  string */
private $name;

/** @var  User */
private $admin;

/** @var  CpaOffer[] */
private $offers;

/**
 * Cpa constructor.
 * @param string $name
 * @param User $admin
 */
public function __construct($name, User $admin)
{
    $this->id = Uuid::uuid4()->toString();
    $this->name = $name;
    $this->admin = $admin;
    $this->offers = [];
}

/**
 * @return string
 */
public function getId(): string
{
    return $this->id;
}

/**
 * @return string
 */
public function getName(): string
{
    return $this->name;
}

/**
 * @return User
 */
public function getAdmin(): User
{
    return $this->admin;
}

/**
 * @return CpaOffer[]
 */
public function getOffers()//: array
{
    return $this->offers;
}

}

serialization.yml

Domain\Cpa\Models\Cpa:
 attributes:
   id:
    groups: ['show']
   name:
    groups: ['show']
   admin:
    groups: ['show']

Body:
To use groups, you need to initialize the ClassMetadataFactory too:

// Don't forget to add the new use statements
// ...
$normalizer = new GetSetMethodNormalizer(
  new ClassMetadataFactory(
    new YamlFileLoader('/the/path/to/yourfile.yaml')
  )
);
// ...

You must also fix the indentation of your YAML file:

'Domain\Cpa\Models\Cpa':
  attributes:
    id:
      groups: ['show']
    name:
      groups: ['show']
    admin:
      groups: ['show']


来源: stackexchange

问:
Not getting first character after an attempt to downcast an object in java using charAt();
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

```<code>String name = "Mike";
</code>```

if I try the charAt() method it works fine using the above code.

```<code>name.charAt(0);
</code>```

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

```<code>Object obj = (String) name;

obj ==> "Mike"; // is what we get
</code>```

But if I use the method:

```<code>obj.charAt(0);
</code>```

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?

答: obj is a Object not a String so that it does not have the charAt() method. If you already know your object is type of String then you can cast it ((String) obj).charAt(0) or you can using: obj.toString().charAt(0)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

String name = "Mike";

if I try the charAt() method it works fine using the above code.

name.charAt(0);

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

Object obj = (String) name;

obj ==> "Mike"; // is what we get

But if I use the method:

obj.charAt(0);

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?


问:
Google Analytics Sampling despite low sessions
I'm using Google Analytics Reporting API but I get sampled results even though the sessions in the specified date range are much less than the 500K limit. I have only ~4K sessions in a month.

I have also set "samplingLevel" as "LARGE".

Here's the Python query:

```<code>    response=analytics.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":myViewID,
      "dateRanges":[
        {
          "startDate":"2017-05-01",
          "endDate":"2017-05-30"
        }],
    "samplingLevel":"LARGE",
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"

        },
        {
          "name":"ga:city",
        }
        ]
      }]
  }
).execute()
</code>```

As you can see below the sample space is 4365 sessions, much lesser than the 500K limit

```<code>response.get('reports', [])[0].get('data',[]).get('samplesReadCounts',[])
Out[31]: [u'2051']

response.get('reports', [])[0].get('data',[]).get('samplingSpaceSizes',[])
Out[32]: [u'4365']
</code>```

Breaking the request into a smaller date range doesn't help either. I tried this using the GoogleAnalyticsR library in R with anti_sample=TRUE.

```<code>    > web_data <- google_analytics_4(view_id,
+                                 date_range = c("2017-05-01", "2017-05-30"),
+                                 dimensions = c("city","browser"),
+                                 metrics = c("hits"),
+                                samplingLevel="LARGE",
+                                 anti_sample = TRUE)
2017-06-04 11:54:51> anti_sample set to TRUE. Mitigating sampling via multiple API calls.
2017-06-04 11:54:51> Finding how much sampling in data request...
2017-06-04 11:54:52> Downloaded [10] rows from a total of [15].
2017-06-04 11:54:52> Data is sampled, based on 47% of sessions.
2017-06-04 11:54:52> Finding number of sessions for anti-sample calculations...
2017-06-04 11:54:53> Downloaded [30] rows from a total of [30].
2017-06-04 11:54:53> Calculated [3] batches are needed to download approx. [18] rows unsampled.
2017-06-04 11:54:53> Anti-sample call covering 14 days: 2017-05-01, 2017-05-14
2017-06-04 11:54:54> Downloaded [7] rows from a total of [7].
2017-06-04 11:54:54> Data is sampled, based on 53.2% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 9 days: 2017-05-15, 2017-05-23
2017-06-04 11:54:54> Downloaded [4] rows from a total of [4].
2017-06-04 11:54:54> Data is sampled, based on 55.7% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 7 days: 2017-05-24, 2017-05-30
2017-06-04 11:54:55> Downloaded [10] rows from a total of [10].
2017-06-04 11:54:55> Data is sampled, based on 52.3% of sessions.
2017-06-04 11:54:55> Anti-sampling failed
Joining, by = c("city", "browser")
Joining, by = c("city", "browser")
2017-06-04 11:54:55> Finished unsampled data request, total rows [13]
</code>```

When I check for the same data in a custom request, I see similar sampling

Any idea why I get sampled results even thought the session count is much less than the limit?

答: You have only 4k sessions in that View... but maybe that view is using filters... Check how much traffic you have in that property by looking at a view without filters.... The 500k sessions is at property Level not at view level. </p>

Body:
I'm using Google Analytics Reporting API but I get sampled results even though the sessions in the specified date range are much less than the 500K limit. I have only ~4K sessions in a month.

I have also set "samplingLevel" as "LARGE".

Here's the Python query:

    response=analytics.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":myViewID,
      "dateRanges":[
        {
          "startDate":"2017-05-01",
          "endDate":"2017-05-30"
        }],
    "samplingLevel":"LARGE",
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"

        },
        {
          "name":"ga:city",
        }
        ]
      }]
  }
).execute()

As you can see below the sample space is 4365 sessions, much lesser than the 500K limit

response.get('reports', [])[0].get('data',[]).get('samplesReadCounts',[])
Out[31]: [u'2051']

response.get('reports', [])[0].get('data',[]).get('samplingSpaceSizes',[])
Out[32]: [u'4365']

Breaking the request into a smaller date range doesn't help either. I tried this using the GoogleAnalyticsR library in R with anti_sample=TRUE.

    > web_data <- google_analytics_4(view_id,
+                                 date_range = c("2017-05-01", "2017-05-30"),
+                                 dimensions = c("city","browser"),
+                                 metrics = c("hits"),
+                                samplingLevel="LARGE",
+                                 anti_sample = TRUE)
2017-06-04 11:54:51> anti_sample set to TRUE. Mitigating sampling via multiple API calls.
2017-06-04 11:54:51> Finding how much sampling in data request...
2017-06-04 11:54:52> Downloaded [10] rows from a total of [15].
2017-06-04 11:54:52> Data is sampled, based on 47% of sessions.
2017-06-04 11:54:52> Finding number of sessions for anti-sample calculations...
2017-06-04 11:54:53> Downloaded [30] rows from a total of [30].
2017-06-04 11:54:53> Calculated [3] batches are needed to download approx. [18] rows unsampled.
2017-06-04 11:54:53> Anti-sample call covering 14 days: 2017-05-01, 2017-05-14
2017-06-04 11:54:54> Downloaded [7] rows from a total of [7].
2017-06-04 11:54:54> Data is sampled, based on 53.2% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 9 days: 2017-05-15, 2017-05-23
2017-06-04 11:54:54> Downloaded [4] rows from a total of [4].
2017-06-04 11:54:54> Data is sampled, based on 55.7% of sessions.
2017-06-04 11:54:54> Anti-sampling failed
2017-06-04 11:54:54> Anti-sample call covering 7 days: 2017-05-24, 2017-05-30
2017-06-04 11:54:55> Downloaded [10] rows from a total of [10].
2017-06-04 11:54:55> Data is sampled, based on 52.3% of sessions.
2017-06-04 11:54:55> Anti-sampling failed
Joining, by = c("city", "browser")
Joining, by = c("city", "browser")
2017-06-04 11:54:55> Finished unsampled data request, total rows [13]

When I check for the same data in a custom request, I see similar sampling

Any idea why I get sampled results even thought the session count is much less than the limit?


问:
OpenMQ and JMX - Is it possible to query for messages?
I am able to query for queues by invoking a GET_DESTINATIONS operation using JMX. With that I will receive the queue info (attributes).
I would like now to query the messages that are stored in this queue, is that possible? Could someone give me some direction?

I have already tried using this code

```<code>ConnectionFactory connectionFactory = new
   com.sun.messaging.QueueConnectionFactory();

  Connection connection = connectionFactory.createConnection();
  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Queue myQueue = session.createQueue(string);

  QueueBrowser browser = session.createBrowser(myQueue);
  Enumeration msgs = browser.getEnumeration();

  if (!msgs.hasMoreElements()) {
   System.out.println("No messages in queue");
  } else {
   while (msgs.hasMoreElements()) {
    Message tempMsg = (Message) msgs.nextElement();
    System.out.println("Message: " + tempMsg);
   }
  }

  connection.close();
</code>```

But for some reason O can't access the same queue as using JMX. I didn't made any research on that because I want to use JMX as the access standard.

I am still trying to find any JMX operation that could help me, but I am not finding anything that could help me.

Could you please give me some hints what can I look for?

thank you,
Oscar

Edit: just to let you know: I don't want to consume the queues, I want a similar behavior to the Browser, in which I can read the messages without removing them from the queue.

答:
```<code>QueueBrowser browser = null;

try{
  Queue myQueue = session.createQueue(getName());

  //Create the browser and session to be able to iterate
  browser = session.createBrowser(myQueue);
  Enumeration msgs = browser.getEnumeration();
</code>```

This code will give you the messages, then just iterate through it and you can get get infos about the message and its content

ContentLicense: CC BY-SA 2.5

Body:
I am able to query for queues by invoking a GET_DESTINATIONS operation using JMX. With that I will receive the queue info (attributes).
I would like now to query the messages that are stored in this queue, is that possible? Could someone give me some direction?

I have already tried using this code

ConnectionFactory connectionFactory = new
   com.sun.messaging.QueueConnectionFactory();

  Connection connection = connectionFactory.createConnection();
  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Queue myQueue = session.createQueue(string);

  QueueBrowser browser = session.createBrowser(myQueue);
  Enumeration msgs = browser.getEnumeration();

  if (!msgs.hasMoreElements()) {
   System.out.println("No messages in queue");
  } else {
   while (msgs.hasMoreElements()) {
    Message tempMsg = (Message) msgs.nextElement();
    System.out.println("Message: " + tempMsg);
   }
  }

  connection.close();

But for some reason O can't access the same queue as using JMX. I didn't made any research on that because I want to use JMX as the access standard.

I am still trying to find any JMX operation that could help me, but I am not finding anything that could help me.

Could you please give me some hints what can I look for?

thank you,
Oscar

Edit: just to let you know: I don't want to consume the queues, I want a similar behavior to the Browser, in which I can read the messages without removing them from the queue.

Body:
QueueBrowser browser = null;

try{
  Queue myQueue = session.createQueue(getName());

  //Create the browser and session to be able to iterate
  browser = session.createBrowser(myQueue);
  Enumeration msgs = browser.getEnumeration();

This code will give you the messages, then just iterate through it and you can get get infos about the message and its content


问:
How to use logical indexing on multiple criteria
I have a table that has a column containing values between 1 and 20. I want to filter the table such that I can show only certain discrete values, i.e. 3, 10, 12, and 19. The problem is writing this is cumbersome, especially since I want to write other criteria for filtering too.:

```<code>i = tb.subn==3 | tb.subn==10 | tb.subn==12 | tb.subn==19
</code>```

If I use i = tb.subn==[3 10 12 19] then I get a :x4 boolean matrix. How can I get that into just one column?

If it were &, I suppose I could use prod(tb.subn==[3 10 12 19],2) but I can't figure out or.

Thanks.

答: You can use ismember(tb.subn, [3, 10, 12, 19])

Body:
I have a table that has a column containing values between 1 and 20. I want to filter the table such that I can show only certain discrete values, i.e. 3, 10, 12, and 19. The problem is writing this is cumbersome, especially since I want to write other criteria for filtering too.:

i = tb.subn==3 | tb.subn==10 | tb.subn==12 | tb.subn==19

If I use i = tb.subn==[3 10 12 19] then I get a :x4 boolean matrix. How can I get that into just one column?

If it were &, I suppose I could use prod(tb.subn==[3 10 12 19],2) but I can't figure out or.

Thanks.


问:
Is this a bug: stored procedure runs fine without parameters, causes error when parameters are added?
I have a stored procedure created in MySQL DB. This database is accessed as linked server through Microsoft SQL Server 2012 using Microsoft SQL Server Management Studio. The provider selected while creating linked server is "Microsoft OLE DB Provider for ODBC Drivers".

When I run following as text from Report builder 3.0 it runs fine and fetch data.

```<code>EXEC('CALL storedProcedureName(''string1'', ''string2'', ''string3'')') AT LinkedServerName;
</code>```

But when I try to replace string1, string2, string3 with parameter name parameter1, parameter2, parameter3 as:

```<code>EXEC('CALL storedProcedureName(@parameter1, @parameter2, @parameter3)') AT LinkedServerName;
</code>```

I get error:

Could not execute statement on remote server 'LinkedServerName'.

  (Microsoft SQL Server, Error: 7215)

And when I try:

```<code>EXEC('CALL storedProcedureName('@parameter1', '@parameter2', '@parameter3')') AT LinkedServerName;
</code>```

I get the prompt to enter values for parameter1, parameter2, parameter3. But when I enter the values and click ok, I get error:

Incorrect syntax near '@parameter1'. (Microsoft SQL Server, Error: 102)

Question: Am I missing something in syntax or is this a bug?

The linked server has:

"RPC" and "RPC out" set to True.

And the OLEDB provider has:

Enabled allow inprocess

Enabled dynamic parameter

答:
I believe you have to call it like the below.  So params become strings wrapped in single quotes:</p>

```<code>EXEC('CALL storedProcedureName('''+@parameter1+''', '''+@parameter2+''', '''+@parameter3+''')') AT LinkedServerName;
</code>```

Body:
I have a stored procedure created in MySQL DB. This database is accessed as linked server through Microsoft SQL Server 2012 using Microsoft SQL Server Management Studio. The provider selected while creating linked server is "Microsoft OLE DB Provider for ODBC Drivers".

When I run following as text from Report builder 3.0 it runs fine and fetch data.

EXEC('CALL storedProcedureName(''string1'', ''string2'', ''string3'')') AT LinkedServerName;

But when I try to replace string1, string2, string3 with parameter name parameter1, parameter2, parameter3 as:

EXEC('CALL storedProcedureName(@parameter1, @parameter2, @parameter3)') AT LinkedServerName;

I get error:

Could not execute statement on remote server 'LinkedServerName'.

  (Microsoft SQL Server, Error: 7215)

And when I try:

EXEC('CALL storedProcedureName('@parameter1', '@parameter2', '@parameter3')') AT LinkedServerName;

I get the prompt to enter values for parameter1, parameter2, parameter3. But when I enter the values and click ok, I get error:

Incorrect syntax near '@parameter1'. (Microsoft SQL Server, Error: 102)

Question: Am I missing something in syntax or is this a bug?

The linked server has:

"RPC" and "RPC out" set to True.

And the OLEDB provider has:

Enabled allow inprocess

Enabled dynamic parameter

Body:
I believe you have to call it like the below.  So params become strings wrapped in single quotes:

EXEC('CALL storedProcedureName('''+@parameter1+''', '''+@parameter2+''', '''+@parameter3+''')') AT LinkedServerName;


问:
php http post response for web hook
I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.

```<code>{
  "type": "ping"
}
</code>```

I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).

答:
The response code is in the response header, not in the content.

PHP defaults to a response code of 200, so if you don't mess with it at all, you should be good.

If you want to set a different response code (202 for example), just call:

```<code>http_response_code(202);
</code>```

Or set the full header yourself:

```<code>header('HTTP/1.1 202 Accepted');
</code>```

Title: php http post response for web hook

Body:
I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.

{
  "type": "ping"
}

I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).

Body:
The response code is in the response header, not in the content.

PHP defaults to a response code of 200, so if you don't mess with it at all, you should be good.

If you want to set a different response code (202 for example), just call:

http_response_code(202);

Or set the full header yourself:

header('HTTP/1.1 202 Accepted');


问:
SSIS reading LF as terminator when its set as CRLF
using SSIS 2012. My flat file connection manager I have a delimited file where the row delimiter is set to CRLF, but when it processes the file, I have a text column that has an LF in it. This is causing it to read that as a row terminator causing it fail. Any ideas?

答: thank u for all the suggestions. turned out that the vendor had changed the encoding of the file from Ascii to unicode. changing the the package to read the correct encoding did the trick.</p>


问:
Why exactly is this syntax error happening in C++ for me..?
why exactly is this happening?

```<code>cout << "Your choice of numbers is...?" << endl;
</code>```

error C2143: syntax error : missing
  ';' before '<<'

答:
Hi do you include iostream and use namespace</p>

```<code>#include <iostream>
using namespace std;
</code>```

Body:
why exactly is this happening?

cout << "Your choice of numbers is...?" << endl;

error C2143: syntax error : missing
  ';' before '<<'

Body:
Hi do you include iostream and use namespace

#include <iostream>
using namespace std;


问:
Lucene and EntityGraphs
I recently started using Lucene in combination with Hibernate and JPA and wondered how to load lazy relations.
I am used to using JPAs EntityGraphs but I couldn't find anything in their documentation about lazy collections.

So what is the best way to handle loading lazy collections?

Thanks!

答:
Map your entities to the Lucene index using Hibernate Search.

When you'll make any CRUD operation on the RDBMS via Hibernate ORM, it will keep the Lucene index in synch.

More importantly, it gives you an API to run Lucene Queries with all the benefits of Lucene, but return managed entities loaded from the RDBMS via Hibernate ORM.

This has several benefits:

the entity will have lazy collections

loaded within the same transaction

easier to process than a Lucene query hit

you express the Query using Lucene APIs (no loss in flexibility)

the Query is also a JPA Query so it can be treated as such (easy pagination, framework integration)

...

Title: Lucene and EntityGraphs


问:
DB::raw not using model connection
I'm trying to get a count of model rows from a different database. I have both databases configured fine. My problem is that it doesn't seem to be using the same connection when attempting to perform raw queries.

Code:

```<code>class Lead extends Model
{
    protected $connection = 'infused2';
    public $timestamps = false;

    function campaignCount(Campaign $campaign)
    {
        $leads = $this->join('lead_history', 'leads.id', '=', 'lead_history.id_lead')->join('assignments', 'leads.id', '=', 'assignments.id_lead');

        if (!empty($campaign->lead_date_created_operand)) {
            if ($campaign->leadDateCreatedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateCreatedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%m-%Y')"));
            }
        }

        if (!empty($campaign->lead_date_assigned_operand)) {
            if ($campaign->leadDateAssignedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateAssignedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%m-%Y')"));
            }
        }

        return $leads->count();
    }
}
</code>```

I am getting error Database [mysql] not configured. Why is this happening and how do I make the raw queries use the model connection?

答:
Got it.</p>

```<code>    $query = DB::connection($this->connection)->table($this->getTable());

    if (!empty($campaign->lead_date_created_operand)) {
        $query->join('lead_history', 'lead_history.id_lead', '=', 'leads.id');

        if ($campaign->leadDateCreatedOperand->name == 'day age') {
            $query->whereRaw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_created_value)."), '%d-%m-%Y')");
        }
        else if ($campaign->leadDateCreatedOperand->name == 'month age') {
            $query->whereRaw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_created_value)."), '%m-%Y')");
        }
    }

    if (!empty($campaign->lead_date_assigned_operand)) {
        $query->join('assignments', 'assignments.id_lead', '=', 'leads.id');

        if ($campaign->leadDateAssignedOperand->name == 'day age') {
            $query->whereRaw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_assigned_value)."), '%d-%m-%Y')");
        }
        else if ($campaign->leadDateAssignedOperand->name == 'month age') {
            $query->whereRaw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_assigned_value)."), '%m-%Y')");
        }
    }

    return $query->count();
</code>```

Title: DB::raw not using model connection

Body:
I'm trying to get a count of model rows from a different database. I have both databases configured fine. My problem is that it doesn't seem to be using the same connection when attempting to perform raw queries.

Code:

class Lead extends Model
{
    protected $connection = 'infused2';
    public $timestamps = false;

    function campaignCount(Campaign $campaign)
    {
        $leads = $this->join('lead_history', 'leads.id', '=', 'lead_history.id_lead')->join('assignments', 'leads.id', '=', 'assignments.id_lead');

        if (!empty($campaign->lead_date_created_operand)) {
            if ($campaign->leadDateCreatedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateCreatedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(".strtotime($campaign->lead_date_created_value).", '%m-%Y')"));
            }
        }

        if (!empty($campaign->lead_date_assigned_operand)) {
            if ($campaign->leadDateAssignedOperand->name == 'day age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%d-%m-%Y')"));
            }
            else if ($campaign->leadDateAssignedOperand->name == 'month age') {
                $leads->where(DB::raw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(".strtotime($campaign->lead_date_assigned_value).", '%m-%Y')"));
            }
        }

        return $leads->count();
    }
}

I am getting error Database [mysql] not configured. Why is this happening and how do I make the raw queries use the model connection?

Body:
Got it.

    $query = DB::connection($this->connection)->table($this->getTable());

    if (!empty($campaign->lead_date_created_operand)) {
        $query->join('lead_history', 'lead_history.id_lead', '=', 'leads.id');

        if ($campaign->leadDateCreatedOperand->name == 'day age') {
            $query->whereRaw("date_format(from_unixtime(lead_history.date_created), '%d-%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_created_value)."), '%d-%m-%Y')");
        }
        else if ($campaign->leadDateCreatedOperand->name == 'month age') {
            $query->whereRaw("date_format(from_unixtime(lead_history.date_created), '%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_created_value)."), '%m-%Y')");
        }
    }

    if (!empty($campaign->lead_date_assigned_operand)) {
        $query->join('assignments', 'assignments.id_lead', '=', 'leads.id');

        if ($campaign->leadDateAssignedOperand->name == 'day age') {
            $query->whereRaw("date_format(from_unixtime(assignments.date_assigned), '%d-%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_assigned_value)."), '%d-%m-%Y')");
        }
        else if ($campaign->leadDateAssignedOperand->name == 'month age') {
            $query->whereRaw("date_format(from_unixtime(assignments.date_assigned), '%m-%Y') = date_format(from_unixtime(".strtotime('-'.$campaign->lead_date_assigned_value)."), '%m-%Y')");
        }
    }

    return $query->count();


问:
Nodejs require('this')(that) in Typescript
I'm using @awspilot/dynamodb in a node lambda function, but also using typescript.

A standard nodejs var x = require('x') becomes import * as x from 'x' in typescript no problem - but @awspilot/dynamodb needs the slightly more unusual:

```<code>var $db = new AWS.DynamoDB()
var awspilotDB = require('@awspilot/dynamodb')($db)
</code>```

Is there a typescript-y way of rendering this as an import and still passing the extra parameter?

Thanks,

D

答:
require('@awspilot/dynamodb') is returning a function. Therefore the following should work fine:

```<code>import * as DynamodbFactory from '@awspilot/dynamodb'
const awspilotDB = DynamodbFactory($db)
</code>```

You can, of course, choose whatever name you like for DynamodbFactory.

Alternatively you can also use the require function with TypeScript as described here

Body:
I'm using @awspilot/dynamodb in a node lambda function, but also using typescript.

A standard nodejs var x = require('x') becomes import * as x from 'x' in typescript no problem - but @awspilot/dynamodb needs the slightly more unusual:

var $db = new AWS.DynamoDB()
var awspilotDB = require('@awspilot/dynamodb')($db)

Is there a typescript-y way of rendering this as an import and still passing the extra parameter?

Thanks,

D

Body:
require('@awspilot/dynamodb') is returning a function. Therefore the following should work fine:

import * as DynamodbFactory from '@awspilot/dynamodb'
const awspilotDB = DynamodbFactory($db)

You can, of course, choose whatever name you like for DynamodbFactory.

Alternatively you can also use the require function with TypeScript as described here


问:
jest typescript not using __mocks__ for node_modules
I had a functioning Jest/Flow setup for my application.  We switched to TypeScript, and all of my tests broke.  I converted everything over to .ts and .test.ts and fixed all the bugs.  For some reason, none of my __mocks__ are used anymore. ( I had to mock some modules that were failing to automock)

For example, the below code used to mock electron any time it was required, and allow the code to invoke mocked dialogs so i could check that error cases reported errors.  Since i converted to TypeScript, any time the require ("electron") is hit in a test, it fails saying remote is undefined.

ex) aFile.test.ts

```<code>import reportError from "../aFile.ts";
const { dialog } = require ("electron").remote;

describe ("reportError", () =>
{
   test ("creates dialog", () =>
   {
      const title   = "foo";
      const message = "bar";
      reportError (title, message);

      expect (dialog.showErrorBox).toHaveBeenLastCalledWith (title, message);
   });
});
</code>```

ex) aFile.ts

```<code>const { dialog } = require ("electron").remote;
export default function reportError (title: string, message: string)
{
   dialog.showErrorBox (title, message);
}
</code>```

ex) __mocks__/electron.js  (sibling of node_modules)

module.exports = { remote: { dialog: { showErrorBox: jest.fn () } } };

I know for certain the mock isn't being used, because when i add the following to any failing .test.ts file, it starts to pass:

jest.mock ("electron", () => { return { remote: { dialog: { showErrorBox: jest.fn () } } } });

Why isn't TypeScript finding my __mocks__?

答:
I used the following workaround to fix this:

create mocks.js:

```<code>jest.mock ("electron", () =>
  {
     return { remote: { dialog: { showErrorBox: jest.fn () } } };
  });
</code>```

in package.json add this to the jest section (path to where your mocks.js is):

```<code>"jest":
{
   "setupFiles": [ "<rootDir>/../mocks.js" ]
},
</code>```

This will globally mock electron, and any other module you declare here, similar to having __mocks__ folder. You could probably put each module in its own file and add to setupFiles array.

Body:
I had a functioning Jest/Flow setup for my application.  We switched to TypeScript, and all of my tests broke.  I converted everything over to .ts and .test.ts and fixed all the bugs.  For some reason, none of my __mocks__ are used anymore. ( I had to mock some modules that were failing to automock)

For example, the below code used to mock electron any time it was required, and allow the code to invoke mocked dialogs so i could check that error cases reported errors.  Since i converted to TypeScript, any time the require ("electron") is hit in a test, it fails saying remote is undefined.

ex) aFile.test.ts

import reportError from "../aFile.ts";
const { dialog } = require ("electron").remote;

describe ("reportError", () =>
{
   test ("creates dialog", () =>
   {
      const title   = "foo";
      const message = "bar";
      reportError (title, message);

      expect (dialog.showErrorBox).toHaveBeenLastCalledWith (title, message);
   });
});

ex) aFile.ts

const { dialog } = require ("electron").remote;
export default function reportError (title: string, message: string)
{
   dialog.showErrorBox (title, message);
}

ex) __mocks__/electron.js  (sibling of node_modules)

module.exports = { remote: { dialog: { showErrorBox: jest.fn () } } };

I know for certain the mock isn't being used, because when i add the following to any failing .test.ts file, it starts to pass:

jest.mock ("electron", () => { return { remote: { dialog: { showErrorBox: jest.fn () } } } });

Why isn't TypeScript finding my __mocks__?

Body:
I used the following workaround to fix this:

create mocks.js:

jest.mock ("electron", () =>
  {
     return { remote: { dialog: { showErrorBox: jest.fn () } } };
  });

in package.json add this to the jest section (path to where your mocks.js is):

"jest":
{
   "setupFiles": [ "<rootDir>/../mocks.js" ]
},

This will globally mock electron, and any other module you declare here, similar to having __mocks__ folder. You could probably put each module in its own file and add to setupFiles array.


问:
SQL tag list and tag filtering
I have a SQL database in which I store users and tags associated to users (many to many relationship). I have the classic schema with users table, tags table and the "bridge" table usertag which links users with tags:

```<code>users table:
    +---------+---------+
    | Id      |  Name   |
    +---------+---------+
    | 1       | Alice   |
    | 2       | Bob     |
    | 3       | Carl    |
    | 4       | David   |
    | 5       | Eve     |
    +---------+---------+

tags table:
    +---------+---------+
    | Id      | Name    |
    +---------+---------+
    | 10      | Red     |
    | 20      | Green   |
    | 30      | Blue    |
    +---------+---------+

usertag table:
    +---------+---------+
    | UserId  |  TagId  |
    +---------+---------+
    | 2       | 10      |
    | 2       | 20      |
    | 1       | 30      |
    | 4       | 20      |
    | 4       | 10      |
    | 4       | 30      |
    | 5       | 10      |
    +---------+---------+
</code>```

Now, I made a query to retrieve all the users and their tags as a comma separated field, using the GROUP_CONCAT() function:

```<code>SELECT u.*, GROUP_CONCAT(ut.tagid) as tags FROM users as u LEFT JOIN usertag as ut ON u.id = ut.userid GROUP BY u.id
</code>```

which gives me the correct output:

```<code>output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 1       | Alice   | 30       |
    | 2       | Bob     | 10,20    |
    | 3       | Carl    | (null)   |
    | 4       | David   | 10,30,20 |
    | 5       | Eve     | 10       |
    +---------+---------+----------+
</code>```

The problem is that now I want to implement tag filtering on top of that, i.e. being able to query the users by tag (or multiple tags). The filter should work using the AND operator.

For example: Get users with tag Red (10) AND Green (20):

```<code>output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,30,20 |
    +---------+---------+----------+
</code>```

Another example: Get users with tag Red (10):

```<code>output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,30,20 |
    | 5       | Eve     | 10       |
    +---------+---------+----------+
</code>```

Another example: Get users with tag Red (10), Green (20) and Blue (30):

```<code>output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 4       | David   | 10,30,20 |
    +---------+---------+----------+
</code>```

How can I implement such query? This question on SO is very similar and it actually works but it doesn't deal with the GROUP_CONCAT() field which is something I'd like to keep as it is

Here the SQL fiddle http://sqlfiddle.com/#!9/291a5c/8

EDIT

One may imagine that this query works:

Retrieve all users with tag Red (10) and Blue (20):

```<code> SELECT u.name, GROUP_CONCAT(ut.tagid)
    FROM users as u
    JOIN usertag as ut ON u.id = ut.userid
   WHERE ut.tagid IN (10,20)
GROUP BY u.id
  HAVING COUNT(DISTINCT ut.tagid) = 2
</code>```

Which gives:

```<code>output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,20    |
    +---------+---------+----------+
</code>```

which username-wise is correct (Bob and David) but the Tags field is missing the tag 30 from David's list!

答:
left join the tags table and include the id's being searched for in the join clause and check for counts in having.

```<code>SELECT u.id,u.name,GROUP_CONCAT(ut.tagid) as tags
FROM users u
LEFT JOIN usertag as ut ON u.id = ut.userid
LEFT JOIN tags t ON t.id=ut.tagid AND t.ID IN (10,20,30) --change this as needed
GROUP BY u.id,u.name
HAVING COUNT(ut.tagid) >= COUNT(t.id) AND COUNT(t.id) = 3 --change this number to the number of tags
</code>```

One more option is to use FIND_IN_SET if there are limited values. For example,

```<code>SELECT * FROM (
SELECT u.*, GROUP_CONCAT(ut.tagid) as tags
FROM users as u
LEFT JOIN usertag as ut ON u.id = ut.userid
GROUP BY u.id
) T
WHERE FIND_IN_SET('10',tags) > 0 AND FIND_IN_SET('20',tags) > 0
</code>```

Title: SQL tag list and tag filtering

Body:
I have a SQL database in which I store users and tags associated to users (many to many relationship). I have the classic schema with users table, tags table and the "bridge" table usertag which links users with tags:

users table:
    +---------+---------+
    | Id      |  Name   |
    +---------+---------+
    | 1       | Alice   |
    | 2       | Bob     |
    | 3       | Carl    |
    | 4       | David   |
    | 5       | Eve     |
    +---------+---------+

tags table:
    +---------+---------+
    | Id      | Name    |
    +---------+---------+
    | 10      | Red     |
    | 20      | Green   |
    | 30      | Blue    |
    +---------+---------+

usertag table:
    +---------+---------+
    | UserId  |  TagId  |
    +---------+---------+
    | 2       | 10      |
    | 2       | 20      |
    | 1       | 30      |
    | 4       | 20      |
    | 4       | 10      |
    | 4       | 30      |
    | 5       | 10      |
    +---------+---------+

Now, I made a query to retrieve all the users and their tags as a comma separated field, using the GROUP_CONCAT() function:

SELECT u.*, GROUP_CONCAT(ut.tagid) as tags FROM users as u LEFT JOIN usertag as ut ON u.id = ut.userid GROUP BY u.id

which gives me the correct output:

output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 1       | Alice   | 30       |
    | 2       | Bob     | 10,20    |
    | 3       | Carl    | (null)   |
    | 4       | David   | 10,30,20 |
    | 5       | Eve     | 10       |
    +---------+---------+----------+

The problem is that now I want to implement tag filtering on top of that, i.e. being able to query the users by tag (or multiple tags). The filter should work using the AND operator.

For example: Get users with tag Red (10) AND Green (20):

output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,30,20 |
    +---------+---------+----------+

Another example: Get users with tag Red (10):

output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,30,20 |
    | 5       | Eve     | 10       |
    +---------+---------+----------+

Another example: Get users with tag Red (10), Green (20) and Blue (30):

output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 4       | David   | 10,30,20 |
    +---------+---------+----------+

How can I implement such query? This question on SO is very similar and it actually works but it doesn't deal with the GROUP_CONCAT() field which is something I'd like to keep as it is

Here the SQL fiddle http://sqlfiddle.com/#!9/291a5c/8

EDIT

One may imagine that this query works:

Retrieve all users with tag Red (10) and Blue (20):

 SELECT u.name, GROUP_CONCAT(ut.tagid)
    FROM users as u
    JOIN usertag as ut ON u.id = ut.userid
   WHERE ut.tagid IN (10,20)
GROUP BY u.id
  HAVING COUNT(DISTINCT ut.tagid) = 2

Which gives:

output:
    +---------+---------+----------+
    | Id      |  Name   | Tags     |
    +---------+---------+----------+
    | 2       | Bob     | 10,20    |
    | 4       | David   | 10,20    |
    +---------+---------+----------+

which username-wise is correct (Bob and David) but the Tags field is missing the tag 30 from David's list!

Body:
left join the tags table and include the id's being searched for in the join clause and check for counts in having.

SELECT u.id,u.name,GROUP_CONCAT(ut.tagid) as tags
FROM users u
LEFT JOIN usertag as ut ON u.id = ut.userid
LEFT JOIN tags t ON t.id=ut.tagid AND t.ID IN (10,20,30) --change this as needed
GROUP BY u.id,u.name
HAVING COUNT(ut.tagid) >= COUNT(t.id) AND COUNT(t.id) = 3 --change this number to the number of tags

One more option is to use FIND_IN_SET if there are limited values. For example,

SELECT * FROM (
SELECT u.*, GROUP_CONCAT(ut.tagid) as tags
FROM users as u
LEFT JOIN usertag as ut ON u.id = ut.userid
GROUP BY u.id
) T
WHERE FIND_IN_SET('10',tags) > 0 AND FIND_IN_SET('20',tags) > 0


问:
have access to a variable after callback is called
There is an existing API that I'd rather not change that gets the connection to a database.  The signature looks like

```<code>getDBConnection(function(error, DBConnection) {
   // do biz logic
});
</code>```

There is another variable that I want to use within getDBConnection

```<code>exports.doSomething = function(foo) {
    getDBConnection(function(error, DBConnection) {
        logger.info(foo);
    });
};
</code>```

But foo is undefined in the getDBConnection callback.  Is there somethign I can do to have access to Foo within getDBConnection?

答:
foo is still in scope, but perhaps it is getting overwritten by some other code before your callback is being invoked. You can explicitly create a new foo scoped only for your callback with an IIFE:

```<code>var foo;
getDBConnection((function(foo) {
    return function(error, DBConnection) {
        // foo = whatever it was
    }
})(foo));
</code>```

Body:
There is an existing API that I'd rather not change that gets the connection to a database.  The signature looks like

getDBConnection(function(error, DBConnection) {
   // do biz logic
});

There is another variable that I want to use within getDBConnection

exports.doSomething = function(foo) {
    getDBConnection(function(error, DBConnection) {
        logger.info(foo);
    });
};

But foo is undefined in the getDBConnection callback.  Is there somethign I can do to have access to Foo within getDBConnection?

Body:
foo is still in scope, but perhaps it is getting overwritten by some other code before your callback is being invoked. You can explicitly create a new foo scoped only for your callback with an IIFE:

var foo;
getDBConnection((function(foo) {
    return function(error, DBConnection) {
        // foo = whatever it was
    }
})(foo));


问:
Excel migrate to database design
I have many tables that exactly mirror Excel sheets.

For example

Excel

```<code>Region  Year    Jan     Feb     Mar     Apr     May     Jun     July    Aug     Sep     Oct     Nov     Dec
North   2008    100     200     400     600     800     900     180     290     720     900     400     120
South   2008    100     300     600     900     899     900     300     900     300     900     100     200
...
</code>```

I would rather not store the above excel sheet in the database .

But people are asking me why?

Why not store it exactly like Excel as the number of rows would be fewer and performance faster?

How do I convince that storing with fewer columns is a better design?

Like the one below:

I am using many RDBMS like Sybase, Oracle, SQL Server, MySQL

```<code>Region  Year    Month   Profit
North   2008    Jan     100
South   2008    Jan     100.
North   2008    Feb     200
South   2008    Mar     400
...
</code>```

I feel the above design is elegant and that's what I have seen every other place I have been, but people at my current assignment want the table to be Excel like.

How do I convince them that mirroring Excel design into database is a bad idea?

答:
I'd want to find out who'll be entering/modifying/querying data, and how they'll perform such operations (eg, writing actual SQL, using Excel as a front-end, some other fill-in-the-black application, etc).

If the users will be writing any SQL I'm guessing you'll have a much easier time selling them on the relational model based on how much coding they'll have to do.  Take for example a search of months where Profit > 350:

```<code>-- excel-like structure

select Region, Year, 'Jan' as Month, Jan as Profit from excel_table where Jan > 350
union all
select Region, Year, 'Feb' as Month, Feb as Profit from excel_table where Feb > 350
union all
select Region, Year, 'Mar' as Month, Mar as Profit from excel_table where Mar > 350
union all
... and on and on and on and on ...

-- relational structure

select Region, Year, Month, Profit
from relation_table
where Profit > 350
</code>```

Another tedious example for the excel_table: adding a new Profit value for each month (as it becomes available).

Once you get them used to writing lots of queries with separate where clauses for each month, you can point out how performance could be degraded if you don't have indices on each 'month' column, which in turn could mean more db space usage, possibly less room in cache for data, and potentially longer times to insert/update/delete data (due to updating more indexes).

The one drawback to the relational model will of course be the display of the data to look like the excel spreadsheet.

If the users will be writing their own code then they'll have to jump through some hoops to build a pivot table (ie, turn a month/profit row into a column).

Then again, this may not be as much of a problem if their front-end/application can handle this for them ... ?

Title: Excel migrate to database design

Body:
I have many tables that exactly mirror Excel sheets.

For example

Excel

Region  Year    Jan     Feb     Mar     Apr     May     Jun     July    Aug     Sep     Oct     Nov     Dec
North   2008    100     200     400     600     800     900     180     290     720     900     400     120
South   2008    100     300     600     900     899     900     300     900     300     900     100     200
...

I would rather not store the above excel sheet in the database .

But people are asking me why?

Why not store it exactly like Excel as the number of rows would be fewer and performance faster?

How do I convince that storing with fewer columns is a better design?

Like the one below:

I am using many RDBMS like Sybase, Oracle, SQL Server, MySQL

Region  Year    Month   Profit
North   2008    Jan     100
South   2008    Jan     100.
North   2008    Feb     200
South   2008    Mar     400
...

I feel the above design is elegant and that's what I have seen every other place I have been, but people at my current assignment want the table to be Excel like.

How do I convince them that mirroring Excel design into database is a bad idea?

Body:
I'd want to find out who'll be entering/modifying/querying data, and how they'll perform such operations (eg, writing actual SQL, using Excel as a front-end, some other fill-in-the-black application, etc).

If the users will be writing any SQL I'm guessing you'll have a much easier time selling them on the relational model based on how much coding they'll have to do.  Take for example a search of months where Profit > 350:

-- excel-like structure

select Region, Year, 'Jan' as Month, Jan as Profit from excel_table where Jan > 350
union all
select Region, Year, 'Feb' as Month, Feb as Profit from excel_table where Feb > 350
union all
select Region, Year, 'Mar' as Month, Mar as Profit from excel_table where Mar > 350
union all
... and on and on and on and on ...

-- relational structure

select Region, Year, Month, Profit
from relation_table
where Profit > 350

Another tedious example for the excel_table: adding a new Profit value for each month (as it becomes available).

Once you get them used to writing lots of queries with separate where clauses for each month, you can point out how performance could be degraded if you don't have indices on each 'month' column, which in turn could mean more db space usage, possibly less room in cache for data, and potentially longer times to insert/update/delete data (due to updating more indexes).

The one drawback to the relational model will of course be the display of the data to look like the excel spreadsheet.

If the users will be writing their own code then they'll have to jump through some hoops to build a pivot table (ie, turn a month/profit row into a column).

Then again, this may not be as much of a problem if their front-end/application can handle this for them ... ?


答:
Proper way to explicitly set 200 (or any other) status code with http_response_code function is just as following (don't echo or json_encode it):

```<code>http_response_code(200);
</code>```

It should force webserver to use 200 status code in it's response. However, webserver could possibly ignore it. To check what response code your webserver sends, use telnet or any REST tool like Postman

Title: php http post response for web hook

Body:
Proper way to explicitly set 200 (or any other) status code with http_response_code function is just as following (don't echo or json_encode it):

http_response_code(200);

It should force webserver to use 200 status code in it's response. However, webserver could possibly ignore it. To check what response code your webserver sends, use telnet or any REST tool like Postman


问:
How to select option in select list using jquery
i have a form that has select element

```<code><select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>
</code>```

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

答:
You can pass an array to the .val() method. For instance:

```<code>$('#adddisplaypage').val(['index', 'tour']);
</code>```

Body:
i have a form that has select element

<select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

Body:
You can pass an array to the .val() method. For instance:

$('#adddisplaypage').val(['index', 'tour']);


问:
node/passportjs how to update homepage with welcome user, after logging in and redirect
So after landing on the home page, click to sign in, redirect home and at the top I want it to now show the 'welcome [user]'. How do i do that? Basically change from 'login here' to 'welcome user and sign out' after logging in.
I want to add this:

```<code>h1.text-center.login-title Welcome #{user.firstName}.
</code>```

To my current html/jade after logging in:

```<code> extends layout
    block content

    body(style='background-color:black')
   p
    a.fade(href="#")
     img.fade(src='http://data.whicdn.com/images/18140107/large.jpg',
  height='150', width='200')

  p
    ul.centered
      li.none
      li Chapter 1
      li Chapter 2
      li Chapter 3
      li Chapter 4
      li Chapter 5
      li Chapter 6
      li Chapter 7
      li Chapter 8
      li Chapter 9
      li Chapter 10
</code>```

答:
This is quite simple to do with Pug. When you render, simply pass the username to pug and handle it like so:

```<code>if user.firstName
    h1.text-center.login-title Welcome #{user.firstName}.
else
    h1.text-center.login-title Please Login
</code>```

Read more here: https://pugjs.org/language/conditionals.html

Body:
So after landing on the home page, click to sign in, redirect home and at the top I want it to now show the 'welcome [user]'. How do i do that? Basically change from 'login here' to 'welcome user and sign out' after logging in.
I want to add this:

h1.text-center.login-title Welcome #{user.firstName}.

To my current html/jade after logging in:

 extends layout
    block content

    body(style='background-color:black')
   p
    a.fade(href="#")
     img.fade(src='http://data.whicdn.com/images/18140107/large.jpg',
  height='150', width='200')

  p
    ul.centered
      li.none
      li Chapter 1
      li Chapter 2
      li Chapter 3
      li Chapter 4
      li Chapter 5
      li Chapter 6
      li Chapter 7
      li Chapter 8
      li Chapter 9
      li Chapter 10

Body:
This is quite simple to do with Pug. When you render, simply pass the username to pug and handle it like so:

if user.firstName
    h1.text-center.login-title Welcome #{user.firstName}.
else
    h1.text-center.login-title Please Login

Read more here: https://pugjs.org/language/conditionals.html


问:
Perl: Don't print any lines that are duplicates
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

```<code>line1
line2
line2
line3
line1
line4
line5
</code>```

The output should be:

```<code>line3
line4
line5
</code>```

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

```<code>line2
line1
</code>```

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

```<code>perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5
</code>```

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

答:
As mentioned above, to filter the file in this way and keep the lines in order you need to either read through the file twice or to store line number information while you read

This one-liner seems the best option

```<code>perl -e '@a = @ARGV; ++$c{$_} while <>; @ARGV = @a; $c{$_} == 1 and print while <>;'  myfile.txt
</code>```

output

```<code>line3
line4
line5
</code>```

This is a slightly shorter alternative, but it uses double the amount of memory to store the file data

```<code>perl -e '@l = <>; ++$c{$_} for @l; $c{$_} == 1 and print for @l;' myfile.txt
</code>```

Body:
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

line1
line2
line2
line3
line1
line4
line5

The output should be:

line3
line4
line5

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

line2
line1

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

Body:
As mentioned above, to filter the file in this way and keep the lines in order you need to either read through the file twice or to store line number information while you read

This one-liner seems the best option

perl -e '@a = @ARGV; ++$c{$_} while <>; @ARGV = @a; $c{$_} == 1 and print while <>;'  myfile.txt

output

line3
line4
line5

This is a slightly shorter alternative, but it uses double the amount of memory to store the file data

perl -e '@l = <>; ++$c{$_} for @l; $c{$_} == 1 and print for @l;' myfile.txt


问:
recursive find for specific text for last n lines
I want to find some specific text in recursive way, I have read this very popular answer:

```<code>grep -rnw '/path/to/somewhere/' -e 'pattern'
</code>```

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

答:
I would use GNU's parallel, bash, and tail:

```<code>my_tail_grep() {
    file="$1"
    pattern="$2"
    N="${3:-100}"  # Optional -- defaults to 100
    res=$(tail -n "$N" "$file" | grep -we "$pattern")
    [[ -n "$res" ]] && echo -e "${file}\n${res}" || :
}

export -f my_tail_grep # Necessary for parallel

find /path -type f | parallel my_tail_grep {} "$pattern" 100
</code>```

Body:
I want to find some specific text in recursive way, I have read this very popular answer:

grep -rnw '/path/to/somewhere/' -e 'pattern'

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

Body:
I would use GNU's parallel, bash, and tail:

my_tail_grep() {
    file="$1"
    pattern="$2"
    N="${3:-100}"  # Optional -- defaults to 100
    res=$(tail -n "$N" "$file" | grep -we "$pattern")
    [[ -n "$res" ]] && echo -e "${file}\n${res}" || :
}

export -f my_tail_grep # Necessary for parallel

find /path -type f | parallel my_tail_grep {} "$pattern" 100


问:
How can I preserve order with an EnumMap in java
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

```<code>HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();
</code>```

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

```<code>EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();
</code>```

答:
Some possibilities:

Use LinkedHashMap and construct an EnumMap from it each time you need one.

As biziclop suggested in a comment, extend EnumMap.

I was going to suggest extending or modifying ContentType to contain mutable static ordering information, which would be horribly hacky but maybe okay for testing.  But I like the above two ideas better.

Body:
I have an EnumMap that I'm using and I will need to keep the order of the items that I'm passing in. I know that when using a HashMap, I can initialize a LinkedHashMap in order to preserve order like so:

HashMap<String, List<String>> contentTypeToIdList = new LinkedHashMap<String, List<String>>();

However, I'd like to use an EnumMap instead. How would I be able to do something like this:

EnumMap<ContentType, List<String>> contentTypeToIdList = new LinkedHashMap<ContentType, List<String>>();


问:
Filter a dom object of input tags
I am building an object from a form that is currently rendered server side. I collect all the check boxes displayed in the image below and I am trying to sort them in a way that all the check boxes under each step (1, 2, 3 etc) is a single object based on the property parentNode.

Currently the document.querySelectorAll('.checkboxes')  fetches all the checkboxes in following format.

```<code>var newObj = [
    {
      name: 'one',
      parentNode: {
        id: 'stepOne'
      }
    },
    {
      name: 'two',
      parentNode: {
        id: 'stepTwo'
      }
    },
    {
      name: 'three',
      parentNode: {
        id: 'stepOne'
      }
    },
]
</code>```

The new object should be:

```<code>var newObj = {
    stepOne: [
      {
        name: 'one',
        parentNode: {
          id: 'stepOne'
        }
      },
      {
        name: 'three',
        parentNode: {
          id: 'stepOne'
        }
      },
    ],
    stepTwo: [
      {
        name: 'two',
        parentNode: {
          id: 'stepTwo'
        }
      },
    ]
}
</code>```

Usually I do something like this:

```<code>let stepOne = function(step) {
  return step.parentNode.getAttribute('id') === 'stepOne';
}

let stepTwo = function(step) {
  return step.parentNode.getAttribute('id') === 'stepTwo';
}

let allTheStepOnes = fetchCheckBoxes.filter(stepOne);
</code>```

But filter doesn't work on dom object and this seems inefficient as well.

答:
Using reduce we can reduce your current array into the new structure.

```<code>return newObj.reduce(function(acc, item) {
</code>```

If acc[item.parentNode.id] has been defined before, retrieve this.  Otherwise set it to an empty array:

```<code>acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
</code>```

Add the item to the array and then return it:

```<code>acc[item.parentNode.id].push(item);
return acc;
</code>```

We set the accumulator as {} to start with.

Snippet to show the workings.

var newObj = [{
  name: 'one',
  parentNode: {
    id: 'stepOne'
  }
}, {
  name: 'two',
  parentNode: {
    id: 'stepTwo'
  }
}, {
  name: 'three',
  parentNode: {
    id: 'stepOne'
  }
}, ];

var newOrder = function(prevList) {
        return prevList.reduce(function(acc, item) {
            acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
            acc[item.parentNode.id].push(item);
            return acc;
        }, {});
    }

console.log(newOrder(newObj));```

Title: Filter a dom object of input tags

Body:
I am building an object from a form that is currently rendered server side. I collect all the check boxes displayed in the image below and I am trying to sort them in a way that all the check boxes under each step (1, 2, 3 etc) is a single object based on the property parentNode.

Currently the document.querySelectorAll('.checkboxes')  fetches all the checkboxes in following format.

var newObj = [
    {
      name: 'one',
      parentNode: {
        id: 'stepOne'
      }
    },
    {
      name: 'two',
      parentNode: {
        id: 'stepTwo'
      }
    },
    {
      name: 'three',
      parentNode: {
        id: 'stepOne'
      }
    },
]

The new object should be:

var newObj = {
    stepOne: [
      {
        name: 'one',
        parentNode: {
          id: 'stepOne'
        }
      },
      {
        name: 'three',
        parentNode: {
          id: 'stepOne'
        }
      },
    ],
    stepTwo: [
      {
        name: 'two',
        parentNode: {
          id: 'stepTwo'
        }
      },
    ]
}

Usually I do something like this:

let stepOne = function(step) {
  return step.parentNode.getAttribute('id') === 'stepOne';
}

let stepTwo = function(step) {
  return step.parentNode.getAttribute('id') === 'stepTwo';
}

let allTheStepOnes = fetchCheckBoxes.filter(stepOne);

But filter doesn't work on dom object and this seems inefficient as well.

Body:
Using reduce we can reduce your current array into the new structure.

return newObj.reduce(function(acc, item) {

If acc[item.parentNode.id] has been defined before, retrieve this.  Otherwise set it to an empty array:

acc[item.parentNode.id] = (acc[item.parentNode.id] || [])

Add the item to the array and then return it:

acc[item.parentNode.id].push(item);
return acc;

We set the accumulator as {} to start with.

Snippet to show the workings.

var newObj = [{
  name: 'one',
  parentNode: {
    id: 'stepOne'
  }
}, {
  name: 'two',
  parentNode: {
    id: 'stepTwo'
  }
}, {
  name: 'three',
  parentNode: {
    id: 'stepOne'
  }
}, ];

var newOrder = function(prevList) {
        return prevList.reduce(function(acc, item) {
            acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
            acc[item.parentNode.id].push(item);
            return acc;
        }, {});
    }

console.log(newOrder(newObj));


问:
splash screen in framework 7 when exported app with phonegap
I want to change my splash screen in my app when I exported it with PhoneGap.
I read in the documentation about each size, but I'm not sure if I need to do it manually. I mean to save each logo in each format with Photoshop.
So I want to know how to do that?

When I used in Ionic, I know I just have to run a command and it saves it when I exported the app in each size.
I already tried to save each photo manually but I'm not sure if this is what I need to export.
These are the sizes for example:

```<code>     <gap:splash src="application_icons/SAMSSplash_640x960.png" />
  <gap:splash src="application_icons/SAMSSplash_ldpi.png"        gap:platform="android" gap:qualifier="port-ldpi" />
  <gap:splash src="application_icons/SAMSSplash_mdpi.png"       gap:platform="android" gap:qualifier="port-mdpi" />
  <gap:splash src="application_icons/SAMSSplash_hdpi.png"        gap:platform="android" gap:qualifier="port-hdpi" />
  <gap:splash src="application_icons/SAMSSplash_xhdpi.png"       gap:platform="android" gap:qualifier="port-xhdpi" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"               gap:platform="blackberry" />
  <gap:splash src="application_icons/SAMSSplash_mdpi.png"          gap:platform="ios"     width="320" height="480" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"       gap:platform="ios"     width="640" height="960" />
  <gap:splash src="application_icons/SAMSSplash_640x1136.png"   gap:platform="ios"     width="640" height="1136" />
  <gap:splash src="application_icons/SAMSSplash_768x1024.png"             gap:platform="ios"     width="768" height="1024" />
  <gap:splash src="application_icons/SAMSSplash_1024x768.png"           gap:platform="ios"     width="1024" height="768" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"        gap:platform="winphone" />
</code>```

How can I do that here?

答:
I use this web site is very simple and easy to use.
Or this one a little more complete.</p>

Body:
I want to change my splash screen in my app when I exported it with PhoneGap.
I read in the documentation about each size, but I'm not sure if I need to do it manually. I mean to save each logo in each format with Photoshop.
So I want to know how to do that?

When I used in Ionic, I know I just have to run a command and it saves it when I exported the app in each size.
I already tried to save each photo manually but I'm not sure if this is what I need to export.
These are the sizes for example:

     <gap:splash src="application_icons/SAMSSplash_640x960.png" />
  <gap:splash src="application_icons/SAMSSplash_ldpi.png"        gap:platform="android" gap:qualifier="port-ldpi" />
  <gap:splash src="application_icons/SAMSSplash_mdpi.png"       gap:platform="android" gap:qualifier="port-mdpi" />
  <gap:splash src="application_icons/SAMSSplash_hdpi.png"        gap:platform="android" gap:qualifier="port-hdpi" />
  <gap:splash src="application_icons/SAMSSplash_xhdpi.png"       gap:platform="android" gap:qualifier="port-xhdpi" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"               gap:platform="blackberry" />
  <gap:splash src="application_icons/SAMSSplash_mdpi.png"          gap:platform="ios"     width="320" height="480" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"       gap:platform="ios"     width="640" height="960" />
  <gap:splash src="application_icons/SAMSSplash_640x1136.png"   gap:platform="ios"     width="640" height="1136" />
  <gap:splash src="application_icons/SAMSSplash_768x1024.png"             gap:platform="ios"     width="768" height="1024" />
  <gap:splash src="application_icons/SAMSSplash_1024x768.png"           gap:platform="ios"     width="1024" height="768" />
  <gap:splash src="application_icons/SAMSSplash_640x960.png"        gap:platform="winphone" />

How can I do that here?


问:
argsort in Python3
I am wondering why I get different results by using argsort in Python2 and Python3. My codes are as follows:

```<code>## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
    encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()

X_transform = X[:, freqrank < 1000].transpose().toarray()

freq1000terms = dict_index.keys()
freq1000terms = np.array(freq1000terms)[freqrank < 1000]
</code>```

In Python2, freqrank contains the results as:
array([4215, 2825, 7066, ...,  539, 3188, 5239]). However, in Python3, freqrank only contains array([0]), and this result further causes an error in the last line of codes as IndexError: too many indices for array. How can I get the same results that freqrank contains the sorted list in Python3 as I have in Python2? Or, how can I make the codes above work in Python3? Thanks.

答:
values() (and keys()) return view objects backed by the dict on Python 3, rather than lists. numpy.array can't convert a dict view to an array.

You can call list on the views to get a list, but rather than doing that, I'd recommend eliminating the dict entirely. You don't seem to be doing anything but calling keys() and values() on it.

Title: argsort in Python3

Body:
I am wondering why I get different results by using argsort in Python2 and Python3. My codes are as follows:

## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
    encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()

X_transform = X[:, freqrank < 1000].transpose().toarray()

freq1000terms = dict_index.keys()
freq1000terms = np.array(freq1000terms)[freqrank < 1000]

In Python2, freqrank contains the results as:
array([4215, 2825, 7066, ...,  539, 3188, 5239]). However, in Python3, freqrank only contains array([0]), and this result further causes an error in the last line of codes as IndexError: too many indices for array. How can I get the same results that freqrank contains the sorted list in Python3 as I have in Python2? Or, how can I make the codes above work in Python3? Thanks.


问:
jmeter - how to make a groovy script easier to maintain for extentreports
Below is a script that helps me build an extentreport for jmeter.  It is a JSR223 PostProcessor element.  It's working nicely however, the problem is that I have it duplicated after every HTTP Request in the script.  I have several scripts with 100's of HTTP requests that would need essentially a copy of the same PostProcessor groovy script.  This = hard to maintain!

I have tried splitting common parts into an external groovy script that I tried calling on the JSR223 PostProcessor.  I also tried chunking up the bits of the script and putting the values into a csv so that I could just update the csv values if anything changed.

I'm sure there's a cleaner/better way to do this but I'm still learning so I'm not sure of the best way to make this easier to maintain.  Here's the JSR223 PostProcessor.  The only bit that changes with each http request is the "//test result" section

```<code>import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//configure object for response data
def response = prev.getResponseDataAsString();

//configure extentreports objects
ExtentReports report;
ExtentTest testLogger;

//set location for file and report config
String resultsPath = "C:/portalQA/Automation/Results/";
String configPath = "C:/portalQA/Automation/JMeter/TestReportConfig/";
String reportPath =
resultsPath+"Login_Results_${reportDate}_${currentTime}_${testenv}.html";

File file = new File(reportPath);

if (!file.exists()) {

    //if file does not exist, create it
    report = new ExtentReports(reportPath, true);
    report.loadConfig( new File(configPath+"extent-config.xml"));
} else {
    //else append to existing report
    report = new ExtentReports(reportPath, false);
    report.loadConfig( new File(configPath+"extent-config.xml"));
}

//test result

testLogger = report.startTest("Authenticate");
testLogger.assignCategory("Initialize Session");
if (response.contains("com.blah.portal.model.User")) {
    testLogger.log(LogStatus.PASS, "Logged in with:  ${username}");
    testLogger.log(LogStatus.INFO, response);
} else {
    testLogger.log(LogStatus.FAIL, "Could not authenticate session");
    testLogger.log(LogStatus.INFO, response);
}

log.info("Authenticate");
print("Authenticate print");

report.endTest(testLogger);
report.flush();
</code>```

答:
I see two options:

I suggest using JSR223 Listener instead. First of all, that way you will only have 1 listener in your script, which resolves your original problem, but it is a better option for writing into file in general, since listener has only one instance for all running threads, so you won't be creating a race condition when writing to file.

If you rather have a post-processor, you can put it on higher level (not under any particular sampler) which will cause it to run after each request within the same scope or below.

For example, configuration like

```<code>Thread Group
    Post-processor
    Sampler 1
    ...
    Sampler N
</code>```

Will cause Post-processor to run after each Sampler 1...Sampler N

In both cases you may need to check which sampler you are processing, and skip those you don't want to add to your report (easiest way to do it, is to come up with some name convention for excluded samplers)

Body:
Below is a script that helps me build an extentreport for jmeter.  It is a JSR223 PostProcessor element.  It's working nicely however, the problem is that I have it duplicated after every HTTP Request in the script.  I have several scripts with 100's of HTTP requests that would need essentially a copy of the same PostProcessor groovy script.  This = hard to maintain!

I have tried splitting common parts into an external groovy script that I tried calling on the JSR223 PostProcessor.  I also tried chunking up the bits of the script and putting the values into a csv so that I could just update the csv values if anything changed.

I'm sure there's a cleaner/better way to do this but I'm still learning so I'm not sure of the best way to make this easier to maintain.  Here's the JSR223 PostProcessor.  The only bit that changes with each http request is the "//test result" section

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//configure object for response data
def response = prev.getResponseDataAsString();

//configure extentreports objects
ExtentReports report;
ExtentTest testLogger;

//set location for file and report config
String resultsPath = "C:/portalQA/Automation/Results/";
String configPath = "C:/portalQA/Automation/JMeter/TestReportConfig/";
String reportPath =
resultsPath+"Login_Results_${reportDate}_${currentTime}_${testenv}.html";

File file = new File(reportPath);

if (!file.exists()) {

    //if file does not exist, create it
    report = new ExtentReports(reportPath, true);
    report.loadConfig( new File(configPath+"extent-config.xml"));
} else {
    //else append to existing report
    report = new ExtentReports(reportPath, false);
    report.loadConfig( new File(configPath+"extent-config.xml"));
}

//test result

testLogger = report.startTest("Authenticate");
testLogger.assignCategory("Initialize Session");
if (response.contains("com.blah.portal.model.User")) {
    testLogger.log(LogStatus.PASS, "Logged in with:  ${username}");
    testLogger.log(LogStatus.INFO, response);
} else {
    testLogger.log(LogStatus.FAIL, "Could not authenticate session");
    testLogger.log(LogStatus.INFO, response);
}

log.info("Authenticate");
print("Authenticate print");

report.endTest(testLogger);
report.flush();

Body:
I see two options:

I suggest using JSR223 Listener instead. First of all, that way you will only have 1 listener in your script, which resolves your original problem, but it is a better option for writing into file in general, since listener has only one instance for all running threads, so you won't be creating a race condition when writing to file.

If you rather have a post-processor, you can put it on higher level (not under any particular sampler) which will cause it to run after each request within the same scope or below.

For example, configuration like

Thread Group
    Post-processor
    Sampler 1
    ...
    Sampler N

Will cause Post-processor to run after each Sampler 1...Sampler N

In both cases you may need to check which sampler you are processing, and skip those you don't want to add to your report (easiest way to do it, is to come up with some name convention for excluded samplers)


问:
C++ When are characters widened in output stream operator<<()?
It seems to me, that there is an inconsistency in the C++ standard, specifically in §30.7.5.2.4 of the C++17 draft (N4659), about when characters are widened in formatted output operations on output streams (operator<<()). Exactly the same inconsistency seems to be reflected in en.cppreference.com.

First, assume the following declarations:

```<code>std::ostream out;
std::wostream wout;
char ch;
wchar_t wch;
const char* str;
const wchar_t* wstr;
</code>```

It is then stated that

out << ch does not perform character widening,

out << str performs character widening,

wout << ch performs character widening,

wout << str performs character widening,

wout << wch does not perform character widening,

wout << wstr performs character widening.

The first and most obvious inconsistency is that (6) cannot be true, as there is no widen() function taking a wchar_t argument, only one that takes a char argument.

The second (seeming) inconsistency is between (1) and (2). It seems strange to me that out << "x" should widen 'x', while out << 'x' should not.

Am I misinterpreting the standard text, or is there something wrong there? If the latter is true, do you know what the intended behavior is?

EDIT: Apparently, this inconsistency (if I am right), has been present in the standard since at least C++03 (§27.6.2.5.4). The text changes a bit through the intermediate standards, but the inconsistency, as I explain it above, remains.

答:
It looks as if the standard isn't entirely correct. Most of the issue stems from the bulk-specification of the respective operations. Instead of handling each overload individually similar overloads are described together resulting in a misleading specification.

I doubt, any implementer has any trouble understanding what is intended, though. Essentially when a char is inserted into a non-char stream the character needs to be widen()ed to obtain the character of the stream's character type. This widening is intended to map one character from the source character set to the one character in the stream's wide character set.

Note that the IOStreams specification assumes the original notion of characters in streams being individual entities. Since the specification was created (for the C++1998 version) the text wasn't really updates substantially but with wide use of Unicode the "characters" in a stream are really bytes of an encoding. Although the streams mostly function OK in this modified environment, some flexibility which would be helpful to deal with Unicode characters isn't really properly supported. The absence of something "widening" one character into a sequence of UTF8 bytes is probably one of these.

If you feel the inconsistency/incorrectness in the stream's section warrants addressing, file a defect report. Instruction on filing defect reports are at http://isocpp.org. When you do raise an issue consider providing proposed wording to correct the issue. Since there is no lack of clarity what is actually intended and probably most implementations do the right thing anyway I'd expect this issue to get fairly low priority and without proposed wording it is unlikely to receive much attention. Of course, addressing the issue won't change the intended behavior, e.g., to "widen" chars into a UTF8 sequence: that would effectively be a redesign of the streams library which may be in order but won't be done as part of defect resolution.

Body:
It seems to me, that there is an inconsistency in the C++ standard, specifically in §30.7.5.2.4 of the C++17 draft (N4659), about when characters are widened in formatted output operations on output streams (operator<<()). Exactly the same inconsistency seems to be reflected in en.cppreference.com.

First, assume the following declarations:

std::ostream out;
std::wostream wout;
char ch;
wchar_t wch;
const char* str;
const wchar_t* wstr;

It is then stated that

out << ch does not perform character widening,

out << str performs character widening,

wout << ch performs character widening,

wout << str performs character widening,

wout << wch does not perform character widening,

wout << wstr performs character widening.

The first and most obvious inconsistency is that (6) cannot be true, as there is no widen() function taking a wchar_t argument, only one that takes a char argument.

The second (seeming) inconsistency is between (1) and (2). It seems strange to me that out << "x" should widen 'x', while out << 'x' should not.

Am I misinterpreting the standard text, or is there something wrong there? If the latter is true, do you know what the intended behavior is?

EDIT: Apparently, this inconsistency (if I am right), has been present in the standard since at least C++03 (§27.6.2.5.4). The text changes a bit through the intermediate standards, but the inconsistency, as I explain it above, remains.


问:
Hosting Firebase.json SEO-friendly URLs
I want this --> example myapp.com/myurl/

This is the custom config

```<code>"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]
</code>```

The result is this myapp.com/myurl with this config

答:
There's a deployment option for trailingslash, you should set it to true.
Firebase Hosting Config</p>

```<code>"trailingSlash": true
</code>```

Title: Hosting Firebase.json SEO-friendly URLs

Body:
I want this --> example myapp.com/myurl/

This is the custom config

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

The result is this myapp.com/myurl with this config

Body:
There's a deployment option for trailingslash, you should set it to true.
Firebase Hosting Config

"trailingSlash": true


问:
Static method heritation
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

```<code>public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}
</code>```

Child class:

```<code>public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}
</code>```

thanks

答:
Static methods can't be overridden. You can only hide superclass methods by defining a method with same name and signature in the subclass, but it's quite confusing and therefore generally not recommended. The original superclass method could be still accessed by, for example, ((SuperClassName) subClassInstance).staticMethod().

In your case it's probably better to make the method non-static.

Title: Static method heritation

Body:
I have a parent class with methods for writing and reading it from the db. The problem is I have a static method which I want to generalise. What is the best practice for doing this? I've came up with some solutions but all don't work with the static method.

Is there a way to force the childobject to implement the abstract method?

Parent Class:

public class Data_object  {

    public byte[] toByteArray() throws IOException  {
        return null;
    }
    public static Data_object fromByteArray(byte[] data){
        return null
    }
}

Child class:

public class ModelObject extends Data_object {

    public static Data_object fromByteArray(byte[] data){
        ModelObject result = new ModelObject();
        //set data from byte arrray
        return result;
    }
}

thanks


问:
Not getting first character after an attempt to downcast an object in java using charAt();
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

```<code>String name = "Mike";
</code>```

if I try the charAt() method it works fine using the above code.

```<code>name.charAt(0);
</code>```

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

```<code>Object obj = (String) name;

obj ==> "Mike"; // is what we get
</code>```

But if I use the method:

```<code>obj.charAt(0);
</code>```

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?

答:
Your problem is that by assigning String name to Object obj you hide that whatever is obj referencing to, is a String.

Of course you can cast obj to String by using

```<code>(String)obj
</code>```

because underlying reference is an reference to object of type String.

You have to consider that as obj is an Object it might be whatever type your language supports (is it Java?) so that's why you are getting error when executing obj.chatAt(0).

What would you expect it to return if underlying reference was to e.g. Integer?

That's why to use charAt() you have to cast it back to String

```<code>String str = (String)obj;
char ch = str.charAt(0);
</code>```

Or simpler:

```<code>char ch = ((String)obj).charAt(0);
</code>```

keeping in mind, that if obj's reference changed in meantime to e.g. some Integer, you won't succeed at casting probably throwing another error / exception.

P.S. Sample code is assuming, that your language is using char as type that is meant to contain single character.

Body:
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

String name = "Mike";

if I try the charAt() method it works fine using the above code.

name.charAt(0);

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

Object obj = (String) name;

obj ==> "Mike"; // is what we get

But if I use the method:

obj.charAt(0);

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?

Body:
Your problem is that by assigning String name to Object obj you hide that whatever is obj referencing to, is a String.

Of course you can cast obj to String by using

(String)obj

because underlying reference is an reference to object of type String.

You have to consider that as obj is an Object it might be whatever type your language supports (is it Java?) so that's why you are getting error when executing obj.chatAt(0).

What would you expect it to return if underlying reference was to e.g. Integer?

That's why to use charAt() you have to cast it back to String

String str = (String)obj;
char ch = str.charAt(0);

Or simpler:

char ch = ((String)obj).charAt(0);

keeping in mind, that if obj's reference changed in meantime to e.g. some Integer, you won't succeed at casting probably throwing another error / exception.

P.S. Sample code is assuming, that your language is using char as type that is meant to contain single character.