问:
Excel 2013 VBA multiple email addresses to Outlook
I am coding in Excel 2013. I've got a table of client data that will increase and decrease in number over time depending my active veteran caseload:

Column A - Last Name

Column B - First Name

Column C - Email Address

Column D - etc...

I need the code to reference column C and place all the emails therein in the BCC of a single Outlook email. The code I have created (through my study) allows for only hard-coded email addresses to the TO, CC or BCC fields of Outlook--with a semicolon between multiple entries.  My issue is that the number of email addresses will vary depending on the number of records in the spreadsheet so hard-coding them is useless. The code below has all the functionality I require with the exception of the email problem.

```<code>Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = ""
    .Subject = "Test Message"
    '.Send
End With
End Sub
</code>```

答:
I'd just loop over the column and make string holding the addresses separated by semi-colons.</p>

```<code>Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)

'set your range as needed, i chose one named "recipients"
bc_r = ""
For each cl in range("recipients")
    bc_r = bc_r & "; " & cl.Value
Next cl

With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = bc_r
    .Subject = "Test Message"
    '.Send
End With
End Sub
</code>```

Body:
I am coding in Excel 2013. I've got a table of client data that will increase and decrease in number over time depending my active veteran caseload:

Column A - Last Name

Column B - First Name

Column C - Email Address

Column D - etc...

I need the code to reference column C and place all the emails therein in the BCC of a single Outlook email. The code I have created (through my study) allows for only hard-coded email addresses to the TO, CC or BCC fields of Outlook--with a semicolon between multiple entries.  My issue is that the number of email addresses will vary depending on the number of records in the spreadsheet so hard-coding them is useless. The code below has all the functionality I require with the exception of the email problem.

Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "
Testing

" & "
" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = ""
    .Subject = "Test Message"
    '.Send
End With
End Sub

Body:
I'd just loop over the column and make string holding the addresses separated by semi-colons.

Sub SendBasicEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)

'set your range as needed, i chose one named "recipients"
bc_r = ""
For each cl in range("recipients")
    bc_r = bc_r & "; " & cl.Value
Next cl

With olEmail
    .BodyFormat = olFormatHTML
    .Display
    .HTMLBody = "<h3>Testing</h3><br>" & "<br>" & .HTMLBody
    .Attachments.Add "xxx/test.pdf"
    .To = ""
    .BCC = bc_r
    .Subject = "Test Message"
    '.Send
End With
End Sub


来源: stackexchange

问:
C# Mysql move row to another table and get max value of cell
I have a method that moves a row from one table to another. That itself works fine. What I am trying to do now is to select the highest value of a cell inside the table Callbacks. This is what I have tried:

```<code>public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            string query = "BEGIN;  select max(UniqueID) from Callbacks;     INSERT INTO Callbacks select * from " + Table + " where UniqueID = " + UniqueID + "; DELETE FROM " + Table + " where UniqueID = " + UniqueID + "; COMMIT;";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();

                Console.WriteLine("query" + Convert.ToInt32(cmd.ExecuteScalar()));
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
</code>```

Thanks in advance

答:
You are executing command two times - with "ExecuteNonQuery" and "ExecuteReader".
Just remove "cmd.ExecuteNonQuery()" and you are done.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a method that moves a row from one table to another. That itself works fine. What I am trying to do now is to select the highest value of a cell inside the table Callbacks. This is what I have tried:

public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            string query = "BEGIN;  select max(UniqueID) from Callbacks;     INSERT INTO Callbacks select * from " + Table + " where UniqueID = " + UniqueID + "; DELETE FROM " + Table + " where UniqueID = " + UniqueID + "; COMMIT;";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();

                Console.WriteLine("query" + Convert.ToInt32(cmd.ExecuteScalar()));
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Thanks in advance


问:
In Angular2, while I have a named outlet open, how can I navigate to another route with matrix param AND close the named outlet?
I'm using named outlets to show a sidebar. Works fine:

```<code>router.navigate(['/', {outlets: {sidebar: 'profile'}}])
</code>```

I also have a button which on click, closes the sidebar. Also works fine:

```<code>router.navigate(['/', {outlets: {sidebar: null}}])
</code>```

The other button should close the sidebar and route to contacts with matrix parameters

```<code>router.navigate(['/', {outlets: {sidebar: null, primary: "contacts"}}]">
</code>```

I'm able to route but unable to pass parameters.

答:
I'm not sure what you've tried so far, but would something like this work?</p>

```<code>router.navigate(['/', {outlets: {sidebar: null,
                       primary: ["/contacts", {field: value}]}}]"
</code>```

Body:
I'm using named outlets to show a sidebar. Works fine:

router.navigate(['/', {outlets: {sidebar: 'profile'}}])

I also have a button which on click, closes the sidebar. Also works fine:

router.navigate(['/', {outlets: {sidebar: null}}])

The other button should close the sidebar and route to contacts with matrix parameters

router.navigate(['/', {outlets: {sidebar: null, primary: "contacts"}}]">

I'm able to route but unable to pass parameters.

Body:
I'm not sure what you've tried so far, but would something like this work?

router.navigate(['/', {outlets: {sidebar: null,
                       primary: ["/contacts", {field: value}]}}]"


问:
Obtaining the number of comments of a list of youtube videos
I have been coding a simple python script for obtaining number of views and number of comments of a list of videos. Using csv, I have converted a tab-separated table into a list of lists, and then I tried to obtain both elements. Inspecting number of views, the element is "div", {"class":"watch-view-count"}. It works as intended

```<code>r = requests.get(list_youtube_reading[n][0]) # it retrieves each video URL from a csv
soup = BeautifulSoup(r.text)
for element in soup.findAll("div", {"class":"watch-view-count"}):
    patternviews = re.compile('^(.*?) .*')
    scissorviews = patternviews.match(element.text.encode("utf-8"))
    views = re.sub('\.','', tijeraviews.group(1))
</code>```

However, element for number of comments is

    Comments
    " • 6"

When I tried to obtain it, with

```<code>for element in soup.findAll("h2", {"class":"comment-section-header-renderer"}):
    comments = element.text.encode("utf-8")
    print comments
</code>```

nothing happens, and actually soupdoesn't contain any
 tag

What can I do in order to retrieve number of comments? I tried to use youtube v3 data API, but for no avail

thanks in advance

答:
One simple way would be using the Selenium WebDriver to simulate a web browser. I have observed that when we scroll down, only then YouTube loads the comments section. So my solution is to make the web-driver to scroll down and wait until the desired element is found. After it has been located, the following script grabs it and gets the value.

For using Selenium, we need to download one of the third party drivers from this page. I have used the Mozilla GeckoDriver. And we also need to put the path to this executable file in the system environment variables. As I am on an Ubuntu machine, I put the downloaded file (after extracting it) in /usr/local/bin/and I didn't need anything more. After setting the path properly, we can run the following script to get our desired values.
And we also do need to install Selenium itself. The instructions are here.

```<code># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

video_url = 'https://www.youtube.com/watch?v=NP189MPfR7Q'
driver = webdriver.Firefox()
driver.set_page_load_timeout(30)
driver.get(video_url)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
for view_num in driver.find_elements_by_class_name("watch-view-count"):
    print 'Number of views: ' + view_num.text.replace(' views', '')

try:
    element = WebDriverWait(driver, 30).until(
        EC.presence_of_element_located((By.CLASS_NAME, "comment-section-header-renderer")))
    for comment_num in driver.find_elements_by_class_name("comment-section-header-renderer"):
        print u'Number of comments: ' + comment_num.text.replace(u'COMMENTS • ', '')
finally:
    driver.quit()
</code>```

Output:

```<code>Number of views: 3,555
Number of comments: 3
</code>```

NOTE
Since the DOM element (that contains the comment-count) has some NON-ASCII character inside, I needed to put the very first line of the script.

And if you don't like Selenium to show the GUI, follow these instructions. I did not do this but the instructions should be enough.

Body:
I have been coding a simple python script for obtaining number of views and number of comments of a list of videos. Using csv, I have converted a tab-separated table into a list of lists, and then I tried to obtain both elements. Inspecting number of views, the element is "div", {"class":"watch-view-count"}. It works as intended

r = requests.get(list_youtube_reading[n][0]) # it retrieves each video URL from a csv
soup = BeautifulSoup(r.text)
for element in soup.findAll("div", {"class":"watch-view-count"}):
    patternviews = re.compile('^(.*?) .*')
    scissorviews = patternviews.match(element.text.encode("utf-8"))
    views = re.sub('\.','', tijeraviews.group(1))

However, element for number of comments is

    Comments
    " • 6"

When I tried to obtain it, with

for element in soup.findAll("h2", {"class":"comment-section-header-renderer"}):
    comments = element.text.encode("utf-8")
    print comments

nothing happens, and actually soupdoesn't contain any
 tag

What can I do in order to retrieve number of comments? I tried to use youtube v3 data API, but for no avail

thanks in advance

Body:
One simple way would be using the Selenium WebDriver to simulate a web browser. I have observed that when we scroll down, only then YouTube loads the comments section. So my solution is to make the web-driver to scroll down and wait until the desired element is found. After it has been located, the following script grabs it and gets the value.

For using Selenium, we need to download one of the third party drivers from this page. I have used the Mozilla GeckoDriver. And we also need to put the path to this executable file in the system environment variables. As I am on an Ubuntu machine, I put the downloaded file (after extracting it) in /usr/local/bin/and I didn't need anything more. After setting the path properly, we can run the following script to get our desired values.
And we also do need to install Selenium itself. The instructions are here.

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

video_url = 'https://www.youtube.com/watch?v=NP189MPfR7Q'
driver = webdriver.Firefox()
driver.set_page_load_timeout(30)
driver.get(video_url)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
for view_num in driver.find_elements_by_class_name("watch-view-count"):
    print 'Number of views: ' + view_num.text.replace(' views', '')

try:
    element = WebDriverWait(driver, 30).until(
        EC.presence_of_element_located((By.CLASS_NAME, "comment-section-header-renderer")))
    for comment_num in driver.find_elements_by_class_name("comment-section-header-renderer"):
        print u'Number of comments: ' + comment_num.text.replace(u'COMMENTS • ', '')
finally:
    driver.quit()

Output:

Number of views: 3,555
Number of comments: 3

NOTE
Since the DOM element (that contains the comment-count) has some NON-ASCII character inside, I needed to put the very first line of the script.

And if you don't like Selenium to show the GUI, follow these instructions. I did not do this but the instructions should be enough.


问:
Renaming groupId in maven
I'm in a middle of a refactoring and house keeping process of a multi-module Maven3 project and I need to rename groupId and artifactId of some artifacts.

Is there a way to rename both groupId and artifactId?

I know I can use some find-and-replace tool like sed, but I'm wondering if there's a mojo like versions-maven-plugin (e.g.: mvn versions:set -DnewVersion=1.0.3-SNAPSHOT) but for groupId and artifactId.

答: Simple solution would be use textpad or notepad++ or other tool as you said sed and use find in file and replace the group id and artifact ids.</p>

Title: Renaming groupId in maven


问:
How do I set up Visual Studio Code to compile C++ code?
Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.

How do I configure it to do this?

答:
With an updated VS Code you can do it in the following manner:

Hit (Ctrl+P) and type:

ext install cpptools
```
<ol start="2">
<li><p>Open a folder (<kbd>Ctrl</kbd>+<kbd>K</kbd> & <kbd>Ctrl</kbd>+<kbd>O</kbd>) and create a new file inside the folder with the extension <strong>.cpp</strong> (ex: <strong>hello.cpp</strong>):</p>
</li>
<li><p>Type in your code and hit save.</p>
</li>
<li><p>Hit (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> and type, <code>Configure task runner</code> and then select <code>other</code> at the bottom of the list.</p>
</li>
<li><p>Create a batch file in the same folder with the name <strong>build.bat</strong> and include the following code to the body of the file:</p>
</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
</code>```

Edit the task.json file as follows and save it:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
}
```
<ol start="7">
<li><p>Hit (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> to run Build task. This will create the <strong>.obj</strong> and <strong>.exe</strong> files for the project.</p>
</li>
<li><p>For debugging the project, Hit <kbd>F5</kbd> and select <strong>C++(Windows)</strong>.</p>
</li>
<li><p>In <strong>launch.json</strong> file, edit the following line and <strong>save</strong> the file:</p>
</li>
</ol>
<pre class="lang-json prettyprint-override"><code>"program": "${workspaceRoot}/hello.exe",
</code>```

Hit F5.

Body:
With an updated VS Code you can do it in the following manner:

Hit (Ctrl+P) and type:

ext install cpptools

Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):

