问:
Run phantomjs from php
I;m trying to run phantomjs from php. To check correct path and permissions, as first I execute this commands:

```<code>$output = shell_exec('ls /opt/phantomjs-1.9.2-linux-x86_64/bin/ -l');
echo "```$output```";
</code>```

Result:

```<code>-rwxrwxrwx. 1 root root 38526976 Sep  7 11:17 phantomjs
drwxrwxrwx. 2 root root     4096 Feb 10 15:44 savedpages
-rwxrwxrwx. 1 root root      803 Jan 19 18:36 saveonepagelin.js
-rwxrwxrwx. 1 root root     4074 Jan 19 19:00 test.js
</code>```

But when I run:

```<code>$output = shell_exec('/opt/phantomjs-1.9.2-linux-x86_64/bin/phantomjs --version');
echo "```$output```";
</code>```

Output is empty :( why? Thanks!

答:
I got the same error, and I try to modify the dir where I execute the phantomjs and set the mode with 777, then it worked. I guess the root cause if the owner of the php-fpm doesn't have right to write image into the dir.

my code for refer:

```<code>$output = passthru('phantomjs echarts-convert.js -options ' . $options . ' -outfile line.png');

echo $output;
</code>```

Title: Run phantomjs from php

Body:
I;m trying to run phantomjs from php. To check correct path and permissions, as first I execute this commands:

$output = shell_exec('ls /opt/phantomjs-1.9.2-linux-x86_64/bin/ -l');
echo "
$output
";

Result:

-rwxrwxrwx. 1 root root 38526976 Sep  7 11:17 phantomjs
drwxrwxrwx. 2 root root     4096 Feb 10 15:44 savedpages
-rwxrwxrwx. 1 root root      803 Jan 19 18:36 saveonepagelin.js
-rwxrwxrwx. 1 root root     4074 Jan 19 19:00 test.js

But when I run:

$output = shell_exec('/opt/phantomjs-1.9.2-linux-x86_64/bin/phantomjs --version');
echo "
$output
";

Output is empty :( why? Thanks!

Body:
I got the same error, and I try to modify the dir where I execute the phantomjs and set the mode with 777, then it worked. I guess the root cause if the owner of the php-fpm doesn't have right to write image into the dir.

my code for refer:

$output = passthru('phantomjs echarts-convert.js -options ' . $options . ' -outfile line.png');

echo $output;


来源: stackexchange

问:
cannot ping website or vmnet8 successfully
I run Ubuntu on VMworkstation12, but it can not be connected to the internet.
At first, My friends help me configure the net, it seems to work for a short period, but when I restart the network or Ubuntu, it fails again.
windows 7 (host)
this is the VMware Network Adapter VMnet8:
IP address 192.168.213.1
mask 255.255.255.0

net configuration at VMware:
VMnet8 NAT mode
ip 192.168.213.0
mask 255.255.255.0
getway 192.168.213.2

net configuration of Ubuntu:

/etc/network/interfaces

auto lo
iface lo inet loopback

auto ens33
iface ens33 inet static
address 192.168.213.3
netmask 255.255.255.0
gateway 192.168.213.2
dns-nameservers 8.8.8.8 8.8.4.4

at this situation, I can ping 192.168.213.2 successfully
ping 10.202.214.68(address of host) successfully
but cannot ping 192.168.213.1(VMne8) or any website.
What should i do to make it work?
Really appreciate your help! Thanks very much

答:
ok, problem solved almost.
change the dns-nameservers as same as the getway.
the website can be connected to the ubuntu.
but the host still can not ping subnet ip
the ubuntu can not ping VMnet8</p>

ContentLicense: CC BY-SA 3.0


问:
bookdown section label not referenced after backticks
I would like to use a code part in the name of a chapter / section, and reference that using a label.

```<code># Venn diagrams: function `venn()`{#venn}
</code>```

If not using the backticks, the reference works as expected but using the backticks prevents the label to be referenced:

```<code>Warning messages:
1: The label(s) venn not found
2: The label(s) venn not found
</code>```

Is there a way to obtain this?

答:
This is a known issue in Pandoc, and I think it is by design. You have to either remove the backticks, or insert something between venn() and the section ID, e.g.,

```<code># Venn diagrams: the `venn()` function {#venn}
</code>```

Body:
I would like to use a code part in the name of a chapter / section, and reference that using a label.

# Venn diagrams: function `venn()`{#venn}

If not using the backticks, the reference works as expected but using the backticks prevents the label to be referenced:

Warning messages:
1: The label(s) venn not found
2: The label(s) venn not found

Is there a way to obtain this?

Body:
This is a known issue in Pandoc, and I think it is by design. You have to either remove the backticks, or insert something between venn() and the section ID, e.g.,

# Venn diagrams: the `venn()` function {#venn}


问:
Lucene.net IndexWriter lock obtains
been pulling hair out for several hours trying to find a way around a limitation to Lucene.Net (2.9.2)'s FSLock problem.

Basically, identified that whenever a write action against the index is performed a lock gets put on the directory, nothing new. This lock should be released after every addition, but IndexWriter.Unlock just does nothing, so finally figured out that I can release the lock via:

```<code>FSDirectory.GetLockFactory().ClearLock("write.lock");
</code>```

however, as soon as I try and ensure that my IndexWriter instance has been initialized, do I get a NativeFSLock exception, assuming that the IndexWriter still believes that a lock is persistent on the directory.

Any ideas as to how I can overcome this?

Thanks,
Eric

答: My IndexWriter instance was not thread-safe.</p>

ContentLicense: CC BY-SA 2.5

Title: Lucene.net IndexWriter lock obtains

Body:
been pulling hair out for several hours trying to find a way around a limitation to Lucene.Net (2.9.2)'s FSLock problem.

Basically, identified that whenever a write action against the index is performed a lock gets put on the directory, nothing new. This lock should be released after every addition, but IndexWriter.Unlock just does nothing, so finally figured out that I can release the lock via:

FSDirectory.GetLockFactory().ClearLock("write.lock");

however, as soon as I try and ensure that my IndexWriter instance has been initialized, do I get a NativeFSLock exception, assuming that the IndexWriter still believes that a lock is persistent on the directory.

Any ideas as to how I can overcome this?

Thanks,
Eric


问:
Show DIV only in a certain date range
Hi SO-Community,

i figure this may be an amateur type of question, but i just could not find a proper solution anywhere:

I am trying to show a specific DIV only in Christmas Time via JavaScript. Here goes my code so far:

```<code>function WinterTime() {
var WinterStart = new Date(2017, 12, 21);
var WinterEnd = new Date(2017, 12, 27);
if
(WinterStart <= CurrentDate && CurrentDate <= WinterEnd) {
song2.style.display = "block";
}
else {
song2.style.display = "none";
}
}
</code>```

I defined the variable "song2" earlier in case you're wondering.

I figure this may be complete rubbish code but please show mercy since I am a total noob and just tried to learn from various other threats.
I am grateful for your Feedback. :)

Regards

Jonas

答:
Your logic is fine, the implementation is a little off though. ;-)

// Function names starting with a capital letter are,
// by convention, reserved for constructors.
// The function should accept a date or default to the current date
function winterTime(currentDate) {
  currentDate = currentDate || new Date();
  // Months are zero indexed, so for 21 December:
  var winterStart = new Date(2017, 11, 21);
  var winterEnd = new Date(2017, 11, 27);

  // Get a reference to the element
  var song2 = document.getElementById('song2');

  if (winterStart <= currentDate && currentDate <= winterEnd) {
    // Set display to '' (empty string) so the element adopts its default or inherited value
    song2.style.display = "";
    console.log('Winter');

  } else {
    song2.style.display = "none";
    console.log('Not winter');
  }
}

// Call function when page loaded
window.onload = winterTime;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="song1">Song 1</div>
<div id="song2">Song 2</div></code>```

If you use some recently added features, you can apply the style using CSS fairly simply:

function winterTime(currentDate = new Date()) {
  var winterStart = new Date(2017, 11, 21);
  var winterEnd = new Date(2017, 11, 27);
  var isWinter = winterStart <= currentDate && currentDate <= winterEnd;
  var song2 = document.getElementById('song2');
  song2.classList[isWinter? 'remove' : 'add']('hidden');

  // Just for testing
  console.log(isWinter? 'Winter' : 'Not winter');
}

// Call function when page loaded
window.onload = function() {
  winterTime(new Date(2017, 11, 25)); // Christmas day
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}</code>```

