问:
Doctrine: Number of bound variables does not match number of tokens
When I execute my query it looks like this:

```<code>SELECT p FROM AppBundle\Entity\Shrubs p

WHERE p.botanicalname LIKE :botanicalname

AND p.commonname LIKE :commonname

AND p.borderlinehardy = :x

ORDER BY p.commonname ASC
</code>```

But I want the x to have quotation marks around it. In the query, I have that particular line like this:

```<code>andWhere("p.$key = :x")
</code>```

But if I add single quotes around the x, I get the "Invalid parameter number" error. How do I put quotes around that x without getting the error?

EDIT: My entire query looks like this:

```<code> $shrubs = $query
            ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
            ->setParameter('botanicalname', '%' . $botanicalname . '%')
            ->andwhere($query->expr()->like('p.commonname', ':commonname'))
            ->setParameter('commonname', '%' . $commonname . '%')
            ->orderBy('p.commonname', 'ASC');

        $checkfor = array("wetsoil"=>"Tolerates Wet Soil",
            "borderlinehardy"=>"Borderline Hardy",
            "moistsoil"=>"Prefers Moist Soil",
            "peatysoil"=>"Prefers Peaty Soil",
            "welldrainedsoil"=>"Prefers Well-drained Soil",
            "drought"=>"Tolerates Drought",
            "claysoil"=>"Tolerates Clay Soil",
            "sandysoil"=>"Prefers Sandy Soil",
            "loamsoil"=>"Prefers Loam Soil",
            "infertilesoil"=>"Tolerates Infertile Soil",
            "richsoil"=>"Prefers Rich Soil",
            "compactedsoil"=>"Tolerates Compacted Soil",
            "cityconditions"=>"Tolerates City Conditions",
            "pollution"=>"Tolerates Pollution",
            "salt"=>"Tolerates Salt Conditions",
            "windy"=>"Tolerates Windy Conditions",
            "shade"=>"Prefers Shade",
            "partshade"=>"Prefers Part Shade",
            "fullsun"=>"Prefers Full Sun");

        reset($checkfor);

        foreach ($checkfor as $key => $value) {
            if (${$key} == "x") {
                $shrubs = $query->andWhere("p.$key = ':x'")
                    ->setParameter('x', $key)
                    ->getQuery()
                    ->getResult();
            }
        }
</code>```

答:
Build the hole query for each call</p>

```<code>$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
            "borderlinehardy"=>"Borderline Hardy",
            "moistsoil"=>"Prefers Moist Soil",
            "peatysoil"=>"Prefers Peaty Soil",
            "welldrainedsoil"=>"Prefers Well-drained Soil",
            "drought"=>"Tolerates Drought",
            "claysoil"=>"Tolerates Clay Soil",
            "sandysoil"=>"Prefers Sandy Soil",
            "loamsoil"=>"Prefers Loam Soil",
            "infertilesoil"=>"Tolerates Infertile Soil",
            "richsoil"=>"Prefers Rich Soil",
            "compactedsoil"=>"Tolerates Compacted Soil",
            "cityconditions"=>"Tolerates City Conditions",
            "pollution"=>"Tolerates Pollution",
            "salt"=>"Tolerates Salt Conditions",
            "windy"=>"Tolerates Windy Conditions",
            "shade"=>"Prefers Shade",
            "partshade"=>"Prefers Part Shade",
            "fullsun"=>"Prefers Full Sun");

reset($checkfor);

foreach ($checkfor as $key => $value) {
      if (${$key} == "x") {
          //create for each call a full query ,
          //maybe you have not $this, then chnage it,
          //but get a new instacne
          $query = $this->entityManager->createQueryBuilder();
         //create
         $shrubs = $query
            ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
            ->setParameter('botanicalname', '%' . $botanicalname . '%')
            ->andwhere($query->expr()->like('p.commonname', ':commonname'))
            ->setParameter('commonname', '%' . $commonname . '%')
            ->andWhere("p.$key = :$key")
            ->setParameter($key, $key)
            ->orderBy('p.commonname', 'ASC')
            ->getQuery()
            ->getResult();
       }
 }
</code>```

Body:
When I execute my query it looks like this:

SELECT p FROM AppBundle\Entity\Shrubs p

WHERE p.botanicalname LIKE :botanicalname

AND p.commonname LIKE :commonname

AND p.borderlinehardy = :x

ORDER BY p.commonname ASC

But I want the x to have quotation marks around it. In the query, I have that particular line like this:

andWhere("p.$key = :x")

But if I add single quotes around the x, I get the "Invalid parameter number" error. How do I put quotes around that x without getting the error?

EDIT: My entire query looks like this:

 $shrubs = $query
            ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
            ->setParameter('botanicalname', '%' . $botanicalname . '%')
            ->andwhere($query->expr()->like('p.commonname', ':commonname'))
            ->setParameter('commonname', '%' . $commonname . '%')
            ->orderBy('p.commonname', 'ASC');

        $checkfor = array("wetsoil"=>"Tolerates Wet Soil",
            "borderlinehardy"=>"Borderline Hardy",
            "moistsoil"=>"Prefers Moist Soil",
            "peatysoil"=>"Prefers Peaty Soil",
            "welldrainedsoil"=>"Prefers Well-drained Soil",
            "drought"=>"Tolerates Drought",
            "claysoil"=>"Tolerates Clay Soil",
            "sandysoil"=>"Prefers Sandy Soil",
            "loamsoil"=>"Prefers Loam Soil",
            "infertilesoil"=>"Tolerates Infertile Soil",
            "richsoil"=>"Prefers Rich Soil",
            "compactedsoil"=>"Tolerates Compacted Soil",
            "cityconditions"=>"Tolerates City Conditions",
            "pollution"=>"Tolerates Pollution",
            "salt"=>"Tolerates Salt Conditions",
            "windy"=>"Tolerates Windy Conditions",
            "shade"=>"Prefers Shade",
            "partshade"=>"Prefers Part Shade",
            "fullsun"=>"Prefers Full Sun");

        reset($checkfor);

        foreach ($checkfor as $key => $value) {
            if (${$key} == "x") {
                $shrubs = $query->andWhere("p.$key = ':x'")
                    ->setParameter('x', $key)
                    ->getQuery()
                    ->getResult();
            }
        }

Body:
Build the hole query for each call

$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
            "borderlinehardy"=>"Borderline Hardy",
            "moistsoil"=>"Prefers Moist Soil",
            "peatysoil"=>"Prefers Peaty Soil",
            "welldrainedsoil"=>"Prefers Well-drained Soil",
            "drought"=>"Tolerates Drought",
            "claysoil"=>"Tolerates Clay Soil",
            "sandysoil"=>"Prefers Sandy Soil",
            "loamsoil"=>"Prefers Loam Soil",
            "infertilesoil"=>"Tolerates Infertile Soil",
            "richsoil"=>"Prefers Rich Soil",
            "compactedsoil"=>"Tolerates Compacted Soil",
            "cityconditions"=>"Tolerates City Conditions",
            "pollution"=>"Tolerates Pollution",
            "salt"=>"Tolerates Salt Conditions",
            "windy"=>"Tolerates Windy Conditions",
            "shade"=>"Prefers Shade",
            "partshade"=>"Prefers Part Shade",
            "fullsun"=>"Prefers Full Sun");

reset($checkfor);

foreach ($checkfor as $key => $value) {
      if (${$key} == "x") {
          //create for each call a full query ,
          //maybe you have not $this, then chnage it,
          //but get a new instacne
          $query = $this->entityManager->createQueryBuilder();
         //create
         $shrubs = $query
            ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
            ->setParameter('botanicalname', '%' . $botanicalname . '%')
            ->andwhere($query->expr()->like('p.commonname', ':commonname'))
            ->setParameter('commonname', '%' . $commonname . '%')
            ->andWhere("p.$key = :$key")
            ->setParameter($key, $key)
            ->orderBy('p.commonname', 'ASC')
            ->getQuery()
            ->getResult();
       }
 }


来源: stackexchange

问:
i'm making an 2 bit Arithmetic logic unit in VHDL.Its giving an type error
```<code>entity alu is
        Port ( a,b,Sel : in  STD_LOGIC_VECTOR (1 downto 0);
               res : out  STD_LOGIC_VECTOR (1 downto 0));
end alu;
architecture Behavioral of alu is
begin
process(Sel,a,b)
begin
case Sel is
when "00" =>
    res<=a+b;
when "01" =>
    res<=a+(not b)+1;
when "10" =>
    res<=a and b;
when "11" =>
    res<=a or b;
when others =>
    res<="xx";
end case;
end process;
end Behavioral;
</code>```

My file name is alu.vhd
However running this gives me an error:
Type of res is incompatible with type of xx
in line 4.

答:
You have missed a vital part of your entity structure:

```<code>architecture Behavioral of alu is
begin
  case Sel is
    -- ...
  end case;
end process;
end Behavioral;
</code>```

Where is the start of the process? It needs to look like:

```<code>architecture Behavioral of alu is
begin
  process (Sel, a, b)  -- process definition and sensitivity list
  begin
    case Sel is
      -- ...
    end case;
  end process;
end Behavioral;
</code>```

Per the comment, you also have a duplicate case.

Lastly, your assignment to "xx" needs to use a capital letter, i.e.  "XX". However, since you will have covered all the valid states for Sel once you correct the duplicate, you might more conventionally complete your others clause like so:

```<code>when others =>
  NULL;
</code>```

This means 'do nothing' for other cases.

ContentLicense: CC BY-SA 3.0

Body:
entity alu is
        Port ( a,b,Sel : in  STD_LOGIC_VECTOR (1 downto 0);
               res : out  STD_LOGIC_VECTOR (1 downto 0));
end alu;
architecture Behavioral of alu is
begin
process(Sel,a,b)
begin
case Sel is
when "00" =>
    res<=a+b;
when "01" =>
    res<=a+(not b)+1;
when "10" =>
    res<=a and b;
when "11" =>
    res<=a or b;
when others =>
    res<="xx";
end case;
end process;
end Behavioral;

My file name is alu.vhd
However running this gives me an error:
Type of res is incompatible with type of xx
in line 4.

Body:
You have missed a vital part of your entity structure:

architecture Behavioral of alu is
begin
  case Sel is
    -- ...
  end case;
end process;
end Behavioral;

Where is the start of the process? It needs to look like:

architecture Behavioral of alu is
begin
  process (Sel, a, b)  -- process definition and sensitivity list
  begin
    case Sel is
      -- ...
    end case;
  end process;
end Behavioral;

Per the comment, you also have a duplicate case.

Lastly, your assignment to "xx" needs to use a capital letter, i.e.  "XX". However, since you will have covered all the valid states for Sel once you correct the duplicate, you might more conventionally complete your others clause like so:

