问:
Java JDBC MySQL exception: “Operation not allowed after ResultSet closed” with Web Page read
I am using the MySQL connector to get the URL to find values on the web pages.

I am getting the above message and I am not sure why. It inserts the first record from the rs1, but I am not sure why it is closing it.

Below is my code

```<code>    String strSQL = "SELECT * FROM element_info;";
    String sElementID = "";
    String sSymbol = "";
    URL urlChartLink;
    URLConnection urlconn;
    String sChartLink = "";
    String sCurrentPrice = "";
    String FindValue = "last_last";

    try {

        Class.forName(driver).newInstance();
        Connection mysqlconn = DriverManager.getConnection(url + dbName, userName, password);
        Statement st1 = mysqlconn.createStatement();
        ResultSet rs1 = st1.executeQuery(strSQL);

        while (rs1.next()) {
            // Get all of the elements
            // Retrieve the ElementID
            sElementID = rs1.getString(1);
            // Retrieve the Symbol
            sSymbol = rs1.getString(2);
            // Retrieve the Chartlink
            sChartLink = rs1.getString(3);
            if (sChartLink == "") {
                break;
            }

            try {

                urlChartLink = new URL(sChartLink);
                urlconn = urlChartLink.openConnection();
                urlconn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
                String currentLine;

                while ((currentLine = in.readLine()) != null) {
                    // See if the value is on this record
                    int pos1 = currentLine.indexOf(FindValue);
                    int pos2 = currentLine.indexOf("</span>");
                    // pos1 = 66
                    if (pos1 > 0) {
                        pos1 = pos1 + 21;
                        pos2 = pos2 - 1;
                        // System.out.print("pos1 = " + pos1 + "\n");
                        // System.out.print("pos2 = " + pos2 + "\n");

                        sCurrentPrice = currentLine.substring(pos1, pos2);
                        // System.out.print("sCurrentPrice = " + sCurrentPrice + "\n");

                        // Import into the marketprices
                        strSQL = "INSERT INTO marketprices"
                                + "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"
                                + sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";

                        int val = st1.executeUpdate(strSQL);

                        if (val == 1)
                            System.out.print("Successfully inserted from " + sChartLink + "\n");
                        break;
                    }
                }
                in.close();
            } catch (IOException e) {
                System.out.print("Error getting ChartLink website: " + e.getMessage() + "\n");
                break;
            }
        }
    } catch (Exception e) {
        System.out.print("Error: " + e.getMessage() + "\n");
        e.printStackTrace();
    }
</code>```

答:
You are trying to write with a statement object that is already in use as you are still reading the existing resultset from that statement object. You need to create a new statement object for the update portion of your code:</p>

```<code>strSQL = "INSERT INTO marketprices"+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
Connection mysqlconn2 = DriverManager.getConnection(url + dbName, userName, password);
Statement st2 = mysqlconn.createStatement();
int val = st2.executeUpdate(strSQL);
</code>```

Body:
I am using the MySQL connector to get the URL to find values on the web pages.

I am getting the above message and I am not sure why. It inserts the first record from the rs1, but I am not sure why it is closing it.

Below is my code

    String strSQL = "SELECT * FROM element_info;";
    String sElementID = "";
    String sSymbol = "";
    URL urlChartLink;
    URLConnection urlconn;
    String sChartLink = "";
    String sCurrentPrice = "";
    String FindValue = "last_last";

    try {

        Class.forName(driver).newInstance();
        Connection mysqlconn = DriverManager.getConnection(url + dbName, userName, password);
        Statement st1 = mysqlconn.createStatement();
        ResultSet rs1 = st1.executeQuery(strSQL);

        while (rs1.next()) {
            // Get all of the elements
            // Retrieve the ElementID
            sElementID = rs1.getString(1);
            // Retrieve the Symbol
            sSymbol = rs1.getString(2);
            // Retrieve the Chartlink
            sChartLink = rs1.getString(3);
            if (sChartLink == "") {
                break;
            }

            try {

                urlChartLink = new URL(sChartLink);
                urlconn = urlChartLink.openConnection();
                urlconn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
                String currentLine;

                while ((currentLine = in.readLine()) != null) {
                    // See if the value is on this record
                    int pos1 = currentLine.indexOf(FindValue);
                    int pos2 = currentLine.indexOf("");
                    // pos1 = 66
                    if (pos1 > 0) {
                        pos1 = pos1 + 21;
                        pos2 = pos2 - 1;
                        // System.out.print("pos1 = " + pos1 + "\n");
                        // System.out.print("pos2 = " + pos2 + "\n");

                        sCurrentPrice = currentLine.substring(pos1, pos2);
                        // System.out.print("sCurrentPrice = " + sCurrentPrice + "\n");

                        // Import into the marketprices
                        strSQL = "INSERT INTO marketprices"
                                + "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"
                                + sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";

                        int val = st1.executeUpdate(strSQL);

                        if (val == 1)
                            System.out.print("Successfully inserted from " + sChartLink + "\n");
                        break;
                    }
                }
                in.close();
            } catch (IOException e) {
                System.out.print("Error getting ChartLink website: " + e.getMessage() + "\n");
                break;
            }
        }
    } catch (Exception e) {
        System.out.print("Error: " + e.getMessage() + "\n");
        e.printStackTrace();
    }

Body:
You are trying to write with a statement object that is already in use as you are still reading the existing resultset from that statement object. You need to create a new statement object for the update portion of your code:

strSQL = "INSERT INTO marketprices"+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
Connection mysqlconn2 = DriverManager.getConnection(url + dbName, userName, password);
Statement st2 = mysqlconn.createStatement();
int val = st2.executeUpdate(strSQL);


来源: stackexchange

问:
Why are string in .net case sensitive by default?
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

```<code>"John Smith" == "JOHN SMITH"
</code>```

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords

答:
Because case insensitivity is not performant and because it works even when you intend it not to.

Vendors need to compete based on performance and for that reason the default option tends to be the one that performs best.  At best, case insensitivity requires folding both strings to a common case prior to comparing.  At worst, depending on locale, it requires a code path that can be twice as long.  If the vendor defaulted to the less performant version, competitors would pick the worst-case scenarios to benchmark against.

Since case sensitivity fails on certain searches you are forced to address this in your code.  It forces a conscious decision.  In contrast, case insensitivity works, even in cases where you don't want it to.  Rather than forcing you to make a decision it creates a scenario where you can overlook it to your detriment.  As a matter of choice architecture, vendors tend to pick the option that leads to fewer defects - in this case that's case sensitivity.

ContentLicense: CC BY-SA 2.5

Body:
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

"John Smith" == "JOHN SMITH"

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords


问:
Error while installing textblob on ubuntu 14.04
I'm trying to install textblob on my system. By following the documentation, I had run the command

```<code>pip3 install -U textblob
</code>```

But while running the command, I'm getting an error like this.

答: pip install attempts to write files to /usr/local, as seen in the error message. You should run it from the root user.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to install textblob on my system. By following the documentation, I had run the command

pip3 install -U textblob

But while running the command, I'm getting an error like this.


问:
Pandas read_csv() - Flie contains different data
Problem:
I am trying to read in a csv to a pandas dataframe that contains data of different column sizes.

Example & Description:

```<code>Code:
df = pd.read_csv(input, error_bad_lines=False)

input:
ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8
</code>```

and this pattern continues for the entirety of the file. Originally I was thinking about throwing away the extra columns since read_csv option throws and error and doesn't read them I just started to ignore them. However I then get duplicate headers in my dataframe... To combat this I tried the drop_duplicates() but found out that only in V0.17 of pandas do they include the keep=False option. I eventually started to convince myself that try to keep the data. So here is my question. Based on the dataset above I was hoping that I might be able to create two unique dataframes. You can assume that the ID will always be unique so you can create N number of frames for the number of different IDs you have. Each ID will not have the same number of headers. Once a different ID is encountered its header will be printed. So for example if we hit another ID 16 its header will be printed prior to the data. And again if we hit another ID 15 its header will be printed prior to its data.

I was thinking maybe to just preprocess the data before I started using dataframes since that is an option. But since I am still fairly new to all that pandas can do, I was hoping maybe some people here would have suggestions before I went ahead and wrote some nasty preprocessing code :). The other thought I had which turns into a question is - For the error_bad_lines, is there a way to save those lines to another dataframe or something else? Additionally, I tell pandas in the read_csv to only look for items that have an ID of X and just do that for all my ID's? I will add that the number of IDs is finite and known.

My current version of pandas is 0.14.

答:
You can treat the file as having four columns:

```<code>df = pd.read_csv(input, names=['id', 'time', 'v1', 'v2'])
</code>```

and filter out the extra headers:

```<code>df = df[df.id != 'ID']
</code>```

Then your two data sets are simply df[pd.isnull(df.v2)] and df[~pd.isnull(df.v2)].

Body:
Problem:
I am trying to read in a csv to a pandas dataframe that contains data of different column sizes.

Example & Description:

Code:
df = pd.read_csv(input, error_bad_lines=False)

input:
ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8

and this pattern continues for the entirety of the file. Originally I was thinking about throwing away the extra columns since read_csv option throws and error and doesn't read them I just started to ignore them. However I then get duplicate headers in my dataframe... To combat this I tried the drop_duplicates() but found out that only in V0.17 of pandas do they include the keep=False option. I eventually started to convince myself that try to keep the data. So here is my question. Based on the dataset above I was hoping that I might be able to create two unique dataframes. You can assume that the ID will always be unique so you can create N number of frames for the number of different IDs you have. Each ID will not have the same number of headers. Once a different ID is encountered its header will be printed. So for example if we hit another ID 16 its header will be printed prior to the data. And again if we hit another ID 15 its header will be printed prior to its data.