Song 1

Song 2
```

Title: Show DIV only in a certain date range

Body:
Hi SO-Community,

i figure this may be an amateur type of question, but i just could not find a proper solution anywhere:

I am trying to show a specific DIV only in Christmas Time via JavaScript. Here goes my code so far:

function WinterTime() {
var WinterStart = new Date(2017, 12, 21);
var WinterEnd = new Date(2017, 12, 27);
if
(WinterStart <= CurrentDate && CurrentDate <= WinterEnd) {
song2.style.display = "block";
}
else {
song2.style.display = "none";
}
}

I defined the variable "song2" earlier in case you're wondering.

I figure this may be complete rubbish code but please show mercy since I am a total noob and just tried to learn from various other threats.
I am grateful for your Feedback. :)

Regards

Jonas

Body:
Your logic is fine, the implementation is a little off though. ;-)

// Function names starting with a capital letter are,
// by convention, reserved for constructors.
// The function should accept a date or default to the current date
function winterTime(currentDate) {
  currentDate = currentDate || new Date();
  // Months are zero indexed, so for 21 December:
  var winterStart = new Date(2017, 11, 21);
  var winterEnd = new Date(2017, 11, 27);

  // Get a reference to the element
  var song2 = document.getElementById('song2');

  if (winterStart <= currentDate && currentDate <= winterEnd) {
    // Set display to '' (empty string) so the element adopts its default or inherited value
    song2.style.display = "";
    console.log('Winter');

  } else {
    song2.style.display = "none";
    console.log('Not winter');
  }
}

// Call function when page loaded
window.onload = winterTime;

<div id="song1">Song 1</div>
<div id="song2">Song 2</div>

If you use some recently added features, you can apply the style using CSS fairly simply:

function winterTime(currentDate = new Date()) {
  var winterStart = new Date(2017, 11, 21);
  var winterEnd = new Date(2017, 11, 27);
  var isWinter = winterStart <= currentDate && currentDate <= winterEnd;
  var song2 = document.getElementById('song2');
  song2.classList[isWinter? 'remove' : 'add']('hidden');

  // Just for testing
  console.log(isWinter? 'Winter' : 'Not winter');
}

// Call function when page loaded
window.onload = function() {
  winterTime(new Date(2017, 11, 25)); // Christmas day
};

.hidden {
  display: none;
}

<div id="song1">Song 1</div>
<div id="song2">Song 2</div>


问:
Variable undefined inside the self-invoking function
I wonder why its undefined if I declare like so:

```<code>var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // undefined
        return arguments.callee;
    })();
</code>```

or even:

```<code>var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
    })();
</code>```

答:
You should have:</p>

```<code>var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
})(btn); // need to add the argument when invoked
</code>```

Body:
I wonder why its undefined if I declare like so:

var mainBtn = $('.main-button'),
    cloneFund = (function(mainBtn) {
        console.log(mainBtn); // undefined
        return arguments.callee;
    })();

or even:

var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
    })();

Body:
You should have:

var btn = $('.main-button'),
    cloneFund = (function(btn) {
        console.log(btn); // undefined
        return arguments.callee;
})(btn); // need to add the argument when invoked


问:
Getting a certain class from an element using wildcard
I am wanting to get the class starting with logo, only example item is:

jQuery(document).ready(function($) {

  // add classes to tab items
  var listItems = $(".vc_tta-tab a");
  // loop through all tab items
  listItems.each(function(idx, item) {
    var listItem = $(item);
    var tabID = listItem.attr("href");
    console.log(tabID);
    var matchCard = $(tabID).find('[class^="logo-"]');
    var tabClass = $(tabID).attr("class");
    console.log(tabClass);
    console.log(matchCard);

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vc_general vc_tta vc_tta-tabs vc_tta-color-grey vc_tta-style-classic vc_tta-shape-rounded vc_tta-spacing-1 vc_tta-tabs-position-top vc_tta-controls-align-left">
  <div class="vc_tta-tabs-container">
    <ul class="vc_tta-tabs-list">
      <li class="vc_tta-tab vc_active" data-vc-tab=""><span class="vc_tta-title-text">Symantec SSL/TLS Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">GeoTrust SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">RapidSSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Thawte SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Certum SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Comodo SSL Certificates</span></li>
    </ul>
  </div>
  <div class="vc_tta-panels-container">
    <div class="vc_tta-panels">
      <div class="vc_tta-panel vc_active logo-ssl-symantec" id="ssl-brand-symantec" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Symantec SSL/TLS Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-geotrust" id="ssl-brand-geotrust" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">GeoTrust SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-rapidssl" id="ssl-brand-rapidssl" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">RapidSSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-thawte" id="ssl-brand-thawte" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Thawte SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-certum" id="ssl-brand-certum" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Certum SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-comodo" id="ssl-brand-comodo" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Comodo SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
    </div>
  </div>
</div></code>```

It is working by finding ID and matching that but can't get it to select that class I am wanting.

Also, I then want to take that class and set to the parent element of the initial href.

答:
If you are wanting what I believe you are wanting (which is to select a class that starts with logo-, then you could use Regular expressions, also known as a Regex.

I would use /^logo-[^ ]*/g as the Regex.

The / and /g symbolise a new Regular Expression. The ^ symbolises the start of the word. The logo- symbolises that the start of the word contains the string logo-. The [^ ] symbolises that it will have a character that isn't a space after it and the * symbolises that there will be one or more characters that isn't a space.

Body:
I am wanting to get the class starting with logo, only example item is:

jQuery(document).ready(function($) {

  // add classes to tab items
  var listItems = $(".vc_tta-tab a");
  // loop through all tab items
  listItems.each(function(idx, item) {
    var listItem = $(item);
    var tabID = listItem.attr("href");
    console.log(tabID);
    var matchCard = $(tabID).find('[class^="logo-"]');
    var tabClass = $(tabID).attr("class");
    console.log(tabClass);
    console.log(matchCard);

  });
});

Symantec SSL/TLS Certificates

GeoTrust SSL Certificates

RapidSSL Certificates

Thawte SSL Certificates

Certum SSL Certificates

Comodo SSL Certificates

Symantec SSL/TLS Certificates

GeoTrust SSL Certificates

RapidSSL Certificates

Thawte SSL Certificates

Certum SSL Certificates

Comodo SSL Certificates

It is working by finding ID and matching that but can't get it to select that class I am wanting.

Also, I then want to take that class and set to the parent element of the initial href.


问:
How to depict a Network with Donut shaped vertices with Igraph?
I would like to depict a network with Ring/Donut Shaped Vertices. I did not find such a shape in Igraph documentation, but I found a pie shaped instead. Like the following code:

```<code>library(igraph)
g <- make_ring(10)
values <- lapply(1:10, function(x) sample(1:10,3))
if (interactive()) {
    plot(g, vertex.shape="pie", vertex.pie=values,
         vertex.pie.color=list(heat.colors(5)),
         vertex.size=seq(10,30,length=10), vertex.label=NA)
}
</code>```

Here the resulting image:

Do you know a way of turning a pie shaped vertex into a ring/donut shaped vertex using Igraph itself? I searched for a "vertex.pie.hole" parameter, but it does not exist. The easiest way I see to do this is to depict "white points" in the centroids of the vertices, but it is clearly not an ideal situation.

I also know it is possible to define our own vertex shape, but I must confess it is been really hard for me to do this for a ring/donut shape.

Thanks a lot for your attention,

答:
I'm not sure if there's a way to plot donuts directly, but here's a hack to get the same result: We plot the graph once using your code, then we overplot smaller white circles to create the donuts. Setting a seed ensures that the vertices are in the same location each time.

```<code>  set.seed(2)
  plot(g, vertex.shape="pie", vertex.pie=values,
       vertex.pie.color=list(heat.colors(5)),
       vertex.size=seq(10,30,length=10), vertex.label=NA)

  set.seed(2)
  plot(g,
       vertex.size=seq(5,15,length=10), vertex.label=NA,
       vertex.color="white",
       edge.color=NA,
       add=TRUE)
</code>```

Body:
I would like to depict a network with Ring/Donut Shaped Vertices. I did not find such a shape in Igraph documentation, but I found a pie shaped instead. Like the following code:

library(igraph)
g <- make_ring(10)
values <- lapply(1:10, function(x) sample(1:10,3))
if (interactive()) {
    plot(g, vertex.shape="pie", vertex.pie=values,
         vertex.pie.color=list(heat.colors(5)),
         vertex.size=seq(10,30,length=10), vertex.label=NA)
}

Here the resulting image:

Do you know a way of turning a pie shaped vertex into a ring/donut shaped vertex using Igraph itself? I searched for a "vertex.pie.hole" parameter, but it does not exist. The easiest way I see to do this is to depict "white points" in the centroids of the vertices, but it is clearly not an ideal situation.

I also know it is possible to define our own vertex shape, but I must confess it is been really hard for me to do this for a ring/donut shape.

Thanks a lot for your attention,

Body:
I'm not sure if there's a way to plot donuts directly, but here's a hack to get the same result: We plot the graph once using your code, then we overplot smaller white circles to create the donuts. Setting a seed ensures that the vertices are in the same location each time.

  set.seed(2)
  plot(g, vertex.shape="pie", vertex.pie=values,
       vertex.pie.color=list(heat.colors(5)),
       vertex.size=seq(10,30,length=10), vertex.label=NA)

  set.seed(2)
  plot(g,
       vertex.size=seq(5,15,length=10), vertex.label=NA,
       vertex.color="white",
       edge.color=NA,
       add=TRUE)


问:
Beginner Python Objective Specific Explanation
```<code>A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]

x = 0
for i in range(2):
    x = x + A[i][i]
    print(x)
print(x)
</code>```

The answer/output is:

```<code>1,3,3
</code>```

How does that happen? Explain everything in detail

答:
A is a list of 3 elements, each has an index number, beginning with zero (0,1,2). Each element of the list is also a list.

The syntax A[i] returns the i-th value of the list. e.g. A[0] = [1, 1, 2]. The syntax A[i][i] returns the i-th value of the i-th list. A[2][2] = 4

range(2) evaluates to 0,1

The value of i is set to 0 for the first run of the for loop

A[0][0] evaluates to the first element of the first list (1). This is added to x to give x the value 1, which is printed

The second loop picks up A[1][1], the second element of the second list (2). This is added to the value of x, which was 1. The new value of x is now printed (1 + 2 = 3).

The loop is finished and the value of x is unchanged and is printed again (3)

Body:
A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]