when others =>
  NULL;

This means 'do nothing' for other cases.


问:
TinyMce Editor Pop css override
I want to override css of all popup in tinymce editor like image upload popup.I tried changing styling using Jquery, is there any way i can override.</p>

答:
Have you looked at creating your own TinyMCE Skin?  The skin creator:

http://skin.tinymce.com

Allows you to change the styles of all aspects of the editor including the dialogs.

Title: TinyMce Editor Pop css override


问:
excel multiple on error goto
I am trying to get multiple on error statements to work and can't figure it out.

If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.

```<code>Sub Cutsheets()
Application.ScreenUpdating = False

Dim finalrow As Integer

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1

If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

whoa:
MsgBox ("No cutsheet can be found for this item.")

Application.ScreenUpdating = True

End Sub
</code>```

Also I don't remember why I put sendkeys in there but it doesn't work without it.

答:
Using multiple On Error Goto XYZ handlers for control flow is over-complicating some easy validation checks you can do and then simply use the error handling for actual errors.

As @Rory pointed out in a comment you can use the Dir function. You can combine the use of Dir with an If...ElseIf...Else...End If construct to control what you code does:

```<code>Option Explicit

Sub Cutsheets()

    On Error GoTo ErrHandler

    Dim strLocalCheck As String
    Dim strNetworkCheck As String

    'check for files - Dir will return "" if file not found
    strLocalCheck = Dir("C:\Local" & ActiveCell.Value & ".pdf")
    strNetworkCheck = Dir("P:\Network" & ActiveCell.Value & ".pdf")

    'control flow
    If strLocalCheck <> "" Then
        ActiveWorkbook.FollowHyperlink strLocalCheck
        Application.SendKeys "{ENTER}", True

    ElseIf strNetworkCheck <> "" Then
        ActiveWorkbook.FollowHyperlink strNetworkCheck
        Application.SendKeys "{ENTER}", True

    Else
        MsgBox "No cutsheet can be found for this item."

    End If

    Exit Sub

ErrHandler:
    Debug.Print "A real error occurred: " & Err.Description

End Sub
</code>```

Title: excel multiple on error goto

Body:
I am trying to get multiple on error statements to work and can't figure it out.

If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.

Sub Cutsheets()
Application.ScreenUpdating = False

Dim finalrow As Integer

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1

If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

whoa:
MsgBox ("No cutsheet can be found for this item.")

Application.ScreenUpdating = True

End Sub

Also I don't remember why I put sendkeys in there but it doesn't work without it.

Body:
Using multiple On Error Goto XYZ handlers for control flow is over-complicating some easy validation checks you can do and then simply use the error handling for actual errors.

As @Rory pointed out in a comment you can use the Dir function. You can combine the use of Dir with an If...ElseIf...Else...End If construct to control what you code does:

Option Explicit

Sub Cutsheets()

    On Error GoTo ErrHandler

    Dim strLocalCheck As String
    Dim strNetworkCheck As String

    'check for files - Dir will return "" if file not found
    strLocalCheck = Dir("C:\Local" & ActiveCell.Value & ".pdf")
    strNetworkCheck = Dir("P:\Network" & ActiveCell.Value & ".pdf")

    'control flow
    If strLocalCheck <> "" Then
        ActiveWorkbook.FollowHyperlink strLocalCheck
        Application.SendKeys "{ENTER}", True

    ElseIf strNetworkCheck <> "" Then
        ActiveWorkbook.FollowHyperlink strNetworkCheck
        Application.SendKeys "{ENTER}", True

    Else
        MsgBox "No cutsheet can be found for this item."

    End If

    Exit Sub

ErrHandler:
    Debug.Print "A real error occurred: " & Err.Description

End Sub


问:
How to replace \\\ 3 consecutive backslashes to 2 \\ in js using regex
I need to replace 3 \\\ consecutive backslashes to \\. Is it possible?

I tried these options:

const str="example\\\\\\txt";
str.replace(new RegExp('\\{3}','g'),'\\\\')
```
<p>Here replace is any js string prototypes default method</p>
<p>this never creates a regexp object :</p>
```new RegExp('\\\\\\','g')
```

Please suggest.

答:
You can use rgex literal instead of RegExp:

```<code>var s='Bob\\\\\\Jones';

var r = s.replace(/\\{3}/g, '\\');
//=> Bob\Jones
</code>```

Regex /\\{3}/ matches 3 consecutive instances of \

ContentLicense: CC BY-SA 4.0

Body:
I need to replace 3 \\\ consecutive backslashes to \\. Is it possible?

I tried these options:

const str="example\\\\\\txt";
str.replace(new RegExp('\\{3}','g'),'\\\\')

Here replace is any js string prototypes default method

this never creates a regexp object :

new RegExp('\\\\\\','g')

Please suggest.

Body:
You can use rgex literal instead of RegExp:

var s='Bob\\\\\\Jones';

var r = s.replace(/\\{3}/g, '\\');
//=> Bob\Jones

Regex /\\{3}/ matches 3 consecutive instances of \


问:
setting the execution rate of while loop in a C++ code for real time synchronization
I am doing a real_time simulation using a .cpp source code. I have to take a sample every 0.2 seconds (200 ms) ... There is a while loop that takes a sample every time step... I want to synchronize the execution of this while loop to get a sample every (200 ms) ... How should I modify the while loop ?

```<code>while (1){
          // get a sample every 200 ms
         }
</code>```

答:
Simple and accurate solution with std::this_thread::sleep_until:

```<code>#include "date.h"
#include <chrono>
#include <iostream>
#include <thread>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    auto next = steady_clock::now();
    auto prev = next - 200ms;
    while (true)
    {
        // do stuff
        auto now = steady_clock::now();
        std::cout << round<milliseconds>(now - prev) << '\n';
        prev = now;

        // delay until time to iterate again
        next += 200ms;
        std::this_thread::sleep_until(next);
    }
}
</code>```

"date.h" isn't needed for the delay part.  It is there to provide the round<duration> function (which is now in C++17), and to make it easier to print out durations.  This is all under "do stuff", and doesn't matter for the loop delay.

Just get a chrono::time_point, add your delay to it, and sleep until that time_point.  Your loop will on average stay true to your delay, as long as your "stuff" takes less time than your delay.  No other thread needed.  No timer needed.  Just <chrono> and sleep_until.

This example just output for me:

```<code>200ms
205ms
200ms
195ms
205ms
198ms
202ms
199ms
196ms
203ms
...
</code>```

Body:
I am doing a real_time simulation using a .cpp source code. I have to take a sample every 0.2 seconds (200 ms) ... There is a while loop that takes a sample every time step... I want to synchronize the execution of this while loop to get a sample every (200 ms) ... How should I modify the while loop ?

while (1){
          // get a sample every 200 ms
         }

Body:
Simple and accurate solution with std::this_thread::sleep_until:

#include "date.h"
#include <chrono>
#include <iostream>
#include <thread>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    auto next = steady_clock::now();
    auto prev = next - 200ms;
    while (true)
    {
        // do stuff
        auto now = steady_clock::now();
        std::cout << round<milliseconds>(now - prev) << '\n';
        prev = now;

        // delay until time to iterate again
        next += 200ms;
        std::this_thread::sleep_until(next);
    }
}

"date.h" isn't needed for the delay part.  It is there to provide the round<duration> function (which is now in C++17), and to make it easier to print out durations.  This is all under "do stuff", and doesn't matter for the loop delay.

Just get a chrono::time_point, add your delay to it, and sleep until that time_point.  Your loop will on average stay true to your delay, as long as your "stuff" takes less time than your delay.  No other thread needed.  No timer needed.  Just <chrono> and sleep_until.

This example just output for me:

200ms
205ms
200ms
195ms
205ms
198ms
202ms
199ms
196ms
203ms
...


问:
Display ñ on a C# .NET application
I have a localization issue.

One of my industrious coworkers has replaced all the strings throughout our application with constants that are contained in a dictionary.  That dictionary gets various strings placed in it once the user selects a language (English by default, but target languages are German, Spanish, French, Portuguese, Mandarin, and Thai).

For our test of this functionality, we wanted to change a button to include text which has a ñ character, which appears both in Spanish and in the Arial Unicode MS font (which we're using throughout the application).

Problem is, the ñ is appearing as a square block, as if the program did not know how to display it.  When I debug into that particular string being read from disk, the debugger reports that character as a square block as well.

So where is the failure?  I think it could be in a few places:

1) Notepad may not be unicode aware, so the ñ displayed there is not the same as what vs2008 expects, and so the program interprets the character as a square (EDIT: notepad shows the same characters as vs; ie, they both show the ñ.  In the same place.).

2) vs2008 can't handle ñ.  I find that very, very hard to believe.

3) The text is read in properly, but the default font for vs2008 can't display it, which is why the debugger shows a square.

4) The text is not read in properly, and I should use something other than a regular StreamReader to get strings.

5) The text is read in properly, but the default String class in C# doesn't handle ñ well.  I find that very, very hard to believe.

6) The version of Arial Unicode MS I have doesn't have ñ, despite it being listed as one of the 50k characters by http://www.fileinfo.info.

Anything else I could have left out?

Thanks for any help!

答:
Have you checked that your source file encoding is really utf-8? May not be applicable to default vs2008 install but IDE may detect your OS' default locale (or filesystem encoding) and set the matching non-utf-8 encoding for all your files. You might want to try with the doubly encoded mess (which you often come across on the web) "Ã±" without changing anything in your setup to test your encoding mismatches.

I have bitten by this thing when I get to work on a coworker's god-knows-what-editor-in-what-encoding code.

I'm quite sure and assume all your api calls are utf-8 aware so all your text is interpreted as utf-8 even if it is not.

OwnerDisplayName: mmr

ContentLicense: CC BY-SA 2.5

Title: Display ñ on a C# .NET application

LastEditorDisplayName: moocha


问:
How to truncate or pad a string to a fixed length in c#
Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces (' ').

For example:

```<code>string s1 = "abcdef";
string s2 = "abc";
</code>```

after setting both to length 5, we should have:

```<code>"abcde"
"abc  "
</code>```

答:
Have you tried
    s1.PadLeft(5);

you can also specify the character for padding if you want something else than spaces

```<code>s1.PadLeft(6, '.');
</code>```

Would give you: "abcdef."

to do both:

```<code>var s1 = "1234567890";
var s2 = s1.SubString(5).PadLeft(5);
</code>```

Body:
Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces (' ').

For example:

string s1 = "abcdef";
string s2 = "abc";

after setting both to length 5, we should have:

"abcde"
"abc  "

Body:
Have you tried
    s1.PadLeft(5);

you can also specify the character for padding if you want something else than spaces

s1.PadLeft(6, '.');

Would give you: "abcdef."

to do both:

var s1 = "1234567890";
var s2 = s1.SubString(5).PadLeft(5);


答:
```<code>private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}
</code>```

Title: How to truncate or pad a string to a fixed length in c#


问:
Read 2D matrix from file to 2D int array in C#
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
</code>```