I was thinking maybe to just preprocess the data before I started using dataframes since that is an option. But since I am still fairly new to all that pandas can do, I was hoping maybe some people here would have suggestions before I went ahead and wrote some nasty preprocessing code :). The other thought I had which turns into a question is - For the error_bad_lines, is there a way to save those lines to another dataframe or something else? Additionally, I tell pandas in the read_csv to only look for items that have an ID of X and just do that for all my ID's? I will add that the number of IDs is finite and known.

My current version of pandas is 0.14.

Body:
You can treat the file as having four columns:

df = pd.read_csv(input, names=['id', 'time', 'v1', 'v2'])

and filter out the extra headers:

df = df[df.id != 'ID']

Then your two data sets are simply df[pd.isnull(df.v2)] and df[~pd.isnull(df.v2)].


问:
How to call a class infinitely
I have this piece of code which runs infinitely. I want to put this code in a class and define a button in another class. When the button is clicked, it should call the class (in which the code is) and this class should run infinitely like the original code. As I have tried several methods which I learnt from internet but no luck at all. As I'm totally new to python. Any help would be appreciated.

```<code>import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
import matplotlib.animation as animation

j=0
fig = plt.figure()
ax1 = fig.add_axes([0.85, 0.093, 0.04, 0.8])
cax = fig.add_subplot(1, 1, 1)

H = np.array([[1, 2, 3, 1], [4, 5, 6, 10], [3, 7, 8, 4], [10, 5, 3, 1]])
Z = np.array([[3, 290, 600], [1011, 230, 830], [152, 750, 5]])

def func(i):
    global j
    if j == 0:
        j += 1
        rows, cols = H.shape

        im = plt.imshow(H, interpolation='nearest',
                    extent=[0, cols, 0, rows],
                    cmap='bwr', vmin=0, vmax=10)
        fig.colorbar(im, cax=ax1, orientation='vertical')

    elif j == 1:
        j -= 1
        rows, cols = H.shape

        im = plt.imshow(Z, interpolation='nearest', cmap='Spectral', vmin=0, vmax=1023,
                    extent=[0, cols, 0, rows])
        v = np.linspace(0, 1023, 15, endpoint=True)
        fig.colorbar(im, cax=ax1, orientation='vertical', ticks=v)

ani = animation.FuncAnimation(fig, func, interval=1000)
plt.show()
</code>```

It should be better to use Canvas instead of imshowbecause later on I will make a GUI and will use Tkinter.

答:
Let's assume you have a function do_something which you want to call repeatedly in a loop:

```<code>def do_something(...):
    <whatever code you want>
</code>```

Assuming you pass in a reference to a widget (eg: root), you can run this function continuously with something like the following example. In this example it runs the code every second (eg: 1000 ms).

```<code>def run_every_second(root):
    do_something()
    root.after(1000, run_every_second, root)
</code>```

You start the process by calling run_every_second just once:

```<code>root = tk.Tk()
...
run_every_second(root)
</code>```

I do not know if this method works well in conjunction with matplotlib, but with normal tkinter this is a very standard technique.

Title: How to call a class infinitely

Body:
I have this piece of code which runs infinitely. I want to put this code in a class and define a button in another class. When the button is clicked, it should call the class (in which the code is) and this class should run infinitely like the original code. As I have tried several methods which I learnt from internet but no luck at all. As I'm totally new to python. Any help would be appreciated.

import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
import matplotlib.animation as animation

j=0
fig = plt.figure()
ax1 = fig.add_axes([0.85, 0.093, 0.04, 0.8])
cax = fig.add_subplot(1, 1, 1)

H = np.array([[1, 2, 3, 1], [4, 5, 6, 10], [3, 7, 8, 4], [10, 5, 3, 1]])
Z = np.array([[3, 290, 600], [1011, 230, 830], [152, 750, 5]])

def func(i):
    global j
    if j == 0:
        j += 1
        rows, cols = H.shape

        im = plt.imshow(H, interpolation='nearest',
                    extent=[0, cols, 0, rows],
                    cmap='bwr', vmin=0, vmax=10)
        fig.colorbar(im, cax=ax1, orientation='vertical')

    elif j == 1:
        j -= 1
        rows, cols = H.shape

        im = plt.imshow(Z, interpolation='nearest', cmap='Spectral', vmin=0, vmax=1023,
                    extent=[0, cols, 0, rows])
        v = np.linspace(0, 1023, 15, endpoint=True)
        fig.colorbar(im, cax=ax1, orientation='vertical', ticks=v)

ani = animation.FuncAnimation(fig, func, interval=1000)
plt.show()

It should be better to use Canvas instead of imshowbecause later on I will make a GUI and will use Tkinter.

Body:
Let's assume you have a function do_something which you want to call repeatedly in a loop:

def do_something(...):
    <whatever code you want>

Assuming you pass in a reference to a widget (eg: root), you can run this function continuously with something like the following example. In this example it runs the code every second (eg: 1000 ms).

def run_every_second(root):
    do_something()
    root.after(1000, run_every_second, root)

You start the process by calling run_every_second just once:

root = tk.Tk()
...
run_every_second(root)

I do not know if this method works well in conjunction with matplotlib, but with normal tkinter this is a very standard technique.


问:
sql server 2000 backup directly to a separate server
SQL Server 2000 on Windows Server 2003.

I am trying to run a backup, from within EM, directly over to another server, as follows:

backup database AbraEmployeeSelfService
to disk = '\\servername\f$\Backup\myDB_backup.bak'

I get this error:
Cannot open backup device '\\servername\f$\Backup\myDB_backup.bak'.
Device error or device off-line. See the SQL Server error log for more details.
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.

The error log shows this message:
BackupDiskFile::CreateMedia: Backup device '\\servername\f$\Backup\myDB_backup.bak' failed to create. Operating system error = 5(Access is denied.).

I am running the command using a windows login that has full rights on the destination path. At least, from my desktop I can open a run window, enter \\servername\f$\Backup, and in the resulting Explorer window I can add/edit/delete files in that directory.

What do I need to do to get past that access denial?

答:
I'm not sure if SO is escaping your destination, but it should read:

```<code>'\\servername\f$\Backup\myDB_backup.bak'
</code>```