Type in your code and hit save.

Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.

Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%

Edit the task.json file as follows and save it:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
}

Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.

For debugging the project, Hit F5 and select C++(Windows).

In launch.json file, edit the following line and save the file:

"program": "${workspaceRoot}/hello.exe",

Hit F5.

ContentLicense: CC BY-SA 4.0


问:
Docker build apt-get update failed to fetch with a 403
I've seen a few questions about this already but none are the same as my issue. I have a server running Ubuntu 16.04 in our data center so it is technically a virtual machine. I've installed Docker and now I'm trying to build the following Dockerfile:

```<code>FROM ubuntu:16.04

RUN apt-get update
</code>```

The update is failing. I get a bunch of this:

```<code>Ign:35 http://archive.ubuntu.com/ubuntu xenial-updates/multiverse all Packages
Ign:36 http://archive.ubuntu.com/ubuntu xenial-backports/main amd64 Packages
Ign:37 http://archive.ubuntu.com/ubuntu xenial-backports/main all Packages
Ign:38 http://archive.ubuntu.com/ubuntu xenial-backports/restricted amd64 Packages
Ign:39 http://archive.ubuntu.com/ubuntu xenial-backports/restricted all Packages
Ign:40 http://archive.ubuntu.com/ubuntu xenial-backports/universe amd64 Packages
Ign:41 http://archive.ubuntu.com/ubuntu xenial-backports/universe all Packages
</code>```

And then:

```<code>E: Failed to fetch http://security.ubuntu.com/ubuntu/dists/xenial-security/universe/source/Sources  403  Forbidden [IP: 91.189.91.26 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial/universe/source/Sources  403  Forbidden [IP: 91.189.88.152 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial-updates/universe/source/Sources  403  Forbidden [IP: 91.189.88.152 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial-backports/main/binary-amd64/Packages  403  Forbidden [IP: 91.189.88.152 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

Running sudo apt-get update on my server (not in the Docker image) works just fine.

答:
I hit something similar: apt-get update would fail during 'docker build' though /etc/apt/apt.conf

is set up in the host, and 'sudo apt-get update' works in the host.

I fixed it as follows:

Step 1:    Copy /etc/apt/apt.conf to the local directory where
  Dockerfile resides (build context directory for docker).

Step 2:  Add the following lines to Dockerfile:

```<code>RUN mkdir -p /etc/apt
COPY apt.conf /etc/apt`
RUN apt-get update && \
  apt-get -y install`
</code>```

Body:
I've seen a few questions about this already but none are the same as my issue. I have a server running Ubuntu 16.04 in our data center so it is technically a virtual machine. I've installed Docker and now I'm trying to build the following Dockerfile:

FROM ubuntu:16.04

RUN apt-get update

The update is failing. I get a bunch of this:

Ign:35 http://archive.ubuntu.com/ubuntu xenial-updates/multiverse all Packages
Ign:36 http://archive.ubuntu.com/ubuntu xenial-backports/main amd64 Packages
Ign:37 http://archive.ubuntu.com/ubuntu xenial-backports/main all Packages
Ign:38 http://archive.ubuntu.com/ubuntu xenial-backports/restricted amd64 Packages
Ign:39 http://archive.ubuntu.com/ubuntu xenial-backports/restricted all Packages
Ign:40 http://archive.ubuntu.com/ubuntu xenial-backports/universe amd64 Packages
Ign:41 http://archive.ubuntu.com/ubuntu xenial-backports/universe all Packages

And then:

E: Failed to fetch http://security.ubuntu.com/ubuntu/dists/xenial-security/universe/source/Sources  403  Forbidden [IP: 91.189.91.26 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial/universe/source/Sources  403  Forbidden [IP: 91.189.88.152 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial-updates/universe/source/Sources  403  Forbidden [IP: 91.189.88.152 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/xenial-backports/main/binary-amd64/Packages  403  Forbidden [IP: 91.189.88.152 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

Running sudo apt-get update on my server (not in the Docker image) works just fine.

Body:
I hit something similar: apt-get update would fail during 'docker build' though /etc/apt/apt.conf

is set up in the host, and 'sudo apt-get update' works in the host.

I fixed it as follows:

Step 1:    Copy /etc/apt/apt.conf to the local directory where
  Dockerfile resides (build context directory for docker).

Step 2:  Add the following lines to Dockerfile:

RUN mkdir -p /etc/apt
COPY apt.conf /etc/apt`
RUN apt-get update && \
  apt-get -y install`


问:
Mapping an int to a struct of vectors in C++
I am trying to learn how std::map works, I have the following problem:

```<code>int id; // stores some id