答:
You are reading all lines, but the code then only processes one line.  If you're trying to make a 2D array of integers, you want something like this:

string text = @"2,3,4,5,6
5,2,3,4,5
2,4,6,7,4";

text.Split('\n').Select(line => line.Split(',').Select(t => int.Parse(t)).ToArray()).ToArray();

(where for test purposes I've replaced the file read with a static string)

Body:
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();


问:
Number of Duplicate Rows in multiple columns (more than 10) in SQL Server
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

```<code>Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3
</code>```

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

```<code>Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2
</code>```

答:
First here is some sample data - please do this for any further sql questions you ask:

```<code>declare @table table (Customer  char(1), Account char(3), X char(2), Y char(2), Z char(2));
insert into @table values
('A', '001', 'X1', 'Y1', 'Z1'),
('A', '002', 'X2', 'Y1', 'Z1'),
('A', '003', 'X1', 'Y1', 'Z1'),
('B', '004', 'X3', 'Y2', 'Z2'),
('B', '005', 'X4', 'Y2', 'Z2'),
('C', '006', 'X5', 'Y3', 'Z3'),
('C', '007', 'X5', 'Y3', 'Z3');
</code>```

Create 2 ctes - one to group together your X,Y,Z columns for each customer, and the next to see how many different groups you have (per customer).

Then select from your original table all the information, and inner join on cte2 to restrict to only customers with duplicate non-matching rows.

```<code>with cte as (
    select Customer, X, Y, Z from @table
    group by Customer, X, Y, Z
), cte2 as (
    select Customer, COUNT(*) groups
    from cte
    group by Customer
)
select t.Customer, t.Account, t.X, t.Y, t.Z
from @table t
inner join cte2 on t.Customer = cte2.Customer
where cte2.groups >1;
</code>```

Body:
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2

Body:
First here is some sample data - please do this for any further sql questions you ask:

declare @table table (Customer  char(1), Account char(3), X char(2), Y char(2), Z char(2));
insert into @table values
('A', '001', 'X1', 'Y1', 'Z1'),
('A', '002', 'X2', 'Y1', 'Z1'),
('A', '003', 'X1', 'Y1', 'Z1'),
('B', '004', 'X3', 'Y2', 'Z2'),
('B', '005', 'X4', 'Y2', 'Z2'),
('C', '006', 'X5', 'Y3', 'Z3'),
('C', '007', 'X5', 'Y3', 'Z3');

Create 2 ctes - one to group together your X,Y,Z columns for each customer, and the next to see how many different groups you have (per customer).

Then select from your original table all the information, and inner join on cte2 to restrict to only customers with duplicate non-matching rows.

with cte as (
    select Customer, X, Y, Z from @table
    group by Customer, X, Y, Z
), cte2 as (
    select Customer, COUNT(*) groups
    from cte
    group by Customer
)
select t.Customer, t.Account, t.X, t.Y, t.Z
from @table t
inner join cte2 on t.Customer = cte2.Customer
where cte2.groups >1;


问:
Getting a Syntax error in INSERT INTO statement
I need help figuring out why I'm getting this syntax error when trying to run this code in Microsoft Access. I am working on this database for work and have some experience with it, but not a whole lot.

I created a database before the one I'm currently working on and it works fine. It is very similar to the database that I'm working on now, so I just copied it and then renamed the fields and text boxes and everything to match the information that this database will be handling.

Essentially I have a table with the data and then I want a form that has a text box for each field in the table with a subtable of the main table incorporated into the form. The user fills in the text boxes with the information and then either adds it to the table or they can click on a record and edit it or delete it with the corresponding buttons on the form.

Now I'm getting a runtime error '3134': syntax error in INSERT INTO statement when trying to click the add button on one of my forms. This only happens on the add button and consequently the update button if it is set to update, but all of the other buttons work fine.

Here is the code for the new database:

```<code>Option Compare Database

Private Sub cmdAdd_Click()
    'when we click on button Add there are two options
    '1. for insert
    '2. for update
    If Me.txtICN.Tag & "" = "" Then
        'this is for insert new
        'add data to table
        CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, model, serial, desc, dateRec, dateRem, dispo, project, AMCA, UL, comments) " & _
        " VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDesc & "', '" & Me.txtDateRec & "', '" & Me.txtDateRem & "', '" & Me.txtDispo & "', '" & Me.txtProject & "', '" & Me.txtAMCA & "', '" & Me.txtUL & "', '" & Me.txtComments & "')"
    Else
        'otherwise (Tag of txtICN store the ICN of item to be modified)
        CurrentDb.Execute "UPDATE tblInventory " & _
        " SET ICN = " & Me.txtICN & _
        ", manu = '" & Me.txtManu & "'" & _
        ", model = '" & Me.txtModel & "'" & _
        ", serial = '" & Me.txtSerial & "'" & _
        ", desc = '" & Me.txtDesc & "'" & _
        ", dateRec = '" & Me.txtDateRec & "'" & _
        ", dateRem = '" & Me.txtDateRem & "'" & _
        ", dispo = '" & Me.txtDispo & "'" & _
        ", project = '" & Me.txtProject & "'" & _
        ", AMCA = '" & Me.txtAMCA & "'" & _
        ", UL = '" & Me.txtUL & "'" & _
        ", comments = '" & Me.txtComments & "'" & _
        " WHERE ICN = " & Me.txtICN.Tag
    End If

    'clear form
    cmdClear_Click
    'refresh data in list on form
    frmInventorySub.Form.Requery
End Sub

Private Sub cmdClear_Click()
    Me.txtICN = ""
    Me.txtManu = ""
    Me.txtModel = ""
    Me.txtSerial = ""
    Me.txtDesc = ""
    Me.txtDateRec = ""
    Me.txtDateRem = ""
    Me.txtDispo = ""
    Me.txtProject = ""
    Me.txtAMCA = ""
    Me.txtUL = ""
    Me.txtComments = ""

    'focus on ID text box
    Me.txtICN.SetFocus
    'set button edit to enable
    Me.cmdEdit.Enabled = True
    'change caption of button add to Add
    Me.cmdAdd.Caption = "Add"
    'clear tag on txtICN for reset new
    Me.txtICN.Tag = ""
End Sub

Private Sub cmdClose_Click()
    DoCmd.Close
End Sub

Private Sub cmdDelete_Click()
    'delete record
    'check existing selected record
    If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
        'confirm delete
        If MsgBox("Are you sure you want to delete this item?", vbYesNo) = vbYes Then
            'delete now
            CurrentDb.Execute "DELETE FROM tblInventory " & _
                "WHERE ICN =" & Me.frmInventorySub.Form.Recordset.Fields("ICN")
            'refresh data in list
            Me.frmInventorySub.Form.Requery
        End If
    End If
End Sub

Private Sub cmdEdit_Click()
    'check whether there exists data in list
    If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
        'get data to text box control
        With Me.frmInventorySub.Form.Recordset
            Me.txtICN = .Fields("ICN")
            Me.txtManu = .Fields("manu")
            Me.txtModel = .Fields("model")
            Me.txtSerial = .Fields("serial")
            Me.txtDesc = .Fields("desc")
            Me.txtDateRec = .Fields("dateRec")
            Me.txtDateRem = .Fields("dateRem")
            Me.txtDispo = .Fields("dispo")
            Me.txtProject = .Fields("project")
            Me.txtAMCA = .Fields("AMCA")
            Me.txtUL = .Fields("UL")
            Me.txtComments = .Fields("comments")
            'store id of item in Tag of txtICN in case ICN is modified
            Me.txtICN.Tag = .Fields("ICN")
            'change caption of button add to Update
            Me.cmdAdd.Caption = "Update"
            'disable button edit
            Me.cmdEdit.Enabled = False
        End With
    End If
End Sub
</code>```

And here is the code for the old database:

```<code>Option Compare Database

Private Sub cmdAdd_Click()
    'when we click on button Add there are two options
    '1. for insert
    '2. for update
    If Me.txtID.Tag & "" = "" Then
        'this is for insert new
        'add data to table
        CurrentDb.Execute "INSERT INTO tblEquipmentList(equipID, equipDesc, equipManu, equipModelNum, equipSerNum, lastCalDate, calDue) " & _
        " VALUES(" & Me.txtID & ", '" & Me.txtDesc & "', '" & Me.txtManu & "', '" & Me.txtModelNum & "', '" & Me.txtSerNum & "', '" & Me.txtLastCalDate & "', '" & Me.txtCalDueDate & "')"
    Else
        'otherwise (Tag of txtID store the id of equipment to be modified)
        CurrentDb.Execute "UPDATE tblEquipmentList " & _
        " SET equipID = " & Me.txtID & _
        ", equipDesc = '" & Me.txtDesc & "'" & _
        ", equipManu = '" & Me.txtManu & "'" & _
        ", equipModelNum = '" & Me.txtModelNum & "'" & _
        ", equipSerNum = '" & Me.txtSerNum & "'" & _
        ", lastCalDate = '" & Me.txtLastCalDate & "'" & _
        ", calDue = '" & Me.txtCalDueDate & "'" & _
        " WHERE equipID = " & Me.txtID.Tag
    End If

    'clear form
    cmdClear_Click
    'refresh data in list on form
    frmEquipmentListSub.Form.Requery
End Sub

Private Sub cmdClear_Click()
    Me.txtID = ""
    Me.txtDesc = ""
    Me.txtManu = ""
    Me.txtModelNum = ""
    Me.txtSerNum = ""
    Me.txtLastCalDate = ""
    Me.txtCalDueDate = ""

    'focus on ID text box
    Me.txtID.SetFocus
    'set button edit to enable
    Me.cmdEdit.Enabled = True
    'change caption of button add to Add
    Me.cmdAdd.Caption = "Add"
    'clear tag on txtID for reset new
    Me.txtID.Tag = ""
End Sub

Private Sub cmdClose_Click()
    DoCmd.Close
End Sub

Private Sub cmdDelete_Click()
    'delete record
    'check existing selected record
    If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
        'confirm delete
        If MsgBox("Are you sure you want to delete this piece of equipment?", vbYesNo) = vbYes Then
            'delete now
            CurrentDb.Execute "DELETE FROM tblEquipmentList " & _
                "WHERE equipID =" & Me.frmEquipmentListSub.Form.Recordset.Fields("equipID")
            'refresh data in list
            Me.frmEquipmentListSub.Form.Requery
        End If
    End If
End Sub

Private Sub cmdEdit_Click()
    'check whether there exists data in list
    If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
        'get data to text box control
        With Me.frmEquipmentListSub.Form.Recordset
            Me.txtID = .Fields("equipID")
            Me.txtDesc = .Fields("equipDesc")
            Me.txtManu = .Fields("equipManu")
            Me.txtModelNum = .Fields("equipModelNum")
            Me.txtSerNum = .Fields("equipSerNum")
            Me.txtLastCalDate = .Fields("lastCalDate")
            Me.txtCalDueDate = .Fields("calDue")
            'store id of equipment in Tag of txtID in case id is modified
            Me.txtID.Tag = .Fields("equipID")
            'change caption of button add to Update
            Me.cmdAdd.Caption = "Update"
            'disable button edit
            Me.cmdEdit.Enabled = False
        End With
    End If
End Sub
</code>```

As you can see, I'm pretty confident that they're pretty much identical except for the field names.

I'm also linking an album of screenshots of the database here: http://imgur.com/a/xLV3Q

Thanks for any help you guys can provide.

答:
The problem may be:
Your new table tblInventory has a column DESC which is a SQL reserved keyword. You have two options:

Drop the column DESC and create a new column with different name OR;

Add brackets to your script like this: INSERT INTO tblInventory([ICN], [manu], [model], [serial], [desc], [dateRec], [dateRem], [dispo], [project], [AMCA], [UL], [comments]).

Please check a full list of SQL reserved keywords: Reserved Keywords-Transact-SQL

Body:
I need help figuring out why I'm getting this syntax error when trying to run this code in Microsoft Access. I am working on this database for work and have some experience with it, but not a whole lot.

I created a database before the one I'm currently working on and it works fine. It is very similar to the database that I'm working on now, so I just copied it and then renamed the fields and text boxes and everything to match the information that this database will be handling.

Essentially I have a table with the data and then I want a form that has a text box for each field in the table with a subtable of the main table incorporated into the form. The user fills in the text boxes with the information and then either adds it to the table or they can click on a record and edit it or delete it with the corresponding buttons on the form.

Now I'm getting a runtime error '3134': syntax error in INSERT INTO statement when trying to click the add button on one of my forms. This only happens on the add button and consequently the update button if it is set to update, but all of the other buttons work fine.

Here is the code for the new database:

Option Compare Database

Private Sub cmdAdd_Click()
    'when we click on button Add there are two options
    '1. for insert
    '2. for update
    If Me.txtICN.Tag & "" = "" Then
        'this is for insert new
        'add data to table
        CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, model, serial, desc, dateRec, dateRem, dispo, project, AMCA, UL, comments) " & _
        " VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDesc & "', '" & Me.txtDateRec & "', '" & Me.txtDateRem & "', '" & Me.txtDispo & "', '" & Me.txtProject & "', '" & Me.txtAMCA & "', '" & Me.txtUL & "', '" & Me.txtComments & "')"
    Else
        'otherwise (Tag of txtICN store the ICN of item to be modified)
        CurrentDb.Execute "UPDATE tblInventory " & _
        " SET ICN = " & Me.txtICN & _
        ", manu = '" & Me.txtManu & "'" & _
        ", model = '" & Me.txtModel & "'" & _
        ", serial = '" & Me.txtSerial & "'" & _
        ", desc = '" & Me.txtDesc & "'" & _
        ", dateRec = '" & Me.txtDateRec & "'" & _
        ", dateRem = '" & Me.txtDateRem & "'" & _
        ", dispo = '" & Me.txtDispo & "'" & _
        ", project = '" & Me.txtProject & "'" & _
        ", AMCA = '" & Me.txtAMCA & "'" & _
        ", UL = '" & Me.txtUL & "'" & _
        ", comments = '" & Me.txtComments & "'" & _
        " WHERE ICN = " & Me.txtICN.Tag
    End If

    'clear form
    cmdClear_Click
    'refresh data in list on form
    frmInventorySub.Form.Requery