(There's two \'s prefixing the server name)

SQL Server will attempt connecting to this network share as the user that SQL Server's service is running as. You might need to run SQL Server as another account that matches an account with priveleges to that destination.

Troubleshooting SQL Server backup and restore dilemmas

LastEditorDisplayName: Oliver

Body:
I'm not sure if SO is escaping your destination, but it should read:

'\\servername\f$\Backup\myDB_backup.bak'

(There's two \'s prefixing the server name)

SQL Server will attempt connecting to this network share as the user that SQL Server's service is running as. You might need to run SQL Server as another account that matches an account with priveleges to that destination.

Troubleshooting SQL Server backup and restore dilemmas

OwnerDisplayName: Adam


问:
How to print a variable of type NVARCHAR(MAX) while looping over a CURSOR
I am trying to write a stored procedure which generates dynamic views for tables. For that purpose I am storing the generated View in a NVARCHAR(MAX) type variable. But due to size limitations the variable is getting truncated.

I tried a couple of work around techniques but none of them seem to work for me. I can't split the variable into chunks because I do not know what size the variable will be and I want to write a generic logic for generating views.

Here is the code snippet -

```<code>DECLARE CURTABLE CURSOR FOR
SELECT A
FROM TABLE A
WHERE ID = 189
Order By ID
OPEN curTable
FETCH NEXT FROM curTable INTO @columnname
DECLARE @tsql NVARCHAR(MAX)
WHILE @@fetch_status=0
BEGIN
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' ' + quotename(@columnname,'[')
    ELSE
        SET @tsql=@tsql+@ViewFunctionValue
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' AS ' + quotename(@columnname,'[')

    SET @tsql = @tsql + ', '  + CHAR(10)

    FETCH NEXT FROM curTable INTO @columnname
END
CLOSE curTable
DEALLOCATE curTable

SET @tsql = LEFT(@tsql,LEN(@tsql)-3) + CHAR(10)
SET @tsql= @tsql+' FROM ' + TABLEA

PRINT @tsql
</code>```

答:
As per https://learn.microsoft.com/en-us/sql/t-sql/language-elements/print-transact-sql:

Remarks

A message string can be up to 8,000 characters long if it is a non-Unicode string, and 4,000 characters long if it is a Unicode string. Longer strings are truncated. The varchar(max) and nvarchar(max) data types are truncated to data types that are no larger than varchar(8000) and nvarchar(4000).

This being the case you'll want to perform mulltiple Print actions, each one dealing with the next valid Chunk size, depending on if your're dealing with Standard or Unicode data types.

e.g. something like this untested code:

```<code>Set @p = 1
Print SubStr(@tsql, @p, 4000);
While @p < Len(@tSql)
Begin
    Set @p = @p + 4000;
    If @p < Len(@tSql)
        Print SubStr(@tsql, @p, 4000);
End
</code>```

Body:
I am trying to write a stored procedure which generates dynamic views for tables. For that purpose I am storing the generated View in a NVARCHAR(MAX) type variable. But due to size limitations the variable is getting truncated.

I tried a couple of work around techniques but none of them seem to work for me. I can't split the variable into chunks because I do not know what size the variable will be and I want to write a generic logic for generating views.

Here is the code snippet -

DECLARE CURTABLE CURSOR FOR
SELECT A
FROM TABLE A
WHERE ID = 189
Order By ID
OPEN curTable
FETCH NEXT FROM curTable INTO @columnname
DECLARE @tsql NVARCHAR(MAX)
WHILE @@fetch_status=0
BEGIN
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' ' + quotename(@columnname,'[')
    ELSE
        SET @tsql=@tsql+@ViewFunctionValue
    IF @ViewFunctionValue IS NULL
        SET @tsql = @tsql + ' AS ' + quotename(@columnname,'[')

    SET @tsql = @tsql + ', '  + CHAR(10)

    FETCH NEXT FROM curTable INTO @columnname
END
CLOSE curTable
DEALLOCATE curTable

SET @tsql = LEFT(@tsql,LEN(@tsql)-3) + CHAR(10)
SET @tsql= @tsql+' FROM ' + TABLEA

PRINT @tsql

Body:
As per https://learn.microsoft.com/en-us/sql/t-sql/language-elements/print-transact-sql:

Remarks

A message string can be up to 8,000 characters long if it is a non-Unicode string, and 4,000 characters long if it is a Unicode string. Longer strings are truncated. The varchar(max) and nvarchar(max) data types are truncated to data types that are no larger than varchar(8000) and nvarchar(4000).

This being the case you'll want to perform mulltiple Print actions, each one dealing with the next valid Chunk size, depending on if your're dealing with Standard or Unicode data types.

e.g. something like this untested code:

Set @p = 1
Print SubStr(@tsql, @p, 4000);
While @p < Len(@tSql)
Begin
    Set @p = @p + 4000;
    If @p < Len(@tSql)
        Print SubStr(@tsql, @p, 4000);
End


问:
Put component inside the smaller one
I wanna get Frame(640x640) with DrawCanvas(960x960) inside like this:

So the part of DrawCanvas must be hidden and frame centered. What layout should I choose? Now I put DrawCanvas inside the frame like this:

```<code>    class extends JFrame {
        canvas = new DrawCanvas();
        canvas.setPreferredSize(new Dimension(960, 960));
        Container cp = getContentPane();
        cp.add(canvas);
        setPreferredSize(new Dimension(640, 640));
    }
</code>```

答:
Again as stated in your previous question, a way to do this is to embed the inner component within a JScrollPane, but rid the scrollpane of scrollbars.

For example, say you had a class called DrawPanel that extended JPanel and held a 12 x 12 grid of cells, but you only wanted to show 8 x 8 of them. You could have this class implement the Scrollable interface, have its getPreferredScrollableViewportSize method return the dimensions of what you want displayed, while its getPreferredSize method would return the actual dimensions of the component:

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Scrollable;

@SuppressWarnings("serial")
public class DrawPanel extends JPanel implements Scrollable {
    public static final int VISIBLE_ROW_COUNT = 8;
    private static final int ROW_COUNT = 12;
    private static final Color DARK_COLOR = Color.DARK_GRAY;
    private static final Color LIGHT_COLOR = Color.WHITE;
    private int cellWidth;

    public DrawPanel(int cellWidth) {
        super(new GridLayout(ROW_COUNT, ROW_COUNT));
        this.cellWidth = cellWidth;
        Dimension prefSize = new Dimension(cellWidth, cellWidth);
        for (int i = 0; i < ROW_COUNT; i++) {
            for (int j = 0; j < ROW_COUNT; j++) {
                JPanel cell = new JPanel();
                cell.setPreferredSize(prefSize);
                Color c = i % 2 == j % 2 ? DARK_COLOR : LIGHT_COLOR;
                cell.setBackground(c);
                add(cell);

                // TODO: delete the code below. For demo/debug purposes only
                String text = String.format("[%d, %d]", j, i);
                JLabel label = new JLabel(text);
                c = c == DARK_COLOR ? LIGHT_COLOR : DARK_COLOR;
                label.setForeground(c);
                cell.add(label);
                // TODO: end delete block
            }
        }
    }

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        Dimension viewportSize = new Dimension(VISIBLE_ROW_COUNT * cellWidth, VISIBLE_ROW_COUNT * cellWidth);
        return viewportSize;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation,
            int direction) {
        return cellWidth;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
            int direction) {
        return 1;
    }

    // note that getPreferredSize already returns the size of the 12 x 12 grid
    // since it is composed of a grid sized JPanels

}
</code>```

You could then place this within your JScrollPane,

```<code>private static final int CELL_WIDTH = 80;
private DrawPanel drawPanel = new DrawPanel(CELL_WIDTH);
private JScrollPane drawPanelScrollPane = new JScrollPane(drawPanel);
</code>```

get rid of the scrollbars,

```<code>    drawPanelScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    drawPanelScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
</code>```

and scroll it to the spot where you want the upper left point:

```<code>    int x = 2 * CELL_WIDTH;
    int y = x;
    Point pt = new Point(x, y);
    drawPanelScrollPane.getViewport().setViewPosition(pt);
</code>```

The example GUI:

```<code>import java.awt.BorderLayout;
import java.awt.Point;

import javax.swing.*;

@SuppressWarnings("serial")
public class FrameAGrid extends JPanel {
    private static final int CELL_WIDTH = 80;
    private DrawPanel drawPanel = new DrawPanel(CELL_WIDTH);
    private JScrollPane drawPanelScrollPane = new JScrollPane(drawPanel);

    public FrameAGrid() {
        drawPanelScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        drawPanelScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        setLayout(new BorderLayout());
        add(drawPanelScrollPane);

        int x = 2 * CELL_WIDTH;
        int y = x;
        Point pt = new Point(x, y);
        drawPanelScrollPane.getViewport().setViewPosition(pt);
    }

    private static void createAndShowGui() {
        FrameAGrid mainPanel = new FrameAGrid();

        JFrame frame = new JFrame("FrameAGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

This displays as:

Note that the upper left hand corner is at 2, 2 not at 0, 0

Title: Put component inside the smaller one

Body:
I wanna get Frame(640x640) with DrawCanvas(960x960) inside like this:

So the part of DrawCanvas must be hidden and frame centered. What layout should I choose? Now I put DrawCanvas inside the frame like this:

    class extends JFrame {
        canvas = new DrawCanvas();
        canvas.setPreferredSize(new Dimension(960, 960));
        Container cp = getContentPane();
        cp.add(canvas);
        setPreferredSize(new Dimension(640, 640));
    }

Body:
Again as stated in your previous question, a way to do this is to embed the inner component within a JScrollPane, but rid the scrollpane of scrollbars.

For example, say you had a class called DrawPanel that extended JPanel and held a 12 x 12 grid of cells, but you only wanted to show 8 x 8 of them. You could have this class implement the Scrollable interface, have its getPreferredScrollableViewportSize method return the dimensions of what you want displayed, while its getPreferredSize method would return the actual dimensions of the component:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Scrollable;

@SuppressWarnings("serial")
public class DrawPanel extends JPanel implements Scrollable {
    public static final int VISIBLE_ROW_COUNT = 8;
    private static final int ROW_COUNT = 12;
    private static final Color DARK_COLOR = Color.DARK_GRAY;
    private static final Color LIGHT_COLOR = Color.WHITE;
    private int cellWidth;

    public DrawPanel(int cellWidth) {
        super(new GridLayout(ROW_COUNT, ROW_COUNT));
        this.cellWidth = cellWidth;
        Dimension prefSize = new Dimension(cellWidth, cellWidth);
        for (int i = 0; i < ROW_COUNT; i++) {
            for (int j = 0; j < ROW_COUNT; j++) {
                JPanel cell = new JPanel();
                cell.setPreferredSize(prefSize);
                Color c = i % 2 == j % 2 ? DARK_COLOR : LIGHT_COLOR;
                cell.setBackground(c);
                add(cell);

                // TODO: delete the code below. For demo/debug purposes only
                String text = String.format("[%d, %d]", j, i);
                JLabel label = new JLabel(text);
                c = c == DARK_COLOR ? LIGHT_COLOR : DARK_COLOR;
                label.setForeground(c);
                cell.add(label);
                // TODO: end delete block
            }
        }
    }

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        Dimension viewportSize = new Dimension(VISIBLE_ROW_COUNT * cellWidth, VISIBLE_ROW_COUNT * cellWidth);
        return viewportSize;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation,
            int direction) {
        return cellWidth;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
            int direction) {
        return 1;
    }

    // note that getPreferredSize already returns the size of the 12 x 12 grid
    // since it is composed of a grid sized JPanels

}

You could then place this within your JScrollPane,

private static final int CELL_WIDTH = 80;
private DrawPanel drawPanel = new DrawPanel(CELL_WIDTH);
private JScrollPane drawPanelScrollPane = new JScrollPane(drawPanel);

get rid of the scrollbars,

    drawPanelScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    drawPanelScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

and scroll it to the spot where you want the upper left point:

    int x = 2 * CELL_WIDTH;
    int y = x;
    Point pt = new Point(x, y);
    drawPanelScrollPane.getViewport().setViewPosition(pt);

The example GUI:

import java.awt.BorderLayout;
import java.awt.Point;

import javax.swing.*;

@SuppressWarnings("serial")
public class FrameAGrid extends JPanel {
    private static final int CELL_WIDTH = 80;
    private DrawPanel drawPanel = new DrawPanel(CELL_WIDTH);
    private JScrollPane drawPanelScrollPane = new JScrollPane(drawPanel);

    public FrameAGrid() {
        drawPanelScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        drawPanelScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        setLayout(new BorderLayout());
        add(drawPanelScrollPane);

        int x = 2 * CELL_WIDTH;
        int y = x;
        Point pt = new Point(x, y);
        drawPanelScrollPane.getViewport().setViewPosition(pt);
    }

    private static void createAndShowGui() {
        FrameAGrid mainPanel = new FrameAGrid();

        JFrame frame = new JFrame("FrameAGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

This displays as:

Note that the upper left hand corner is at 2, 2 not at 0, 0


问:
Can't register Mediatr automatically trough structuremap IoC
I have a web application with multilayer architecture and the classes of handlers and queries in the separate layer from a structuremap configuration. I tried to register all handlers and queries dynamically but I couldn't.When I try to run the application I receive the runtime error:

No default Instance is registered and cannot be automatically determined for type 'IRequestHandler'
There is no configuration specified for IRequestHandler

```<code>        public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.AssemblyContainingType<IMediator>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.With(new ControllerConvention());
            });
        //For<IExample>().Use<Example
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
        For<IMediator>().Use<Mediator>();
        For<IUnitOfWork>().Use<UnitOfWork>().LifecycleIs<TransientLifecycle>();
        For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(Business.Pipeline.MediatorPipeline<,>));
    }
</code>```

controller
var query = new GetUserQuery(id);var user = _mediator.Send(query);

query

```<code>    public class GetUserQuery : IRequest<User>
{
    public GetUserQuery() { }
    public GetUserQuery(int id)
    {
        Id = id;
    }

    public int Id { get; set; }
}
</code>```

handler

```<code> public class GetUserHandler : IRequestHandler<GetUserQuery, User>
{
    private readonly IUnitOfWork _uow;
    public GetUserHandler(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public User Handle(GetUserQuery message)
    {
        return _uow.UserRepository.Get(message.Id);
    }
}
</code>```

答:
You need to add something like

```<code>scan.AssemblyContainingType<GetUserHandler>();
</code>```

To your registry

Body:
I have a web application with multilayer architecture and the classes of handlers and queries in the separate layer from a structuremap configuration. I tried to register all handlers and queries dynamically but I couldn't.When I try to run the application I receive the runtime error:

No default Instance is registered and cannot be automatically determined for type 'IRequestHandler'
There is no configuration specified for IRequestHandler

        public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AssemblyContainingType<DefaultRegistry>();
                scan.AssemblyContainingType<IMediator>();
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
                scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
                scan.With(new ControllerConvention());
            });
        //For<IExample>().Use<Example
        For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
        For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
        For<IMediator>().Use<Mediator>();
        For<IUnitOfWork>().Use<UnitOfWork>().LifecycleIs<TransientLifecycle>();
        For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(Business.Pipeline.MediatorPipeline<,>));
    }

controller
var query = new GetUserQuery(id);var user = _mediator.Send(query);

query

    public class GetUserQuery : IRequest<User>
{
    public GetUserQuery() { }
    public GetUserQuery(int id)
    {
        Id = id;
    }

    public int Id { get; set; }
}

handler

 public class GetUserHandler : IRequestHandler<GetUserQuery, User>
{
    private readonly IUnitOfWork _uow;
    public GetUserHandler(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public User Handle(GetUserQuery message)
    {
        return _uow.UserRepository.Get(message.Id);
    }
}

Body:
You need to add something like

scan.AssemblyContainingType<GetUserHandler>();

To your registry


问:
How to change one array's values from another array?
```<code>String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];
</code>```

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

```<code>board[0]="X";
board[1]="X";
board[2]="O";
</code>```

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

```<code>for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}
</code>```

答:
As you want only one character as an element in your board array you can use character array instead of String array and then can use </p>

```<code>char board[] = new char[9];
board = sequence[0].toCharArray();
</code>```

Body:
String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

board[0]="X";
board[1]="X";
board[2]="O";

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}

Body:
As you want only one character as an element in your board array you can use character array instead of String array and then can use

char board[] = new char[9];
board = sequence[0].toCharArray();


问:
Add a Camera Preview
I want my Activity background to be the Camera(Back) view,I have so far tried to add a surfaceView but no luck,the tutorials I found were for opening the camera app.
P.S- I do want to add more resources over the SurfaceView/Camera.
&
I don't want to click a picture only the preview
As I do not have any code to show as they are not what I need,so here is the <img src="https://i.stack.imgur.com/Oji1X.png" alt="next best thing">  though it may have not been necessary. </p>

答:
have you tried something like this?</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent" android:layout_height="match_parent">

      <SurfaceView
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

   <!--views on top should come after the surfaceview,
   at the same level    in the view heirarchy.
   this gives them a higher z-index (i.e. drawn afterwards)
   ... you could also use a RelativeLayout as the root view -->

      <ImageView
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:layout_gravity="center"/>

 </FrameLayout>
</code>```

Title: Add a Camera Preview

Body:
I want my Activity background to be the Camera(Back) view,I have so far tried to add a surfaceView but no luck,the tutorials I found were for opening the camera app.
P.S- I do want to add more resources over the SurfaceView/Camera.
&
I don't want to click a picture only the preview
As I do not have any code to show as they are not what I need,so here is the   though it may have not been necessary.

Body:
have you tried something like this?

 <?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent" android:layout_height="match_parent">

      <SurfaceView
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

   <!--views on top should come after the surfaceview,
   at the same level    in the view heirarchy.
   this gives them a higher z-index (i.e. drawn afterwards)
   ... you could also use a RelativeLayout as the root view -->

      <ImageView
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:layout_gravity="center"/>

 </FrameLayout>


问:
How to replace character at even position by ( and odd position by )
Is it possible to write down a regular expression such that the first $ sign will be replaced by a (, the second with a ), the third with a (, etc ?

For instance, the string

```<code>This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.
</code>```

should become

```<code>This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).
</code>```

答:
In JavaScript:</p>

```<code>function replace$(str) {
  let first = false;
  return str.replace(/\$/, _ => (first = !first) ? '(' : ')');
}
</code>```

Body:
Is it possible to write down a regular expression such that the first $ sign will be replaced by a (, the second with a ), the third with a (, etc ?

For instance, the string

This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.

should become

This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).

Body:
In JavaScript:

function replace$(str) {
  let first = false;
  return str.replace(/\$/, _ => (first = !first) ? '(' : ')');
}


问:
show the values of string variables in a string array
I created an array of strings and I want to get the value of a given string at a given position, but the returned value is the character and not the string, eg:

```<code>myArray = ['string1' 'string2' 'string3'];
s = myArray(1); //returns the character at the position 1, instead of the string
</code>```

How can I get the value of these strings based on a given position i ?

答:
You can do a for loop if this is what you are asking for.

```<code>myArray=['b' 'c' 'd']
for i =1:lenght(myArray)
s(i)=myArray(i);

end
</code>```

Not sure what you are asking for exactly.

Body:
I created an array of strings and I want to get the value of a given string at a given position, but the returned value is the character and not the string, eg:

myArray = ['string1' 'string2' 'string3'];
s = myArray(1); //returns the character at the position 1, instead of the string

How can I get the value of these strings based on a given position i ?

Body:
You can do a for loop if this is what you are asking for.

myArray=['b' 'c' 'd']
for i =1:lenght(myArray)
s(i)=myArray(i);

end

Not sure what you are asking for exactly.


问:
How to convert Address from user input into LatLng Xamarin.Android
I am trying to convert a users input in Edit text to LatLng when the Search button is clicked. This will then update the camera and move tot hat position.
Here is my code in the main:

```<code>using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;

namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private GoogleMap mMap;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        SetUpMap();
    }
    private void SetUpMap()
    {
        if (mMap == null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        }
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

    }
    // Button to Search for Address//
    public void onMapSearch(View view)
    {
        EditText address = (EditText)FindViewById(Resource.Id.searchText);
         var addressnew = address.Text;
        if (addressnew != null)
        {
            addressnew = address.Text;
        }
        Geocoder geoCoder = new Geocoder(this);
        IList<Address> coordinates = geoCoder.GetFromLocationName(addressnew, 0);
        Address gotAddress = coordinates.FirstOrDefault();
        LatLng latLng = new LatLng(gotAddress.Latitude, gotAddress.Longitude);
        CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
        builder.Target(latLng);
        builder.Zoom(10);
        CameraPosition cameraPosition = builder.Build();
        CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);

    }
}
}
</code>```

When I use this right now, I get an exception error. Please HELP!!!

答:
First you need to check if the Geocoder service is available on the device/emulator via the static method:

```<code>Geocoder.isPresent
</code>```

Note: The use of Geocoder requires Internet access and Google Play services to be installed...

Next you are requesting zero results in the "maxResults" parameter:

```<code>GetFromLocationName(addressnew, 0);
</code>```

int: max number of results to return. Smaller numbers (1 to 5) are recommended

Also you might need to retry the request to obtain results. You should not hammer the service as you will get throttled. Use a retry delay that  increasing after each attempt.

Example:

```<code>if (!Geocoder.IsPresent)
{
    Log.Error("SO", "Geocoder is not present");
}
else
{
    var geocoder = new Geocoder(this);
    var retry = 0;
    do
    {
        var addressList = await geocoder.GetFromLocationNameAsync("Starbucks 523 Pine Street, Seattle, WA, 98101", 5);
        if (addressList.Count > 0)
        {
            foreach (var address in addressList)
            {
                Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
            }
            break;
        }
        retry++;
        Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
        await Task.Delay(retry * 1000);
    } while (retry < 5);
}
</code>```

Output:

```<code>[SO] 47.611423:-122.337519 - Starbucks : Starbucks : 400 Pine Street
[SO] 47.611848:-122.335693 - Starbucks : Starbucks : 515 Pine Street
</code>```

Body:
I am trying to convert a users input in Edit text to LatLng when the Search button is clicked. This will then update the camera and move tot hat position.
Here is my code in the main:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;

namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private GoogleMap mMap;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        SetUpMap();
    }
    private void SetUpMap()
    {
        if (mMap == null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
        }
    }

    public void OnMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

    }
    // Button to Search for Address//
    public void onMapSearch(View view)
    {
        EditText address = (EditText)FindViewById(Resource.Id.searchText);
         var addressnew = address.Text;
        if (addressnew != null)
        {
            addressnew = address.Text;
        }
        Geocoder geoCoder = new Geocoder(this);
        IList<Address> coordinates = geoCoder.GetFromLocationName(addressnew, 0);
        Address gotAddress = coordinates.FirstOrDefault();
        LatLng latLng = new LatLng(gotAddress.Latitude, gotAddress.Longitude);
        CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
        builder.Target(latLng);
        builder.Zoom(10);
        CameraPosition cameraPosition = builder.Build();
        CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);

    }
}
}

When I use this right now, I get an exception error. Please HELP!!!

Body:
First you need to check if the Geocoder service is available on the device/emulator via the static method:

Geocoder.isPresent

Note: The use of Geocoder requires Internet access and Google Play services to be installed...

Next you are requesting zero results in the "maxResults" parameter:

GetFromLocationName(addressnew, 0);

int: max number of results to return. Smaller numbers (1 to 5) are recommended

Also you might need to retry the request to obtain results. You should not hammer the service as you will get throttled. Use a retry delay that  increasing after each attempt.

Example:

if (!Geocoder.IsPresent)
{
    Log.Error("SO", "Geocoder is not present");
}
else
{
    var geocoder = new Geocoder(this);
    var retry = 0;
    do
    {
        var addressList = await geocoder.GetFromLocationNameAsync("Starbucks 523 Pine Street, Seattle, WA, 98101", 5);
        if (addressList.Count > 0)
        {
            foreach (var address in addressList)
            {
                Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
            }
            break;
        }
        retry++;
        Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
        await Task.Delay(retry * 1000);
    } while (retry < 5);
}

Output:

[SO] 47.611423:-122.337519 - Starbucks : Starbucks : 400 Pine Street
[SO] 47.611848:-122.335693 - Starbucks : Starbucks : 515 Pine Street


问:
#including <alsa/asoundlib.h> and <sys/time.h> results in multiple definition conflict
Here is the minimal C program to reproduce:

```<code>#include <alsa/asoundlib.h>
#include <sys/time.h>