x = 0
for i in range(2):
    x = x + A[i][i]
    print(x)
print(x)

The answer/output is:

1,3,3

How does that happen? Explain everything in detail


问:
View MongoDB array in order of indices with Compass
I am working on a database of Polish verbs and I'd like to find out how to display my results such that each verb conjugation appears in the following order: 1ps (1st person singular), 2ps, 3ps, 1ppl (1st person plural, etc.), 2ppl, 3ppl. It displays fine when I insert documents:

verb "żyć/przeżyć" conjugation as array and nested document

But when I go to perform queries it jumbles all the array elements up, in the first case (I want to see them in order of array indices), and sorts the nested document elements into alphabetical order (whereas I want to see them in the order in which they were inserted).

verb "żyć/przeżyć" conjugation array/document query

This should be an easy one to solve, I hope this comes across as a reasonable beginner's question. I have searched for answers but couldn't find much info on this topic. Any and all help is greatly appreciated!

Cheers,
LC.

答:
Your screenshots highlight two different views in MongoDB Compass.

The Schema view is based on a sampling of multiple documents and the order of the fields displayed cannot be specified. The schema analysis (as at Compass 1.7) lists fields in case-insensitive alphabetical order with the _id field at the top. Since this is an aggregate schema view based on multiple documents, the ordering of fields is not expected to reflect individual document order.

If you want to work with individual documents and field ordering you need to use the Documents view, as per your second screenshot. In addition to displaying the actual documents, this view allows you to include sort and skip options for queries:


问:
Django - "Relation Does Not Exist" on Fresh Migrations
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!

Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?

```<code>pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
                                                             ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
    utility.execute()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
    self.check()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Genius/urls.py", line 12, in <module>
    url(r'^', include('Inventory.urls', namespace="Inventory")),
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Inventory/urls.py", line 3, in <module>
    from Inventory import views
  File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
    class SummaryView(InventoryView):
  File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
    summary_table = build_summary_table()
  File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
    table_query = Purchase.inventory.current_summary_data(**kwargs)
  File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
    for item in totals:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
    self._fetch_all()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
    for row in compiler.results_iter():
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
    results = self.execute_sql(MULTI)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
</code>```

My files are kinda bulky, but this is the Manager that is tripping it up:

```<code>class EntryManager(Manager):

    def user_create(self, request):
        type = request.POST.get('type', None)
        label = request.POST.get('label', None)
        details = request.POST.get('details', None)
        date_added = date.today()
        sequence = 1 + self.model.objects.filter(type=type, active=True).count()
        label = type + str(sequence) + "- " + label

        entry = self.model.objects.create(
            type=type,
            label=label,
            details=details,
            date_added=date_added,
            sequence=sequence,
            user=request.user
        )

        return entry

    def user_update(self, request, pk):
        entry = self.model.objects.get(id=pk)
        entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
        entry.details = request.POST.get("details")
        entry.user = request.user

        entry.save()

        return entry

    def user_delete(self, pk):
        entry = self.model.objects.get(id=pk)

        successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
        for obj in successors:
            obj.sequence -= 1
            obj.label = obj.label.split(" ", 1)[1]
            obj.label = obj.type + str(obj.sequence) + "- " + obj.label
            obj.save()

        key = entry.id
        entry.delete()
        return key

    def get_entry_set(self, request):
        """
        Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
        setStratEntries method.

        Args:
            Request Delivers two relevant variables:
                s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
                o_or_t: Indicates "X-axis" (opportunity or threat) requirement.

        Returns:
            All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
        """

        # Build Dictionary of active Strengths or Weaknesses
        s_or_w = request.GET.get("s_or_w")
        strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
        s_or_w_data = []
        for entry in strengths_or_weaknesses:
            s_or_w_data.append({
                "id": entry.id,
                "label": entry.label
            })

        # Build Dictionary of active Opportunities or Threats
        o_or_t = request.GET.get("o_or_t")
        opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
        o_or_t_data = []
        for entry in opportunities_or_threats:
            o_or_t_data.append({
                "id": entry.id,
                "label": entry.label,
            })

        # Combine for for JSON delivery.
        data = {
            "s_or_w": s_or_w_data,
            "o_or_t": o_or_t_data
        }

        return data
</code>```

This is the associated model:

```<code>class Entry(GenericObject):
    type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
    sequence = models.IntegerField()
    label = models.CharField(max_length=124)
    actions = managers.EntryManager()
    objects = models.Manager()

    class Meta:
        ordering = ["id"]
</code>```

Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?

答: first migrate that particular app. python manage.py migrate app_name. Which will resolve the dependency.</p>

Body:
I'm trying to deploy my app, but when running migrate.py for the first time, I get an error explaining that a "relation does not exist". Of course it wouldn't, because I haven't been able to migrate yet!

Looking through the traceback, it seems to be getting tripped up in my managers.py file, but I can't understand why my managers would be getting in the way?

pyto(genius) 00:24 ~/genius (master)$ python manage.py migrate
Traceback (most recent call last):
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...
                                                             ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_comm
and_line
    utility.execute()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 342, in execute
    self.check()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_check