End Sub

Private Sub cmdClear_Click()
    Me.txtICN = ""
    Me.txtManu = ""
    Me.txtModel = ""
    Me.txtSerial = ""
    Me.txtDesc = ""
    Me.txtDateRec = ""
    Me.txtDateRem = ""
    Me.txtDispo = ""
    Me.txtProject = ""
    Me.txtAMCA = ""
    Me.txtUL = ""
    Me.txtComments = ""

    'focus on ID text box
    Me.txtICN.SetFocus
    'set button edit to enable
    Me.cmdEdit.Enabled = True
    'change caption of button add to Add
    Me.cmdAdd.Caption = "Add"
    'clear tag on txtICN for reset new
    Me.txtICN.Tag = ""
End Sub

Private Sub cmdClose_Click()
    DoCmd.Close
End Sub

Private Sub cmdDelete_Click()
    'delete record
    'check existing selected record
    If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
        'confirm delete
        If MsgBox("Are you sure you want to delete this item?", vbYesNo) = vbYes Then
            'delete now
            CurrentDb.Execute "DELETE FROM tblInventory " & _
                "WHERE ICN =" & Me.frmInventorySub.Form.Recordset.Fields("ICN")
            'refresh data in list
            Me.frmInventorySub.Form.Requery
        End If
    End If
End Sub

Private Sub cmdEdit_Click()
    'check whether there exists data in list
    If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
        'get data to text box control
        With Me.frmInventorySub.Form.Recordset
            Me.txtICN = .Fields("ICN")
            Me.txtManu = .Fields("manu")
            Me.txtModel = .Fields("model")
            Me.txtSerial = .Fields("serial")
            Me.txtDesc = .Fields("desc")
            Me.txtDateRec = .Fields("dateRec")
            Me.txtDateRem = .Fields("dateRem")
            Me.txtDispo = .Fields("dispo")
            Me.txtProject = .Fields("project")
            Me.txtAMCA = .Fields("AMCA")
            Me.txtUL = .Fields("UL")
            Me.txtComments = .Fields("comments")
            'store id of item in Tag of txtICN in case ICN is modified
            Me.txtICN.Tag = .Fields("ICN")
            'change caption of button add to Update
            Me.cmdAdd.Caption = "Update"
            'disable button edit
            Me.cmdEdit.Enabled = False
        End With
    End If
End Sub

And here is the code for the old database:

Option Compare Database

Private Sub cmdAdd_Click()
    'when we click on button Add there are two options
    '1. for insert
    '2. for update
    If Me.txtID.Tag & "" = "" Then
        'this is for insert new
        'add data to table
        CurrentDb.Execute "INSERT INTO tblEquipmentList(equipID, equipDesc, equipManu, equipModelNum, equipSerNum, lastCalDate, calDue) " & _
        " VALUES(" & Me.txtID & ", '" & Me.txtDesc & "', '" & Me.txtManu & "', '" & Me.txtModelNum & "', '" & Me.txtSerNum & "', '" & Me.txtLastCalDate & "', '" & Me.txtCalDueDate & "')"
    Else
        'otherwise (Tag of txtID store the id of equipment to be modified)
        CurrentDb.Execute "UPDATE tblEquipmentList " & _
        " SET equipID = " & Me.txtID & _
        ", equipDesc = '" & Me.txtDesc & "'" & _
        ", equipManu = '" & Me.txtManu & "'" & _
        ", equipModelNum = '" & Me.txtModelNum & "'" & _
        ", equipSerNum = '" & Me.txtSerNum & "'" & _
        ", lastCalDate = '" & Me.txtLastCalDate & "'" & _
        ", calDue = '" & Me.txtCalDueDate & "'" & _
        " WHERE equipID = " & Me.txtID.Tag
    End If

    'clear form
    cmdClear_Click
    'refresh data in list on form
    frmEquipmentListSub.Form.Requery
End Sub

Private Sub cmdClear_Click()
    Me.txtID = ""
    Me.txtDesc = ""
    Me.txtManu = ""
    Me.txtModelNum = ""
    Me.txtSerNum = ""
    Me.txtLastCalDate = ""
    Me.txtCalDueDate = ""

    'focus on ID text box
    Me.txtID.SetFocus
    'set button edit to enable
    Me.cmdEdit.Enabled = True
    'change caption of button add to Add
    Me.cmdAdd.Caption = "Add"
    'clear tag on txtID for reset new
    Me.txtID.Tag = ""
End Sub

Private Sub cmdClose_Click()
    DoCmd.Close
End Sub

Private Sub cmdDelete_Click()
    'delete record
    'check existing selected record
    If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
        'confirm delete
        If MsgBox("Are you sure you want to delete this piece of equipment?", vbYesNo) = vbYes Then
            'delete now
            CurrentDb.Execute "DELETE FROM tblEquipmentList " & _
                "WHERE equipID =" & Me.frmEquipmentListSub.Form.Recordset.Fields("equipID")
            'refresh data in list
            Me.frmEquipmentListSub.Form.Requery
        End If
    End If
End Sub

Private Sub cmdEdit_Click()
    'check whether there exists data in list
    If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
        'get data to text box control
        With Me.frmEquipmentListSub.Form.Recordset
            Me.txtID = .Fields("equipID")
            Me.txtDesc = .Fields("equipDesc")
            Me.txtManu = .Fields("equipManu")
            Me.txtModelNum = .Fields("equipModelNum")
            Me.txtSerNum = .Fields("equipSerNum")
            Me.txtLastCalDate = .Fields("lastCalDate")
            Me.txtCalDueDate = .Fields("calDue")
            'store id of equipment in Tag of txtID in case id is modified
            Me.txtID.Tag = .Fields("equipID")
            'change caption of button add to Update
            Me.cmdAdd.Caption = "Update"
            'disable button edit
            Me.cmdEdit.Enabled = False
        End With
    End If
End Sub

As you can see, I'm pretty confident that they're pretty much identical except for the field names.

I'm also linking an album of screenshots of the database here: http://imgur.com/a/xLV3Q

Thanks for any help you guys can provide.


问:
Copy Disjointed Cells from Excel Table to Word Table Using VBA
I'm trying to copy disjointed cells from an excel document to the cursor location in word and use my predefined table style.

The disjoint copy/paste works nicely in excel when I just copy and paste into the current active worksheet, but as soon as I try to execute the same copy/paste from word, it ends up copying the entire table from top-left all the way to bottom-right, instead of doing the disjointed copy/paste.

I know there are some differences between the individual function from excel VBA to word VBA, but I thought it's possible to get around that by specifying the library when calling functions.

Seen below is a successful disjointed copy:

Successful Disjointed Copy

Here is the functioning excel code, edited for length.