int main( void )
{
}
</code>```

This will compile with gcc -c -o timealsa.o timealsa.c, but if you include the -std=c99 switch, you get a redefinition error:

```<code>In file included from /usr/include/sys/time.h:28:0,
                 from timealsa.c:3:
/usr/include/bits/time.h:30:8: error: redefinition of ‘struct timeval’
 struct timeval
        ^
In file included from /usr/include/alsa/asoundlib.h:49:0,
                 from timealsa.c:2:
/usr/include/alsa/global.h:138:8: note: originally defined here
 struct timeval {
        ^
</code>```

How can I resolve this conflict while still using -std=c99?

答:
With C99 and later you can't have duplicate definitions of the same struct. The problem is that alsa/asoundlib.h includes alsa/global.h which contains this code:

```<code>/* for timeval and timespec */
#include <time.h>

...

#ifdef __GLIBC__
#if !defined(_POSIX_C_SOURCE) && !defined(_POSIX_SOURCE)
struct timeval {
        time_t          tv_sec;         /* seconds */
        long            tv_usec;        /* microseconds */
};

struct timespec {
        time_t          tv_sec;         /* seconds */
        long            tv_nsec;        /* nanoseconds */
};
#endif
#endif
</code>```

So the Michael Petch's solution won't work - by the time you've included alsa/asoundlib.h it is already too late. The proper solution is to define _POSIX_C_SOURCE (_POSIX_SOURCE is obsolete). There's more information about these macros here and here.

For example you could try -D_POSIX_C_SOURCE=200809L. However, if you do that you'll get errors like this:

```<code>/usr/include/arm-linux-gnueabihf/sys/time.h:110:20: error: field ‘it_interval’ has incomplete type
     struct timeval it_interval;
                    ^
/usr/include/arm-linux-gnueabihf/sys/time.h:112:20: error: field ‘it_value’ has incomplete type
     struct timeval it_value;
                    ^
/usr/include/arm-linux-gnueabihf/sys/time.h:138:61: error: array type has incomplete element type
 extern int utimes (const char *__file, const struct timeval __tvp[2])
                                                             ^
</code>```

This is all a big mess of old C code and macro madness. The only way I got it to work was to give up and use -std=gnu11.

Body:
Here is the minimal C program to reproduce:

#include <alsa/asoundlib.h>
#include <sys/time.h>

int main( void )
{
}

This will compile with gcc -c -o timealsa.o timealsa.c, but if you include the -std=c99 switch, you get a redefinition error:

In file included from /usr/include/sys/time.h:28:0,
                 from timealsa.c:3:
/usr/include/bits/time.h:30:8: error: redefinition of ‘struct timeval’
 struct timeval
        ^
In file included from /usr/include/alsa/asoundlib.h:49:0,
                 from timealsa.c:2:
/usr/include/alsa/global.h:138:8: note: originally defined here
 struct timeval {
        ^

How can I resolve this conflict while still using -std=c99?

Body:
With C99 and later you can't have duplicate definitions of the same struct. The problem is that alsa/asoundlib.h includes alsa/global.h which contains this code:

/* for timeval and timespec */
#include <time.h>

...

#ifdef __GLIBC__
#if !defined(_POSIX_C_SOURCE) && !defined(_POSIX_SOURCE)
struct timeval {
        time_t          tv_sec;         /* seconds */
        long            tv_usec;        /* microseconds */
};

struct timespec {
        time_t          tv_sec;         /* seconds */
        long            tv_nsec;        /* nanoseconds */
};
#endif
#endif

So the Michael Petch's solution won't work - by the time you've included alsa/asoundlib.h it is already too late. The proper solution is to define _POSIX_C_SOURCE (_POSIX_SOURCE is obsolete). There's more information about these macros here and here.

For example you could try -D_POSIX_C_SOURCE=200809L. However, if you do that you'll get errors like this:

/usr/include/arm-linux-gnueabihf/sys/time.h:110:20: error: field ‘it_interval’ has incomplete type
     struct timeval it_interval;
                    ^
/usr/include/arm-linux-gnueabihf/sys/time.h:112:20: error: field ‘it_value’ has incomplete type
     struct timeval it_value;
                    ^
/usr/include/arm-linux-gnueabihf/sys/time.h:138:61: error: array type has incomplete element type
 extern int utimes (const char *__file, const struct timeval __tvp[2])
                                                             ^

This is all a big mess of old C code and macro madness. The only way I got it to work was to give up and use -std=gnu11.


问:
Add all Glyphicons to Bootstrap 3
I'm diggin' the Glyphicons in Bootstrap 3, but it looks like they're not all there! I'd really like to use the building icon, but Googling hasn't turned up much of anything.

Does anyone know how to add the missing Glyphicons to Bootstrap 3?

答:
I have  purchased the full Gylphicons set from http://glyphicons.com/ and wanted to use all the icons available. If you are using less you may have to do something different I dont know.

What I have done and worked for me after trying various things posted from this thread and others on the stackexchange network is the following:

(1) Backed up my original bootstrap.css file (I have modified mine, plus good idea)

(2) Copied all the glyphicons-regular font files from /web/html_css/fonts directory to the fonts directory where my bootstrap font files are located

(3) Starting on line 263ish of bootstrap.css make the change to reflect like below: (yours might be slightly different)

```<code>@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-regular.eot');
  src: url('../fonts/glyphicons-regular.eot?#iefix')
  format('embedded-opentype'), url('../fonts/glyphicons-regular.woff')
  format('woff'), url('../fonts/glyphicons-regular.ttf')
  format('truetype'), url('../fonts/glyphicons-regular.svg#glyphiconsregular') format('svg');
}
</code>```

They url's should be pointed at the new font files.

(4) If you want all of the glyphs like I did then open up the file in the /web/html_css/css/ directory labeled glyphicons.css and copy all the css for the glyhicons except the part with @font-face{} and the .glyphicon{}
and paste into empty text document.

(5) You will need to do a search and replace (I did anyway) for .glyphicons, mind the (s) at the end and replace with .glyphicon no (s) on the end

(6) Next open up the bootstrap.css file and comment out or remove all the other .glyphicon-whatever styles and paste in your new styles.

(7) You may need to remove the line from the very bottom of the file which point to the bootstrap.css.map file. I didn't have to but you may need to.

(8) Happy Glyphing!

NOTE You should be setup to use all the glyhpicons now. Just keep in mind that some of the names of the glyphicons are different then in the original bootstrap file.

I created a repository for the modified css file: https://github.com/snowballrandom/bootstrap

Title: Add all Glyphicons to Bootstrap 3

Body:
I have  purchased the full Gylphicons set from http://glyphicons.com/ and wanted to use all the icons available. If you are using less you may have to do something different I dont know.

What I have done and worked for me after trying various things posted from this thread and others on the stackexchange network is the following:

(1) Backed up my original bootstrap.css file (I have modified mine, plus good idea)

(2) Copied all the glyphicons-regular font files from /web/html_css/fonts directory to the fonts directory where my bootstrap font files are located

(3) Starting on line 263ish of bootstrap.css make the change to reflect like below: (yours might be slightly different)

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-regular.eot');
  src: url('../fonts/glyphicons-regular.eot?#iefix')
  format('embedded-opentype'), url('../fonts/glyphicons-regular.woff')
  format('woff'), url('../fonts/glyphicons-regular.ttf')
  format('truetype'), url('../fonts/glyphicons-regular.svg#glyphiconsregular') format('svg');
}

They url's should be pointed at the new font files.

(4) If you want all of the glyphs like I did then open up the file in the /web/html_css/css/ directory labeled glyphicons.css and copy all the css for the glyhicons except the part with @font-face{} and the .glyphicon{}
and paste into empty text document.

(5) You will need to do a search and replace (I did anyway) for .glyphicons, mind the (s) at the end and replace with .glyphicon no (s) on the end

(6) Next open up the bootstrap.css file and comment out or remove all the other .glyphicon-whatever styles and paste in your new styles.

(7) You may need to remove the line from the very bottom of the file which point to the bootstrap.css.map file. I didn't have to but you may need to.

(8) Happy Glyphing!

NOTE You should be setup to use all the glyhpicons now. Just keep in mind that some of the names of the glyphicons are different then in the original bootstrap file.

I created a repository for the modified css file: https://github.com/snowballrandom/bootstrap


问:
Broken Rails Routes after implementing Single Table Inheritance
I have implemented single table inheritance for a person class

```<code>class Person < ActiveRecord::Base

