问:
Regular expression in distinct texts
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

```<code>referente[,;]*\s\S\s(.+)\.\sOnde
</code>```

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

答:
you can use the following regex to match the 2 bold parts of your examples:

```<code>(à\sELIANE\s\w+\s\w+SES)|(referente[,;]*\s\S\s.+\.\sOnde)
</code>```

Good luck!

Title: Regular expression in distinct texts

Body:
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

referente[,;]*\s\S\s(.+)\.\sOnde

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

Body:
you can use the following regex to match the 2 bold parts of your examples:

(à\sELIANE\s\w+\s\w+SES)|(referente[,;]*\s\S\s.+\.\sOnde)

Good luck!


来源: stackexchange

问:
Google Calendar API PHP (400) Missing end time
I use the following code to create an event but got error.

```<code>$service = new Google_Service_Calendar();
$calendarId = "<some calendar id>";
$startDate = "2017-12-04";
$startTime = "18:00:00";
$endDate = "2017-12-04";
$endTime = "19:00:00";
$tzOffset = "+08";
$newEvent = new Google_Service_Calendar_Event();
$newEvent->setSummary("title");
$newEvent->setLocation("where");
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime("{$startDate}T{$startTime}.000{$tzOffset}:00");
$newEvent->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime("{$endDate}T{$endTime}.000{$tzOffset}:00");
$newEvent->setEnd($end);
$newEvent->setDescription("desc");

$result = $service->events->insert($calendarId, $newEvent);
</code>```

The result as follows.

```<code>Error calling PUT <some url>: (400) Missing end time.
</code>```

So what's wrong? Please help. Thanks!

答:
I finally figured out the reason. It was my bad.

The function was to create the whole schedule on Google Calendar based on the schedule in my system. I tried to truncate the summary field before this function. The problem was here since there're chances that the summary field is multibyte string while I used substr() to truncate, the resulting string would occasionally contain unwanted characters. Those characters malformed the JSON created by the API. And the server probably parse the JSON properly therefore couldn't get some attributes, say, the end time attribute. The error message was correct but misleading.

ContentLicense: CC BY-SA 3.0

Body:
I use the following code to create an event but got error.

$service = new Google_Service_Calendar();
$calendarId = "<some calendar id>";
$startDate = "2017-12-04";
$startTime = "18:00:00";
$endDate = "2017-12-04";
$endTime = "19:00:00";
$tzOffset = "+08";
$newEvent = new Google_Service_Calendar_Event();
$newEvent->setSummary("title");
$newEvent->setLocation("where");
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime("{$startDate}T{$startTime}.000{$tzOffset}:00");
$newEvent->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime("{$endDate}T{$endTime}.000{$tzOffset}:00");
$newEvent->setEnd($end);
$newEvent->setDescription("desc");

$result = $service->events->insert($calendarId, $newEvent);

The result as follows.

Error calling PUT <some url>: (400) Missing end time.

So what's wrong? Please help. Thanks!


问:
Querying mongodb for documents by age
On a monthly basis, I want to delete all documents older than 1 month from one of my collections. An example document from the collection looks something like this:

```<code>{
    _id: ObjectId("56e75f1ce851695805ead8ae"),
    createDate: ISODate("2016-03-15T01:02:20.821Z"),
    foo: "bar"
}
</code>```

I want to have this task be automatically scheduled to happen so it requires no human input--say, as a cron job--and so I would like for it to have as little logic as possible.

How would I query for documents where the createDate is older than 1 month? I had thought to try something like this:

```<code>db.col.find({createDate: {$lt: ISODate(ISODate().getTime() - 1000*3600*24*30)}});
</code>```

... where I create a new ISODate with the current time minus 1 month of milliseconds, but this isn't returning any data. It's also kinda ugly, even if it did work. How would I go about accomplishing this?

答:
Well, I figured it out. It seems my syntax was a bit wrong... not entirely certain how this correct syntax works, to be honest, but it does what I need.</p>

```<code>db.col.find({createDate: {$lt: new Date((new Date())-1000*3600*24*30)}});
</code>```

Title: Querying mongodb for documents by age

Body:
On a monthly basis, I want to delete all documents older than 1 month from one of my collections. An example document from the collection looks something like this:

{
    _id: ObjectId("56e75f1ce851695805ead8ae"),
    createDate: ISODate("2016-03-15T01:02:20.821Z"),
    foo: "bar"
}

I want to have this task be automatically scheduled to happen so it requires no human input--say, as a cron job--and so I would like for it to have as little logic as possible.

How would I query for documents where the createDate is older than 1 month? I had thought to try something like this:

db.col.find({createDate: {$lt: ISODate(ISODate().getTime() - 1000*3600*24*30)}});

... where I create a new ISODate with the current time minus 1 month of milliseconds, but this isn't returning any data. It's also kinda ugly, even if it did work. How would I go about accomplishing this?

Body:
Well, I figured it out. It seems my syntax was a bit wrong... not entirely certain how this correct syntax works, to be honest, but it does what I need.

db.col.find({createDate: {$lt: new Date((new Date())-1000*3600*24*30)}});


问:
Python Selenium : finding an element and clicking a button based on Text
Basically, I am trying to create a bot that can find an element on a page with a given raw_input text, finding the button, and clicking it. The purpose of this is to click on links (buttons) that may not be on the web page yet, but will appear after the site refreshes. Because of this, I cannot find elements by XPATH, because the XPATH will be unknown until the second the link becomes available. So, my question is: is there a way for Selenium to find a button based on text and click it? Here is some of my code:

```<code>key1 = raw_input('Enter the first keyword: ')
key2 = raw_input('Enter the second keyword: ')
key3 = raw_input('Enter the third keyword: ')
</code>```

...

```<code>elem1 =driver.find_elements_by_xpath("//*[contains(text(), key1)]")
    if elem1.is_displayed():
        elem1.click()
    else:
        print "Cannot find element to click. Retrying..."
        driver.refresh()
</code>```

I need the program to find the text based on the keywords, and then click the button / link with these keywords in it. Is this possible? or only possible with XPATHs? The example code i gave with giving an elem has not been working.

thanks in advance

答:
Ok first of all, the only one of selecting an element by text is sadly xpath, but do not worry, there is a workaround you could use waits </p>

```<code>#Libraries (those comes with selenium, you don't have to install anything)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#Way
elem1 = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(),
{})]'.format(key1))
)
elem1.click()
</code>```

<p>this will make it wait for the element to be clickable if the element is not clickable after 10 seconds it will raise an error if it gets clickable before that time it will return the element and break the wait automatically. </p>