The code within if Copy3 is the interesting part:

```<code>Sub GrabExcelTables()

' !Initializing everything

Dim phasesArray As Variant
phasesArray = Array("Scoping", "Umsetzung (Dev)", "Go Live")

With wsFrom

    'Copy schema for tables 1 and 2
    ' !Omitted for length

    'Copy schema for tables 3 and 4
    ' !Omitted for length

    'Copy schema for tables 5 and 6
    If Copy3 Then

        'Iterate through all columns to find which ones are filled
        For colCounter = Left + 1 To Right - 1
            If .Cells(22, colCounter).Value <> "-" Then
                wantedColumn.Add colCounter
            End If
        Next colCounter

        'Initialize RangeToCopy with top left cell of table
        Set RangeToCopy = .Cells(22, Left)

        'Iterate through all rows
        For rowCounter = 22 To 29

            'Only check those rows desired i.e.  part of phasesArray
            If (IsInArray(.Cells(rowCounter, Left).Value, phasesArray) Or rowCounter = 22 Or rowCounter = 29) Then

                'Union row phase header
                Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, Left))

                'Add all columns within row that were selected as filled earlier
                For Each col In wantedColumn
                    Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, col))
                Next col

                'Union final total column
                Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, Right))
            End If
        Next rowCounter
    End If

    'Copy schema for table 7
    ' !Omitted for length

    'Copy range
    RangeToCopy.Copy
    .Range("A42").PasteSpecial Paste:=xlValues

End With

Set RangeToCopy = Nothing

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

Now pretty much the same code except adapted to word VBA, again edited for length:

```<code>Sub GrabExcelTables()

' !Initializing everything

Dim phasesArray As Variant
phasesArray = Array("Scoping", "Umsetzung (Dev)", "Go Live")

'specify the workbook to work on
WorkbookToWorkOn = ActiveDocument.Path & "\Kalkulationssheet_edit.xlsx"

Set oXL = CreateObject("Excel.Application")

On Error GoTo Err_Handler

'Open the workbook
Set oWB = Workbooks.Open(FileName:=WorkbookToWorkOn)

Set wsFrom = oWB.Sheets(7)

' !Initializing everything

With wsFrom

    'Copy schema for tables 1 and 2
    ' !Omitted for length

    'Copy schema for tables 3 and 4
    ' !Omitted for length

    'Copy schema for tables 5 and 6
    If Copy3 Then

        'Iterate through all columns to find which ones are filled
        For colCounter = Left + 1 To Right - 1
            If .Cells(22, colCounter).Value <> "-" Then
                wantedColumn.Add colCounter

                'MsgBox "Wanted Column: " & colCounter

            End If
        Next colCounter

        'Initialize RangeToCopy with top left cell of table
        Set RangeToCopy = .Cells(22, Left)

        'Iterate through all rows
        For rowCounter = 22 To 29

            'Only check those rows desired i.e.  part of phasesArray
            If (IsInArray(.Cells(rowCounter, Left).Value, phasesArray) Or rowCounter = 22 Or rowCounter = 29) Then

                'MsgBox "rowCounter: " & rowCounter & "cell value: " & .Cells(rowCounter, Left).Value

                'Union row phase header
                Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, Left))

                'Add all columns within row that were selected as filled earlier
                For Each col In wantedColumn
                    Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, col))
                Next col

                'Union final total column
                Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, Right))
            End If
        Next rowCounter

    End If

    'Copy schema for table 7
    ' !Omitted for length

    'Copy range
    'MsgBox RangeToCopy.Text
    'MsgBox RangeToCopy.Value
    RangeToCopy.Copy
    '.Range("A42").PasteSpecial Paste:=xlValues

End With

'MsgBox Range.Text
Selection.PasteExcelTable False, True, False
'Selection.PasteSpecial DataType:=wdPasteRTF
Selection.MoveUp Unit:=wdLine, count:=11
Selection.MoveDown Unit:=wdLine, count:=1
ActiveWindow.View.ShowXMLMarkup = wdToggle
ActiveDocument.ToggleFormsDesign
Selection.Tables(1).Style = "StandardAngebotTable"

'Release object references
oWB.Close SaveChanges:=True
Set oWB = Nothing

Set RangeToCopy = Nothing

oXL.Quit
Set oXL = Nothing

'quit
Exit Sub

' Error Handler

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

The changing of table style and pasting into the correct position works exactly as expected, but using the exact same code from excel with Excel library calls doesn't function as expected.

Instead of getting a nice disjointed copy/paste, I always copy past the entire table, or more specifically a rectangle from the top-left most cell to the bottom-right most cell.

Does anyone know a way to force word vba to use the same copy/paste commands from excel? The other idea I had was to just fill the table cell for cell, but that would require quite a bit of code restructuring and would be nice if I didn't need to do that. Thanks for the help!

答:
Personally, I'd try using

Selection.PasteSpecial DataType:=wdPasteHTML

or

Selection.PasteSpecial DataType:=wdPasteOLEObject

instead of

Selection.PasteExcelTable False, True, False

If this one isn't what you expect, here are the other members of that Enum :

Body:
I'm trying to copy disjointed cells from an excel document to the cursor location in word and use my predefined table style.

The disjoint copy/paste works nicely in excel when I just copy and paste into the current active worksheet, but as soon as I try to execute the same copy/paste from word, it ends up copying the entire table from top-left all the way to bottom-right, instead of doing the disjointed copy/paste.

I know there are some differences between the individual function from excel VBA to word VBA, but I thought it's possible to get around that by specifying the library when calling functions.

Seen below is a successful disjointed copy:

Successful Disjointed Copy

Here is the functioning excel code, edited for length.

The code within if Copy3 is the interesting part:

Sub GrabExcelTables()

' !Initializing everything

Dim phasesArray As Variant
phasesArray = Array("Scoping", "Umsetzung (Dev)", "Go Live")

With wsFrom

    'Copy schema for tables 1 and 2
    ' !Omitted for length

    'Copy schema for tables 3 and 4
    ' !Omitted for length

    'Copy schema for tables 5 and 6
    If Copy3 Then

        'Iterate through all columns to find which ones are filled
        For colCounter = Left + 1 To Right - 1
            If .Cells(22, colCounter).Value <> "-" Then
                wantedColumn.Add colCounter
            End If
        Next colCounter

        'Initialize RangeToCopy with top left cell of table
        Set RangeToCopy = .Cells(22, Left)

        'Iterate through all rows
        For rowCounter = 22 To 29

            'Only check those rows desired i.e.  part of phasesArray
            If (IsInArray(.Cells(rowCounter, Left).Value, phasesArray) Or rowCounter = 22 Or rowCounter = 29) Then

                'Union row phase header
                Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, Left))

                'Add all columns within row that were selected as filled earlier
                For Each col In wantedColumn
                    Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, col))
                Next col

                'Union final total column
                Set RangeToCopy = Union(RangeToCopy, .Cells(rowCounter, Right))
            End If
        Next rowCounter
    End If

    'Copy schema for table 7
    ' !Omitted for length

    'Copy range
    RangeToCopy.Copy
    .Range("A42").PasteSpecial Paste:=xlValues

End With

Set RangeToCopy = Nothing

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

Now pretty much the same code except adapted to word VBA, again edited for length:

Sub GrabExcelTables()

' !Initializing everything

Dim phasesArray As Variant
phasesArray = Array("Scoping", "Umsetzung (Dev)", "Go Live")

'specify the workbook to work on
WorkbookToWorkOn = ActiveDocument.Path & "\Kalkulationssheet_edit.xlsx"

Set oXL = CreateObject("Excel.Application")

On Error GoTo Err_Handler

'Open the workbook
Set oWB = Workbooks.Open(FileName:=WorkbookToWorkOn)

Set wsFrom = oWB.Sheets(7)

' !Initializing everything

With wsFrom

    'Copy schema for tables 1 and 2
    ' !Omitted for length

    'Copy schema for tables 3 and 4
    ' !Omitted for length

    'Copy schema for tables 5 and 6
    If Copy3 Then

        'Iterate through all columns to find which ones are filled
        For colCounter = Left + 1 To Right - 1
            If .Cells(22, colCounter).Value <> "-" Then
                wantedColumn.Add colCounter

                'MsgBox "Wanted Column: " & colCounter

            End If
        Next colCounter

        'Initialize RangeToCopy with top left cell of table
        Set RangeToCopy = .Cells(22, Left)

        'Iterate through all rows
        For rowCounter = 22 To 29

            'Only check those rows desired i.e.  part of phasesArray
            If (IsInArray(.Cells(rowCounter, Left).Value, phasesArray) Or rowCounter = 22 Or rowCounter = 29) Then

                'MsgBox "rowCounter: " & rowCounter & "cell value: " & .Cells(rowCounter, Left).Value

                'Union row phase header
                Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, Left))

                'Add all columns within row that were selected as filled earlier
                For Each col In wantedColumn
                    Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, col))
                Next col

                'Union final total column
                Set RangeToCopy = Excel.Union(RangeToCopy, .Cells(rowCounter, Right))
            End If
        Next rowCounter

    End If

    'Copy schema for table 7
    ' !Omitted for length

    'Copy range
    'MsgBox RangeToCopy.Text
    'MsgBox RangeToCopy.Value
    RangeToCopy.Copy
    '.Range("A42").PasteSpecial Paste:=xlValues

End With

'MsgBox Range.Text
Selection.PasteExcelTable False, True, False
'Selection.PasteSpecial DataType:=wdPasteRTF
Selection.MoveUp Unit:=wdLine, count:=11
Selection.MoveDown Unit:=wdLine, count:=1
ActiveWindow.View.ShowXMLMarkup = wdToggle
ActiveDocument.ToggleFormsDesign
Selection.Tables(1).Style = "StandardAngebotTable"

'Release object references
oWB.Close SaveChanges:=True
Set oWB = Nothing

Set RangeToCopy = Nothing

oXL.Quit
Set oXL = Nothing

'quit
Exit Sub

' Error Handler

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

The changing of table style and pasting into the correct position works exactly as expected, but using the exact same code from excel with Excel library calls doesn't function as expected.

Instead of getting a nice disjointed copy/paste, I always copy past the entire table, or more specifically a rectangle from the top-left most cell to the bottom-right most cell.

Does anyone know a way to force word vba to use the same copy/paste commands from excel? The other idea I had was to just fill the table cell for cell, but that would require quite a bit of code restructuring and would be nice if I didn't need to do that. Thanks for the help!


问:
Update Model value in ajax post in c#?
I have to update my model and then my view in jquery ajax post

below is my textbox

```<code>@model MvcApplication2.Models.Gender

@Html.TextBoxFor(m => m.id, new { @class = "form-control", @readonly = "readonly" })
</code>```