end

class Teacher < Person

end

class Student < Person

end

class Outsider < Person

end
</code>```

And the create person seems to work creating Teacher, Student or Person according to the what is chosen in the form.select and the type attribute is added.

However, I seem to have broken the routes

<%= link_to 'Edit', edit_person_path(@deal) %> |
<%= link_to 'Back', persons_path %>

They seem to point to teacher_path, student_path and outsider_path instead of person_path.

What changes need to be made in the routes?

答:
From my experience, it's better to use a single controller for all the STI models. If you're keeping your controllers DRY, you shouldn't need to have unique controller logic for each child class. Keep all that in the models.

```<code>resources :people
</code>```

Your named routes will be like:

```<code>people_path
new_person
edit_person
person
etc...
</code>```

Then you can use the same controller/views to manage these models. If you decide later to add new Person STI models, you won't have to make any significant updates to your code.

Body:
I have implemented single table inheritance for a person class

class Person < ActiveRecord::Base

end

class Teacher < Person

end

class Student < Person

end

class Outsider < Person

end

And the create person seems to work creating Teacher, Student or Person according to the what is chosen in the form.select and the type attribute is added.

However, I seem to have broken the routes

<%= link_to 'Edit', edit_person_path(@deal) %> |
<%= link_to 'Back', persons_path %>

They seem to point to teacher_path, student_path and outsider_path instead of person_path.

What changes need to be made in the routes?

Body:
From my experience, it's better to use a single controller for all the STI models. If you're keeping your controllers DRY, you shouldn't need to have unique controller logic for each child class. Keep all that in the models.

resources :people

Your named routes will be like:

people_path
new_person
edit_person
person
etc...

Then you can use the same controller/views to manage these models. If you decide later to add new Person STI models, you won't have to make any significant updates to your code.


问:
sbt fetches the ivy*.xml files and the jars dependencies but not the jar itself
I have mentioned a jar(belonging to my org's artifactory) in my build.sbt file

```<code>lazy val core =
  module("core", deps = Seq(
    "io.swagger" % "swagger-annotations" % "1.5.8"
  )).settings(
      libraryDependencies ++= Seq(
        "com.quantcast" % "quantserve_shared" % "latest.integration"
      ))