Body:
Basically, I am trying to create a bot that can find an element on a page with a given raw_input text, finding the button, and clicking it. The purpose of this is to click on links (buttons) that may not be on the web page yet, but will appear after the site refreshes. Because of this, I cannot find elements by XPATH, because the XPATH will be unknown until the second the link becomes available. So, my question is: is there a way for Selenium to find a button based on text and click it? Here is some of my code:

key1 = raw_input('Enter the first keyword: ')
key2 = raw_input('Enter the second keyword: ')
key3 = raw_input('Enter the third keyword: ')

...

elem1 =driver.find_elements_by_xpath("//*[contains(text(), key1)]")
    if elem1.is_displayed():
        elem1.click()
    else:
        print "Cannot find element to click. Retrying..."
        driver.refresh()

I need the program to find the text based on the keywords, and then click the button / link with these keywords in it. Is this possible? or only possible with XPATHs? The example code i gave with giving an elem has not been working.

thanks in advance

Body:
Ok first of all, the only one of selecting an element by text is sadly xpath, but do not worry, there is a workaround you could use waits

#Libraries (those comes with selenium, you don't have to install anything)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#Way
elem1 = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(),
{})]'.format(key1))
)
elem1.click()

this will make it wait for the element to be clickable if the element is not clickable after 10 seconds it will raise an error if it gets clickable before that time it will return the element and break the wait automatically.


问:
Cordova App's localStorage wiped after AppStore update
I need to save few datas on my App so i used localStorage. Actually LocalStorage is very useful: Free, fast and offline database.

But when I update my app from AppStore, all of my old datas gone. Localstorage wiped. Also when I search in stackoverflow, I learned that localStorage is reset when the memory of the device is full.

I'm looking for an easy to use, offline supported and permanent solution. I found pouchdb, but it's a bit complicated.

I'm curious about your suggestions.

Best.

答:
Right, you shouldn't rely on LocalStorage for anything important. I've used Sqlite for Cordova on a few projects and I think it works pretty well. The plugin provides a native implementation of Sqlite for your app to use. You get SQLite's features and the ability to run SQL queries, etc. The plugin persists the database to the device filesystem, so your data will be there after app updates. No affiliation, just a satisfied customer.

Update: OP clarified the requirements, and for storing a few simple key-value pairs you might consider the Cordova Secure Storage plugin. It works with iOS and Android and Windows 10, and is relatively straightforward to set up and use.


问:
SQL Query: Grouping the latest messages using SQL JOIN
I am trying to retrieve the latest messages about each post from different users using SQL. I have 3 tables:

The Users Table (To collect user Information)

The Post Table (To Collect post information)

The Messages Table (Table containing messages)

However, I am getting an error with my SQL Syntax, Here is the code

```<code>SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username,
   receipient,
   message,
   datestamp
FROM
   messages
   JOIN
      users
      ON messages.username = users.username
   JOIN
      posts
      ON posts.postid = messages.messageid
WHERE
   messages.receipient = 'try-2a'
GROUP BY
   messages.messageid
ORDER BY
   messages.sequence DESC
</code>```

Error: Column 'username' in field list is ambiguous

Link to Fiddle with Schema

答: If you are trying to find the most recent message for each user, you would want to group by user, then find the max timestamp of each message in each user group. You can use that to then select the message with that timestamp matching it.</p>

Body:
I am trying to retrieve the latest messages about each post from different users using SQL. I have 3 tables:

The Users Table (To collect user Information)

The Post Table (To Collect post information)

The Messages Table (Table containing messages)

However, I am getting an error with my SQL Syntax, Here is the code

SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username,
   receipient,
   message,
   datestamp
FROM
   messages
   JOIN
      users
      ON messages.username = users.username
   JOIN
      posts
      ON posts.postid = messages.messageid
WHERE
   messages.receipient = 'try-2a'
GROUP BY
   messages.messageid
ORDER BY
   messages.sequence DESC

Error: Column 'username' in field list is ambiguous

Link to Fiddle with Schema


问:
Replace " with " in c#
In my website I am preparing an array using datagrid items in c#, which works fine, however when I have some text in the grid which has " as value code automatically replaces it with "

i have tried to replace " with " as below, however its failing and replacing " with \"

```<code>Array.Value += "|" + dgrFinal.Rows[i].Cells[1].Text.Replace
("amp;", "").Replace(""","\"")
</code>```

is there any way i can replace " with ".

Can anyone please help me in this.....come on guys you are expert.

答:
You can use HttpUtility. Here is an example.

```<code>using System.Web;
</code>```

...

```<code>string value1 = "<html>";
string value2 = HttpUtility.HtmlDecode(value1);
string value3 = HttpUtility.HtmlEncode(value2);
Debug.WriteLine(value1);
Debug.WriteLine(value2);
Debug.WriteLine(value3);
</code>```

This is the ouput:

```<code><html>
<html>
<html>
</code>```

I took the example from here.

Title: Replace " with " in c#

Body:
In my website I am preparing an array using datagrid items in c#, which works fine, however when I have some text in the grid which has " as value code automatically replaces it with "

i have tried to replace " with " as below, however its failing and replacing " with \"