struct stuff {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff> smap;

void foo () {
  int count = 2;
  int foo_id = 43;
  for (int i = 0; i < count; count++) {
        stuff.As.push_back(count);
        stuff.Bs.push_back(count);
  }
  smap.insert(foo_id, stuff);
}
</code>```

Currently I get:

```<code>error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
  std::map<int, stuff> smap;

error: request for member ‘insert’ in ‘smap’, which is of non-class type ‘int’
   smap.insert(int, stuff);
</code>```

I want to be able to map the id to the struct which is made of two vectors being populated in a for loop. What am I doing wrong? Or is there a better way to map this?

答:
struct stuff defines stuff as a struct, but then } stuff; on the end redefines stuff as a variable of type stuff.

```<code>struct stuff { // stuff is a struct
  std::vector<int> As;
  std::vector<int> Bs;
} stuff; // stuff is now a variable of type stuff.
</code>```

As a result, there is no type named stuff for std::map<int, stuff> to use.

You can resolve the problem by renaming the struct type:

```<code>struct stuff_t {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff_t> smap;
</code>```

Body:
I am trying to learn how std::map works, I have the following problem:

int id; // stores some id

struct stuff {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff> smap;

void foo () {
  int count = 2;
  int foo_id = 43;
  for (int i = 0; i < count; count++) {
        stuff.As.push_back(count);
        stuff.Bs.push_back(count);
  }
  smap.insert(foo_id, stuff);
}

Currently I get:

error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
  std::map<int, stuff> smap;

error: request for member ‘insert’ in ‘smap’, which is of non-class type ‘int’
   smap.insert(int, stuff);

I want to be able to map the id to the struct which is made of two vectors being populated in a for loop. What am I doing wrong? Or is there a better way to map this?

Body:
struct stuff defines stuff as a struct, but then } stuff; on the end redefines stuff as a variable of type stuff.

struct stuff { // stuff is a struct
  std::vector<int> As;
  std::vector<int> Bs;
} stuff; // stuff is now a variable of type stuff.

As a result, there is no type named stuff for std::map<int, stuff> to use.

You can resolve the problem by renaming the struct type:

struct stuff_t {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff_t> smap;


问:
Get text of an element of a dropdown disabled
I want to get the text of the element.

This is the dropdown box in disable mode:

```<code><select disabled="" readonly="readonly" onchange="onChange('incident.priority');" style="; " id="incident.priority" class="form-control readonly disabled" ng-non-bindable="true" name="incident.priority">
    <option value="">-- None --</option>
    <option value="1">1 - Critical</option>
    <option value="2">2 - High</option>
    <option value="3">3 - Moderate</option>
    <option value="4">4 - Low</option>
    <option value="5">5 - Planning</option>
</select>
</code>```

I am using:

```<code>JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement element = driver.findElement(By.xpath("//select[@id='incident.priority']"));
String s = (String) jse.executeScript("return arguments[0].text" + "", element);
System.out.println("Priorityvalue= " + s);
</code>```

The output is null. I want to get that disable element text.

答:
Hmm well I am not sure how the disabled attribute will affect this but when working with dropdown boxes user the SelectElement class.

```<code>IWebElement element = driver.FindElement(By.CssSelector("select[id='incident.priority']"));
SelectElement elementDdl = new SelectElement(element);
var text = elementDdl.SelectedOpiton.Text;
</code>```

Now this is C# code but the methods and classes should all be named similarly.

Body:
I want to get the text of the element.

This is the dropdown box in disable mode:

<select disabled="" readonly="readonly" onchange="onChange('incident.priority');" style="; " id="incident.priority" class="form-control readonly disabled" ng-non-bindable="true" name="incident.priority">
    <option value="">-- None --</option>
    <option value="1">1 - Critical</option>
    <option value="2">2 - High</option>
    <option value="3">3 - Moderate</option>
    <option value="4">4 - Low</option>
    <option value="5">5 - Planning</option>
</select>

I am using:

JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement element = driver.findElement(By.xpath("//select[@id='incident.priority']"));
String s = (String) jse.executeScript("return arguments[0].text" + "", element);
System.out.println("Priorityvalue= " + s);

The output is null. I want to get that disable element text.

Body:
Hmm well I am not sure how the disabled attribute will affect this but when working with dropdown boxes user the SelectElement class.

IWebElement element = driver.FindElement(By.CssSelector("select[id='incident.priority']"));
SelectElement elementDdl = new SelectElement(element);
var text = elementDdl.SelectedOpiton.Text;

Now this is C# code but the methods and classes should all be named similarly.


问:
Is there a binary kind of SVG?
It just seems to me that when writing code for dynamic data visualization, I end up doing the same things over and over in different languages/platforms. Now if I had a cross platform language(which I do) and something like a binary version of SVG, I could make my code target that and use/create interpreters for whatever platform I currently need to use it on.

The reason I don't want SVG is because the plaintext part makes it too slow for my purposes. I could of course just create my own intermediary format but if there is something already out there that's implemented by various things then the less work for me!

答:
Depending on what you mean by “too slow”, the answer varies:

Filesize too large

Officially, the closest thing SVG has to a binary format is SVGZ, which is a gzipped SVG file with the .svgz extension. All conforming SVG viewers should be able to open it. Making one is simple on *nix systems:

```<code>gzip yourfile.svg && mv yourfile.svg.gz yourfile.svgz
</code>```

You could also try Brotli compression, which tends to have smaller filesize at the cost of more compression time.

Including other assets is inefficient

SVG can only bundle bitmaps and other binary data through base64 encoding, which has a fair amount of overhead.

PDF can include “streams” of raw binary data, and is surprisingly efficient when programmatically generated.

Parsing the text data takes too long

This is tricky. PDF and its brother, Encapsulated PostScript, are also old, well-supported vector graphic formats. Unfortunately, they too are also text at their core, with optional compression.

You could try Computer Graphics Metafiles, which can be compiled ahead of time. But I’m unsure how well-supported they are across consumer devices.

Title: Is there a binary kind of SVG?

Body:
Depending on what you mean by “too slow”, the answer varies:

Filesize too large

Officially, the closest thing SVG has to a binary format is SVGZ, which is a gzipped SVG file with the .svgz extension. All conforming SVG viewers should be able to open it. Making one is simple on *nix systems:

gzip yourfile.svg && mv yourfile.svg.gz yourfile.svgz

You could also try Brotli compression, which tends to have smaller filesize at the cost of more compression time.

Including other assets is inefficient

SVG can only bundle bitmaps and other binary data through base64 encoding, which has a fair amount of overhead.

PDF can include “streams” of raw binary data, and is surprisingly efficient when programmatically generated.

Parsing the text data takes too long

This is tricky. PDF and its brother, Encapsulated PostScript, are also old, well-supported vector graphic formats. Unfortunately, they too are also text at their core, with optional compression.

You could try Computer Graphics Metafiles, which can be compiled ahead of time. But I’m unsure how well-supported they are across consumer devices.


问:
playing audio stream in blackberry
I am doing an audio playing Application in blackberry.When i pass a live url stream,it works,but when my url is a fixed one of size say 50 mb.It shows error,can anyone tell me the reason for it?</p>

答:
have you tried to buffer and play the media using custom buffer class or just trying to pass url of media file to player.

if you pass url of media directly (not a streaming link but an mp3 file link for example) then device will try to download the file and then play the file and blackberry has 2 or 1 MB file size limit to download a file.

any how unless you paste some code here it is hard to answer your exact query. I also like to share this link for streaming media over internet.

http://supportforums.blackberry.com/t5/Java-Development/Streaming-media-Start-to-finish/ta-p/488255

ContentLicense: CC BY-SA 2.5

Title: playing audio stream in blackberry


问:
Can ApolloProvider be made to provide to state instead of props?
Redux's Provider component and connect function provide a reference to the store's state to wrapped components via mapStateToProps. As mentioned in the lovely article How to Build a Redux, this is done so that you don't need to refer to a global store object or pass data endlessly down the DOM.

This has a great advantage: the store state is DOM agnostic. You can put any two elements anywhere on the page and provide them with any data you want from the store. If you have a form for customer search and a list of customer search results... the relationship of these presentational elements doesn't affect their access to data.

As far as I can tell, Apollo-react's ApolloProvider does not subscribe to this principle. When I wrap a component with a query using graphql, the results of that query are provided as props to the wrapped component. If those results are needed elsewhere in the app, they must be passed manually or stored on a global reference. In particular, props returned from a graphql query cannot be passed up the DOM.

Is there a way of making ApolloProvider "provide" query results to the rest of the app in the same way redux's Provider does? Do I need to build this functionality myself? Or, better yet, am I misunderstanding something?

答: Apollo uses Redux to cache the graphql query results.  Essentially if you have multiple components that need the same data, just use Apollo to wrap each of them with the same graphql query.  You can even go as far as defining the graphql connector once, and using that same connector to wrap your N components.</p>


问:
PubNub iOS WebRTC Integration
I am trying to use PubNub as the signaling server for a webRTC iOS app. I am using Xirsys for the ICE servers. I have been able to get my app working with googles AppRTC framework, but I can't seem to find any good information on integrating with PubNub as the signaling server.What is the best way to integrate PubNub with webRTC on an iOS app? This app is writen in Swift/Obj-C Thanks!</p>

答:
PubNub as Signal Protocol

You are just going to integrate the PubNub JavaScript SDK into your app to signal (publish a message on a channel) from one client to the other the details of how to connect. This KB article may be helpful to you: Does PubNub provide WebRTC and video chat?

Title: PubNub iOS WebRTC Integration


问:
HTML5 - ApplicationCache not updating (only) some files
I've got an application that is using AppCache to store resources in the browser's cache. I've been able to set up the manifest on a PHP file in order to write automatically all files that must be cached (properly filtered). The headers of this file are the following:

```<code>header('Content-Type: text/cache-manifest');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
</code>```

It's called appcache.php and it's referenced correctly in my HTML:

```<code><html manifest="appcache.php">
</code>```

Everytime I update the manifest, the app detects the update and the events are triggered properly, updating the cache and refreshing the page so they are reloaded.

However, some of the files (mainly Javascript and CSS files) do not refresh properly. Sometimes it takes a few manifest updates (with the whole process), sometimes it takes just one, sometimes it takes forever and I have to delete the browser cache or go Incognito mode.

The app detects the update, so the manifest is not getting catched and it's getting updated correctly. The problem is that, even the files are downloaded again, they are still served in an older version. And the main problem is that this only happens in some files (sometimes they're some css files, sometimes they're js, and so on: the files not updated are random).

Actually, I'm using Chrome v59, and it happens the same on my Android device with Chrome v60.

Is there any explanation to why they're not refreshing correctly? Is this a known bug? Is there anything I can do to solve it?

UPDATE

It seems that it happens the most when I've done some updates with short time between them. After waiting 24h or so, it works at the first try. Maybe this can help you to guess why it happens.

Thank you.

答:
It is possible that your manifest file is getting cached, you can set the expires headers for it to expire rightaway

I would suggest adding swapCache method

```<code>$(function() {
 if (window.applicationCache) {
        applicationCache.addEventListener('updateready', function() {
     if (window.applicationCache.status ==
       window.applicationCache.UPDATEREADY) {
       window.applicationCache.swapCache();
       console.log("appcache updated");
       window.location.reload();
      }
     });
    }
  }
</code>```

Other thing ,To force any new (or changed) file to be downloaded, you must
 update the manifest file (Which seems like you are doing it).

The most common one is that you might not be serving the manifest with the right mime type (text/cache-manifest).

You might be getting error, The easiest way to check error is to open the page in Chrome and look in the console and the resources tab under AppCache to see if there is an error (it will complain about the file being served up incorrectly. You can also test it with the curl -I command:

```<code>curl -I $manifest_file_URL
</code>```

Body:
I've got an application that is using AppCache to store resources in the browser's cache. I've been able to set up the manifest on a PHP file in order to write automatically all files that must be cached (properly filtered). The headers of this file are the following:

header('Content-Type: text/cache-manifest');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

It's called appcache.php and it's referenced correctly in my HTML:

Everytime I update the manifest, the app detects the update and the events are triggered properly, updating the cache and refreshing the page so they are reloaded.

However, some of the files (mainly Javascript and CSS files) do not refresh properly. Sometimes it takes a few manifest updates (with the whole process), sometimes it takes just one, sometimes it takes forever and I have to delete the browser cache or go Incognito mode.

The app detects the update, so the manifest is not getting catched and it's getting updated correctly. The problem is that, even the files are downloaded again, they are still served in an older version. And the main problem is that this only happens in some files (sometimes they're some css files, sometimes they're js, and so on: the files not updated are random).

Actually, I'm using Chrome v59, and it happens the same on my Android device with Chrome v60.

Is there any explanation to why they're not refreshing correctly? Is this a known bug? Is there anything I can do to solve it?

UPDATE

It seems that it happens the most when I've done some updates with short time between them. After waiting 24h or so, it works at the first try. Maybe this can help you to guess why it happens.

Thank you.

Body:
It is possible that your manifest file is getting cached, you can set the expires headers for it to expire rightaway

I would suggest adding swapCache method

$(function() {
 if (window.applicationCache) {
        applicationCache.addEventListener('updateready', function() {
     if (window.applicationCache.status ==
       window.applicationCache.UPDATEREADY) {
       window.applicationCache.swapCache();
       console.log("appcache updated");
       window.location.reload();
      }
     });
    }
  }

Other thing ,To force any new (or changed) file to be downloaded, you must
 update the manifest file (Which seems like you are doing it).

The most common one is that you might not be serving the manifest with the right mime type (text/cache-manifest).

You might be getting error, The easiest way to check error is to open the page in Chrome and look in the console and the resources tab under AppCache to see if there is an error (it will complain about the file being served up incorrectly. You can also test it with the curl -I command:

curl -I $manifest_file_URL


问:
Angular 2 route not working
I have created an angular 2 application using CLI, I'm just learning about it, I'm trying to setup a route but for some reason it's not working, when the link is clicked the url is being displayed correctly but the html content is the same, the content of the component I want to display is not being displayed...

This is the app.module.ts code:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { ProductListComponent } from '../products/product-list.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
      HttpModule,
      RouterModule.forRoot([
          { path: 'products', component: ProductListComponent }
      ])
    ],
  declarations: [
      AppComponent, ProductListComponent
  ],
  //providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And this is the code of my product-list.component.ts file:

```<code>import { Component, OnInit } from '@angular/core';
@Component({
    template: '<p>Component product list</p>'
})

export class ProductListComponent {
 title: 'The Products from Component...';
}
</code>```

I'm not sure of what I'm doing wrong, there are not errors in the Developers Tools Console, there is not any http request made when the link is clicked...

The link I'm talking about is in app.component.html:

```<code><h1>
  {{title}}
</h1>
<p>This is a test</p>
<a [routerLink] ="['/products']"> Values list</a>
</code>```

The main url is this one: http://localhost:4200, and when the link is clicked it changes to http://localhost:4200/products but just the url changes not the html, the content of the product-list.component.ts is not being displayed.. any idea? Do I have any way to find out what's going on?

答:
It looks like you may be missing the router-outlet directive in your .html.

```<code><h1>
  {{title}}
</h1>
<p>This is a test</p>
<router-outlet></router-outlet>
<a [routerLink] ="['/products']"> Values list</a>
</code>```

Title: Angular 2 route not working

Body:
I have created an angular 2 application using CLI, I'm just learning about it, I'm trying to setup a route but for some reason it's not working, when the link is clicked the url is being displayed correctly but the html content is the same, the content of the component I want to display is not being displayed...

This is the app.module.ts code:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { ProductListComponent } from '../products/product-list.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
      HttpModule,
      RouterModule.forRoot([
          { path: 'products', component: ProductListComponent }
      ])
    ],
  declarations: [
      AppComponent, ProductListComponent
  ],
  //providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And this is the code of my product-list.component.ts file:

import { Component, OnInit } from '@angular/core';
@Component({
    template: '
Component product list
'
})

export class ProductListComponent {
 title: 'The Products from Component...';
}

I'm not sure of what I'm doing wrong, there are not errors in the Developers Tools Console, there is not any http request made when the link is clicked...

The link I'm talking about is in app.component.html:

  {{title}}

This is a test

 Values list

The main url is this one: http://localhost:4200, and when the link is clicked it changes to http://localhost:4200/products but just the url changes not the html, the content of the product-list.component.ts is not being displayed.. any idea? Do I have any way to find out what's going on?

Body:
It looks like you may be missing the router-outlet directive in your .html.

<h1>
  {{title}}
</h1>
<p>This is a test</p>
<router-outlet></router-outlet>
<a [routerLink] ="['/products']"> Values list</a>


问:
Having problems outputting proper CGI, Python script?
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

```<code>import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<html><title>Hi</title><body><p>This is a test</p></body></html>")
</code>```

and

```<code>print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")
</code>```

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.

答:
According to the http.server documentation:

This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.

So, http.server is expecting to find CGI scripts in a subfolder named /cgi-bin ot /htbin in your python.exe folder. If you really want to use the test folder, then change the cgi-directories variable in the http/server.py script.

Body:
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<title>Hi</title>
This is a test
")

and

print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title>
hello world
")

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.


问:
Making a "Mad Lib" using the string.replace method and replacing multiple terms
This is a question on an assignment, the important part reading: "Prompt the user for strings to replace the various parts of speech that you have specified.  Print out the revised story.  [Hint:  the string method replace(old,new)may be helpful]"

Here is the code I have so far:

```<code>story = "A long time ago, in a(n) PLACE-ONE far away, lived a BOY-OR-GIRL named NAME. " \
    "They lived with their mother, father, and pet ANIMAL named PET NAME. " \
    "One day, while NAME and PET NAME were playing in the PLACE-TWO, PET NAME " \
    "ran away, and NAME heard a loud SOUND and discovered that PET NAME collided " \
    "with a NOUN, and PET NAME was covered in MESSY-NOUN. As NAME went to go help PET NAME, " \
    "They too became covered in MESSY-NOUN. So they both had to ACTIVE-VERB back to PLACE-ONE and bathe in LIQUID " \
    "to get all clean. The End."
print(story)

place1 = str(input("Enter a place: "))
boyGirl = str(input("Enter a gender (can be a boy or girl): "))
bgName = str(input("Enter a name for your boy or girl: "))
animal = str(input("Enter an animal: "))
animalName = str(input("Enter a name for the animal: "))
place2 = str(input("Enter another place: "))
sound = str(input("Enter a sound: "))
noun1 = str(input("Enter a noun, preferably a large one: "))
messyNoun = str(input("Enter a noun that is messy/dirty: "))
activeVerb = str(input("Enter an action verb: "))
liquid = str(input("Enter a liquid: "))

print(story.replace("PLACE-ONE", place1))
print(story.replace("BOY-OR-GIRL", boyGirl))
print(story.replace("NAME", bgName))
print(story.replace("ANIMAL", animal))
print(story.replace("PET NAME", animalName))
print(story.replace("PLACE-TWO", place2))
print(story.replace("SOUND", sound))
print(story.replace("NOUN", noun1))
print(story.replace("MESSY-NOUN", messyNoun))
print(story.replace("ACTIVE-VERB", activeVerb))
print(story.replace("LIQUID", liquid))
</code>```

Do I need to make a loop to replace everything in the strings?

When I run it, it replaces just that term instead of it, so I just have a bunch of copies of the story with each one only having one term replaced. Or do I need to create a function to do the replacements?

答:
you don't really need a loop, @Barmar answer is totally sufficient but if you don't like typing (like me) or want to make things shorter this may also help:

```<code>keywords = ["PLACE-ONE","BOY-OR-GIRL","NAME","ANIMAL","PET NAME","PLACE-TWO","SOUND","NOUN","MESSY-NOUN","ACTIVE-VERB","LIQUID"]
replacements = [place1,boyGirl,bgName,animal,animalName,place2,sound,noun1,messyNoun,activeVerb,liquid]

for key,repl in zip(keywords,replacements):
    story = story.replace(key, repl)
</code>```

Hope this was somehow helpful.

Body:
This is a question on an assignment, the important part reading: "Prompt the user for strings to replace the various parts of speech that you have specified.  Print out the revised story.  [Hint:  the string method replace(old,new)may be helpful]"

Here is the code I have so far:

story = "A long time ago, in a(n) PLACE-ONE far away, lived a BOY-OR-GIRL named NAME. " \
    "They lived with their mother, father, and pet ANIMAL named PET NAME. " \
    "One day, while NAME and PET NAME were playing in the PLACE-TWO, PET NAME " \
    "ran away, and NAME heard a loud SOUND and discovered that PET NAME collided " \
    "with a NOUN, and PET NAME was covered in MESSY-NOUN. As NAME went to go help PET NAME, " \
    "They too became covered in MESSY-NOUN. So they both had to ACTIVE-VERB back to PLACE-ONE and bathe in LIQUID " \
    "to get all clean. The End."
print(story)

place1 = str(input("Enter a place: "))
boyGirl = str(input("Enter a gender (can be a boy or girl): "))
bgName = str(input("Enter a name for your boy or girl: "))
animal = str(input("Enter an animal: "))
animalName = str(input("Enter a name for the animal: "))
place2 = str(input("Enter another place: "))
sound = str(input("Enter a sound: "))
noun1 = str(input("Enter a noun, preferably a large one: "))
messyNoun = str(input("Enter a noun that is messy/dirty: "))
activeVerb = str(input("Enter an action verb: "))
liquid = str(input("Enter a liquid: "))

print(story.replace("PLACE-ONE", place1))
print(story.replace("BOY-OR-GIRL", boyGirl))
print(story.replace("NAME", bgName))
print(story.replace("ANIMAL", animal))
print(story.replace("PET NAME", animalName))
print(story.replace("PLACE-TWO", place2))
print(story.replace("SOUND", sound))
print(story.replace("NOUN", noun1))
print(story.replace("MESSY-NOUN", messyNoun))
print(story.replace("ACTIVE-VERB", activeVerb))
print(story.replace("LIQUID", liquid))

Do I need to make a loop to replace everything in the strings?

When I run it, it replaces just that term instead of it, so I just have a bunch of copies of the story with each one only having one term replaced. Or do I need to create a function to do the replacements?

Body:
you don't really need a loop, @Barmar answer is totally sufficient but if you don't like typing (like me) or want to make things shorter this may also help:

keywords = ["PLACE-ONE","BOY-OR-GIRL","NAME","ANIMAL","PET NAME","PLACE-TWO","SOUND","NOUN","MESSY-NOUN","ACTIVE-VERB","LIQUID"]
replacements = [place1,boyGirl,bgName,animal,animalName,place2,sound,noun1,messyNoun,activeVerb,liquid]

for key,repl in zip(keywords,replacements):
    story = story.replace(key, repl)

Hope this was somehow helpful.


问:
Configuring Clojurescript project for garden & hiccup compiled output
How to configure project.clj file to configure it to output html & css files from hiccup & garden on compiling, so that i can deploy to server without any dynamic css/html loading on client side ?</p>

答:
If you don't really need to use Leiningen, using Boot you can do it easily with perun.io, especially if website is the primary objective:

https://perun.io/guides/getting-started/

https://github.com/hashobject/perun.

I rewrote my website that way https://github.com/ArchieT/website-archiet.

If there is a need to use Lein, maybe I'll look at it later as I don't have much time right now.

It should not be hard to do.


问:
Get Twitter Feed as JSON (tweeter scraper) with angular/node/javascript
I want to create dashboard having feed from twitter tweets in angular2/node platform , on googling i found

https://github.com/opensas/twitter-scraper

but after running this script i got error

[ { code: 215, message: 'Bad Authentication data.' } ] }

also i got this meaningful question in SO but this is using php

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

anyone can do this in nodeJs/angular ?

or any suggestion ?

答:
You can use phantomJs  or casperJs (install them with npm)  for scraping site but in this time some sites use distill-network to prevent or block scraping bot .
in your problem you have two solution the clean and easy one :

access tweeter RestAPI .

if this not work with you .
you may try to scrape twitter with your twitter account you will entering your info in the header of your phantomjs bot then browse search page and fill the form with casperjs and submit it you can make this process dynamically and view the return data to store in db or view in node web app
here is an example  http://code-epicenter.com/how-to-login-to-twitter-using-casperjs-and-phantomjs-and-extract-tweets/
and https://gist.github.com/nwaomachux/35d1c424966fccd16ae1


问:
Calling a method with (sometimes) null parameters to execute an SQL statement. C# / ASP.NET
I have a method and am trying to figure out how to handle calling that method with null parameters.

```<code>public static List<Incident> GetIncidentByTechnician(int techID)
    {
        List<Incident> incidents = new List<Incident>();

            Incident inc = null; // found incident
                                 // define connection
            SqlConnection connection = TechSupportDB.GetConnection();

            // define the select query command
            string selectQuery = "select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description " +
                                 "from Incidents " +
                                 "where TechID = @TechID";

        SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
            selectCommand.Parameters.AddWithValue("@TechID", techID);
            try
            {
                // open the connection
                connection.Open();

                // execute the query
                SqlDataReader reader = selectCommand.ExecuteReader();

                // process the result while there are incidents
                while (reader.Read())
                {
                    inc = new Incident();
                    inc.IncidentID = (int)reader["IncidentID"];
                    inc.CustomerID = (int)reader["CustomerId"];
                    inc.ProductCode = reader["ProductCode"].ToString();
                    inc.TechID = (int)reader["TechID"];
                    inc.DateOpened = (DateTime)reader["DateOpened"];
                    inc.DateClosed = (DateTime?)reader["DateClosed"];
                    inc.Title = reader["Title"].ToString();
                    inc.Description = reader["Description"].ToString();
                    incidents.Add(inc); //add to the list
                }
            }
            catch (Exception ex)
            {
                throw ex; // let the form handle it
            }
            finally
            {
                connection.Close(); // close connecto no matter what
            }
        return incidents;
    }
</code>```

it takes "techID" integer as parameter and populates a list of incidents with that technician ID. However, some incidents have null values for techID. I don't want them to be added into my list.

I tried an if(techID !=null) but that gives an error saying it will always be true. I think my sql statement is not good since "where TechID = null " doesn't return results and it should be "where TechID is null" when testing this statement in sql server management studio. Any suggestions to handle these null values?
Also my incident class is shown below. I set the techID to accept null values with int?.

```<code>    public class Incident
{
    public Incident() { }
    public int IncidentID { get; set; }
    public int CustomerID { get; set; }
    public string ProductCode { get; set; }
    public int? TechID { get; set; }
    public DateTime DateOpened { get; set; }
    public DateTime? DateClosed { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}
</code>```

答:
You should add another condition TechID IS NOT NULL to check for non nulity in your SELECT query like

```<code>SELECT IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed,
Title, Description from Incidents
where TechID = @TechID AND TechID IS NOT NULL;
</code>```

Body:
I have a method and am trying to figure out how to handle calling that method with null parameters.

public static List<Incident> GetIncidentByTechnician(int techID)
    {
        List<Incident> incidents = new List<Incident>();

            Incident inc = null; // found incident
                                 // define connection
            SqlConnection connection = TechSupportDB.GetConnection();

            // define the select query command
            string selectQuery = "select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description " +
                                 "from Incidents " +
                                 "where TechID = @TechID";

        SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
            selectCommand.Parameters.AddWithValue("@TechID", techID);
            try
            {
                // open the connection
                connection.Open();

                // execute the query
                SqlDataReader reader = selectCommand.ExecuteReader();

                // process the result while there are incidents
                while (reader.Read())
                {
                    inc = new Incident();
                    inc.IncidentID = (int)reader["IncidentID"];
                    inc.CustomerID = (int)reader["CustomerId"];
                    inc.ProductCode = reader["ProductCode"].ToString();
                    inc.TechID = (int)reader["TechID"];
                    inc.DateOpened = (DateTime)reader["DateOpened"];
                    inc.DateClosed = (DateTime?)reader["DateClosed"];
                    inc.Title = reader["Title"].ToString();
                    inc.Description = reader["Description"].ToString();
                    incidents.Add(inc); //add to the list
                }
            }
            catch (Exception ex)
            {
                throw ex; // let the form handle it
            }
            finally
            {
                connection.Close(); // close connecto no matter what
            }
        return incidents;
    }

it takes "techID" integer as parameter and populates a list of incidents with that technician ID. However, some incidents have null values for techID. I don't want them to be added into my list.

I tried an if(techID !=null) but that gives an error saying it will always be true. I think my sql statement is not good since "where TechID = null " doesn't return results and it should be "where TechID is null" when testing this statement in sql server management studio. Any suggestions to handle these null values?
Also my incident class is shown below. I set the techID to accept null values with int?.

    public class Incident
{
    public Incident() { }
    public int IncidentID { get; set; }
    public int CustomerID { get; set; }
    public string ProductCode { get; set; }
    public int? TechID { get; set; }
    public DateTime DateOpened { get; set; }
    public DateTime? DateClosed { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

Body:
You should add another condition TechID IS NOT NULL to check for non nulity in your SELECT query like

SELECT IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed,
Title, Description from Incidents
where TechID = @TechID AND TechID IS NOT NULL;


问:
Pandas filling missing dates and values within group
I've a data frame that looks like the following

```<code>x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})
</code>```

What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in 0 for the val column. So the desired output is

```<code>            dt user  val
0   2016-01-01    a    1
1   2016-01-02    a   33
2   2016-01-03    a    0
3   2016-01-04    a    0
4   2016-01-05    a    0
5   2016-01-06    a    0
6   2016-01-01    b    0
7   2016-01-02    b    0
8   2016-01-03    b    0
9   2016-01-04    b    0
10  2016-01-05    b    2
11  2016-01-06    b    1
</code>```

I've tried the solution mentioned here and here but they aren't what I'm after.
Any pointers much appreciated.

Body:
I've a data frame that looks like the following

x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})

What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in 0 for the val column. So the desired output is

            dt user  val
0   2016-01-01    a    1
1   2016-01-02    a   33
2   2016-01-03    a    0
3   2016-01-04    a    0
4   2016-01-05    a    0
5   2016-01-06    a    0
6   2016-01-01    b    0
7   2016-01-02    b    0
8   2016-01-03    b    0
9   2016-01-04    b    0
10  2016-01-05    b    2
11  2016-01-06    b    1

I've tried the solution mentioned here and here but they aren't what I'm after.
Any pointers much appreciated.

Body:
As @ayhan suggests

x.dt = pd.to_datetime(x.dt)

One-liner using mostly @ayhan's ideas while incorporating stack/unstack and fill_value

x.set_index(
    ['dt', 'user']
).unstack(
    fill_value=0
).asfreq(
    'D', fill_value=0
).stack().sort_index(level=1).reset_index()

           dt user  val
0  2016-01-01    a    1
1  2016-01-02    a   33
2  2016-01-03    a    0
3  2016-01-04    a    0
4  2016-01-05    a    0
5  2016-01-06    a    0
6  2016-01-01    b    0
7  2016-01-02    b    0
8  2016-01-03    b    0
9  2016-01-04    b    0
10 2016-01-05    b    2
11 2016-01-06    b    1


问:
Change the status bar color of the CNContactPickerViewController
I have a ContactPicker and can control the color for my other ViewControllers in the project but cannot control the ContactsPickers
status bar color.

My goal is to get the status bar text to be white colored.

```<code>- (IBAction)btnSearch:(id)sender {

  //global statusbar color
  UINavigationBar.appearance.translucent = NO;
  UINavigationBar.appearance.barStyle = UIBarStyleBlack;

  CNContactPickerViewController *contactPicker = [CNContactPickerViewController new];

  //local statusbar color
  contactPicker.navigationController.navigationBar.translucent = NO;
  contactPicker.navigationController.navigationBar.barStyle = UIBarStyleBlack;

  contactPicker.delegate = self;

  contactPicker.displayedPropertyKeys = @[CNContactNamePrefixKey, CNContactPhoneNumbersKey];

  [self presentViewController:contactPicker animated:NO completion:nil];

}
</code>```

I have also found this in Xcode Docs:
Apps default to using the new view controller-based status bar management system. To opt out of this, add a value of NO for the UIViewControllerBasedStatusBarAppearance key to your Info.plist.

When I have a global property to not control per view, I can manage
to get the ContactPicker status bar to have white color.

答:
I have been trying all kinds of approaches which did not work for my
situation:

(1)
in my Appdelegate I tried this, it had no effect:

```<code>[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
</code>```

(2)
in my AppDelegate I have this but it had no effect:

```<code>UINavigationBar.appearance.translucent = NO;
UINavigationBar.appearance.barStyle = UIBarStyleBlack;
</code>```

(3)
Just before presenting the ContactsController I had this (no effect):

```<code>self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.translucent = NO;
</code>```

(4)
This too had no effect just before presenting the Controller:

```<code>contactPicker.navigationController.navigationBar.translucent = NO;
contactPicker.navigationController.navigationBar.barStyle = UIBarStyleBlack;
</code>```

(5)
This worked by extending the class and overriding the method "preferredStatusBarStyle":

NOTE: in my plist I have set "View controller-based status bar appearance" to "YES"

For all other ViewControllers simply setting the translucent and the barStyle of the NavigationCotroller to UIBarStyleBlack worked, but
not for the Contacts.

.h

```<code>#import <ContactsUI/ContactsUI.h>

@interface ContactViewController : CNContactPickerViewController

@end
</code>```

.m

```<code>#import "ContactViewController.h"

@interface ContactViewController ()

@end

@implementation ContactViewController

- (void)viewDidLoad {
   [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
}

-(UIStatusBarStyle)preferredStatusBarStyle {
   return UIStatusBarStyleLightContent;
}
@end
</code>```

Body:
I have a ContactPicker and can control the color for my other ViewControllers in the project but cannot control the ContactsPickers
status bar color.

My goal is to get the status bar text to be white colored.

- (IBAction)btnSearch:(id)sender {

  //global statusbar color
  UINavigationBar.appearance.translucent = NO;
  UINavigationBar.appearance.barStyle = UIBarStyleBlack;

  CNContactPickerViewController *contactPicker = [CNContactPickerViewController new];

  //local statusbar color
  contactPicker.navigationController.navigationBar.translucent = NO;
  contactPicker.navigationController.navigationBar.barStyle = UIBarStyleBlack;

  contactPicker.delegate = self;

  contactPicker.displayedPropertyKeys = @[CNContactNamePrefixKey, CNContactPhoneNumbersKey];

  [self presentViewController:contactPicker animated:NO completion:nil];

}

I have also found this in Xcode Docs:
Apps default to using the new view controller-based status bar management system. To opt out of this, add a value of NO for the UIViewControllerBasedStatusBarAppearance key to your Info.plist.

When I have a global property to not control per view, I can manage
to get the ContactPicker status bar to have white color.

Body:
I have been trying all kinds of approaches which did not work for my
situation:

(1)
in my Appdelegate I tried this, it had no effect:

[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

(2)
in my AppDelegate I have this but it had no effect:

UINavigationBar.appearance.translucent = NO;
UINavigationBar.appearance.barStyle = UIBarStyleBlack;

(3)
Just before presenting the ContactsController I had this (no effect):

self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.translucent = NO;

(4)
This too had no effect just before presenting the Controller:

contactPicker.navigationController.navigationBar.translucent = NO;
contactPicker.navigationController.navigationBar.barStyle = UIBarStyleBlack;

(5)
This worked by extending the class and overriding the method "preferredStatusBarStyle":

NOTE: in my plist I have set "View controller-based status bar appearance" to "YES"

For all other ViewControllers simply setting the translucent and the barStyle of the NavigationCotroller to UIBarStyleBlack worked, but
not for the Contacts.

.h

#import <ContactsUI/ContactsUI.h>

@interface ContactViewController : CNContactPickerViewController

@end

.m

#import "ContactViewController.h"

@interface ContactViewController ()

@end

@implementation ContactViewController

- (void)viewDidLoad {
   [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
}

-(UIStatusBarStyle)preferredStatusBarStyle {
   return UIStatusBarStyleLightContent;
}
@end


问:
Why did PCI Express suffer high latency in pipeline transfer mode?
I used the Arria V GX FPGA Starter Kit connected to a computer via PCI Express (PCIE). In the Kit, I implemented my Direct Memory Access (DMA) Read/Write using the pipeline transfer. The DMA read the data from the PC's memory then write to another region of the PC's memory via the PCIE.

The IP I used is Avalon-MM Arria V Hard IP for PCIE with the configuration: Gen1 x8, 32-bit Avalon-MM address width. The software on the PC is Visual Studio programming by C++ and using the 12.0.0 Jungo Windriver.

The project works fine but the transferring speed, especially the reading speed, is too slow. I had done a lot of projects with this DMA, so I don't think the problem is because of my DMA. I have checked the Altera SignalTap of the project, and find out that:
+ (Figure 1) There are always over 100 clocks since the DMA began to read (the first time 'read' signal is asserted) to the first returning data (the first time 'readdatavalid' signal is asserted)
+ (Figure 2) After that, there are always about 20 to 50 standby clocks between two returning data, which is too slow.

My design needs to read the data from PC: (1) very little data (about 5 to 10 data for each time); (2) random access (that's why I didn't use burst transfer). But every time a new transferring session started, over 100 clocks are wasted at the beginning and I don't know why. To conclude, Avalon memory-mapped read pipeline costs about 200 clocks just to read 5 data from the PC's memory via PCIE.

My questions are: (1) Why there are so many clocks being wasted in the read pipeline transfer via PCIE? (2) Is there anything else I can do to speed up the transfer rate?

Thank you very much

答:
PCIE was really designed to maximize I/O bandwidth but not to minimize latency. In my designs, I have often seen such a long latency for the first read response from system memory and I do not have any suggestions on how to reduce it.

To get performance from PCIE you have to design around the latency, using burst transfers and pipelining requests so that you can keep many requests in flight in order to maximize bandwidth.


问:
asp:ImageButton is not firing in an asp.net UpdatePanel?
I have an asp:ImageButton that is supposed to popup a save dialog when clicked.  When I put it outside the UpdatePanel, it works fine, but when I put it inside the UpdatePanel, the dialog does not popup.</p>

答:
txtmail.Attributes.Add("onkeydown","if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+Ibtnsend.UniqueID+"').click();return false;}} else {return true}; ");

onkeydown="submitOnEnter(this.Form1.Ibtnsend)"

OwnerDisplayName: Xaisoft

LastEditorDisplayName: Xaisoft

OwnerDisplayName: jagadish


问:
Acessing a wordpress database from an iPhone App
I've been asked to create an app that will get data back from a database where the CMS will be Wordpress. I've never used a CMS so I'm trying to get a (overview)picture in my head of how it could all work and what each of the components would be. And what a CMS actually brings to the party.

Creating the app itself is pretty clear. I've done a few already. I've made a database before and shouldnt cause a problem.

But what is going to be in the middle between the app and the database?

Part A:
I'm guessing iphone apps typically would call some php file that's hosted on the server? The php then would make a call to the database and return the data somehow, maybe as xml. But this is really basic and wouldnt require a CMS. Just a database and a phpfile, or am I wrong?

Part B:
If i wanted to run a check on the database every minute to see if any of the data in database was no longer valid and remove it if needed, that would require somekind of program running on the server. So that program would be Wordpress, since it is managing the content, so a content management system is actually needed and is for these kind of taskes. Am i understanding the role of CMS?

Many Thanks,
-Code

答:
I would not try to access the db directly or through some custom php-code, but use the official WordPress API (which uses xml-rpc) instead.

and this xml-rpc objective-c library might even make this a pretty straightforward exercise?


问:
Combining two programs with pipe won't work
I am supposed to make two programs:

First program takes a command line argument which is a number, and then it takes more inputs after execution, and if any those equal the command line number you entered, it comes back true, else it comes back false.

The second program generates a bunch of numbers, and if you want you can give it a seed.

Both of these programs work independently correctly, it stops working when I try to pipeline them (./generate 1000 50 | ./find 817).

Usage:

```<code>./find #
</code>```

if number is found: output true, else false

```<code>./generate [seed]
</code>```

Seeds are generated.

When i try and combine these two commands it doesn't work, I'll see that the generate command generated a number, and wrote ./find for that number, but it doesn't come out as true.

Source code for find.c

```<code>/**
 * Prompts user for as many as MAX values until EOF is reached,
 * then proceeds to search that "haystack" of values for given needle.
 *
 * Usage: ./find needle
 *
 * where needle is the value to find in a haystack of values
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./find needle\n");
        return -1;
    }

    // remember needle
    int needle = atoi(argv[1]);

    // fill haystack
    int size;
    int haystack[MAX];
    for (size = 0; size < MAX; size++)
    {
        // wait for hay until EOF
        printf("\nhaystack[%i] = ", size);
        int straw = get_int();
        if (straw == INT_MAX)
        {
            break;
        }

        // add hay to stack
        haystack[size] = straw;
    }
    printf("\n");

    // sort the haystack
    sort(haystack, size);

    // try to find needle in haystack
    if (search(needle, haystack, size))
    {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    }
    else
    {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}
</code>```

more find.c source code

```<code> /**
 * helpers.c
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(values[4] < 0) {
        return false;
    }
    if(value < 4) {
        printf("Valid usage: ./search array value\n");
        return 52;
    }
    //

    for( long long i = 0 ; i < n ; i++ )
    {
        if (value == values[i])
        {
            return true;
        }

        printf("%i", values[i]);
    }

    return false;
}

/**
 * Sorts array of n values.
 */

void sort(int values[], int n)
{

    int smallest = values[0];
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {

        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {

            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }

            values[smallestSpot] = values[i];
            values[i] = smallest;

        }

    }
    return;
}
</code>```

./generate source code

```<code>/**
 * generate.c
 *
 * Generates pseudo random numbers in [0,MAX), one per line.
 *
 * Usage: generate n [s]
 *
 * where n is number of pseudo random numbers to print
 * and s is an optional seed
 */

#define _XOPEN_SOURCE

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// upper limit on range of integers that can be generated
#define LIMIT 65536

int main(int argc, string argv[])
{
    // Make sure user gave enough inputs
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // convert the string that is inputted to an integer
    int n = atoi(argv[1]);

    // if user gives a seed, use that seed
    if (argc == 3)
    {
        srand48((long) atoi(argv[2]));
    }
    else
    {
        srand48((long) time(NULL));
    }

    // create this amount of random inputs
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", (int) (drand48() * LIMIT));
    }

    // success
    return 0;
}
</code>```

答: Sort is overwriting the first half or so entries from ./generate.</p>

Body:
I am supposed to make two programs:

First program takes a command line argument which is a number, and then it takes more inputs after execution, and if any those equal the command line number you entered, it comes back true, else it comes back false.

The second program generates a bunch of numbers, and if you want you can give it a seed.

Both of these programs work independently correctly, it stops working when I try to pipeline them (./generate 1000 50 | ./find 817).

Usage:

./find #

if number is found: output true, else false

./generate [seed]

Seeds are generated.

When i try and combine these two commands it doesn't work, I'll see that the generate command generated a number, and wrote ./find for that number, but it doesn't come out as true.

Source code for find.c

/**
 * Prompts user for as many as MAX values until EOF is reached,
 * then proceeds to search that "haystack" of values for given needle.
 *
 * Usage: ./find needle
 *
 * where needle is the value to find in a haystack of values
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./find needle\n");
        return -1;
    }

    // remember needle
    int needle = atoi(argv[1]);

    // fill haystack
    int size;
    int haystack[MAX];
    for (size = 0; size < MAX; size++)
    {
        // wait for hay until EOF
        printf("\nhaystack[%i] = ", size);
        int straw = get_int();
        if (straw == INT_MAX)
        {
            break;
        }

        // add hay to stack
        haystack[size] = straw;
    }
    printf("\n");

    // sort the haystack
    sort(haystack, size);

    // try to find needle in haystack
    if (search(needle, haystack, size))
    {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    }
    else
    {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}

more find.c source code

 /**
 * helpers.c
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(values[4] < 0) {
        return false;
    }
    if(value < 4) {
        printf("Valid usage: ./search array value\n");
        return 52;
    }
    //

    for( long long i = 0 ; i < n ; i++ )
    {
        if (value == values[i])
        {
            return true;
        }

        printf("%i", values[i]);
    }

    return false;
}

/**
 * Sorts array of n values.
 */

void sort(int values[], int n)
{

    int smallest = values[0];
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {

        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {

            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }

            values[smallestSpot] = values[i];
            values[i] = smallest;

        }

    }
    return;
}

./generate source code

/**
 * generate.c
 *
 * Generates pseudo random numbers in [0,MAX), one per line.
 *
 * Usage: generate n [s]
 *
 * where n is number of pseudo random numbers to print
 * and s is an optional seed
 */

#define _XOPEN_SOURCE

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// upper limit on range of integers that can be generated
#define LIMIT 65536

int main(int argc, string argv[])
{
    // Make sure user gave enough inputs
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // convert the string that is inputted to an integer
    int n = atoi(argv[1]);

    // if user gives a seed, use that seed
    if (argc == 3)
    {
        srand48((long) atoi(argv[2]));
    }
    else
    {
        srand48((long) time(NULL));
    }

    // create this amount of random inputs
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", (int) (drand48() * LIMIT));
    }

    // success
    return 0;
}


问:
Aggregate fields selectively based on MAX(value)
I have a very large union query that produces the following results:

```<code>p_id       title_id        title        is_live

1          37              TITANIC      1
2          37              TITANIC      0

3          41              AVATAR       0
4          41              AVATAR       0

5          44              HOME ALONE   0

6          11              COMPUTE      1
7          11              COMPUTE      1
8          11              COMPUTE      1
</code>```

From this result, I want to aggregate it so that I get at least one of each title (title_id), but all titles with is_live = True. (In other words, for each title_id, I want to get exactly one result if MAX(is_live)=0, but all results if MAX(is_live)=1 for that title_id.) Here's an example of the result set that I want, with an explanation for each title:

```<code>p_id       title_id        title        is_live

1          37              TITANIC      1 // live one for titanic

3          41              AVATAR       0 # at least one of each title (which one doesn't matter)

5          44              HOME ALONE   0 /* at least one of each title */

6          11              COMPUTE      1 // keep all, since all are live
7          11              COMPUTE      1
8          11              COMPUTE      1
</code>```

The query that I have so far is along the lines of the following:

```<code>SELECT * FROM (
    80-line UNION query
) d
GROUP BY
  d.title_id
</code>```

But this of course isn't accurate enough and is more an outline. How would I do the above?

Here is a SQLFiddle for the question: http://sqlfiddle.com/#!9/739a36/2/0

答:
You can do this with variables:

```<code>select q.*
from (select q.*,
             (@rn := if(@t = title, @rn + 1,
                        if(@t := title, 1, 1)
                       )
             ) as rn
      from (<your query here>) q cross join
           (select @t := '', @rn := 0) params
      order by title, is_live desc
     ) q
where is_live = 1 or rn = 1;
</code>```

Here is the SQL Fiddle.

Body:
I have a very large union query that produces the following results:

p_id       title_id        title        is_live

1          37              TITANIC      1
2          37              TITANIC      0

3          41              AVATAR       0
4          41              AVATAR       0

5          44              HOME ALONE   0

6          11              COMPUTE      1
7          11              COMPUTE      1
8          11              COMPUTE      1

From this result, I want to aggregate it so that I get at least one of each title (title_id), but all titles with is_live = True. (In other words, for each title_id, I want to get exactly one result if MAX(is_live)=0, but all results if MAX(is_live)=1 for that title_id.) Here's an example of the result set that I want, with an explanation for each title:

p_id       title_id        title        is_live

1          37              TITANIC      1 // live one for titanic

3          41              AVATAR       0 # at least one of each title (which one doesn't matter)

5          44              HOME ALONE   0 /* at least one of each title */

6          11              COMPUTE      1 // keep all, since all are live
7          11              COMPUTE      1
8          11              COMPUTE      1

The query that I have so far is along the lines of the following:

SELECT * FROM (
    80-line UNION query
) d
GROUP BY
  d.title_id

But this of course isn't accurate enough and is more an outline. How would I do the above?

Here is a SQLFiddle for the question: http://sqlfiddle.com/#!9/739a36/2/0

Body:
You can do this with variables:

select q.*
from (select q.*,
             (@rn := if(@t = title, @rn + 1,
                        if(@t := title, 1, 1)
                       )
             ) as rn
      from (<your query here>) q cross join
           (select @t := '', @rn := 0) params
      order by title, is_live desc
     ) q
where is_live = 1 or rn = 1;

Here is the SQL Fiddle.


问:
pass a javascript variable as a param in url_for
i'm trying to pass a javascript variable into the ruby on rails 「 url_for」method

is that possible??

```<code><a href="<%= url_for(:controller => 'epgs', :action => 'show', :parameter1 => myJavaScriptVariable %>" data-inline="true">
</code>```

答:
No, JavaScript variables are not in the scope when your ERB is being rendered as this is being done server-side. Javascript can only be used once the page has been fully rendered by Rails and returned to the user (i.e in the user's browser). If you really need a JavaScript variable in the URL then a simple way to do it would be to add the extra parameter to the href using JavaScript once the page has loaded:

```<code>  new_link = $('#link').attr('href') + '&parameter_1=' + myJavaScriptVariable;
  $('#link').attr('href', new_link);
</code>```

using jQuery or something similar.

Body:
i'm trying to pass a javascript variable into the ruby on rails 「 url_for」method

is that possible??

<a href="<%= url_for(:controller => 'epgs', :action => 'show', :parameter1 => myJavaScriptVariable %>" data-inline="true">

Body:
No, JavaScript variables are not in the scope when your ERB is being rendered as this is being done server-side. Javascript can only be used once the page has been fully rendered by Rails and returned to the user (i.e in the user's browser). If you really need a JavaScript variable in the URL then a simple way to do it would be to add the extra parameter to the href using JavaScript once the page has loaded:

  new_link = $('#link').attr('href') + '&parameter_1=' + myJavaScriptVariable;
  $('#link').attr('href', new_link);

using jQuery or something similar.


问:
Switch line placements in bash
is it possible to switch the placement of lines in bash given some string in the lines with sed?

For example:

I have the lines

```<code>2. diskusage1: 27.0572519084
3. partition1:
</code>```

which are both output as part of a bash command to a text file.

Is there a way to reverse the order of these lines? To have them switch places to look like:

```<code>3. partition1:
2. diskusage1: 27.0572519084
</code>```

Thanks

答:
That will do:</p>

```<code>command | sed '2{h;d};3{p;x}' > file.txt
</code>```

Title: Switch line placements in bash

Body:
is it possible to switch the placement of lines in bash given some string in the lines with sed?

For example:

I have the lines

2. diskusage1: 27.0572519084
3. partition1:

which are both output as part of a bash command to a text file.

Is there a way to reverse the order of these lines? To have them switch places to look like:

3. partition1:
2. diskusage1: 27.0572519084

Thanks

Body:
That will do:

command | sed '2{h;d};3{p;x}' > file.txt


问:
JS/CSS files not refreshing (probably server side)
I'm working on a javascript file. Everything was functioning normally for my first few edits, but now when I make changes and reload my page, I get a browser console error SyntaxError: illegal character, and when I check the source, I see an old version of my file with a bunch of �s at the end.

I've been working on this site without issue for a week or two. However, the other day I had a similar issue to this with a CSS file. I think I got it working by renaming the file, refreshing, and naming it back. It still doesn't refresh properly, and obviously this isn't a practical way to do development.

My Environment

I'm developing a website on Centos 7 under VirtualBox in Windows 7.

My site code is in a shared folder. (In Windows, accessible by Centos).

Apache, PHP 7, MariaDB.

TYPO3 8.7.3 CMS

I view my site at a local domain defined in my Windows hosts file.

What I've Tried

Refresh page (multiple times, using Ctrl+F5).

View JS file directly. Refresh. (at mydomain/typo3conf/ext/myext/Resources/Public/js/file.js)

Add ?somerandomstring after file.js and refresh.

Clear my CMS caches, using "Flush all caches".

Rename my CMSs .htaccess file. In Centos run /sbin/service httpd restart. Refresh JS file.

Open JS file in other browser.

On restarting Centos, and refreshing, I get the current version of the file. But if I edit it again, then I get the same error.

If I undo the changes to my file, then it loads and runs normally.

I think this rules out it being my browser. I think renaming .htaccess should rule out it being the CMS, but I don't have the knowledge to be certain of that.

So, what do I check next?

Edit:

Also noticed, If I edit my file to make it shorter, it trims the old file to the length of the new file.

答:
I have the same problem with my assets (css, js, images, etc.).
The only thing that works (as of my current knowledge) is adding a random number next to the url like this: /main.js?someRandomNumber.

This forces the browser to reload the file and load new code.

To achieve this, use php like this:

```<code><script src=<?php echo '"main.js?' . rand() .'"'; ?>></script>
</code>```

If you find a better way to do this please let me know...

Body:
I have the same problem with my assets (css, js, images, etc.).
The only thing that works (as of my current knowledge) is adding a random number next to the url like this: /main.js?someRandomNumber.

This forces the browser to reload the file and load new code.

To achieve this, use php like this:

<script src=<?php echo '"main.js?' . rand() .'"'; ?>></script>

If you find a better way to do this please let me know...


问:
Counting Rows Based on Exist Condition
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

```<code>CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)
</code>```

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

```<code>| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |
</code>```

So here is what I have so far:

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

答:
```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 END),0) AS AssignedToMe,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId <> @userId THEN 1 END),0) AS AssignedToOthers
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskOwner pto
    ON pto.ProjectTaskId = pt.ProjectTaskId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId and
    pte.AssignedUserId = pto.UserId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

http://www.sqlfiddle.com/#!6/58f1e4/28

Title: Counting Rows Based on Exist Condition

Body:
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |

So here is what I have so far:

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

Body:
DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 END),0) AS AssignedToMe,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId <> @userId THEN 1 END),0) AS AssignedToOthers
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskOwner pto
    ON pto.ProjectTaskId = pt.ProjectTaskId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId and
    pte.AssignedUserId = pto.UserId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

http://www.sqlfiddle.com/#!6/58f1e4/28