i am having another normal textbox with read only false. White updating this second input box this first box need to be update (like angular but i dont want to use any template) with value given in post

Ajax post that called on second textbox focusout

```<code>function onChange(args) {
        var value = JSON.stringify({ empcode: 0});
        $.ajax({
            type: "Post",
            url: '@Url.Action("UpdateCode1", "Button")',
            data: value ,
            contentType: 'application/json',

        });
    }
</code>```

Here i am getting my value properly and i am posting this to below controller

```<code>[HttpPost]
    public ActionResult UpdateCode1(Gender empcode)
    {
        return PartialView("UpdateCode1", empcode);
    }
</code>```

but its not updating textboxfor value

Any suggestion?

答:
You need a function on success of the ajax to perform what needs to be done with the response of the ajax call.

```<code>    $.ajax({
        type...
        .... json',
        success: function (response) {
            $("#DivSelector").html(response);
        }
    });
    </script>
</code>```

And make a div surrounding the first text box so that the content can be refreshed after ajax call.

```<code>   <div id="DivSelector">
       @Html.TextBoxFor(m => m.id, new { @class = "form-control", @readonly = "readonly" })
   </div>
</code>```

If just to update one textbox with other textbox content is the requirement then why need ajax and controller ?? Can be just done with jquery alone.

Title: Update Model value in ajax post in c#?

Body:
I have to update my model and then my view in jquery ajax post

below is my textbox

@model MvcApplication2.Models.Gender

@Html.TextBoxFor(m => m.id, new { @class = "form-control", @readonly = "readonly" })

i am having another normal textbox with read only false. White updating this second input box this first box need to be update (like angular but i dont want to use any template) with value given in post

Ajax post that called on second textbox focusout

function onChange(args) {
        var value = JSON.stringify({ empcode: 0});
        $.ajax({
            type: "Post",
            url: '@Url.Action("UpdateCode1", "Button")',
            data: value ,
            contentType: 'application/json',

        });
    }

Here i am getting my value properly and i am posting this to below controller

[HttpPost]
    public ActionResult UpdateCode1(Gender empcode)
    {
        return PartialView("UpdateCode1", empcode);
    }

but its not updating textboxfor value

Any suggestion?

Body:
You need a function on success of the ajax to perform what needs to be done with the response of the ajax call.

    $.ajax({
        type...
        .... json',
        success: function (response) {
            $("#DivSelector").html(response);
        }
    });
    </script>

And make a div surrounding the first text box so that the content can be refreshed after ajax call.

   <div id="DivSelector">
       @Html.TextBoxFor(m => m.id, new { @class = "form-control", @readonly = "readonly" })
   </div>

If just to update one textbox with other textbox content is the requirement then why need ajax and controller ?? Can be just done with jquery alone.


问:
Detect face from Live Video with Microsoft Cognitive service
Currently, Working on project for detect face from Live Video and for this I am using MS cognitive service face api.
Previously,it is working fine but from today it is not working and gives error when I call face detect method.
The error like as "Rate limit is exceeded. Try again later."
Please suggest me what I need to do.</p>

答:
As the error says, you reached the limit of the free offer. You can not send more informations to decode for free.

The Video API says : "Free: 300 calls per month per feature"

You certainly reached the limit of 300 calls

EDIT

Moreover @cthrash specified that you can't send more than 5 reqs per minutes for getResults and 1 per minute for the other services


问:
Kentico: How to redirect based on document type field
I have a certain document type in Kentico that has a boolean field that when true i need the page to redirect to another URL (in this case a 404 page).

Where is the best place to do this?

and how do i access the kentico data context in code so that i can write code that pulls the document types field and redirects based on it (because currently trying to access Dataitem("MyFieldName") errors because Kentico doesn't use DataItem for data binding, even though Eval("MyFieldName") still works.

答:
If you only want to be able to redirect a page to another page. Kentico already have something built in, just go to the Page->Properties->Menu. In the menu actions section you can specify a URL for redirection.

Otherwise for requirement described you can get the boolean value by:

```<code>if(ValidationHelper.GetBoolean(
    CMSContext.CurrentDocument.GetValue("MyFieldName"), false)))
{
    Response.Redirect("/404.aspx");
}
</code>```

Body:
If you only want to be able to redirect a page to another page. Kentico already have something built in, just go to the Page->Properties->Menu. In the menu actions section you can specify a URL for redirection.

Otherwise for requirement described you can get the boolean value by:

if(ValidationHelper.GetBoolean(
    CMSContext.CurrentDocument.GetValue("MyFieldName"), false)))
{
    Response.Redirect("/404.aspx");
}


问:
Changing the Content-Type in axios header to fix a 415 error
I am trying to send a file to my back-end through an axios post request.

This is the error I currently have:

cherrypy._cperror.HTTPError: (415, 'Expected an entity of content
  type application/json, text/javascript')

From what I have read I need to change the Content-Type in my post request, I looked around I am currently attempting to do so like this:

```<code>handleUploadButton(e){
            const upload_file = this.state.file;
            const formData = new FormData();
            formData.append('file', upload_file);
            const request = axios.post(someUrl, formData, {headers: {
                "Content-Type": "application/json"}
            })
                .then(function (response) {
                    console.log('successfully uploaded', upload_file);
                });
    }
</code>```

Not sure if relevant, but all this is happening through a reactjs form.
This is my current Content-Type: Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBwjjjGuJEySeXdRU

I have no idea where to go from here. Any help would be greatly appreciated.

答:
In order to make axios include Content-Type: application-json you need to do that:

```<code>javascript
window.axios = require('axios')
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
</code>```

Body:
I am trying to send a file to my back-end through an axios post request.

This is the error I currently have:

cherrypy._cperror.HTTPError: (415, 'Expected an entity of content
  type application/json, text/javascript')

From what I have read I need to change the Content-Type in my post request, I looked around I am currently attempting to do so like this:

handleUploadButton(e){
            const upload_file = this.state.file;
            const formData = new FormData();
            formData.append('file', upload_file);
            const request = axios.post(someUrl, formData, {headers: {
                "Content-Type": "application/json"}
            })
                .then(function (response) {
                    console.log('successfully uploaded', upload_file);
                });
    }

Not sure if relevant, but all this is happening through a reactjs form.
This is my current Content-Type: Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBwjjjGuJEySeXdRU

I have no idea where to go from here. Any help would be greatly appreciated.

Body:
In order to make axios include Content-Type: application-json you need to do that:

javascript
window.axios = require('axios')
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'


问:
Actual JFrame size does not match with declared
Im using Java on MacOS. Actual screen resolution is 2560x1600. But JFrame with size 1200x900 or more doesnt fit into the screen.

```<code>JFrame frame = new JFrame();
frame.setBounds(0,0,1200,900);
frame.setLayout(null);
frame.setVisible(true);
</code>```

Furthermore this:

```<code>JFrame frame = new JFrame();
frame.setBounds(0,0,3000,3000);
frame.setLayout(null);
frame.setVisible(true);
System.out.println(frame.getWidth() + "x" + frame.getHeight());
</code>```

outputs 1280x773. Why does this happen and how to deal with it?

EDIT: There is x2 scale. Might be because of retina and OS configurations. Looking for the way to change that scale.

答:
try to add frame.pack() to your code here is how you should type

```<code>    JFrame frame = new JFrame();
    frame.setBounds(0,0,3000,3000);
    frame.setLayout(null);
    frame.setVisible(true);
</code>```

frame.pack();
        System.out.println(frame.getWidth() + "x" + frame.getHeight());

Body:
Im using Java on MacOS. Actual screen resolution is 2560x1600. But JFrame with size 1200x900 or more doesnt fit into the screen.

JFrame frame = new JFrame();
frame.setBounds(0,0,1200,900);
frame.setLayout(null);
frame.setVisible(true);

Furthermore this:

JFrame frame = new JFrame();
frame.setBounds(0,0,3000,3000);
frame.setLayout(null);
frame.setVisible(true);
System.out.println(frame.getWidth() + "x" + frame.getHeight());

outputs 1280x773. Why does this happen and how to deal with it?

EDIT: There is x2 scale. Might be because of retina and OS configurations. Looking for the way to change that scale.

Body:
try to add frame.pack() to your code here is how you should type

    JFrame frame = new JFrame();
    frame.setBounds(0,0,3000,3000);
    frame.setLayout(null);
    frame.setVisible(true);

frame.pack();
        System.out.println(frame.getWidth() + "x" + frame.getHeight());


问:
check for duplicates in diffrent worksheets and thereafter print value
I have searched but i cant seem to figure out how to print specified value in the column next to where i find my duplicate. What i have since earlier are code that first specify the diffrent ranges and thereafter look if a duplicate is found in sheet Y from sheet X. Sheet Le is this weeks information and sheet Be is the last weeks information.

IF i find a duplicate in the specified range i want to on my Delivery sheet print in column A next to the duplicate either Delivered or not delivered depending on if my output from function compareAEO print true or false.

The conditions that i am looking for are that if the we can find the same value that are in column B in sheet (Le) on sheet (Be) it will then check if the text in column F has changed. IF SO then it shall print in column A on sheet (Le) = Delivered. Otherwise not delivered.

It then checks to se if the dates in column M is the same. IF not then it shall print Replanned in column A on sheet (Le).

Shortly
IF value in cell on column B, Sheet (Le) = Value in column B, Sheet (Be) then
value in column A on sheet Le = "Delivered" Else "not deliverd".

Then

If value in cell in column M, Sheet (Le) <> If value in cell in column M, Sheet (Be) then value in column A, Sheet(Le) = "replanned"

This is how my data looks like,
Sheet (Le)

```<code>Col B   Col F    Col M
PZ2408  X13    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X45    2017-02-25
PZ2513  X13    2017-02-10
PZ2533  X70    2017-02-05
PZ2561  X60    2017-02-20
</code>```

For sheet (Be) my data looks like this

```<code>Col B   Col F    Col M
PZ2408  X30    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X30    2017-02-25
PZ2513  X13    2017-02-05
PZ2533  X13    2017-02-10
PZ2561  X60    2017-02-17
</code>```

After the code has done its course i would like it to show for example,

Sheet (Le)

```<code>    col A           Col B   Col F    Col M
   Delivered       PZ2408   X13    2017-02-13
Not Delivered      PZ2345   X30    2017-02-23
   Delivered       PZ2463   X45    2017-02-25
  replanned        PZ2513   X13    2017-02-10
   Delivered       PZ2533   X70    2017-02-05
   replanned       PZ2561   X60    2017-02-20
</code>```

Bascilly my Not delivered, delivered and Replanned statements does not work and my brain does not work.

Can SO help save my day?

```<code>Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowSource As Long
Dim lastRowTarget As Long
Dim row As Long
Dim ASMT As String

'Looping trough Range
With ThisWorkbook.Worksheets("Le")

   lastRowTarget = .Range("B" & .Rows.Count).End(xlUp).row
   For i = 29 To lastRowTarget
        ASMT = .Range("b" & i).value
        'Define range and see if we can find duplicates
        With ThisWorkbook.Worksheets("Be")
            lastRowSource = .Range("B" & .Rows.Count).End(xlUp).row
            Set rng1 = .Range("B3", "B" & lastRowSource)

            row = findValueInRangeReturnRow(rng1, ASMT)

            'Check FAX
            If compareAEO(i, row, "FAX") = True Then
                'Debug.Print compareASMT(i, row, "FAX")
                Worksheets("Le").Cells(i, ASMT).value = "Not Delivered"

                Else

                .Worksheets("Le").Cells(i, ASMT).value = "delivered"

                'Check if dax are correct
                If compareAEO(i, row, "DAX") = False Then
                .Worksheets("Le").ASMT.Offset(0, 1).value = "Replan"

            End If

        End With
    Next i

End With

 End Sub
</code>```

here are my first function

```<code> Function findValueInRangeReturnRow(rng As Range, value As Variant) As Long

        Set c = rng.Find(value, LookIn:=xlValues)

        If Not c Is Nothing Then

            findValueInRangeReturnRow = c.row

        End If

End Function
</code>```

My second function that checks if duplicates are found in specified ranges.

```<code>Function compareAEO(rad1 As Variant, rad2 As Variant, typeCOMPARE As String) As Boolean

Dim col1 As String
Dim col2 As String

  Select Case typeCOMPARE
    Case "FAX"
        col1 = "F"
        col2 = "F"

    Case "DAX"
        col1 = "M"
        col2 = "M"

    End Select

   If ThisWorkbook.Worksheets("Le").Range(col1 & rad1).value =   ThisWorkbook.Worksheets("Be").Range(col2 & rad2).value Then

    compareAEO = True
    Else

    compareAEO = False
End If

End Function
</code>```

答:
You were getting the last row of both pages in each loop.  It is only necessary to get them once at the top, outside the loop.  Same for the range you were setting.  You can see that I put them at the top, before the loop.

I don't really know what you were using ASMT for.  It looks like you were trying to use it as a range in some of your coding instead of range("B" & I).  I used strings in the "B" column of Le to compare to the "B" column of Be when I tested it.

It works for me.  You'll have to change it to suit your needs.  You don't need all the functions, what they accomplished are all within this subroutine.

```<code>Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowLE As Long
Dim lastRowBe As Long
Dim row As Long
Dim ASMT As String
Dim LEws As Worksheet
Dim tmpRng As Range

    Set LEws = Worksheets("Le")
    lastRowLE = Sheets("Le").Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row
    lastRowBe = Sheets("Be").Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row
    Set rng1 = Sheets("Be").Range("B3", "B" & lastRowBe)

   For i = 29 To lastRowLE
        Set tmpRng = Sheets("Le").Range("b" & i)
        ASMT = tmpRng.Value

        Set c = rng1.Find(ASMT, LookIn:=xlValues)
        If Not c Is Nothing Then
                row = c.row
                If ThisWorkbook.Worksheets("Le").Range("F" & i).Value = ThisWorkbook.Worksheets("Be").Range("F" & row).Value Then
'                    Worksheets("Le").Cells(i, ASMT).Value = "Not Delivered"
'                   Did you intend to use ASMT as the column number?
'                   I'm going to hard code that as column 27 for my purposes.  You can change it if you need to
                    LEws.Cells(i, 27).Value = "Not Delivered"   ' column 27 is "AA"
                Else
                    LEws.Cells(i, 27).Value = "Delivered"
                End If
                If ThisWorkbook.Worksheets("Le").Range("M" & i).Value = ThisWorkbook.Worksheets("Be").Range("M" & row).Value Then
'                    .Worksheets("Le").ASMT.Offset(0, 1).Value = "Replan"
'                       again I don't understand the reference to ASMT.  That is a string value - unless it is a numeric value in the string
'                       I'm going to assume that you intended for "Replan" to go into column C on row i
                Else
                    LEws.Range("C" & i).Value = "Replan"
                End If
         End If
    Next i

 End Sub
</code>```

Body:
I have searched but i cant seem to figure out how to print specified value in the column next to where i find my duplicate. What i have since earlier are code that first specify the diffrent ranges and thereafter look if a duplicate is found in sheet Y from sheet X. Sheet Le is this weeks information and sheet Be is the last weeks information.

IF i find a duplicate in the specified range i want to on my Delivery sheet print in column A next to the duplicate either Delivered or not delivered depending on if my output from function compareAEO print true or false.

The conditions that i am looking for are that if the we can find the same value that are in column B in sheet (Le) on sheet (Be) it will then check if the text in column F has changed. IF SO then it shall print in column A on sheet (Le) = Delivered. Otherwise not delivered.

It then checks to se if the dates in column M is the same. IF not then it shall print Replanned in column A on sheet (Le).

Shortly
IF value in cell on column B, Sheet (Le) = Value in column B, Sheet (Be) then
value in column A on sheet Le = "Delivered" Else "not deliverd".

Then

If value in cell in column M, Sheet (Le) <> If value in cell in column M, Sheet (Be) then value in column A, Sheet(Le) = "replanned"

This is how my data looks like,
Sheet (Le)

Col B   Col F    Col M
PZ2408  X13    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X45    2017-02-25
PZ2513  X13    2017-02-10
PZ2533  X70    2017-02-05
PZ2561  X60    2017-02-20

For sheet (Be) my data looks like this

Col B   Col F    Col M
PZ2408  X30    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X30    2017-02-25
PZ2513  X13    2017-02-05
PZ2533  X13    2017-02-10
PZ2561  X60    2017-02-17

After the code has done its course i would like it to show for example,

Sheet (Le)

    col A           Col B   Col F    Col M
   Delivered       PZ2408   X13    2017-02-13
Not Delivered      PZ2345   X30    2017-02-23
   Delivered       PZ2463   X45    2017-02-25
  replanned        PZ2513   X13    2017-02-10
   Delivered       PZ2533   X70    2017-02-05
   replanned       PZ2561   X60    2017-02-20

Bascilly my Not delivered, delivered and Replanned statements does not work and my brain does not work.

Can SO help save my day?

Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowSource As Long
Dim lastRowTarget As Long
Dim row As Long
Dim ASMT As String

'Looping trough Range
With ThisWorkbook.Worksheets("Le")

   lastRowTarget = .Range("B" & .Rows.Count).End(xlUp).row
   For i = 29 To lastRowTarget
        ASMT = .Range("b" & i).value
        'Define range and see if we can find duplicates
        With ThisWorkbook.Worksheets("Be")
            lastRowSource = .Range("B" & .Rows.Count).End(xlUp).row
            Set rng1 = .Range("B3", "B" & lastRowSource)

            row = findValueInRangeReturnRow(rng1, ASMT)

            'Check FAX
            If compareAEO(i, row, "FAX") = True Then
                'Debug.Print compareASMT(i, row, "FAX")
                Worksheets("Le").Cells(i, ASMT).value = "Not Delivered"

                Else

                .Worksheets("Le").Cells(i, ASMT).value = "delivered"

                'Check if dax are correct
                If compareAEO(i, row, "DAX") = False Then
                .Worksheets("Le").ASMT.Offset(0, 1).value = "Replan"

            End If

        End With
    Next i

End With

 End Sub

here are my first function

 Function findValueInRangeReturnRow(rng As Range, value As Variant) As Long

        Set c = rng.Find(value, LookIn:=xlValues)

        If Not c Is Nothing Then

            findValueInRangeReturnRow = c.row

        End If

End Function

My second function that checks if duplicates are found in specified ranges.

Function compareAEO(rad1 As Variant, rad2 As Variant, typeCOMPARE As String) As Boolean

Dim col1 As String
Dim col2 As String

  Select Case typeCOMPARE
    Case "FAX"
        col1 = "F"
        col2 = "F"

    Case "DAX"
        col1 = "M"
        col2 = "M"

    End Select

   If ThisWorkbook.Worksheets("Le").Range(col1 & rad1).value =   ThisWorkbook.Worksheets("Be").Range(col2 & rad2).value Then

    compareAEO = True
    Else

    compareAEO = False
End If

End Function

Body:
You were getting the last row of both pages in each loop.  It is only necessary to get them once at the top, outside the loop.  Same for the range you were setting.  You can see that I put them at the top, before the loop.

I don't really know what you were using ASMT for.  It looks like you were trying to use it as a range in some of your coding instead of range("B" & I).  I used strings in the "B" column of Le to compare to the "B" column of Be when I tested it.

It works for me.  You'll have to change it to suit your needs.  You don't need all the functions, what they accomplished are all within this subroutine.

Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowLE As Long
Dim lastRowBe As Long
Dim row As Long
Dim ASMT As String
Dim LEws As Worksheet
Dim tmpRng As Range

    Set LEws = Worksheets("Le")
    lastRowLE = Sheets("Le").Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row
    lastRowBe = Sheets("Be").Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row
    Set rng1 = Sheets("Be").Range("B3", "B" & lastRowBe)

   For i = 29 To lastRowLE
        Set tmpRng = Sheets("Le").Range("b" & i)
        ASMT = tmpRng.Value

        Set c = rng1.Find(ASMT, LookIn:=xlValues)
        If Not c Is Nothing Then
                row = c.row
                If ThisWorkbook.Worksheets("Le").Range("F" & i).Value = ThisWorkbook.Worksheets("Be").Range("F" & row).Value Then
'                    Worksheets("Le").Cells(i, ASMT).Value = "Not Delivered"
'                   Did you intend to use ASMT as the column number?
'                   I'm going to hard code that as column 27 for my purposes.  You can change it if you need to
                    LEws.Cells(i, 27).Value = "Not Delivered"   ' column 27 is "AA"
                Else
                    LEws.Cells(i, 27).Value = "Delivered"
                End If
                If ThisWorkbook.Worksheets("Le").Range("M" & i).Value = ThisWorkbook.Worksheets("Be").Range("M" & row).Value Then
'                    .Worksheets("Le").ASMT.Offset(0, 1).Value = "Replan"
'                       again I don't understand the reference to ASMT.  That is a string value - unless it is a numeric value in the string
'                       I'm going to assume that you intended for "Replan" to go into column C on row i
                Else
                    LEws.Range("C" & i).Value = "Replan"
                End If
         End If
    Next i

 End Sub


问:
Shiny DownloadHandler doesn't update filename using Sys.time()
How do you get a downloadHandler in shiny to update the value of filename after every click on the download button? I try to construct a unique filename using Sys.time. Alas, Sys.time() appears to be executed only once when the Shiny app is opened. Hence, an attempt to download the file a second time doesn't give a new filename, it just gives a [1] at the end of the file name.

Minimal reproducible example below:

```<code>library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = paste("example",gsub(":","-",Sys.time()), ".csv", sep=""),
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}
</code>```

Make sure you try to download the file a second time within the same instance, checking the name on the file.

答:
This is because you don't give a function but a value as argument for filename. That's the reason you always have the same filename: a value is assigned when the downloadHandler is initiated, whereas a function is evaluated at every click on the downloadButton.

So wrap your code for the filename in a function, and your problem is solved:

```<code>library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = function(){
        paste("example",gsub(":","-",Sys.time()), ".csv", sep="")
        },
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}
</code>```

This information can also be found on the following article of RStudio:

https://shiny.rstudio.com/articles/download.html

Body:
How do you get a downloadHandler in shiny to update the value of filename after every click on the download button? I try to construct a unique filename using Sys.time. Alas, Sys.time() appears to be executed only once when the Shiny app is opened. Hence, an attempt to download the file a second time doesn't give a new filename, it just gives a [1] at the end of the file name.

Minimal reproducible example below:

library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = paste("example",gsub(":","-",Sys.time()), ".csv", sep=""),
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}

Make sure you try to download the file a second time within the same instance, checking the name on the file.

Body:
This is because you don't give a function but a value as argument for filename. That's the reason you always have the same filename: a value is assigned when the downloadHandler is initiated, whereas a function is evaluated at every click on the downloadButton.

So wrap your code for the filename in a function, and your problem is solved:

library(shiny)

if (interactive()) {

  ui <- fluidPage(
    downloadButton("downloadData", "Download")
  )

  server <- function(input, output) {
    # Our dataset
    data <- mtcars

    output$downloadData <- downloadHandler(
      filename = function(){
        paste("example",gsub(":","-",Sys.time()), ".csv", sep="")
        },
      content = function(file) {
        write.csv(mtcars,file)
      }
    )
  }

  runApp(list(ui=ui,server=server),launch.browser=T)
}

This information can also be found on the following article of RStudio:

https://shiny.rstudio.com/articles/download.html


问:
How to change query type for drag and drop action in SQLDeveloper
In SQLDeveloper there is a feature which generates query when you drag and drop table from connection browser to worksheet. There is a window which asks if one want select, update or delete query to be generated. I've marked once select and checked the box to not ask again. Now when I drag and drop I got always select without pop-up window.

How can I change query that is generated (I need insert not select) without reinstalling SQLDeveloper?

答: Go into the preferences. Database page. Then on 'Drag and Drop.'


问:
Getting data from main program
I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.

public class ATM {

```<code>public static Scanner kbd;

public static void main(String[] args) {
    String acctNum, acctPword;
    String balance;
    int x = 1;
    kbd = new Scanner(System.in);

    System.out.print("Enter your account number: ");
    acctNum = kbd.nextLine();

    System.out.print("Enter your account password: ");
    acctPword = kbd.nextLine();
    balance = checkID(acctNum, acctPword);
    double balance1 = Double.parseDouble(balance);
    System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************

    while (balance.equals("error") && x <4){
        System.out.println("Wrong password try again.");
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        x++;
    }

    if (x == 4)
        System.out.println("Maximum number of attempts reached, Please try again later.");

    if (x == 1){
        menu();
    }

    kbd.close();
}

/**
 * Determines if acctNum is a valid account number, and pwd is the correct
 * password for the account.
 * @param acctNum The account number to be checked
 * @param pwd The password to be checked
 * @return If the account information is valid, returns the current account
 * balance, as a string. If the account information is invalid, returns
 * the string "error".
 */
public static String checkID(String acctNum, String pwd)
{
    String result = "error";

    // Strings a, b, and c contain the valid account numbers and passwords.
    // For each string, the account number is listed first, followed by
    // a space, followed by the password for the account, followed by a space,
    // followed by the current balance.
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
        result = "520.36";
        return result;
    }

    if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
        result = "48.20";
        return result;
    }

    if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
        result = "96.74";
        return result;
    }

    return result;
}

public static void menu(){
    int x = 0;
    double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.

    System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
    x = kbd.nextInt();
    switch(x){
    case 1:
        displayBalance(acctBal);
        break;
    case 2:
        deposit(acctBal, deposit);
        break;
    case 3:
        withdraw(acctBal, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        break;
    }

}

public static double deposit(double acctBal, double depAmnt){

    System.out.print("How much money would you like to deposit? $");
    depAmnt = kbd.nextDouble();
    acctBal = acctBal + depAmnt;
    System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
    return acctBal;
}

public static double withdraw(double acctBal, double withAmnt){

    System.out.print("How much money would you like to withdraw? $");
    withAmnt = kbd.nextDouble();

    if (acctBal <= 0){
        System.out.println("You do not have any money.");
        return acctBal;
    }

    if (acctBal < withAmnt){
        System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();
    }
    else{
        acctBal = acctBal - withAmnt;
    }

    return acctBal;
}

public static double displayBalance(double balance){
    System.out.println("Your balance is $" + String.format("%.2f", balance));
    return balance;
}
</code>```

答:
Your code has a problem, you do not treat the situation where checkID returns "error". You cannot assign "error" to some String and then try to convert a double from that String.

Minor fix

```<code>balance = checkID(acctNum, acctPword);
double balance1 = 0.0;

if (balance.equals("error"))
{
    // TODO: do something with invalid number.
}
else
{
    balance1 = Double.parseDouble(balance);
}
System.out.println("You currently have $" + String.format("%.2f",balance1));
</code>```

Title: Getting data from main program

Body:
I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.

public class ATM {

public static Scanner kbd;

public static void main(String[] args) {
    String acctNum, acctPword;
    String balance;
    int x = 1;
    kbd = new Scanner(System.in);

    System.out.print("Enter your account number: ");
    acctNum = kbd.nextLine();

    System.out.print("Enter your account password: ");
    acctPword = kbd.nextLine();
    balance = checkID(acctNum, acctPword);
    double balance1 = Double.parseDouble(balance);
    System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************

    while (balance.equals("error") && x <4){
        System.out.println("Wrong password try again.");
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        x++;
    }

    if (x == 4)
        System.out.println("Maximum number of attempts reached, Please try again later.");

    if (x == 1){
        menu();
    }

    kbd.close();
}

/**
 * Determines if acctNum is a valid account number, and pwd is the correct
 * password for the account.
 * @param acctNum The account number to be checked
 * @param pwd The password to be checked
 * @return If the account information is valid, returns the current account
 * balance, as a string. If the account information is invalid, returns
 * the string "error".
 */
public static String checkID(String acctNum, String pwd)
{
    String result = "error";

    // Strings a, b, and c contain the valid account numbers and passwords.
    // For each string, the account number is listed first, followed by
    // a space, followed by the password for the account, followed by a space,
    // followed by the current balance.
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
        result = "520.36";
        return result;
    }

    if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
        result = "48.20";
        return result;
    }

    if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
        result = "96.74";
        return result;
    }

    return result;
}