Array.Value += "|" + dgrFinal.Rows[i].Cells[1].Text.Replace
("amp;", "").Replace(""","\"")

is there any way i can replace " with ".

Can anyone please help me in this.....come on guys you are expert.

Body:
You can use HttpUtility. Here is an example.

using System.Web;

...

string value1 = "&lt;html&gt;";
string value2 = HttpUtility.HtmlDecode(value1);
string value3 = HttpUtility.HtmlEncode(value2);
Debug.WriteLine(value1);
Debug.WriteLine(value2);
Debug.WriteLine(value3);

This is the ouput:

&lt;html&gt;
<html>
&lt;html&gt;

I took the example from here.


问:
Firefox Quantum - user-agent incorrect?
My Firefox was just updated to Quantum and looks like user-agent is incorrect. It's now:

Mozilla/5.0 (Windows; U; Windows NT 5.0; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3

All websites, also mozilla.org, show me "Your browser version is old, please update." But after I first run this version, I was informed that this is latest, new Firefox.

Due to this I cannot do anything and also can't install User-Agent switcher which is worked with previous Firefox version.

How I can restore Firefox?

答: I'm having the same issue. I have multiple computers and each computer is stuck on a different user/agent when the update occurred. Obviously if you used an add-on, whatever the setting was at update is the one you have been branded with. If you do a full delete and reinstall it should fix it. A real pain, but another option may be to dowload a newer user/agent add-on and try to change it that way.</p>

Title: Firefox Quantum - user-agent incorrect?


问:
Problem with Array Search in PHP
I am not finding what might be the problem in my program.

I am having an array like this

```<code>$arr = array("1", "urgent", "4", "low", "15", "avg");
</code>```

When i am searching this array using

```<code>$key = array_search("4", $arr);// Working
</code>```

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

```<code>$key = array_search("4", $arr); // Not working here - for searching "1"
</code>```

What might be the problem.

Thank You

答: I think you are using $key in thewrong way. $key = 0 and now if you do boolean evaluation it will act as false. You should use something like if($key >= 0) or if(is_int($key))

ContentLicense: CC BY-SA 2.5

Title: Problem with Array Search in PHP

Body:
I am not finding what might be the problem in my program.

I am having an array like this

$arr = array("1", "urgent", "4", "low", "15", "avg");

When i am searching this array using

$key = array_search("4", $arr);// Working

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

$key = array_search("4", $arr); // Not working here - for searching "1"

What might be the problem.

Thank You


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib / Image not found
I am running my app from xcode to my iOS device and I get this and black screen on iOS device.

Console text:

```<code>dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/10DB2FE8-EF09-4857-B4AC-0DB2E4419D6F/App-Name.app/App-Name
Reason: image not found
(lldb)
</code>```

答:
I got such issue, too
All other ways could not help me,
so I have done it on stupid way
created new project and pod install from scratch
and after confirmed it is working correctly, I copied all class files and storyboard files, at last done!
I think it is the last way for it, maybe could help you</p>

Body:
I am running my app from xcode to my iOS device and I get this and black screen on iOS device.

Console text:

dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/10DB2FE8-EF09-4857-B4AC-0DB2E4419D6F/App-Name.app/App-Name
Reason: image not found
(lldb)


问:
CSS center with translate and prevent content overflow
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div></code>```

答:
What I would recommend is to make use of a flexbox container.

With flexbox, all you need is three different styles in order to centralise an element both horizontally and vertically:

display: flex;

align-items: self;

justify-content: center;

In addition to using significantly less CSS rules, this will automatically ensure that the child element(s) doesn't overflow.

Then you just need to set a width on the child element(s) to showcase the horizontal centering.

This can be seen in the following:

.a {
  display: flex;
  align-items: center;
  justify-content: center;
}

.b {
  width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div></code>```

Hope this helps! :)

Body:
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus.

Body:
What I would recommend is to make use of a flexbox container.

With flexbox, all you need is three different styles in order to centralise an element both horizontally and vertically:

display: flex;

align-items: self;

justify-content: center;

In addition to using significantly less CSS rules, this will automatically ensure that the child element(s) doesn't overflow.

Then you just need to set a width on the child element(s) to showcase the horizontal centering.

This can be seen in the following:

.a {
  display: flex;
  align-items: center;
  justify-content: center;
}

.b {
  width: 200px;
}

<div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div>

Hope this helps! :)


问:
Preserving input filter activeadmin
I am trying to keep my inputs in my filter in activeadmin here my code:

```<code>controller do
    before_filter by_resolved_at_in: :index do
      if params[:q][:by_resolved_at_in_gteq].blank?
          params[:q][:by_resolved_at_in_gteq] = params[:q][:by_resolved_at_in_gteq]
    end
end
</code>```

but this doesnot work. Could you help me please?

答:
I'm not sure what you need, but because of the question I think that when working with ActiveAdmin it automatically creates a filter for each of your model attributes but if you add a custom filter all of them are taken away.

So, If you want to preserve the automatic created ones along with yours, maybe adding this line could solve the problem.

```<code>preserve_default_filters!
</code>```

Let me know if this was your question.

Title: Preserving input filter activeadmin

Body:
I am trying to keep my inputs in my filter in activeadmin here my code:

controller do
    before_filter by_resolved_at_in: :index do
      if params[:q][:by_resolved_at_in_gteq].blank?
          params[:q][:by_resolved_at_in_gteq] = params[:q][:by_resolved_at_in_gteq]
    end
end

but this doesnot work. Could you help me please?

Body:
I'm not sure what you need, but because of the question I think that when working with ActiveAdmin it automatically creates a filter for each of your model attributes but if you add a custom filter all of them are taken away.

So, If you want to preserve the automatic created ones along with yours, maybe adding this line could solve the problem.

preserve_default_filters!

Let me know if this was your question.


问:
How Hibernate uses(if it does) serialization

Does hibernate internally uses Serialization for persisting POJO classes? If yes, How does it use it in persisting data? If No, then how does it persist data to DB?

答:
Hibernate persists data to the database using SQL. Java serialization is not used at all. (SQL) databases are language-agnostic. As such, they cannot depend on language-specific technology such as Java serialization.

Serialization is only relevant when you need to send a POJO over the wire to other servers running Java. For example, if you have some sort of cache of POJOs that spans multiple machines, you could use serialization to send copies of the POJO over the wire.

See https://stackoverflow.com/a/2726387/14731 for a related discussion.


问:
Postgresql UPDATE on multiple columns in the same table
Im trying to update multiple columns in the same table. Im using node-postgres Here is what my code looks like.

```<code>client.query('UPDATE mytable SET column1 = ($1), column2 = ($2) WHERE id = ($3)',[data.a,data.b,data.id]);
</code>```

The code goes through with no errors however the columns don't get updated. The data (data.a,data.b,data.id) is defined properly.

Am I missing something vital?

答:
Thank you to all who helped.

All through the data was defined properly it was not actually being transferred on POST. Specifically data.id so the node-pg would not give an error but would not go through either since the data.id is missing.

After putting data.id within my form group it was solved.

Body:
Im trying to update multiple columns in the same table. Im using node-postgres Here is what my code looks like.

client.query('UPDATE mytable SET column1 = ($1), column2 = ($2) WHERE id = ($3)',[data.a,data.b,data.id]);

The code goes through with no errors however the columns don't get updated. The data (data.a,data.b,data.id) is defined properly.

Am I missing something vital?


问:
JavaScript not printing to textbox
I am trying to make a web tool that takes user imputed values as a list of objects and a number of objects to randomly choose and then will print out the number of objects chosen from the list at random when the button is clicked. However i have not been able to get anything to print. I have tried to call the variables both with qoutes and without them and i still haven't gotten the compute to print any results in the final read only textbox. I think the issue is somewhere in my script functions but i cant figure out where and i've spent hours looking up syntax and possible issues to no avail. Ive tried to work with inner.html without success and the current method (document.getById....) is copied from http://www.mauvecloud.net/randomchooser.html that works to randomly choose one thing and print the result.

```<code><html>
<style></style>
<head>

<title>Random Chooser</title>

<script>

 Array.protoype.chooseFromArray() = function(){
    var chosenIndex = Math.floor(Math.random() * ValueArray.length);
    var elementPicked = ValueArray["chosenIndex"];
    ValueArray.splice("chosenIndex",1);
    return elementPicked;
    }

function chooseRandomly(){
    var ValueArray = document.getElementById("valuelist").value.split("\n");
    var numItems = document.getElementById("items").value;
    var ReturnArray = [];
    for(i=0; i < numItems; i++){
    var element = ValueArray.chooseFromArray();
    ReturnArray.push("element");
    }
    document.getElementById("result").value = ReturnArray.toString();

    }

</script>
</code>```

```<code><body>
Enter some values, one on each line, then click the choose button to pick randomly.
    <form action onsubmit="return false;">
        <textarea id="valuelist" rows="15" cols="60"></textarea>
        <br>
        <br>
        Randomly choose <input type="number" id="items"  > items
        <br>
        <input type="button" value="Choose" onclick="chooseRandomly();return false">
        <br>
        <br>
        <input id="result" type="text" size="80" value readonly="readonly">
        <br>
        <br>
    </form>

</body>

</html>
</code>```

答:
You're confused on a few JavaScript syntax points. I won't bother correcting the non-idiomatic style, you should read more about that here on your own once you understand the changes outlined below.

First, here's the cleaned up and fixed version so we can take a look at it together:

```<code>Array.prototype.chooseFromArray = function() {
    var chosenIndex = Math.floor(Math.random() * this.length);
    var elementPicked = this[chosenIndex];
    this.splice(chosenIndex, 1);
    return elementPicked;
}

function chooseRandomly() {
    var ValueArray = document.getElementById("valuelist").value.split("\n");
    var numItems = document.getElementById("items").value;
    var ReturnArray = [];
    for (var i = 0; i < numItems; i++) {
        var element = ValueArray.chooseFromArray();
        ReturnArray.push(element);
    }

    document.getElementById("result").value = ReturnArray.toString();
}

window.chooseRandomly = chooseRandomly;
</code>```

First thing's first, to reference a function from HTML on JSFiddle you'll need it to be defined on the window. You don't normally need to do that, so you can mostly ignore that point.

Generally, you have several syntax errors.

Defining a property on an object (prototypes are objects (MDN)) happens just like variable assignment, so you just write object.<property_name> = value. You were calling chooseFromArray then assigning to that call (which is just invalid syntax).

When creating functions for prototypes, this will usually reference the object calling the function. In this case, any array calling chooseFromArray will have itself bound to the this reference inside the prototype function.

When accessing properties through the indexer you just pass the string. If it's a variable, you don't surround it with strings. Ex:

```<code>var chosenIndex = 123;
var elementPicked = this["chosenIndex"];
// This is the same as this.elementPicked;

var elementPicked = this[chosenIndex];
// This is what you want as you're accessing the `123` property on `this`
</code>```

The same goes for passing variables to functions. You just pass the variable. Anything inside of 's, ' ` 's and "s are string literals and will not reference any variables.

Title: JavaScript not printing to textbox

Body:
I am trying to make a web tool that takes user imputed values as a list of objects and a number of objects to randomly choose and then will print out the number of objects chosen from the list at random when the button is clicked. However i have not been able to get anything to print. I have tried to call the variables both with qoutes and without them and i still haven't gotten the compute to print any results in the final read only textbox. I think the issue is somewhere in my script functions but i cant figure out where and i've spent hours looking up syntax and possible issues to no avail. Ive tried to work with inner.html without success and the current method (document.getById....) is copied from http://www.mauvecloud.net/randomchooser.html that works to randomly choose one thing and print the result.

<title>Random Chooser</title>

Enter some values, one on each line, then click the choose button to pick randomly.
    <form action onsubmit="return false;">
        <textarea id="valuelist" rows="15" cols="60"></textarea>

        Randomly choose <input type="number" id="items"  > items

        <input type="button" value="Choose" onclick="chooseRandomly();return false">

        <input id="result" type="text" size="80" value readonly="readonly">

    </form>

Body:
You're confused on a few JavaScript syntax points. I won't bother correcting the non-idiomatic style, you should read more about that here on your own once you understand the changes outlined below.

First, here's the cleaned up and fixed version so we can take a look at it together:

Array.prototype.chooseFromArray = function() {
    var chosenIndex = Math.floor(Math.random() * this.length);
    var elementPicked = this[chosenIndex];
    this.splice(chosenIndex, 1);
    return elementPicked;
}

function chooseRandomly() {
    var ValueArray = document.getElementById("valuelist").value.split("\n");
    var numItems = document.getElementById("items").value;
    var ReturnArray = [];
    for (var i = 0; i < numItems; i++) {
        var element = ValueArray.chooseFromArray();
        ReturnArray.push(element);
    }

    document.getElementById("result").value = ReturnArray.toString();
}

window.chooseRandomly = chooseRandomly;

First thing's first, to reference a function from HTML on JSFiddle you'll need it to be defined on the window. You don't normally need to do that, so you can mostly ignore that point.

Generally, you have several syntax errors.

Defining a property on an object (prototypes are objects (MDN)) happens just like variable assignment, so you just write object.<property_name> = value. You were calling chooseFromArray then assigning to that call (which is just invalid syntax).

When creating functions for prototypes, this will usually reference the object calling the function. In this case, any array calling chooseFromArray will have itself bound to the this reference inside the prototype function.

When accessing properties through the indexer you just pass the string. If it's a variable, you don't surround it with strings. Ex:

var chosenIndex = 123;
var elementPicked = this["chosenIndex"];
// This is the same as this.elementPicked;

var elementPicked = this[chosenIndex];
// This is what you want as you're accessing the `123` property on `this`

The same goes for passing variables to functions. You just pass the variable. Anything inside of 's, ' ` 's and "s are string literals and will not reference any variables.


问:
JavaScript code with If Statements
I have been working on a text based game for personal use to get better at JavaScript. With this game, the user answers the questions that is written (like a story/choice game). This is my code...

```<code><!DOCTYPE HTML>
<html>

<head>
<!--<script type="text/javascript" src="gamescript.js"></script>-->

<style>
body {
  font-family: Calibri, sans-serif;
}

#mspace {
  padding: 10px 20px;
  background: #ff0;
}

.hideThis {
  display: none;
}

button {
  margin: 10px;
}

</style>

<script>

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the" + choice1;
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below
document.getElementById("mspace")

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases
window.onload = function(){
    document.getElementById("fight").onclick = fightResponse;
    document.getElementById("run").onclick = runResponse;
}

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

window.onload = function writeMessage() {
  // write message into the yellow paragraph
  document.getElementById("mspace").innerHTML = msg;
}

</script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

<!---- Boss ---->
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>

</body>
</html>
</code>```

When the questions appear, although it does what I want it to, I wanted it so that when the user enters either "Door 1" or "Door 2" for the first question, the 2nd question to appear after it. In my code, it's like a list of questions with text box underneath. It doesn't look nice and I don't know how to change it.

For the "Final Boss" code, It doesn't seem to be working and i don't know why. I have checked the F12 developer tool and no errors are showing.

All the help is appreciated and thank you!

答:
You have got to stop putting "window.onload" before things...
Maybe this example has a more desired effect..

Also a good coding practice is to put your content scripts just before the closing body tag. They you won't have so many onload issues.

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the" + choice1;
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases

document.getElementById("fight").onclick = fightResponse;
document.getElementById("run").onclick = runResponse;

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

function writeMessage() {
  // write message into the yellow paragraph
  document.getElementById("mspace").innerHTML = msg;
}
writeMessage();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>

<head>
<!--<script type="text/javascript" src="gamescript.js"></script>-->
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

<!---- Boss ---->
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>

</body>
</html></code>```

Title: JavaScript code with If Statements

Body:
I have been working on a text based game for personal use to get better at JavaScript. With this game, the user answers the questions that is written (like a story/choice game). This is my code...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

Fight the Monster!

  <button id="fight">Fight</button>
  <button id="run">Run</button>

When the questions appear, although it does what I want it to, I wanted it so that when the user enters either "Door 1" or "Door 2" for the first question, the 2nd question to appear after it. In my code, it's like a list of questions with text box underneath. It doesn't look nice and I don't know how to change it.

For the "Final Boss" code, It doesn't seem to be working and i don't know why. I have checked the F12 developer tool and no errors are showing.

All the help is appreciated and thank you!

Body:
You have got to stop putting "window.onload" before things...
Maybe this example has a more desired effect..

Also a good coding practice is to put your content scripts just before the closing body tag. They you won't have so many onload issues.

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the" + choice1;
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases

document.getElementById("fight").onclick = fightResponse;
document.getElementById("run").onclick = runResponse;

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

function writeMessage() {
  // write message into the yellow paragraph
  document.getElementById("mspace").innerHTML = msg;
}
writeMessage();

<!DOCTYPE HTML>
<html>

<head>
<!--<script type="text/javascript" src="gamescript.js"></script>-->
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

<!---- Boss ---->
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>

</body>
</html>


问:
How to disable stopOnEntry for files that are opened without a workspace?
When I open a python file without a workspace and start debugging it, the debugger breaks on the first line. I would like to change this behaviour, but I don't know how to do it for files that are opened without a workspace.</p>

答: Open launch.json (gear icon when on debugger tab).  Find the section for the python debugger you are using.  Change "stopOnEntry" from true to false.  Save.</p>


问:
React doesn't append class from className
I have a problem with React and don't know why, but React doesn't appent the attribute class in rendered HTML code. I import css file in body, import styles in react script, write className attribute, etc..

The result on page will be block without class –
test

In App.js

```<code>import React, {Component} from 'react';
import styles from '../assets/main.css';

export default class App extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <div className={styles.test}>test</div>
            </div>
        );
    }
}
</code>```

In main.css

```<code>.test {
    color: red;
}
</code>```

Webpack config

```<code>const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
const webpack = require('webpack');

module.exports = {
    entry: [
        'react-hot-loader/patch',
        __dirname + '/app/index.js'
    ],
    devServer: {
        hot: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }
        ]
    },
    output: {
        filename: 'transformed.js',
        path: __dirname + '/build'
    },
    plugins: [
        HTMLWebpackPluginConfig,
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    }
};
</code>```

答:
Importing your CSS stylesheet just causes Webpack to bundle it along with the rest of your JavaScript. You can't add styles.test as an attribute, that won't do anything. You need to specify the className as a string, just like you would for an HTML element.

```<code>render() {
    return (
        <div>
            <div className="test" >test</div>
        </div>
    );
}
</code>```

Body:
I have a problem with React and don't know why, but React doesn't appent the attribute class in rendered HTML code. I import css file in body, import styles in react script, write className attribute, etc..

The result on page will be block without class –
test

In App.js

import React, {Component} from 'react';
import styles from '../assets/main.css';

export default class App extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

test

        );
    }
}

In main.css

.test {
    color: red;
}

Webpack config

const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
const webpack = require('webpack');

module.exports = {
    entry: [
        'react-hot-loader/patch',
        __dirname + '/app/index.js'
    ],
    devServer: {
        hot: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }
        ]
    },
    output: {
        filename: 'transformed.js',
        path: __dirname + '/build'
    },
    plugins: [
        HTMLWebpackPluginConfig,
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.css']
    }
};

Body:
Importing your CSS stylesheet just causes Webpack to bundle it along with the rest of your JavaScript. You can't add styles.test as an attribute, that won't do anything. You need to specify the className as a string, just like you would for an HTML element.

render() {
    return (
        <div>
            <div className="test" >test</div>
        </div>
    );
}


问:
Read all types of files python 3
I'm working on an application in Python 3, but what I want is to upload any type of file. e. g. in c function :

```<code>fopen()
</code>```

you can load any file type. Is there any way to do that? already tried with :

```<code>open ()
</code>```

but it throws me errors:

UnicodeDecodeError:' charmap' code cant decode byte.

Help :(

答: f = open(file, mode='rb') opens file in binary mode.  f.read() then returns the file contents as bytes.

Title: Read all types of files python 3

Body:
I'm working on an application in Python 3, but what I want is to upload any type of file. e. g. in c function :

fopen()

you can load any file type. Is there any way to do that? already tried with :

open ()

but it throws me errors:

UnicodeDecodeError:' charmap' code cant decode byte.

Help :(


问:
Arrays, heap and stack and value types
```<code>int[] myIntegers;
myIntegers = new int[100];
</code>```

In the above code, is new int[100] generating the array on the heap? From what I've read on CLR via c#, the answer is yes. But what I can't understand, is what happens to the actual int's inside the array. As they are value types, I'd guess they'd have to be boxed, as I can, for example, pass myIntegers to other parts of the program and it'd clutter up the stack if they were left on it all the time. Or am I wrong? I'd guess they'd just be boxed and would live on the heap for as long the array existed.

答:
These are illustrations depicting above answer by @P Daddy

And I illustrated the corresponding contents in my style.

Title: Arrays, heap and stack and value types

Body:
int[] myIntegers;
myIntegers = new int[100];

In the above code, is new int[100] generating the array on the heap? From what I've read on CLR via c#, the answer is yes. But what I can't understand, is what happens to the actual int's inside the array. As they are value types, I'd guess they'd have to be boxed, as I can, for example, pass myIntegers to other parts of the program and it'd clutter up the stack if they were left on it all the time. Or am I wrong? I'd guess they'd just be boxed and would live on the heap for as long the array existed.


问:
How do you debug typescript in Visual Studio Code successfully?
I notice if you are using Node Package Manager generally you can have your package.json have something like this:

```<code>(dependencies and devDependencies omitted)..
"scripts": {
    "start": "concurrently \"npm run tscwatch\" \"npm run lite\" ",
    "tsc": "tsc",
    "tscwatch": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  }
</code>```

Then you just get to the level of the folder you are at and type in

```<code>npm install
</code>```

Then

```<code>npm start
</code>```

And lite server hosts your application and typescript compiles to javascript.  Provided that you have ran the equivalent of your typescript configurations and have a valid tsconfig.json.  That aside I am wanting to debug the Typescript and just running into wall after wall getting it working.  I know you can add 'launch.json' that VS Code uses to do MANY types of abilities to start programs.  And a lot of them work fine for simple apps I find online, but not Angular as I am using it.  But when I try to do an NPM Start in the launch.json like:

```<code> {
        "type": "node",
        "request": "launch",
        "name": "Launch via NPM ProAngular Example",
        "runtimeExecutable": "npm",
        "args": ["${relativeFile}"],
        "runtimeArgs": [
            "start"
        ]
    }
</code>```

It will run but then attempt to open Visual Studio Professional(may not be the case for others) and then have an error like: "Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:(port)).  I have tried other configs for NPM for launch and other things.  I just want to debug the Typescript when it is done with Angular, is that possible in VS Code?

答:
Follow the below instructions in VSCode:

1- Download the latest release of VS Code and install the Chrome debugger

2- Make sure Chrome is at least version version 59 (see issue)

3- Create your Angular app using angular-cli

4- Create a launch.jsonfile to configure the VS Code debugger and put it inside .vscode in your root folder.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome with ng serve",
      "url": "http://localhost:4200/#",
      "webRoot": "${workspaceRoot}"
    },
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome with ng test",
      "url": "http://localhost:9876/debug.html",
      "webRoot": "${workspaceRoot}"
    }
  ]
}```

Start your Angular app by running ng serve in your favourite terminal.

Start debugging in VS Code by pressing F5 or going to the debug section select Launch Chrome with ng serve followed by clicking the green debug icon.

Body:
I notice if you are using Node Package Manager generally you can have your package.json have something like this:

(dependencies and devDependencies omitted)..
"scripts": {
    "start": "concurrently \"npm run tscwatch\" \"npm run lite\" ",
    "tsc": "tsc",
    "tscwatch": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  }

Then you just get to the level of the folder you are at and type in

npm install

Then

npm start

And lite server hosts your application and typescript compiles to javascript.  Provided that you have ran the equivalent of your typescript configurations and have a valid tsconfig.json.  That aside I am wanting to debug the Typescript and just running into wall after wall getting it working.  I know you can add 'launch.json' that VS Code uses to do MANY types of abilities to start programs.  And a lot of them work fine for simple apps I find online, but not Angular as I am using it.  But when I try to do an NPM Start in the launch.json like:

 {
        "type": "node",
        "request": "launch",
        "name": "Launch via NPM ProAngular Example",
        "runtimeExecutable": "npm",
        "args": ["${relativeFile}"],
        "runtimeArgs": [
            "start"
        ]
    }

It will run but then attempt to open Visual Studio Professional(may not be the case for others) and then have an error like: "Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:(port)).  I have tried other configs for NPM for launch and other things.  I just want to debug the Typescript when it is done with Angular, is that possible in VS Code?

Body:
Follow the below instructions in VSCode:

1- Download the latest release of VS Code and install the Chrome debugger

2- Make sure Chrome is at least version version 59 (see issue)

3- Create your Angular app using angular-cli

4- Create a launch.jsonfile to configure the VS Code debugger and put it inside .vscode in your root folder.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome with ng serve",
      "url": "http://localhost:4200/#",
      "webRoot": "${workspaceRoot}"
    },
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome with ng test",
      "url": "http://localhost:9876/debug.html",
      "webRoot": "${workspaceRoot}"
    }
  ]
}

Start your Angular app by running ng serve in your favourite terminal.

Start debugging in VS Code by pressing F5 or going to the debug section select Launch Chrome with ng serve followed by clicking the green debug icon.


问:
ModelForm foreignkey field not loaded yet

I'm attempting to develop a work record tracker sort of app, very similar to a ticket tracker. Each 'ticket' can have multiple notes owned by employees (employees are tracked in a different app that has been installed into the ticket-tracker).

i.e.

```<code>MySite
  |___WorkRecords
     |__models.py
     |__views.py
     |__etc..    //standard app stuff
  |___emp #the uncreative name for the employee manager app
     |__         //standard stuff again...
</code>```

Within the models:

WorkRecords.models.py

```<code>class WorkRecord(models.Model):
    issuedate = models.DateField('date first issued',
             editable = False, default = timezone.now)
    owner = models.ForeignKey('emp.Employee', related_name='work_owner',
            on_delete=models.PROTECT)
    other_irrelevant_header_data...

    ....

class WorkRecordNote(models.Model):
    ref_wr = models.ForeignKey(WorkRecord, on_delete=models.CASCADE)
    note_text = models.CharField(max_length=1000)
    author = models.ForeignKey('emp.Employee', related_name='note_author',
            on_delete=models.PROTECT)

#Form class for the Work Record
class EditWR(ModelForm):
    class Meta:
        model = WorkRecord
        fields = '__all__'
</code>```

emp.models.py

```<code>class Employee(models.Model)
    data stuff
</code>```

At the moment, the models have all been migrated, but the data has not been input into the tables yet (MySQL tables are all there, matching models etc...but no data within tables yet)

Now that I've gotten the models and tried working out modelform, I've tried makemigrations, but I'm getting an error traceback...

ValueError: Cannot create form field for 'owner' yet, because its related model u'emp.Employee' has not been loaded yet

I checked my mysite/settings.py to ensure that the apps were installed, and the config files are all there:

```<code>...
INSTALLED_APPS = [
    'WorkRecords.apps.WorkrecordsConfig',
    'emp.apps.EmpConfig',
    etc...
]
...
</code>```

To me, this sounds like it can't create the form because there isn't any data 'loaded' into the database, but what else I've learned about Django suggests that it shouldn't care yet. Is that accurate? Or is there something else I'm missing?

EDIT:
I made a change to the model of WorkRecord that somewhat fixed the problem (at least the error isn't there anymore, but I don't know about side-effects)

```<code>class WorkRecord(models.Model):
    ...
    owner=models.ForeignKey('emp.Employee', related_name='work_owner',
            on_delete=models.PROTECT, editable=False) #Added the editable=False
    ...
</code>```

All else stayed the same, but makemigrations did not throw an error this time. What's the reasoning here?

答:
Try changing the order on your installed apps:</p>

```<code>INSTALLED_APPS = [
    emp.apps.EmpConfig, # first
    WorkRecords.apps.WorkrecordsConfig,
    etc...
]
</code>```

Body:
I'm attempting to develop a work record tracker sort of app, very similar to a ticket tracker. Each 'ticket' can have multiple notes owned by employees (employees are tracked in a different app that has been installed into the ticket-tracker).

i.e.

MySite
  |___WorkRecords
     |__models.py
     |__views.py
     |__etc..    //standard app stuff
  |___emp #the uncreative name for the employee manager app
     |__         //standard stuff again...

Within the models:

WorkRecords.models.py

class WorkRecord(models.Model):
    issuedate = models.DateField('date first issued',
             editable = False, default = timezone.now)
    owner = models.ForeignKey('emp.Employee', related_name='work_owner',
            on_delete=models.PROTECT)
    other_irrelevant_header_data...

    ....

class WorkRecordNote(models.Model):
    ref_wr = models.ForeignKey(WorkRecord, on_delete=models.CASCADE)
    note_text = models.CharField(max_length=1000)
    author = models.ForeignKey('emp.Employee', related_name='note_author',
            on_delete=models.PROTECT)

#Form class for the Work Record
class EditWR(ModelForm):
    class Meta:
        model = WorkRecord
        fields = '__all__'

emp.models.py

class Employee(models.Model)
    data stuff

At the moment, the models have all been migrated, but the data has not been input into the tables yet (MySQL tables are all there, matching models etc...but no data within tables yet)

Now that I've gotten the models and tried working out modelform, I've tried makemigrations, but I'm getting an error traceback...

ValueError: Cannot create form field for 'owner' yet, because its related model u'emp.Employee' has not been loaded yet

I checked my mysite/settings.py to ensure that the apps were installed, and the config files are all there:

...
INSTALLED_APPS = [
    'WorkRecords.apps.WorkrecordsConfig',
    'emp.apps.EmpConfig',
    etc...
]
...

To me, this sounds like it can't create the form because there isn't any data 'loaded' into the database, but what else I've learned about Django suggests that it shouldn't care yet. Is that accurate? Or is there something else I'm missing?

EDIT:
I made a change to the model of WorkRecord that somewhat fixed the problem (at least the error isn't there anymore, but I don't know about side-effects)

class WorkRecord(models.Model):
    ...
    owner=models.ForeignKey('emp.Employee', related_name='work_owner',
            on_delete=models.PROTECT, editable=False) #Added the editable=False
    ...

All else stayed the same, but makemigrations did not throw an error this time. What's the reasoning here?

Body:
Try changing the order on your installed apps:

INSTALLED_APPS = [
    emp.apps.EmpConfig, # first
    WorkRecords.apps.WorkrecordsConfig,
    etc...
]


答:
Command open() as default opens it text mode which tries to decode text to unicode.

If you have to open other file then better use binary mode.

Use "b" in open(filename, "rb") to do it.

Python 3 doc: open()

Title: Read all types of files python 3


问:
(C++) Is creating a class/object specifically for handling all other custom objects a proper way to handle a project?
I asked a question yesterday, but it seems I did ask it incorrectly, so here I go again. I quickly mocked up this code, and I'm wondering if this is a proper way to handle the objects (outside of just putting everything in main(). This would be my first time trying to complete a larger project, so I've never had a need to question how to contain and handle the objects.

skill.h

```<code>#pragma once

#include <string>
#include <vector>
#include <memory>
#include <unordered_map>

class Skill;

typedef std::vector<std::shared_ptr<Skill>> SkillVector;
typedef std::unordered_map<std::string, std::shared_ptr<Skill>> SkillMap;

class Skill {
private:
    std::string _skill_name;
    std::string _skill_description;
    friend std::ostream& operator<< (std::ostream& stream, const Skill& skill);
    void print(std::ostream& stream) const;

public:
    Skill(const std::string& skill_name, const std::string& skill_description);
    const std::string& getSkillName() const;
    const std::string& getSkillDescription() const;
    bool isMatch(const std::string& substring) const;
};
</code>```

application.h

```<code>#pragma once

#include "skill.h"

extern std::string SKILL_FILE;

class Application {
private:
    std::unique_ptr<SkillMap> _skill_map;
    void loadData();
    void loadSkills();
    void printSkillMap();
    void printSkillVector(const SkillVector& skills);
    std::unique_ptr<SkillVector> skillSearch(const std::string& input) const;
public:
    Application();
    void run();
};
</code>```

main.cpp

```<code>#include "application.h"

int main() {
    std::unique_ptr<Application> application(new Application);
    application->run();

    return 0;
}
</code>```

This is going to be a command-line application, so other than this I can't think of doing anything else except putting all the methods from the application class straight into main as regular functions. That doesn't seem like the correct approach though. I've tried researching this pretty extensively, but haven't really found anything that answers this.

What are the other options for containing all the objects in an orderly fashion? What are the advantages of doing it certain ways? And is what I'm doing here acceptable?

NOTE: This isn't an exact representation of my project, and I'm just using it as an example to understand my question at hand.

答:
Follow the following rules:

When you have inheritance, the classes should respond to 'is-a'. For example if you have class Speed : public Skill. That seems logical and: Speed is a Skill.

When you have composition, the classes should respond to 'has-a'. In your case: Application has a Skill map.
If the class was Hero it would be really logical: Hero has a Skill map. And this hero will develop the skills also the hero might need to print its skills... So the Hero will manage his Skills.

Sorry if I misunderstood your question.

Body:
I asked a question yesterday, but it seems I did ask it incorrectly, so here I go again. I quickly mocked up this code, and I'm wondering if this is a proper way to handle the objects (outside of just putting everything in main(). This would be my first time trying to complete a larger project, so I've never had a need to question how to contain and handle the objects.

skill.h

#pragma once

#include <string>
#include <vector>
#include <memory>
#include <unordered_map>

class Skill;

typedef std::vector<std::shared_ptr<Skill>> SkillVector;
typedef std::unordered_map<std::string, std::shared_ptr<Skill>> SkillMap;

class Skill {
private:
    std::string _skill_name;
    std::string _skill_description;
    friend std::ostream& operator<< (std::ostream& stream, const Skill& skill);
    void print(std::ostream& stream) const;

public:
    Skill(const std::string& skill_name, const std::string& skill_description);
    const std::string& getSkillName() const;
    const std::string& getSkillDescription() const;
    bool isMatch(const std::string& substring) const;
};

application.h

#pragma once

#include "skill.h"

extern std::string SKILL_FILE;

class Application {
private:
    std::unique_ptr<SkillMap> _skill_map;
    void loadData();
    void loadSkills();
    void printSkillMap();
    void printSkillVector(const SkillVector& skills);
    std::unique_ptr<SkillVector> skillSearch(const std::string& input) const;
public:
    Application();
    void run();
};

main.cpp

#include "application.h"

int main() {
    std::unique_ptr<Application> application(new Application);
    application->run();

    return 0;
}

This is going to be a command-line application, so other than this I can't think of doing anything else except putting all the methods from the application class straight into main as regular functions. That doesn't seem like the correct approach though. I've tried researching this pretty extensively, but haven't really found anything that answers this.

What are the other options for containing all the objects in an orderly fashion? What are the advantages of doing it certain ways? And is what I'm doing here acceptable?

NOTE: This isn't an exact representation of my project, and I'm just using it as an example to understand my question at hand.


问:
unable to find template, after generating bundle
ok this might be a very strange thing.
it's not the first time I work a symfony project but:

I used the symfony generate:bundle command and after that I created a bundle. Lets call it "CrimeBundle".

I saw it made a folder inside the src/

It also made automatically a DefaultController and an index.html.twig file.

Now whenever I use:

```<code>return $this->render('CrimeBundle:Default:index.html.twig');
</code>```

it doesn't work: I get the error:

Unable to find template "CrimeBundle:Default:index.html.twig" (looked into: /Users/admin/sites/solve/app/Resources/views, /Users/admin/sites/solve/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).

however it works whenever I use the namespaced twig path like:

```<code>return $this->render('@Crime/Default/index.html.twig');
</code>```

I like the first option, because on my other projects I use it too. None of them are the same version, currently I use: 3.4.1
Again the file is there, because it works with namespaced twig paths.

I can't understand why return $this->render('CrimeBundle:Default:index.html.twig'); wouldn't work as symfony generated this code.

答:
According to this - https://symfony.com/doc/3.4/templating.html#referencing-templates-in-a-bundle
That's the only reference type the support for bundle templates

```<code>@BundleName/directory/filename.html.twig
</code>```

If you go to docs for symfony 3.1 you'll see that was the last version that supported old reference

```<code>AcmeBlogBundle:Blog:index.html.twig
</code>```

Body:
ok this might be a very strange thing.
it's not the first time I work a symfony project but:

I used the symfony generate:bundle command and after that I created a bundle. Lets call it "CrimeBundle".

I saw it made a folder inside the src/

It also made automatically a DefaultController and an index.html.twig file.

Now whenever I use:

return $this->render('CrimeBundle:Default:index.html.twig');

it doesn't work: I get the error:

Unable to find template "CrimeBundle:Default:index.html.twig" (looked into: /Users/admin/sites/solve/app/Resources/views, /Users/admin/sites/solve/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).

however it works whenever I use the namespaced twig path like:

return $this->render('@Crime/Default/index.html.twig');

I like the first option, because on my other projects I use it too. None of them are the same version, currently I use: 3.4.1
Again the file is there, because it works with namespaced twig paths.

I can't understand why return $this->render('CrimeBundle:Default:index.html.twig'); wouldn't work as symfony generated this code.

Body:
According to this - https://symfony.com/doc/3.4/templating.html#referencing-templates-in-a-bundle
That's the only reference type the support for bundle templates

@BundleName/directory/filename.html.twig

If you go to docs for symfony 3.1 you'll see that was the last version that supported old reference

AcmeBlogBundle:Blog:index.html.twig


问:
How can I concatenate a string and a number in Python?
I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:

```<code>"abc" + 9
</code>```

The error is:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    "abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects
```

Why am I not able to do this?

How can I concatenate a string and a number in Python?

答:
You would have to convert the int into a string.</p>

```<code># This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:

"abc" + 9

The error is:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    "abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects

Why am I not able to do this?

How can I concatenate a string and a number in Python?

Body:
You would have to convert the int into a string.

# This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)


问:
Call to PageMethod blocks until complete; prevents client or server-side redirect
I'm calling a static Page method via javascript that takes between 5s and 10 min. I'd like to give my user the choice to either continue waiting for the request to complete or not, and use window.setTimeout() to check back every 30s.

I've tried both location.href = '/newpage.aspx' or firing a button's click handler (which does similar redirect) to redirect the user prior to completion of the page method, to no avail. I can immediately send user to a simple html page, but a redirect to any aspx page involving server-side appears to block. When the page method finally completes, the redirect does succeed.

Is this:

a browser issue? If all modern
browsers support at least 2
concurrent requests per domain, why
wouldn't this work?

a framework
limitation?

a desirable design
pattern or even possible? I've
checked, and after redirecting to an
HTML page, the original request continues processing (db updates, no problem).

Are Page method calls simply not asynchronous from a "concurrent HTTP request" perspective?

Any insight greatly appreciated!

答:
It sounds like you're blocking on InProc Session, which is limited to one concurrent request per unique session. If you don't need access to the Session in your page method, you can disable it by modifying the WebMethod attribute:</p>

```<code>[System.Web.Services.WebMethod(EnableSession=false)]
</code>```

Body:
It sounds like you're blocking on InProc Session, which is limited to one concurrent request per unique session. If you don't need access to the Session in your page method, you can disable it by modifying the WebMethod attribute:

[System.Web.Services.WebMethod(EnableSession=false)]