s
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Genius/urls.py", line 12, in <module>
    url(r'^', include('Inventory.urls', namespace="Inventory")),
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/cvcexport/genius/Inventory/urls.py", line 3, in <module>
    from Inventory import views
  File "/home/cvcexport/genius/Inventory/views.py", line 67, in <module>
    class SummaryView(InventoryView):
  File "/home/cvcexport/genius/Inventory/views.py", line 70, in SummaryView
    summary_table = build_summary_table()
  File "/home/cvcexport/genius/Inventory/views.py", line 62, in build_summary_table
    table_query = Purchase.inventory.current_summary_data(**kwargs)
  File "/home/cvcexport/genius/Inventory/managers.py", line 31, in current_summary_data
    for item in totals:
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
    self._fetch_all()
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/query.py", line 109, in __iter__
    for row in compiler.results_iter():
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 789, in results_iter
    results = self.execute_sql(MULTI)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cvcexport/.virtualenvs/genius/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "Inventory_purchase" does not exist
LINE 1: ...entory_purchase"."inr_value") AS "inr_value" FROM "Inventory...

My files are kinda bulky, but this is the Manager that is tripping it up:

class EntryManager(Manager):

    def user_create(self, request):
        type = request.POST.get('type', None)
        label = request.POST.get('label', None)
        details = request.POST.get('details', None)
        date_added = date.today()
        sequence = 1 + self.model.objects.filter(type=type, active=True).count()
        label = type + str(sequence) + "- " + label

        entry = self.model.objects.create(
            type=type,
            label=label,
            details=details,
            date_added=date_added,
            sequence=sequence,
            user=request.user
        )

        return entry

    def user_update(self, request, pk):
        entry = self.model.objects.get(id=pk)
        entry.label = entry.type + str(entry.sequence) + "- " + request.POST.get("label")
        entry.details = request.POST.get("details")
        entry.user = request.user

        entry.save()

        return entry

    def user_delete(self, pk):
        entry = self.model.objects.get(id=pk)

        successors = self.model.objects.filter(type=entry.type, active=True, sequence__gt=entry.sequence)
        for obj in successors:
            obj.sequence -= 1
            obj.label = obj.label.split(" ", 1)[1]
            obj.label = obj.type + str(obj.sequence) + "- " + obj.label
            obj.save()

        key = entry.id
        entry.delete()
        return key

    def get_entry_set(self, request):
        """
        Builds selection lists allowing users to link SWOT entries to strategies. Used in swot-matrix.js with
        setStratEntries method.

        Args:
            Request Delivers two relevant variables:
                s_or_w: Indicates "Y-axis" (strength or weakness) requirement.
                o_or_t: Indicates "X-axis" (opportunity or threat) requirement.

        Returns:
            All active entries that match each requested type, packaged in dictionaries and ready for JSON delivery.
        """

        # Build Dictionary of active Strengths or Weaknesses
        s_or_w = request.GET.get("s_or_w")
        strengths_or_weaknesses = self.model.objects.filter(type=s_or_w, active=True)
        s_or_w_data = []
        for entry in strengths_or_weaknesses:
            s_or_w_data.append({
                "id": entry.id,
                "label": entry.label
            })

        # Build Dictionary of active Opportunities or Threats
        o_or_t = request.GET.get("o_or_t")
        opportunities_or_threats = self.model.objects.filter(type=o_or_t, active=True)
        o_or_t_data = []
        for entry in opportunities_or_threats:
            o_or_t_data.append({
                "id": entry.id,
                "label": entry.label,
            })

        # Combine for for JSON delivery.
        data = {
            "s_or_w": s_or_w_data,
            "o_or_t": o_or_t_data
        }

        return data

This is the associated model:

class Entry(GenericObject):
    type = models.CharField(max_length=1, choices=choices.ENTRY_CHOICES)
    sequence = models.IntegerField()
    label = models.CharField(max_length=124)
    actions = managers.EntryManager()
    objects = models.Manager()

    class Meta:
        ordering = ["id"]

Am I breaking the rules somewhere? Why is migrate.py complaining about missing columns on a brand new postgres database?


问:
How to create JSON from strings without creating a custom class using JSON.Net library
I have this method in which I'm trying to create JSON string:

```<code>//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1,  string val2, string val3,string val4,  string val5, string val6)
{
    //process the six arguments and three key-related member variables to create a JSON array
    //don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class

    var configs = new List<CustomClass>
                         { new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
                            , new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
                        };
    var jsonData = JsonConvert.SerializeObject(configs);
   return jsonData;
}

//A class in another file
public class CustomClass
{
    public string FirstKey { get; set; }
    public string SecondKey{ get; set; }
    public string ThirdKey{ get; set; }

}
</code>```

I'm trying to create the JSON array using JSON.Net. The expected output is as below:

```<code>[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]
</code>```

Here val1 to val6 values should get replaced by the argument values at run-time.

Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format. But soon I stumbled upon the world of escape characters which can deform a JSON string e.g. \r.

I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.

Anyways, coming back to my problem. I was able to solve my problem by creating a custom class having three properties FirstKey, SecondKey, and ThirdKey. Then, create an object of the class, then assign the values in arguments val1 and val2 to then and then use JsonConvert.SerializeObject API.

I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes. Creating a class CustomClass altogether feels like an overhead here. I'm looking for something of sort of like StringBuilder.Append API if it is available in the JSON library I'm using. I'm not sure if I'm missing any of the APIs in JSON.Net.

答:
Getting few clues from [@code4life][1]'s comment in accepted answer, I found out that it is achievable via JArray object as well found under Newtonsoft.Json.Linq namespace.

```<code>using Newtonsoft.Json.Linq;

private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6)
{

    var configs = new[]
    {
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3},
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    return JArray.FromObject(configs).ToString();
}
</code>```

Note: Anonymous types which are being created through new { FirstKey = val1, SecondKey = val2, ThirdKey = val3} syntax can contain any .NET data type and not just strings which I've asked in my original post e.g.new { FirstKey = "AnyString", SecondKey = true, ThirdKey = DateTime.Now}
[1]: https://stackoverflow.com/users/215741/code4life

ContentLicense: CC BY-SA 4.0

Body:
I have this method in which I'm trying to create JSON string:

//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1,  string val2, string val3,string val4,  string val5, string val6)
{
    //process the six arguments and three key-related member variables to create a JSON array
    //don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class

    var configs = new List<CustomClass>
                         { new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
                            , new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
                        };
    var jsonData = JsonConvert.SerializeObject(configs);
   return jsonData;
}

//A class in another file
public class CustomClass
{
    public string FirstKey { get; set; }
    public string SecondKey{ get; set; }
    public string ThirdKey{ get; set; }

}

I'm trying to create the JSON array using JSON.Net. The expected output is as below:

[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]

Here val1 to val6 values should get replaced by the argument values at run-time.

Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format. But soon I stumbled upon the world of escape characters which can deform a JSON string e.g. \r.

I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.

Anyways, coming back to my problem. I was able to solve my problem by creating a custom class having three properties FirstKey, SecondKey, and ThirdKey. Then, create an object of the class, then assign the values in arguments val1 and val2 to then and then use JsonConvert.SerializeObject API.

I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes. Creating a class CustomClass altogether feels like an overhead here. I'm looking for something of sort of like StringBuilder.Append API if it is available in the JSON library I'm using. I'm not sure if I'm missing any of the APIs in JSON.Net.

Body:
Getting few clues from [@code4life][1]'s comment in accepted answer, I found out that it is achievable via JArray object as well found under Newtonsoft.Json.Linq namespace.

using Newtonsoft.Json.Linq;

private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6)
{

    var configs = new[]
    {
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3},
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    return JArray.FromObject(configs).ToString();
}

Note: Anonymous types which are being created through new { FirstKey = val1, SecondKey = val2, ThirdKey = val3} syntax can contain any .NET data type and not just strings which I've asked in my original post e.g.new { FirstKey = "AnyString", SecondKey = true, ThirdKey = DateTime.Now}
[1]: https://stackoverflow.com/users/215741/code4life


问:
Assigning a value to a variable which is stored in another variable
I am looking for some direction in this code.

What I have is 2 variables:

1) CalcTimeDown - a string variable in a for loop which takes various values which correspond to another string variable for each value in the for loop

Initial value is a string - "CalculationTimeDown".  This gets suffixed by 000, 001, 002 and 003 and 004 giving me CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc

2) CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc are "id" in an XML Layout.  And should get values of 00:00, 00:30, 01:00... etc.

What I am trying to do is:

Loop in the for loop from 0 to 4.

Set values to the variable CalcTimeDown to CalculationTimeDown000,
CalculationTimeDown001, ..... etc.

Load variable CalculationTimeDown000 with "00:00"

Load variable CalculationTimeDown001 with "00:30"

Load variable CalculationTimeDown002 with "01:00"

Load variable CalculationTimeDown003 with "00:30"

Load variable CalculationTimeDown004 with "02:00"

The Bold step above is what I am unable to accomplish - can someone guide me?

```<code>        // Assemble the variable name
        this.CalcTimeDownInitial = "CalculationTimeDown";

        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            this.CalcTimeDown = this.CalcTimeDownInitial + i.ToString("000");

            var TimeSlotVariable = new StringtoVariable(CalcTimeDown);

            this.iSlot = (i) * 30;
            //

            // Get the time to be pumped
            DateTime TimeSlotValue = DateTime.Now.AddMinutes(this.iSlot);
            //

            // CalcTimeDown contains the variable name where I want to pump the value of TimeSlotValue
            // TimeSlotValue contains 00:00, 00:30, 01:00 etc.
</code>```

//INCORRECT SYNTAX - HELP HERE PLEASE.

```<code>            TimeSlotVariable = TimeSlotValue;
</code>```

Thank you in advance.

Uttam

PS: I could not find an example using Reflection which I could adapt for my use in the example above - hence this posting.

-------Edit added to explain difference------

This edit to explain how my question is different from the possible duplicate:

That question was about Accessing the value - the value is already loaded in that case.

My question is about loading a value - loading the value is what I am trying to accomplish.

Could you please remove the vote down, if my explanation is reasonable?  Thanks!

答:
Creating variables dynamically is not possible in c# as it is a strongly typed language. You can use dictionary in this case.</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, DateTime> variables = new Dictionary<string,     DateTime>();
        for (int i = 0; i <= 4; i++) {
            variables.Add(String.Format("CalculationTimeDown{0}", i.ToString("000")), DateTime.Now.AddMinutes(i * 30));
        }
    }
}
</code>```

Body:
I am looking for some direction in this code.

What I have is 2 variables:

1) CalcTimeDown - a string variable in a for loop which takes various values which correspond to another string variable for each value in the for loop

Initial value is a string - "CalculationTimeDown".  This gets suffixed by 000, 001, 002 and 003 and 004 giving me CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc

2) CalculationTimeDown000, CalculationTimeDown001, CalculationTimeDown002..etc are "id" in an XML Layout.  And should get values of 00:00, 00:30, 01:00... etc.

What I am trying to do is:

Loop in the for loop from 0 to 4.

Set values to the variable CalcTimeDown to CalculationTimeDown000,
CalculationTimeDown001, ..... etc.

Load variable CalculationTimeDown000 with "00:00"

Load variable CalculationTimeDown001 with "00:30"

Load variable CalculationTimeDown002 with "01:00"

Load variable CalculationTimeDown003 with "00:30"

Load variable CalculationTimeDown004 with "02:00"

The Bold step above is what I am unable to accomplish - can someone guide me?

        // Assemble the variable name
        this.CalcTimeDownInitial = "CalculationTimeDown";

        for (int i = 0; i <= 4; i++)
        {
            // Assemble the variable name
            this.CalcTimeDown = this.CalcTimeDownInitial + i.ToString("000");

            var TimeSlotVariable = new StringtoVariable(CalcTimeDown);

            this.iSlot = (i) * 30;
            //

            // Get the time to be pumped
            DateTime TimeSlotValue = DateTime.Now.AddMinutes(this.iSlot);
            //

            // CalcTimeDown contains the variable name where I want to pump the value of TimeSlotValue
            // TimeSlotValue contains 00:00, 00:30, 01:00 etc.

//INCORRECT SYNTAX - HELP HERE PLEASE.

            TimeSlotVariable = TimeSlotValue;

Thank you in advance.

Uttam

PS: I could not find an example using Reflection which I could adapt for my use in the example above - hence this posting.

-------Edit added to explain difference------

This edit to explain how my question is different from the possible duplicate:

That question was about Accessing the value - the value is already loaded in that case.

My question is about loading a value - loading the value is what I am trying to accomplish.

Could you please remove the vote down, if my explanation is reasonable?  Thanks!

Body:
Creating variables dynamically is not possible in c# as it is a strongly typed language. You can use dictionary in this case.

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, DateTime> variables = new Dictionary<string,     DateTime>();
        for (int i = 0; i <= 4; i++) {
            variables.Add(String.Format("CalculationTimeDown{0}", i.ToString("000")), DateTime.Now.AddMinutes(i * 30));
        }
    }
}


问:
Xamarin Android crashing with Xamarin.Auth
I'm using Xamarin.Auth to log into Facebook. I created a separate Renderer for iOS and Android.
In the auth.Completed I call a method AfterLogin(UserInfo) in the PCL class of the custom renderer. This does some additional work and then calls

```<code>App.Current.MainPage = new NavigationPage(new MainPage());
</code>```

It looks like the page is constructed correctly and all methods return correctly until an Exception Unhandled gets thrown. The only text is "An unhandled exception occured."

In iOS, everything works fine. It calls the exact same PCL code.

I have no idea what view it is referring to.

Edit
Stack trace from ADB

```<code>  I/MonoDroid(11638): UNHANDLED EXCEPTION:

 I/MonoDroid(11638): Java.Lang.IllegalArgumentException: No view found for id 0x4 (unknown) for fragment FragmentContainer{436fa3e8 #0 id=0x4}

I/MonoDroid(11638):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <d18287e1d683419a8ec3216fd78947b9>:0

I/MonoDroid(11638):   at Java.Interop.JniEnvironment+InstanceMethods.CallBooleanMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method) [0x00068] in <5716a943049b49ca928a3a1c8d2386f4>:0

I/MonoDroid(11638):   at Android.Runtime.JNIEnv.CallBooleanMethod (System.IntPtr jobject, System.IntPtr jmethod) [0x0000e] in <33e6e739ac344166b157e323586f11a1>:0

I/MonoDroid(11638):   at Android.Support.V4.App.FragmentManagerInvoker.ExecutePendingTransactions () [0x00033] in <7e083afc7c9045f59e01d9c14931060d>:0

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer.Dispose (System.Boolean disposing) [0x00083] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\NavigationPageRenderer.cs:135

I/MonoDroid(11638):   at Java.Lang.Object.Dispose () [0x00000] in <33e6e739ac344166b157e323586f11a1>:0

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.SetPage (Xamarin.Forms.Page newRoot) [0x0003f] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:226

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.InternalSetPage (Xamarin.Forms.Page page) [0x0001a] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:370

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.AppOnPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs args) [0x00012] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:321

I/MonoDroid(11638):   at Xamarin.Forms.BindableObject.OnPropertyChanged (System.String propertyName) [0x0000a] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\BindableObject.cs:136

I/MonoDroid(11638):   at Xamarin.Forms.Element.OnPropertyChanged (System.String propertyName) [0x00000] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\Element.cs:380

I/MonoDroid(11638):   at Xamarin.Forms.Application.set_MainPage (Xamarin.Forms.Page value) [0x0008b] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\Application.cs:90

I/MonoDroid(11638):   at App.App.Instance_DataIsReady (System.Object sender, App.EventArguments.DataIsReadyEventArgs e) [0x0004d] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at (wrapper delegate-invoke) <Module>:invoke_void_object_DataIsReadyEventArgs (object,App.EventArguments.DataIsReadyEventArgs)