</code>```

When i compile the code, i see these files getting downloaded in my ~/.ivy2 directory but not the jars folder or any jar.

```<code>ls ./cache/com.quantcast/quantserve_shared/
ivy-3.5.3132.xml                        ivy-3.5.3132.xml.original               ivydata-3.5.3132.properties             ivydata-latest.integration.properties
</code>```

I checked my resolution-cache/reports/audience-link-core-audience-link-core_2.11-compile-internal.xml  file and see this :

```<code><module organisation="com.quantcast" name="quantserve_shared">
            <revision name="3.5.3132" status="release" pubdate="20170315145341" resolver="sbt-chain" artresolver="sbt-chain" downloaded="false" searched="true" default="false" conf="compile, default(compile)" position="74">
                <metadata-artifact status="no" details="" size="7161" time="0" location="/Users/pkhurana/.ivy2/cache/com.quantcast/quantserve_shared/ivy-3.5.3132.xml" searched="true" origin-is-local="false" origin-location="http://<My org artifactory>/libs-bmr-releases-local/com/quantcast/quantserve_shared/3.5.3132/ivy-3.5.3132.xml"/>
                <caller organisation="audience-link-core" name="audience-link-core_2.11" conf="compile-internal, compile, provided, optional" rev="latest.integration" rev-constraint-default="latest.integration" rev-constraint-dynamic="latest.integration" callerrev="0.9999999.17.76.111418"/>
                <artifacts>
                </artifacts>
            </revision>
        </module>
</code>```

So nothing comes in artifactory tag, but i do see other jars which are dependencies of quantserve_shared jar gets downloaded and their entry in the resolution cache also fine.

```<code><module organisation="com.twitter.util-core" name="util-core">
            <revision name="1.12.13" status="release" pubdate="20131024042503" resolver="sbt-chain" artresolver="sbt-chain" homepage="" downloaded="false" searched="false" default="false" conf="default, compile, runtime, master" position="127">
                <metadata-artifact status="no" details="" size="2240" time="0" location="/Users/pkhurana/.ivy2/cache/com.twitter.util-core/util-core/ivy-1.12.13.xml" searched="false" origin-is-local="true" origin-location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/ivy-1.12.13.xml"/>
                <caller organisation="com.quantcast" name="quantserve_shared" conf="compile" rev="1.12.13" rev-constraint-default="1.12.13" rev-constraint-dynamic="1.12.13" callerrev="3.5.3132"/>
                <artifacts>
                    <artifact name="util-core" type="jar" ext="jar" status="no" details="" size="632306" time="0" location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/jars/util-core-1.12.13.jar">
                        <origin-location is-local="true" location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/jars/util-core-1.12.13.jar"/>
                    </artifact>
                </artifacts>
            </revision>
        </module>
</code>```

答:
This happened because the dependency jar did not have the configuration 'compile' specified in its ivy file. It has 'master' specified with visibility public. Now sbt tries to find 'compile' by default but fails.
This got solved by changing it to

"com.quantcast" % "quantserve_shared" % "3.5.3166" % "compile->master"

Body:
I have mentioned a jar(belonging to my org's artifactory) in my build.sbt file

lazy val core =
  module("core", deps = Seq(
    "io.swagger" % "swagger-annotations" % "1.5.8"
  )).settings(
      libraryDependencies ++= Seq(
        "com.quantcast" % "quantserve_shared" % "latest.integration"
      ))

When i compile the code, i see these files getting downloaded in my ~/.ivy2 directory but not the jars folder or any jar.

ls ./cache/com.quantcast/quantserve_shared/
ivy-3.5.3132.xml                        ivy-3.5.3132.xml.original               ivydata-3.5.3132.properties             ivydata-latest.integration.properties

I checked my resolution-cache/reports/audience-link-core-audience-link-core_2.11-compile-internal.xml  file and see this :

<module organisation="com.quantcast" name="quantserve_shared">
            <revision name="3.5.3132" status="release" pubdate="20170315145341" resolver="sbt-chain" artresolver="sbt-chain" downloaded="false" searched="true" default="false" conf="compile, default(compile)" position="74">
                <metadata-artifact status="no" details="" size="7161" time="0" location="/Users/pkhurana/.ivy2/cache/com.quantcast/quantserve_shared/ivy-3.5.3132.xml" searched="true" origin-is-local="false" origin-location="http://<My org artifactory>/libs-bmr-releases-local/com/quantcast/quantserve_shared/3.5.3132/ivy-3.5.3132.xml"/>
                <caller organisation="audience-link-core" name="audience-link-core_2.11" conf="compile-internal, compile, provided, optional" rev="latest.integration" rev-constraint-default="latest.integration" rev-constraint-dynamic="latest.integration" callerrev="0.9999999.17.76.111418"/>
                <artifacts>
                </artifacts>
            </revision>
        </module>

So nothing comes in artifactory tag, but i do see other jars which are dependencies of quantserve_shared jar gets downloaded and their entry in the resolution cache also fine.

<module organisation="com.twitter.util-core" name="util-core">
            <revision name="1.12.13" status="release" pubdate="20131024042503" resolver="sbt-chain" artresolver="sbt-chain" homepage="" downloaded="false" searched="false" default="false" conf="default, compile, runtime, master" position="127">
                <metadata-artifact status="no" details="" size="2240" time="0" location="/Users/pkhurana/.ivy2/cache/com.twitter.util-core/util-core/ivy-1.12.13.xml" searched="false" origin-is-local="true" origin-location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/ivy-1.12.13.xml"/>
                <caller organisation="com.quantcast" name="quantserve_shared" conf="compile" rev="1.12.13" rev-constraint-default="1.12.13" rev-constraint-dynamic="1.12.13" callerrev="3.5.3132"/>
                <artifacts>
                    <artifact name="util-core" type="jar" ext="jar" status="no" details="" size="632306" time="0" location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/jars/util-core-1.12.13.jar">
                        <origin-location is-local="true" location="/Users/pkhurana/.ivy2/quantcast-bmr/com.twitter.util-core/util-core/jars/util-core-1.12.13.jar"/>
                    </artifact>
                </artifacts>
            </revision>
        </module>


问:
Given a dictionary and a list of letters find all valid words that can be built with the letters
The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the complexity. I can think of building a tree out of the dictionary but still checking all letters permutations is O(n!). Are there better ways to solve this problem?

Letters can have duplicates.

The api for the function looks like this:

```<code>List<String> findValidWords(Dict dict, char letters[])
</code>```

答:
If letters can be repeated, that means that a word can be infinitely long. You would obviously cap this at the length of the longest word in the dictionary, but there are still too many words to check. Like nmore suggested, you'd rather iterate over the dictionary to do this.</p>

```<code>List<String> findAllValidWords(Set<String> dict, char[] letters) {
  List<String> result = new LinkedList<>();
  Set<Character> charSet = new HashSet<>();
  for (char letter : letters) {
    charSet.add(letter);
  }
  for (String word : dict) {
    if (isPossible(word, charSet)) {
      result.add(word);
    }
  }
  return result;
}