public static void menu(){
    int x = 0;
    double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.

    System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
    x = kbd.nextInt();
    switch(x){
    case 1:
        displayBalance(acctBal);
        break;
    case 2:
        deposit(acctBal, deposit);
        break;
    case 3:
        withdraw(acctBal, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        break;
    }

}

public static double deposit(double acctBal, double depAmnt){

    System.out.print("How much money would you like to deposit? $");
    depAmnt = kbd.nextDouble();
    acctBal = acctBal + depAmnt;
    System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
    return acctBal;
}

public static double withdraw(double acctBal, double withAmnt){

    System.out.print("How much money would you like to withdraw? $");
    withAmnt = kbd.nextDouble();

    if (acctBal <= 0){
        System.out.println("You do not have any money.");
        return acctBal;
    }

    if (acctBal < withAmnt){
        System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();
    }
    else{
        acctBal = acctBal - withAmnt;
    }

    return acctBal;
}

public static double displayBalance(double balance){
    System.out.println("Your balance is $" + String.format("%.2f", balance));
    return balance;
}

Body:
Your code has a problem, you do not treat the situation where checkID returns "error". You cannot assign "error" to some String and then try to convert a double from that String.

Minor fix

balance = checkID(acctNum, acctPword);
double balance1 = 0.0;

if (balance.equals("error"))
{
    // TODO: do something with invalid number.
}
else
{
    balance1 = Double.parseDouble(balance);
}
System.out.println("You currently have $" + String.format("%.2f",balance1));


问:
C++ Unit Tests, mocking objects
I'm currently looking at some unit test librarys in C++ and have some questions:

there seem to be no mocking facility in boost.test but I can hardly think of doing unit tests without creating mock objects/functions. How would you do that in boost.test, are you doing it manually (how? I mean, there are several ways I can think of, none of these seem nice) or are you simply doing without mock objects?

googletest and googlemock looks like nice libraries with mockingsupport however, it requires every object that shall be mocked to be virtual. I don't really like this, it is not that I'm worrying about the performance (I could define a macro to get it out of production code anyway) but I find this very intrusive. I wonder if there's another solution which does not require that much change to the existing code? (love clojure there)

答:
Boost::Test does not have a mocking framework or library. If you want mocks, you have to do it yourself, or use something like GMock. Of course, you could use google mock with Boost::Test without problems.

How else would you expect something to be mockable? That's how it works in every other programming language! (Okay, not with duck typing, but that carries more overhead than virtual methods) If you're concerned about performance:

Implement everything in terms of virtuals as specified in the general google mock docs.

Profile your code for places where that's not sufficient

Replace those profiled sections (or rather, the segment of your code which indicates performance is a problem) with high-perf dependency injection instead.

Don't replace everything with high-perf DI, because that would send compile times through the roof.

In all seriousness though, I don't think the virtual calls are going to make huge differences in performance. The one case where virtuals are bad are where they're located inside of inner loops (such as in the iostream library where they're called possibly for every character of input or output), and even then only in performance sensitive code.

EDIT: I missed the very important word not in the above question #2 -- that you're  not worried about performance. If that's the case then my answer is you're effectively screwed. A plain function or method call in C++ generates a plain method call, and there's no opprotunity for you to change where that call points. In most cases this doesn't require too much code change, because correct C++ code uses references wherever possible, which won't need to be modified despite the fact that virtuals are being used. You will have to watch out however for anyone using value semantics, because they will be subject to the slicing problem.

Title: C++ Unit Tests, mocking objects