I/MonoDroid(11638):   at App.DataCache.OnDataIsReady (App.EventArguments.DataIsReadyStates state) [0x0001b] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at App.DataCache.set_PlayerWinnings (System.Collections.Generic.IEnumerable`1[T] value) [0x00012] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at App.DataCache+<RefreshData>d__37.MoveNext () [0x00351] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638): --- End of stack trace from previous location where exception was thrown ---
</code>```

答: The issue turned out to be that MainPage was being assigned to twice. It wasn't related to Auth.</p>

Body:
I'm using Xamarin.Auth to log into Facebook. I created a separate Renderer for iOS and Android.
In the auth.Completed I call a method AfterLogin(UserInfo) in the PCL class of the custom renderer. This does some additional work and then calls

App.Current.MainPage = new NavigationPage(new MainPage());

It looks like the page is constructed correctly and all methods return correctly until an Exception Unhandled gets thrown. The only text is "An unhandled exception occured."

In iOS, everything works fine. It calls the exact same PCL code.

I have no idea what view it is referring to.

Edit
Stack trace from ADB

  I/MonoDroid(11638): UNHANDLED EXCEPTION:

 I/MonoDroid(11638): Java.Lang.IllegalArgumentException: No view found for id 0x4 (unknown) for fragment FragmentContainer{436fa3e8 #0 id=0x4}

I/MonoDroid(11638):   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <d18287e1d683419a8ec3216fd78947b9>:0

I/MonoDroid(11638):   at Java.Interop.JniEnvironment+InstanceMethods.CallBooleanMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method) [0x00068] in <5716a943049b49ca928a3a1c8d2386f4>:0

I/MonoDroid(11638):   at Android.Runtime.JNIEnv.CallBooleanMethod (System.IntPtr jobject, System.IntPtr jmethod) [0x0000e] in <33e6e739ac344166b157e323586f11a1>:0

I/MonoDroid(11638):   at Android.Support.V4.App.FragmentManagerInvoker.ExecutePendingTransactions () [0x00033] in <7e083afc7c9045f59e01d9c14931060d>:0

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer.Dispose (System.Boolean disposing) [0x00083] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\NavigationPageRenderer.cs:135

I/MonoDroid(11638):   at Java.Lang.Object.Dispose () [0x00000] in <33e6e739ac344166b157e323586f11a1>:0

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.SetPage (Xamarin.Forms.Page newRoot) [0x0003f] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:226

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.InternalSetPage (Xamarin.Forms.Page page) [0x0001a] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:370

I/MonoDroid(11638):   at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.AppOnPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs args) [0x00012] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:321

I/MonoDroid(11638):   at Xamarin.Forms.BindableObject.OnPropertyChanged (System.String propertyName) [0x0000a] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\BindableObject.cs:136

I/MonoDroid(11638):   at Xamarin.Forms.Element.OnPropertyChanged (System.String propertyName) [0x00000] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\Element.cs:380

I/MonoDroid(11638):   at Xamarin.Forms.Application.set_MainPage (Xamarin.Forms.Page value) [0x0008b] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\Application.cs:90

I/MonoDroid(11638):   at App.App.Instance_DataIsReady (System.Object sender, App.EventArguments.DataIsReadyEventArgs e) [0x0004d] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at (wrapper delegate-invoke) <Module>:invoke_void_object_DataIsReadyEventArgs (object,App.EventArguments.DataIsReadyEventArgs)

I/MonoDroid(11638):   at App.DataCache.OnDataIsReady (App.EventArguments.DataIsReadyStates state) [0x0001b] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at App.DataCache.set_PlayerWinnings (System.Collections.Generic.IEnumerable`1[T] value) [0x00012] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638):   at App.DataCache+<RefreshData>d__37.MoveNext () [0x00351] in <9b95d86146df403c82b64e5a8ab6a9cf>:0

I/MonoDroid(11638): --- End of stack trace from previous location where exception was thrown ---


问:
java regular expression to match file path
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

```<code>import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}
</code>```

However it's always giving me , false as result .

答:
Use this regex:

```<code>"([a-zA-Z]:)?(\\\\[a-zA-Z0-9._-]+)+\\\\?";
</code>```

I added two modifications: you forgot to add . for matching the file name abc.txt and backslash escaping (\\) was also needed.

Body:
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

However it's always giving me , false as result .

Body:
Use this regex:

"([a-zA-Z]:)?(\\\\[a-zA-Z0-9._-]+)+\\\\?";

I added two modifications: you forgot to add . for matching the file name abc.txt and backslash escaping (\\) was also needed.


问:
SQL query for full outer join
I have 3 tables a, b, and c.
Table a contains the ids of the stores, their earning date, and count of sale (flight tickets).

Table b contains the id, sale date, and count of clothing orders.

Table c contains the id, date and total count.

```<code>SQL> select * from a;

STOREID          EARNINGDATE COUNT_FLIGHT_TICKETS
-------------------- ----------- ----------------
store01         14980000           10
store01         14980001           32
store02         14980000          134

SQL> select * from b;

STOREID          EARNINGDATE CLOTHES_SALE_COUNT
-------------------- ----------- ---------------
store01         14980000           6
store02         14980000           6

SQL> select * from c;

STOREID          EARNINGDATE TOTAL_SALE_COUNT
-------------------- ----------- -------------
store01         14980001        32
store01         14980000        16
store02         14980000       134
</code>```

Given above the tables, I have to print all the stores ids, with their date of earning for total sale, flight sale, and clothing sale.

```<code>|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |
</code>```

I have used below query, but failing to get the above.

```<code>select b.storeId , sum(a.COUNT_FLIGHT_TICKETS),
  sum(b.CLOTHES_SALE_COUNT), sum (c.TOTAL_SALE_COUNT)
from a
full outer join b on a.storeId = b.storeId
  and a.EarningDate = b.earningdate
full outer join c on a.storeId = c.storeId
  and a.earningDate = b.earningDate group by a.storeId;
</code>```

This query does not give all the rows and having some bug.

```<code>STOREID          flight clothing        total
------       --------- --------- --------------------
store02           134        6           134
store01           52             12           48
</code>```

Can someone help me to correct this query to get the expected output?

答:
Assuming that for each table, (storeId, earningdate) is unique or compound keys, group by will be unnecessary.
You can try this query.

```<code>select
    IF(isnull(a.STOREID), IF(isnull(b.STOREID), c.STOREID, b.STOREID),a.STOREID) as StoreId,
    IF(isnull(a.EARNINGDATE), IF(isnull(b.EARNINGDATE), c.EARNINGDATE, b.EARNINGDATE),a.EARNINGDATE) as EarningDate,
    IF(isnull(COUNT_FLIGHT_TICKETS),0,COUNT_FLIGHT_TICKETS) as FlightCount,
    IF(isnull(CLOTHES_SALE_COUNT),0,CLOTHES_SALE_COUNT) as ClothingCount,
    IF(isnull(TOTAL_SALE_COUNT),0,TOTAL_SALE_COUNT) as TotalCount
from a full outer join b
    on a.storeId = b.storeId and a.EarningDate = b.earningdate
    full outer join c
       on a.storeId = c.storeId and a.earningDate = c.earningDate;