boolean isPossible(String word, Set<Character> charSet) {
  // A word is possible if all its letters are contained in the given letter set
  for (int i = 0; i < word.length(); i++) {
    if (!charSet.contains(word.charAt(i))) {
      return false;
    }
  }
  return true;
}
</code>```

Body:
The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the complexity. I can think of building a tree out of the dictionary but still checking all letters permutations is O(n!). Are there better ways to solve this problem?

Letters can have duplicates.

The api for the function looks like this:

List<String> findValidWords(Dict dict, char letters[])

Body:
If letters can be repeated, that means that a word can be infinitely long. You would obviously cap this at the length of the longest word in the dictionary, but there are still too many words to check. Like nmore suggested, you'd rather iterate over the dictionary to do this.

List<String> findAllValidWords(Set<String> dict, char[] letters) {
  List<String> result = new LinkedList<>();
  Set<Character> charSet = new HashSet<>();
  for (char letter : letters) {
    charSet.add(letter);
  }
  for (String word : dict) {
    if (isPossible(word, charSet)) {
      result.add(word);
    }
  }
  return result;
}

boolean isPossible(String word, Set<Character> charSet) {
  // A word is possible if all its letters are contained in the given letter set
  for (int i = 0; i < word.length(); i++) {
    if (!charSet.contains(word.charAt(i))) {
      return false;
    }
  }
  return true;
}


问:
Wget Download for Multiple Domains and Files
I need to download a list of files from each of the domains listed in another file. I've tried many times but I still failed.

The example list files to download (e.g., file.txt):

```<code>1.jpg
2.jpg
3.jpeg
4.bmp
5.gif
</code>```

The example list of domains (e.g., url.lst):

```<code>google.com
google.co.in
google.com.br
</code>```

The script:

```<code>#!/bin/bash
# Create an array files that contains list of filenames

urls=`cat "url.lst"`
files=`cat "file.txt"`

   for ((file in "${files[@]}" && url in "${urls[@]}"));   do
        wget "${url}${file}"
   done
</code>```

I want to get it so it generates and runs the following commands:

```<code>wget google.com/1.jpg
wget google.com/2.jpg
wget google.com/3.jpeg
wget google.com/4.bmp
wget google.com/5.gif
wget google.co.in/1.jpg
wget google.co.in/2.jpg
wget google.co.in/3.jpeg
wget google.co.in/4.bmp
wget google.co.in/5.gif
wget google.com.br/1.jpg
wget google.com.br/2.jpg
wget google.com.br/3.jpeg
wget google.com.br/4.bmp
wget google.com.br/5.gif
</code>```

答:
You have a few things going on here.  First, your reading the variables isn't creating arrays.  You're getting a string that will be subject to word splitting and globbing and the like.  Second, you will need to do the two file loops separately instead of trying to do it in a single command.

To fix the first part, I'd suggest using readarray or mapfile, for the second, use nested loops like:

```<code>readarray -t urls < url.lst
readarray -t files < file.txt

for dom in "${urls[@]}"; do
    for path in "${files[@]}"; do
        wget "$dom/$path"
    done
done
</code>```

or you could replace the outer for loop with a while loop and skip one of the readarrays like

```<code>readarray -t files < file.txt

while read -r url; do
    for path in "${files[@]}"; do
        wget "$url/$path"
    done
done < url.lst
</code>```

Body:
I need to download a list of files from each of the domains listed in another file. I've tried many times but I still failed.

The example list files to download (e.g., file.txt):

1.jpg
2.jpg
3.jpeg
4.bmp
5.gif

The example list of domains (e.g., url.lst):

google.com
google.co.in
google.com.br

The script:

#!/bin/bash
# Create an array files that contains list of filenames

urls=`cat "url.lst"`
files=`cat "file.txt"`

   for ((file in "${files[@]}" && url in "${urls[@]}"));   do
        wget "${url}${file}"
   done

I want to get it so it generates and runs the following commands:

wget google.com/1.jpg
wget google.com/2.jpg
wget google.com/3.jpeg
wget google.com/4.bmp
wget google.com/5.gif
wget google.co.in/1.jpg
wget google.co.in/2.jpg
wget google.co.in/3.jpeg
wget google.co.in/4.bmp
wget google.co.in/5.gif
wget google.com.br/1.jpg
wget google.com.br/2.jpg
wget google.com.br/3.jpeg
wget google.com.br/4.bmp
wget google.com.br/5.gif

Body:
You have a few things going on here.  First, your reading the variables isn't creating arrays.  You're getting a string that will be subject to word splitting and globbing and the like.  Second, you will need to do the two file loops separately instead of trying to do it in a single command.

To fix the first part, I'd suggest using readarray or mapfile, for the second, use nested loops like:

readarray -t urls < url.lst
readarray -t files < file.txt

for dom in "${urls[@]}"; do
    for path in "${files[@]}"; do
        wget "$dom/$path"
    done
done

or you could replace the outer for loop with a while loop and skip one of the readarrays like

readarray -t files < file.txt

while read -r url; do
    for path in "${files[@]}"; do
        wget "$url/$path"
    done
done < url.lst


问:
how do you properly call AWS Api Gateway from node?
I'm trying to call AWS api gateway from NodeJS, using aws-api-gateway-client module.

Here is my code:

```<code>module.exports = function(app) {

    var apigClientFactory = require('aws-api-gateway-client').default;

    var querystring = require('querystring');

    var apigClient = apigClientFactory.newClient({
        apiKey: '1234'
    });

    var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        userId: '1234'
    };
    var additionalParams = {};

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {
        console.log("name: " + req.body["customer_name"]);

        var body = {"async": true,
            "crossDomain": true,
            "url": "https://mystuff.execute-api.us-west-2.amazonaws.com/staging/api",
            "method": "POST",
            "headers": {
            "cache-control": "no-cache"
        },
        "data": querystring.stringify(req.body["customer_name"])
    };

        apigClient.invokeApi(params, body, additionalParams)
            .then(function(result){
                // Add success callback code here.
            }).catch( function(result){
            // Add error callback code here.
        });
    });

};
</code>```

As soon as I start the node server, I get this error:

```<code>/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84
  var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
                                                        ^

TypeError: Cannot read property '1' of null
    at Object.apigClientFactory.newClient (/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84:57)
    at module.exports (/Users/eugene/Desktop/dms/app/routes.js:7:40)
    at Object.<anonymous> (/Users/eugene/Desktop/dms/server.js:26:24)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.runMain [as _onTimeout] (module.js:441:10)
    at Timer.listOnTimeout (timers.js:92:15)