</code>```

Result was:

```<code>STOREID   EarningDate    flight    clothing        total
------   -------------  --------- --------- --------------------
store01      14980000      10         6             16
store02      14980000      134        6             134
store01      14980001      32         0             32
</code>```

Is this your expected result?
I think you forgot the earning date.

Given above the tables, I have to print all the stores ids, with their
  date of earning for total sale, flight sale, and clothing sale.

|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |

Title: SQL query for full outer join

Body:
I have 3 tables a, b, and c.
Table a contains the ids of the stores, their earning date, and count of sale (flight tickets).

Table b contains the id, sale date, and count of clothing orders.

Table c contains the id, date and total count.

SQL> select * from a;

STOREID          EARNINGDATE COUNT_FLIGHT_TICKETS
-------------------- ----------- ----------------
store01         14980000           10
store01         14980001           32
store02         14980000          134

SQL> select * from b;

STOREID          EARNINGDATE CLOTHES_SALE_COUNT
-------------------- ----------- ---------------
store01         14980000           6
store02         14980000           6

SQL> select * from c;

STOREID          EARNINGDATE TOTAL_SALE_COUNT
-------------------- ----------- -------------
store01         14980001        32
store01         14980000        16
store02         14980000       134

Given above the tables, I have to print all the stores ids, with their date of earning for total sale, flight sale, and clothing sale.

|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |

I have used below query, but failing to get the above.

select b.storeId , sum(a.COUNT_FLIGHT_TICKETS),
  sum(b.CLOTHES_SALE_COUNT), sum (c.TOTAL_SALE_COUNT)
from a
full outer join b on a.storeId = b.storeId
  and a.EarningDate = b.earningdate
full outer join c on a.storeId = c.storeId
  and a.earningDate = b.earningDate group by a.storeId;

This query does not give all the rows and having some bug.

STOREID          flight clothing        total
------       --------- --------- --------------------
store02           134        6           134
store01           52             12           48

Can someone help me to correct this query to get the expected output?

Body:
Assuming that for each table, (storeId, earningdate) is unique or compound keys, group by will be unnecessary.
You can try this query.

select
    IF(isnull(a.STOREID), IF(isnull(b.STOREID), c.STOREID, b.STOREID),a.STOREID) as StoreId,
    IF(isnull(a.EARNINGDATE), IF(isnull(b.EARNINGDATE), c.EARNINGDATE, b.EARNINGDATE),a.EARNINGDATE) as EarningDate,
    IF(isnull(COUNT_FLIGHT_TICKETS),0,COUNT_FLIGHT_TICKETS) as FlightCount,
    IF(isnull(CLOTHES_SALE_COUNT),0,CLOTHES_SALE_COUNT) as ClothingCount,
    IF(isnull(TOTAL_SALE_COUNT),0,TOTAL_SALE_COUNT) as TotalCount
from a full outer join b
    on a.storeId = b.storeId and a.EarningDate = b.earningdate
    full outer join c
       on a.storeId = c.storeId and a.earningDate = c.earningDate;

Result was:

STOREID   EarningDate    flight    clothing        total
------   -------------  --------- --------- --------------------
store01      14980000      10         6             16
store02      14980000      134        6             134
store01      14980001      32         0             32

Is this your expected result?
I think you forgot the earning date.

Given above the tables, I have to print all the stores ids, with their
  date of earning for total sale, flight sale, and clothing sale.

|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |


问:
why does an array with a property cause an undefined error in JS
This syntax works fine:

```<code>var foo = [];
foo[0] = "do";
foo[1] = "re";
</code>```

I'm trying to do the same using properties, like so.

```<code>var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";
</code>```

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

```<code>foo[i] = i
</code>```

but when using an array element with a property, like

```<code>foo[i].note = i
</code>```

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?

答:
Your foo variable has only one element, in this case

```<code>{
note: "",
}
</code>```

so when you try to access to the index [1] this result on a undefined value.

Body:
This syntax works fine:

var foo = [];
foo[0] = "do";
foo[1] = "re";

I'm trying to do the same using properties, like so.

var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

foo[i] = i

but when using an array element with a property, like

foo[i].note = i

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?

Body:
Your foo variable has only one element, in this case

{
note: "",
}

so when you try to access to the index [1] this result on a undefined value.


问:
Disable error reporting entirely in Laravel production?
I would like to disable error reporting entirely on production, because we have some very old code we still need to fix but for now does work (yes I don't like it either). We cannot fix everything in a few days, so we need to just supress the warnings and exceptions like we always did.

The real problem is that it already throws an exception on a simple lazy bug like (because var is not defined)

```<code>if(!$var) {
     // do whatever
}
</code>```

tried

APP_DEBUG=false

APP_LOG_LEVEL=emergency

```<code>display_errors(false);
set_error_handler(null);
set_exception_handler(null);
</code>```

But it still shows an ErrorException

Undefined variable: script_name_vars_def

edit: The code works like this

web.php

```<code>Route::any('/someroute', 'somecontroller@controllerFunc');
</code>```

somecontroller.php

```<code>public controllerFunc() {
    ob_start();
    require '/old_index.php';
    $html = ob_get_clean();

    return response($html);
}
</code>```

This way we use Laravel routing without having to rewrite the old code immediately.

I know I can fix this warning very easy, but there are many, many more of these errors and we need to use Laravel routing now. Fix the problems later.

ideas

Use some wildcard in $dontReport.

Use a @ suppression at the right place

Can it be http://php.net/manual/en/scream.examples-simple.php

edit to explain after which steps middleware didn't work

1) create midddleware

```<code>php artisan make:middleware SuppressExceptions
</code>```

2) Write it

SuppressExceptions.php

```<code>public function handle($request, Closure $next)
{
    error_reporting(0);
    return $next($request);
}
</code>```

3) Register

laravel/app/Http/Kernel.php

```<code>protected $middlewareGroups = [
   'web' => [
       \App\Http\Middleware\SuppressExceptions::class,
],
</code>```

答:
Laravel debug settings is located in the .env file, in which you can set the debug option as follows:

```<code>APP_DEBUG = true
</code>```

but...

Laravel also have config mechanism that located in app.php in the config folder, which defaults to:

```<code>'debug' => env('APP_DEBUG', false),
</code>```

which tells Laravel to use the .env value, and defaults to false, but anyone with access to the file, can simply change it to:

```<code>'debug' => true,
</code>```

so that your .env value gets ignored by Laravel.

Body:
I would like to disable error reporting entirely on production, because we have some very old code we still need to fix but for now does work (yes I don't like it either). We cannot fix everything in a few days, so we need to just supress the warnings and exceptions like we always did.

The real problem is that it already throws an exception on a simple lazy bug like (because var is not defined)

if(!$var) {
     // do whatever
}

tried

APP_DEBUG=false

APP_LOG_LEVEL=emergency

display_errors(false);
set_error_handler(null);
set_exception_handler(null);

But it still shows an ErrorException

Undefined variable: script_name_vars_def

edit: The code works like this

web.php

Route::any('/someroute', 'somecontroller@controllerFunc');

somecontroller.php

public controllerFunc() {
    ob_start();
    require '/old_index.php';
    $html = ob_get_clean();

    return response($html);
}

This way we use Laravel routing without having to rewrite the old code immediately.

I know I can fix this warning very easy, but there are many, many more of these errors and we need to use Laravel routing now. Fix the problems later.

ideas

Use some wildcard in $dontReport.

Use a @ suppression at the right place

Can it be http://php.net/manual/en/scream.examples-simple.php

edit to explain after which steps middleware didn't work

1) create midddleware

php artisan make:middleware SuppressExceptions

2) Write it

SuppressExceptions.php

public function handle($request, Closure $next)
{
    error_reporting(0);
    return $next($request);
}

3) Register

laravel/app/Http/Kernel.php

protected $middlewareGroups = [
   'web' => [
       \App\Http\Middleware\SuppressExceptions::class,
],

Body:
Laravel debug settings is located in the .env file, in which you can set the debug option as follows:

APP_DEBUG = true

but...

Laravel also have config mechanism that located in app.php in the config folder, which defaults to:

'debug' => env('APP_DEBUG', false),

which tells Laravel to use the .env value, and defaults to false, but anyone with access to the file, can simply change it to:

'debug' => true,

so that your .env value gets ignored by Laravel.


问:
Get value from multi tr of table
I have many table row, i want to get the value (it's a number) of each row to an array !

```<code><form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]" /></td>
        </tr>
    </tbody>
</table>
</code>```

Like this code, i want to get the value of each "pduct" !

答:
You can select the elements in question with $('#temp1 input[name="pduct[]"]') - that is, use the elements' name attribute, but limited to inputs that are within #temp1.

To get all their values you could use the .map() method, which returns a new jQuery object, and then the .get() method to convert that to an array:

```<code>var arr = $('#temp1 input[name="pduct[]"]').map(function() { return this.value }).get()
</code>```

In the context of, say, a button click, you'd have something like the following:

$("button").click(function() {
  var arr = $('#temp1 input[name="pduct[]"]').map(function() { return this.value }).get()

  console.log(JSON.stringify(arr))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button">Get Values</button>
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
    </tbody>
</table></code>```

Note that the HTML in the original version of question was invalid because the id attribute needs to be unique. But that doesn't stop this code working because I'm selecting based on the name attribute.

Title: Get value from multi tr of table