</code>```

What is the proper way to call AWS Api Gateway from Node?

答:
When you are calling 'newClient' method of gateway client factory in your code:

```<code>var apigClient = apigClientFactory.newClient({
    apiKey: '1234'
});
</code>```

It expects a key 'invokeUrl' in the configuration object. So you need to pass this key with your specified URL as value of this key. For example: you should try this -

```<code>var apigClient = apigClientFactory.newClient({
    apiKey: '1234',
    invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'
});
</code>```

Hope, it may help you to resolve this issue.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to call AWS api gateway from NodeJS, using aws-api-gateway-client module.

Here is my code:

module.exports = function(app) {

    var apigClientFactory = require('aws-api-gateway-client').default;

    var querystring = require('querystring');

    var apigClient = apigClientFactory.newClient({
        apiKey: '1234'
    });

    var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        userId: '1234'
    };
    var additionalParams = {};

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {
        console.log("name: " + req.body["customer_name"]);

        var body = {"async": true,
            "crossDomain": true,
            "url": "https://mystuff.execute-api.us-west-2.amazonaws.com/staging/api",
            "method": "POST",
            "headers": {
            "cache-control": "no-cache"
        },
        "data": querystring.stringify(req.body["customer_name"])
    };

        apigClient.invokeApi(params, body, additionalParams)
            .then(function(result){
                // Add success callback code here.
            }).catch( function(result){
            // Add error callback code here.
        });
    });

};

As soon as I start the node server, I get this error:

/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84
  var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
                                                        ^

TypeError: Cannot read property '1' of null
    at Object.apigClientFactory.newClient (/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84:57)
    at module.exports (/Users/eugene/Desktop/dms/app/routes.js:7:40)
    at Object.<anonymous> (/Users/eugene/Desktop/dms/server.js:26:24)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.runMain [as _onTimeout] (module.js:441:10)
    at Timer.listOnTimeout (timers.js:92:15)

What is the proper way to call AWS Api Gateway from Node?

Body:
When you are calling 'newClient' method of gateway client factory in your code:

var apigClient = apigClientFactory.newClient({
    apiKey: '1234'
});

It expects a key 'invokeUrl' in the configuration object. So you need to pass this key with your specified URL as value of this key. For example: you should try this -

var apigClient = apigClientFactory.newClient({
    apiKey: '1234',
    invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'
});

Hope, it may help you to resolve this issue.


问:
Returning a value from another thread. Without blocking main thread
Hello i am generally new to java and working on Minecraft Plugins to get started.

Here is my problem. I am trying to call this method on the main server thread and get the return value.

Here is what i am trying to achieve.

```<code> private String FetchEntry(String TableName, String KeyID, String ColumnName) {

    String value = "NOTHING";

        Bukkit.getServer().getScheduler().scheduleAsyncDelayedTask(LGCore.plugin, new Runnable() {
        @Override
        public void run() {

            try {
                ResultSet resultSet;
                resultSet = GetConnection().createStatement().executeQuery("SELECT " + ColumnName + " FROM " + TableName + " WHERE IdKey='" + KeyID + "';");
                resultSet.first();
                String returnvalue = resultSet.getString(1);
                //Here i would like to set value to returnvalue and return it

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    return value;

}
</code>```

答:
You seem to be calling a method that schedules an asynchronous task.
But an asynchronous task directly returning a value without blocking is sort of like an oxymoron: If it would directly return a value, it would be a synchronous operation.
The idea of asynchronous operations is that you run the operation to retrieve the result later when it's ready, but your main thread continues to run.
So you need to store the result of your asynchronous task in a place that's accessible by your main thread when it's ready.

I'm not familiar with the Minecraft code base, but I hope this helps anyway.

Body:
Hello i am generally new to java and working on Minecraft Plugins to get started.

Here is my problem. I am trying to call this method on the main server thread and get the return value.

Here is what i am trying to achieve.

 private String FetchEntry(String TableName, String KeyID, String ColumnName) {

    String value = "NOTHING";

        Bukkit.getServer().getScheduler().scheduleAsyncDelayedTask(LGCore.plugin, new Runnable() {
        @Override
        public void run() {

            try {
                ResultSet resultSet;
                resultSet = GetConnection().createStatement().executeQuery("SELECT " + ColumnName + " FROM " + TableName + " WHERE IdKey='" + KeyID + "';");
                resultSet.first();
                String returnvalue = resultSet.getString(1);
                //Here i would like to set value to returnvalue and return it

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    return value;

}


问:
Is There Any Way To Call a function is in a function individually outside - jQuery
I don't know my question is right or not. But I need to do if it possible.
Here is my function

```<code>function parentfunction(){

var child1 = function() {
  alert('abc');
}

var child2 = function() {
  alert('def');
}

child1();
child2();
return false;
}
</code>```

When I Call  parentfunction(). I got two alerts. abc and def.
But Now I need to call child1() function individually outside parentfunction. But I can't pass any arguments to the functions like parentfunction(argument) also No edits to functions.

When I Tried to call child1 out I got an error in console like.

VM69:1 Uncaught ReferenceError: child1 is not defined
      at :1:1

Is there any way to call those function outside.
Any help will be appreciated.

Thank You.

答:
you can use argument to define the function you want to return

function parentfunction(func_num = null){
  var child1 = function() {
    alert('abc');
  }
  var child2 = function() {
    alert('def');
  }

  return (func_num !== null)?((func_num == 1)? child1() : child2()): child1()+child2() ;
}
parentfunction(); // main function
parentfunction(1); // for child1
//parentfunction(2); // for child2```

Body:
I don't know my question is right or not. But I need to do if it possible.
Here is my function

function parentfunction(){

var child1 = function() {
  alert('abc');
}

var child2 = function() {
  alert('def');
}

child1();
child2();
return false;
}

When I Call  parentfunction(). I got two alerts. abc and def.
But Now I need to call child1() function individually outside parentfunction. But I can't pass any arguments to the functions like parentfunction(argument) also No edits to functions.

When I Tried to call child1 out I got an error in console like.

VM69:1 Uncaught ReferenceError: child1 is not defined
      at :1:1

Is there any way to call those function outside.
Any help will be appreciated.

Thank You.


问:
Optimization in sql server query
My Below query in my stored procedure takes more time.Is there any way to optimize this below query.Input parameters are Name and CA.</p>

```<code>SELECT @E_ID=vb.e_id
FROM VALUES va, mappings im, VALUES va2
WHERE im.pv_name=vb.value
AND va.E_ID in (select e_id from listings where id = 200)
AND va.f_id=100
AND va2.f_id=101 AND va.e_id=va2.e_id
AND im.w_i_name='"'+@NAME+'"' AND va2.value='["'+@CA+'"]'
ORDER BY va.e_id
</code>```

答:
The first thing I would do is to make sure is that every single field mentioned in the WHERE clause and in the ORDER BY clause is indexed.

The second thing I would do is try the following:

```<code>...
LEFT JOIN listings on va.E_ID = listings.e_id WHERE listings.id = 200
...
</code>```

(Though I would be surprised if the query optimizer does not take care of this.)

The third thing I would do is try the following:

```<code>...
(SELECT * FROM VALUES WHERE f_id=100) va,
(SELECT * FROM VALUES WHERE f_id=101) va2,
...
</code>```

Title: Optimization in sql server query

Body:
My Below query in my stored procedure takes more time.Is there any way to optimize this below query.Input parameters are Name and CA.

SELECT @E_ID=vb.e_id
FROM VALUES va, mappings im, VALUES va2
WHERE im.pv_name=vb.value
AND va.E_ID in (select e_id from listings where id = 200)
AND va.f_id=100
AND va2.f_id=101 AND va.e_id=va2.e_id
AND im.w_i_name='"'+@NAME+'"' AND va2.value='["'+@CA+'"]'
ORDER BY va.e_id

Body:
The first thing I would do is to make sure is that every single field mentioned in the WHERE clause and in the ORDER BY clause is indexed.

The second thing I would do is try the following:

...
LEFT JOIN listings on va.E_ID = listings.e_id WHERE listings.id = 200
...

(Though I would be surprised if the query optimizer does not take care of this.)

The third thing I would do is try the following:

...
(SELECT * FROM VALUES WHERE f_id=100) va,
(SELECT * FROM VALUES WHERE f_id=101) va2,
...


问:
Displaying multiple results with 1 button
The issue I am having with my code is trying to only display 1 button for multiple results with the same name field in my search_db table. The name field has different ids. I need to gather all the fullnames that are the same. It's a very complicated topic to explain and that is the best way I can explain it.

Here is my source code:

```<code><?php
    include('connect.php');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <title>Example</title>
    </head>
    <body>
        <form action="test.php" method="POST">
            <input type="text" name="value" placeholder="Hello" />
            <input type="submit" name="submit" value="Search" />
        </form><br />
        <?php
            if(isset($_POST['submit']))
            {
                $value = htmlspecialchars($_POST['value']);
                $stmt = $pdo->prepare("SELECT * FROM search_db WHERE fullname = :fullname");
                $stmt -> execute(array(':fullname' => $value));
                $result = $stmt -> fetchAll();
                foreach($result as $row)
                {
                    $id = $row['id'];
                    $db_name = $row['name'];
                    $name = $row['fullname'];
                    $username = $row['username'];
                    $password = $row['password'];
                    $dob = $row['date'];
                    $email = $row['email'];

                    $test =  '<p >'.$name. ' ' . $password . '</p>';
                }
                echo '<button data-toggle="collapse" data-target="#test">'. count($result) .' Results Found</button><br />';
                echo '<div id="test" class="collapse">'. $test . '</div>';
            }
        ?>
    </body>
</html>
</code>```

答:
I think you need to concat value of php variable form that you can show all value in single button
check $test variable

```<code>if(isset($_POST['submit']))
            {
                $test='';
                $value = htmlspecialchars($_POST['value']);
                $stmt = $pdo->prepare("SELECT * FROM search_db WHERE fullname = :fullname");
                $stmt -> execute(array(':fullname' => $value));
                $result = $stmt -> fetchAll();
                foreach($result as $row)
                {
                    $id = $row['id'];
                    $db_name = $row['name'];
                    $name = $row['fullname'];
                    $username = $row['username'];
                    $password = $row['password'];
                    $dob = $row['date'];
                    $email = $row['email'];

                    $test .=  '<p >'.$name. ' ' . $password . '</p><br>';
                }
</code>```

Body:
The issue I am having with my code is trying to only display 1 button for multiple results with the same name field in my search_db table. The name field has different ids. I need to gather all the fullnames that are the same. It's a very complicated topic to explain and that is the best way I can explain it.

Here is my source code:

<?php
    include('connect.php');
?>
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <title>Example</title>

        <form action="test.php" method="POST">
            <input type="text" name="value" placeholder="Hello" />
            <input type="submit" name="submit" value="Search" />
        </form>

        <?php
            if(isset($_POST['submit']))
            {
                $value = htmlspecialchars($_POST['value']);
                $stmt = $pdo->prepare("SELECT * FROM search_db WHERE fullname = :fullname");
                $stmt -> execute(array(':fullname' => $value));
                $result = $stmt -> fetchAll();
                foreach($result as $row)
                {
                    $id = $row['id'];
                    $db_name = $row['name'];
                    $name = $row['fullname'];
                    $username = $row['username'];
                    $password = $row['password'];
                    $dob = $row['date'];
                    $email = $row['email'];

                    $test =  '
'.$name. ' ' . $password . '
';
                }
                echo '<button data-toggle="collapse" data-target="#test">'. count($result) .' Results Found</button>
';
                echo '
'. $test . '
';
            }
        ?>

Body:
I think you need to concat value of php variable form that you can show all value in single button
check $test variable

if(isset($_POST['submit']))
            {
                $test='';
                $value = htmlspecialchars($_POST['value']);
                $stmt = $pdo->prepare("SELECT * FROM search_db WHERE fullname = :fullname");
                $stmt -> execute(array(':fullname' => $value));
                $result = $stmt -> fetchAll();
                foreach($result as $row)
                {
                    $id = $row['id'];
                    $db_name = $row['name'];
                    $name = $row['fullname'];
                    $username = $row['username'];
                    $password = $row['password'];
                    $dob = $row['date'];
                    $email = $row['email'];

                    $test .=  '<p >'.$name. ' ' . $password . '</p><br>';
                }