Body:
I have many table row, i want to get the value (it's a number) of each row to an array !

<form class="form-horizontal" id="form1" name="form1" method="post" action="url">

            Name
            Number

            A
            <input type="number" id="pduct1" class="product" name="pduct[]" />

            B
            <input type="number" id="pduct2" class="product" name="pduct[]" />

            C
            <input type="number" id="pduct3" class="product" name="pduct[]" />

            D
            <input type="number" id="pduct4" class="product" name="pduct[]" />

Like this code, i want to get the value of each "pduct" !

Body:
You can select the elements in question with $('#temp1 input[name="pduct[]"]') - that is, use the elements' name attribute, but limited to inputs that are within #temp1.

To get all their values you could use the .map() method, which returns a new jQuery object, and then the .get() method to convert that to an array:

var arr = $('#temp1 input[name="pduct[]"]').map(function() { return this.value }).get()

In the context of, say, a button click, you'd have something like the following:

$("button").click(function() {
  var arr = $('#temp1 input[name="pduct[]"]').map(function() { return this.value }).get()

  console.log(JSON.stringify(arr))
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button">Get Values</button>
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct" name="pduct[]" /></td>
        </tr>
    </tbody>
</table>

Note that the HTML in the original version of question was invalid because the id attribute needs to be unique. But that doesn't stop this code working because I'm selecting based on the name attribute.


问:
How to get the template path in the view django
So I'm trying to get the template path in my view. Is there a dynamic way of doing this because at the moment I am hard-coding the path.

```<code>html = 'C:/Users/user/Desktop/project/src/templates/project.html'
</code>```

Templates Path

```<code>TEMPLATES = [
   'DIRS': [os.path.join(BASE_DIR, "templates")],
]
</code>```

View

```<code>html = 'C:/Users/user/Desktop/project/src/templates/project.html'
open_html = open(html, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
image = soup.find('img', {'name':'image_url'})
img_url = image.get('src')
open_html.close()
</code>```

答:
It's best to store your templates within your app.
for example, if your app called polls your template should be at polls/templates/polls/

You can read more about it here:
https://docs.djangoproject.com/en/1.11/intro/tutorial03/

Body:
So I'm trying to get the template path in my view. Is there a dynamic way of doing this because at the moment I am hard-coding the path.

html = 'C:/Users/user/Desktop/project/src/templates/project.html'

Templates Path

TEMPLATES = [
   'DIRS': [os.path.join(BASE_DIR, "templates")],
]

View

html = 'C:/Users/user/Desktop/project/src/templates/project.html'
open_html = open(html, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
image = soup.find('img', {'name':'image_url'})
img_url = image.get('src')
open_html.close()


问:
FindWindowEx Windows API returns nothing in AutoIt
I'm using the following code to return handle for a open file dialog box shown from Notepad.

```<code>Global $Result = DllCall("User32.dll", "HWND", "FindWindowExA", "HWND", WinGetHandle("[CLASS:Notepad]"), "HWND", Null, "STR", "#32770", "STR", "Open")
ConsoleWrite("FindWindowEx Return Value: " & String($Result[0]) & @CRLF)
</code>```

This always returns 0x00000000, but given parameters seems correct.

Why does this function return nothing here?

UPDATE

The following syntax worked, but I still can't specify the parent window:

```<code>Global $Result = DllCall('User32.dll', 'HWND', 'FindWindowExW', 'HWND', Null, 'HWND', Null, 'WSTR', '#32770', 'WSTR', 'Open')
</code>```

This finds every dialog box (Paint, WordPad etc.) , but I only want to get the handle to dialog box with parent as Notepad.

答:
There is no single API to restrict the search to just Notepad.  You will have to enumerate all available #32770 windows, looking for ones that belong to a Notepad process, until you find the one you are looking for.

To enumerate the windows, you can use either:

EnumWindows(), filtering in the callback function using GetClassName() and GetWindowText().

FindWindowEx() in a loop, initially setting hwndParent=0 and hwndChildAfter=0, and then setting hwndChildAfter to the last found window on each subsequent call.

To test if a given window belongs to Notepad, you can:

use GetWindowThreadProcessId() to get the window's owning process ID.

then use OpenProcess() to open a handle to the process.

then use GetModuleFileNameEx(), GetProcessImageFileName(), or QueryFullProcessImageName() to retrieve the path and filename of the EXE that created the process.

check if the filename is notepad.exe and the path is the Windows system folder.

Body:
I'm using the following code to return handle for a open file dialog box shown from Notepad.

Global $Result = DllCall("User32.dll", "HWND", "FindWindowExA", "HWND", WinGetHandle("[CLASS:Notepad]"), "HWND", Null, "STR", "#32770", "STR", "Open")
ConsoleWrite("FindWindowEx Return Value: " & String($Result[0]) & @CRLF)

This always returns 0x00000000, but given parameters seems correct.

Why does this function return nothing here?

UPDATE

The following syntax worked, but I still can't specify the parent window:

Global $Result = DllCall('User32.dll', 'HWND', 'FindWindowExW', 'HWND', Null, 'HWND', Null, 'WSTR', '#32770', 'WSTR', 'Open')

This finds every dialog box (Paint, WordPad etc.) , but I only want to get the handle to dialog box with parent as Notepad.


问:
Number of digits using while true in Python
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

```<code>number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)
</code>```

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

答:
you can try this way

```<code>number = int(input("Write Number:"))
b = len(str(number))
print(b)
</code>```

or you can change '/' into '//' , it does work

update

```<code>b = len(str(abs(number)))
</code>```

Body:
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

Body:
you can try this way

number = int(input("Write Number:"))
b = len(str(number))
print(b)

or you can change '/' into '//' , it does work

update

b = len(str(abs(number)))


问:
Images uploaded from mobile have incorrect orientation
I'm developing Ruby on Rails app with Carrierwave Gem. Inside the app, user can upload profile image. It works well on desktop, but when you upload the image from mobile device, the image is shown sideway.

So my questions are :

1) What is the proper way to correct the orientation?

2) Is it possible to correct the orientation with Carrierwave?

答:
before you do the upload set auto_orient
how about if you set the carrier wave as follow

create / add app/uploaders/image_uploader.rb add this code below

```<code>class ImageUploader < CarrierWave::Uploader::Base
  process :fix_exif_rotation
  def fix_exif_rotation
      manipulate! do |image|
        image.tap(&:auto_orient)
      end
  end
end
</code>```

Body:
before you do the upload set auto_orient
how about if you set the carrier wave as follow

create / add app/uploaders/image_uploader.rb add this code below

class ImageUploader < CarrierWave::Uploader::Base
  process :fix_exif_rotation
  def fix_exif_rotation
      manipulate! do |image|
        image.tap(&:auto_orient)
      end
  end
end


问:
Angular 2 : Define global constants for api endpoints
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

```<code>getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }
</code>```

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

答:
You can just have a constants file. Its not a special file, we can do it in any file.

url.constants.ts

```<code>export const URL1 = "..... "
export const URL2 = " .... "
</code>```

You can then access them anywhere in your code

```<code>import { URL1 } from 'url.constants';
</code>```

or you can put them in a JSON file

Its not straightforward. You can see how it is done here https://hackernoon.com/import-json-into-typescript-8d465beded79

As mentioned in comments, it got easier :  https://stackoverflow.com/a/50674344/1195056

Update:

Another advantage of putting constants in typescript file is: we can use functions.

For ex:

```<code>export const USER_NOT_FOUND = (user:string)=> `${user} not found `
</code>```

This can be used like

```<code>const errorMessage = USER_NOT_FOUND(this.user.name);
</code>```

Body:
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

Body:
You can just have a constants file. Its not a special file, we can do it in any file.

url.constants.ts

export const URL1 = "..... "
export const URL2 = " .... "

You can then access them anywhere in your code

import { URL1 } from 'url.constants';

or you can put them in a JSON file

Its not straightforward. You can see how it is done here https://hackernoon.com/import-json-into-typescript-8d465beded79

As mentioned in comments, it got easier :  https://stackoverflow.com/a/50674344/1195056

Update:

Another advantage of putting constants in typescript file is: we can use functions.

For ex:

export const USER_NOT_FOUND = (user:string)=> `${user} not found `

This can be used like

const errorMessage = USER_NOT_FOUND(this.user.name);