问:
Recursively reading any java Object and pulling out complex types into a hash map
I need to write a utility program which would accept a blank HashMap and any object as arguments and return the HashMap

```<code>public HashMap returnMap(HashMap map,Object parseThisObject){

//logic to strip all children, children of children...... and place it in HashMap
//return map

}
</code>```

This object contains a lot of objects within it and those objects within has a lot of children and the lineage goes on.

My utility must be generic enough to recursively read through all children until it hits primitives in each object, place each of those objects in the hasp map and return it back.
This is something like the parent would be there in the map. but the individual children also would be there as sub sequent entries in the map.

I am new to java reflection and I went through some tutorials and examples on the net. Not very confident about how to proceed. I believe this is one of the frequent requirements experts and professionals over here might have faced.

Plese help me with a starting point on this. If there is any bean utilities open source available to do this? if so please let me know.

答:
Something like this should do it:

```<code>public void fillMap(HashMap<String, Object> map, Object bean) {
    try {
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; i++) {
            Method reader = props[i].getReadMethod();
            if (reader != null && !props[i].getName().equals("class")) {
                Object invoke = reader.invoke(bean, new Object[] {});
                if (invoke != null) {
                    if (!reader.getReturnType().isPrimitive()) {
                        fillMap(map, invoke);
                    } else {
                        map.put(props[i].getName(), invoke);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

this of course puts all fields from all objects into one map. You might have to create a map for each recursion step if you want submaps for children. I can give you that code as well if you need it.

There is no return of a map, because the one that is passed to the method is filled.

Body:
I need to write a utility program which would accept a blank HashMap and any object as arguments and return the HashMap

public HashMap returnMap(HashMap map,Object parseThisObject){

//logic to strip all children, children of children...... and place it in HashMap
//return map

}

This object contains a lot of objects within it and those objects within has a lot of children and the lineage goes on.

My utility must be generic enough to recursively read through all children until it hits primitives in each object, place each of those objects in the hasp map and return it back.
This is something like the parent would be there in the map. but the individual children also would be there as sub sequent entries in the map.

I am new to java reflection and I went through some tutorials and examples on the net. Not very confident about how to proceed. I believe this is one of the frequent requirements experts and professionals over here might have faced.

Plese help me with a starting point on this. If there is any bean utilities open source available to do this? if so please let me know.

Body:
Something like this should do it:

public void fillMap(HashMap<String, Object> map, Object bean) {
    try {
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; i++) {
            Method reader = props[i].getReadMethod();
            if (reader != null && !props[i].getName().equals("class")) {
                Object invoke = reader.invoke(bean, new Object[] {});
                if (invoke != null) {
                    if (!reader.getReturnType().isPrimitive()) {
                        fillMap(map, invoke);
                    } else {
                        map.put(props[i].getName(), invoke);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

this of course puts all fields from all objects into one map. You might have to create a map for each recursion step if you want submaps for children. I can give you that code as well if you need it.

There is no return of a map, because the one that is passed to the method is filled.


来源: stackexchange

问:
join strings in JS
I have an array A and array B:

```<code>A = ["1234","5678","4444"]
B = 7868,9090
</code>```

I want array C to be:

```<code>C = ["1234","5678","4444","7868","9090"]
</code>```

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

答:
For copying an array to another you can use ES6 Spread syntax

```<code>var A = ["1234","5678","4444"];
var B = ["7868","9090"];
var C = [...A, ...B];
console.log(C);
// C will become [1234","5678","4444","7868","9090"];
</code>```

 For, how to use Spread syntax follow this link

Correct way of declaring a string and concatnating it:

```<code>var str_a="123,124";
var str_b ="125,126";
var str_ab= str_a + str_b;
console.log(str_ab);
</code>```

ContentLicense: CC BY-SA 3.0

Title: join strings in JS

Body:
I have an array A and array B:

A = ["1234","5678","4444"]
B = 7868,9090

I want array C to be:

C = ["1234","5678","4444","7868","9090"]

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

Body:
For copying an array to another you can use ES6 Spread syntax

var A = ["1234","5678","4444"];
var B = ["7868","9090"];
var C = [...A, ...B];
console.log(C);
// C will become [1234","5678","4444","7868","9090"];

 For, how to use Spread syntax follow this link

Correct way of declaring a string and concatnating it:

var str_a="123,124";
var str_b ="125,126";
var str_ab= str_a + str_b;
console.log(str_ab);


问:
Dot and Square Bracket Notation
I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var user = {
  name: "John Doe",
  age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);</code>```

The first example returns y to be undefined if in third line I replace the obj[x] with obj.x. Why not "hello"

But in the second example the expression user[key] can simply be replaced with user.key without any anomalous behavior (at-least to me).
Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.

答:
In dot notation, the name after the dot is the name of the property being referenced. So:

```<code>var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj.foo) // = 1, since the "foo" property of obj is 1,
                     //      independent of the variable foo
</code>```

However, in square-bracket notation, the name of the property being referenced is the value  of whatever is in the square brackets:

```<code>var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj[foo])   // = 2, since the value of the variable foo is "bar" and
                        //      the "bar" property of obj is 2

console.log(obj["foo"]) // = 1, since the value of the literal "foo" is "foo" and
                        //      the "foo" property of obj is 1
</code>```

In other words, dot-notation obj.foo is always equivalent to obj["foo"], while obj[foo] depends on the value of the variable foo.

In the specific case of your question, note the differences between dot notation and square-bracket notation:

```<code>// with dot notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj.key = value; // referencing the literal property "key"
console.log(obj) // = { name: "John Doe", age: 30, key: 60 }

// with square bracket notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj[key] = value; // referencing property by the value of the key variable ("age")
console.log(obj)  // = { name: "John Doe", age: 60 }
</code>```

Title: Dot and Square Bracket Notation

Body:
I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

var user = {
  name: "John Doe",
  age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);

The first example returns y to be undefined if in third line I replace the obj[x] with obj.x. Why not "hello"

But in the second example the expression user[key] can simply be replaced with user.key without any anomalous behavior (at-least to me).
Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.

Body:
In dot notation, the name after the dot is the name of the property being referenced. So:

var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj.foo) // = 1, since the "foo" property of obj is 1,
                     //      independent of the variable foo

However, in square-bracket notation, the name of the property being referenced is the value  of whatever is in the square brackets:

var foo = "bar";
var obj = { foo: 1, bar: 2 };

console.log(obj[foo])   // = 2, since the value of the variable foo is "bar" and
                        //      the "bar" property of obj is 2

console.log(obj["foo"]) // = 1, since the value of the literal "foo" is "foo" and
                        //      the "foo" property of obj is 1

In other words, dot-notation obj.foo is always equivalent to obj["foo"], while obj[foo] depends on the value of the variable foo.

In the specific case of your question, note the differences between dot notation and square-bracket notation:

// with dot notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj.key = value; // referencing the literal property "key"
console.log(obj) // = { name: "John Doe", age: 30, key: 60 }

// with square bracket notation
var obj = { name: "John Doe", age: 30 };
var key = "age";
var value = 60;

obj[key] = value; // referencing property by the value of the key variable ("age")
console.log(obj)  // = { name: "John Doe", age: 60 }


问:
A way split an Angular 4 app into user-facing and admin parts
I'm designing an architecture of Angular 4 app. The application will be used by two groups of users: "end-user" and "admin".

I don't want to split the code into two separate applications, because a lot of classes for end-user will also be needed by admins (for example, to preview changes). On the other hand, no classes for admin are required for end-user.

Of course, I don't want to ship scripts for admin to end-user. So I want to have two build plans: full and reduced. This is my vision of the solution, other solutions might be better.

Let me summarize the problem: I need a way to bundle code for end-user separately. But I don't want to have two separate projects for user and admin because of shared code.

What would you recommend to do?

答:
I would recommend dividing your app into 2 features modules and using the concept of lazyModules and the idea of feature modules.

https://angular.io/docs/ts/latest/guide/ngmodule.html#!#feature-modules

https://github.com/AngularClass/angular-starter/wiki/Routing-and-Lazy-loading-@NgModules

Using LazyModules will load a module only if the router is reached . Here you can use guards to control using a service if your user is admin or just user. More info about guards.

https://netbasal.com/implementing-auth-guard-with-componentless-route-in-angular-b50a21f3bd77


问:
Power shell | Extract user name out of computer name in Domain Controller
How can I extract the user name in my active directory when I only have the computer name. </p>

<p>Obviously, no relation whats or ever between the computer name and the user name in terms of naming. </p>

答:
This will get you all users from the domain the current computer is joined to:</p>

```<code>(([adsisearcher]“objectcategory=user”).FindAll()).Properties.samaccountname
</code>```

Body:
How can I extract the user name in my active directory when I only have the computer name.

Obviously, no relation whats or ever between the computer name and the user name in terms of naming.

Body:
This will get you all users from the domain the current computer is joined to:

(([adsisearcher]“objectcategory=user”).FindAll()).Properties.samaccountname


问:
How do I print on the console if a user use a regex?
I've written a regex so when a user writes in the chat "Kosovo", my bot will send him an audio and a text.

```<code>    regex = "k+o+s+o+v+o"
try:
            nick = update.message.from_user.username
            if re.search(regex, contLower):
                    chatid = update.message.chat.id
                    audio1 = "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/SUONI/KosovoBello.ogg"
                    update.message.reply_audio(audio=open(audio1, "rb"))
                    update.message.reply_text("Stay tuned, @PadriFibra")
                    return
except Exception as err:
    print(err)

return
</code>```

Then I added this:

```<code>print(strftime("%H:%M:%S -")," "+(nick)+" triggered KosovoBello")
</code>```

and the result was this:

```<code>    regex = "k+o+s+o+v+o"
try:
            nick = update.message.from_user.username
            if re.search(regex, contLower):
                    chatid = update.message.chat.id
                    audio1 = "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/SUONI/KosovoBello.ogg"
                    update.message.reply_audio(audio=open(audio1, "rb"))
                    update.message.reply_text("Stay tuned, @PadriFibra")
                    print(strftime("%H:%M:%S -")," "+(nick)+" triggered KosovoBello")
                    return
except Exception as err:
    print(err)

return
</code>```

But when I try to start the bot, the console says this:

```<code>    $ python3 /Users/rikardo/Documents/ANGELO/Programmare/Prove\ di\ basi/Mat/prova.py
  File "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/prova.py", line 107
    regex = "k+o+s+o+v+o"
        ^
SyntaxError: invalid syntax
</code>```

答:
This is not exactly correct.  By specifying '+' after each character you allow matching of things like kkooosoovvvvvvo :-)

Instead, you should just use the exact string you want:

```<code>regex="(kosovo)"
</code>```

I'd also suggest including case variations

```<code>regex="(kosovo|Kosovo|KOSOVO)"
</code>```

or just using IGNORECASE so that every variation is covered.

Body:
I've written a regex so when a user writes in the chat "Kosovo", my bot will send him an audio and a text.

    regex = "k+o+s+o+v+o"
try:
            nick = update.message.from_user.username
            if re.search(regex, contLower):
                    chatid = update.message.chat.id
                    audio1 = "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/SUONI/KosovoBello.ogg"
                    update.message.reply_audio(audio=open(audio1, "rb"))
                    update.message.reply_text("Stay tuned, @PadriFibra")
                    return
except Exception as err:
    print(err)

return

Then I added this:

print(strftime("%H:%M:%S -")," "+(nick)+" triggered KosovoBello")

and the result was this:

    regex = "k+o+s+o+v+o"
try:
            nick = update.message.from_user.username
            if re.search(regex, contLower):
                    chatid = update.message.chat.id
                    audio1 = "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/SUONI/KosovoBello.ogg"
                    update.message.reply_audio(audio=open(audio1, "rb"))
                    update.message.reply_text("Stay tuned, @PadriFibra")
                    print(strftime("%H:%M:%S -")," "+(nick)+" triggered KosovoBello")
                    return
except Exception as err:
    print(err)

return

But when I try to start the bot, the console says this:

    $ python3 /Users/rikardo/Documents/ANGELO/Programmare/Prove\ di\ basi/Mat/prova.py
  File "/Users/rikardo/Documents/ANGELO/Programmare/Prove di basi/Mat/prova.py", line 107
    regex = "k+o+s+o+v+o"
        ^
SyntaxError: invalid syntax

Body:
This is not exactly correct.  By specifying '+' after each character you allow matching of things like kkooosoovvvvvvo :-)

Instead, you should just use the exact string you want:

regex="(kosovo)"

I'd also suggest including case variations

regex="(kosovo|Kosovo|KOSOVO)"

or just using IGNORECASE so that every variation is covered.


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答:
Something like this allows you to add any number of output streams, and allows changing them at runtime simply by modifying the PrintTarget linked list.

```<code>/** gcc -Wall -o print_target print_target.c && ./print_target */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct PrintTarget* PrintTargetp;

void* xmalloc (size_t size);
PrintTargetp pntCreate (PrintTargetp head, FILE* target);
void pntDestroy (PrintTargetp list);

typedef struct PrintTarget
{
  FILE* target;
  PrintTargetp next;
} PrintTarget;

void myPrintf (PrintTargetp streams, char* format, ...)
{
  va_list args;
  va_start(args, format);
  while (streams)
    {
      vfprintf(streams->target, format, args);
      streams = streams->next;
    }
  va_end(args);
}

int main(void)
{
  PrintTargetp streams = pntCreate(NULL, stdout);
  streams = pntCreate(streams, fopen("somefile.txt", "a+")); //XXX IO errors?

  myPrintf(streams, "blah blah blah...\n");
  pntDestroy(streams);
  return 0;
}
</code>```

Here's a definition of auxiliary functions:

```<code>PrintTargetp pntCreate (PrintTargetp head, FILE* target)
{
  PrintTargetp node = xmalloc(sizeof(PrintTarget));
  node->target = target;
  node->next   = head;
  return node;
}

void pntDestroy (PrintTargetp list)
{
  while (list)
    {
      PrintTargetp next = list->next;
      free(list);
      list = next;
      //XXX cycles?
      //XXX close files?
    }
}

void* xmalloc (size_t size)
{
  void* p = malloc(size);
  if (p == NULL)
    {
      fputs("malloc error\n", stderr);
      abort();
    }
  return p;
}
</code>```

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

Body:
Something like this allows you to add any number of output streams, and allows changing them at runtime simply by modifying the PrintTarget linked list.

/** gcc -Wall -o print_target print_target.c && ./print_target */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct PrintTarget* PrintTargetp;

void* xmalloc (size_t size);
PrintTargetp pntCreate (PrintTargetp head, FILE* target);
void pntDestroy (PrintTargetp list);

typedef struct PrintTarget
{
  FILE* target;
  PrintTargetp next;
} PrintTarget;

void myPrintf (PrintTargetp streams, char* format, ...)
{
  va_list args;
  va_start(args, format);
  while (streams)
    {
      vfprintf(streams->target, format, args);
      streams = streams->next;
    }
  va_end(args);
}

int main(void)
{
  PrintTargetp streams = pntCreate(NULL, stdout);
  streams = pntCreate(streams, fopen("somefile.txt", "a+")); //XXX IO errors?

  myPrintf(streams, "blah blah blah...\n");
  pntDestroy(streams);
  return 0;
}

Here's a definition of auxiliary functions:

PrintTargetp pntCreate (PrintTargetp head, FILE* target)
{
  PrintTargetp node = xmalloc(sizeof(PrintTarget));
  node->target = target;
  node->next   = head;
  return node;
}

void pntDestroy (PrintTargetp list)
{
  while (list)
    {
      PrintTargetp next = list->next;
      free(list);
      list = next;
      //XXX cycles?
      //XXX close files?
    }
}

void* xmalloc (size_t size)
{
  void* p = malloc(size);
  if (p == NULL)
    {
      fputs("malloc error\n", stderr);
      abort();
    }
  return p;
}

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: J.F. Sebastian


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
You mention: But if only $dirchk2 exist then process else statement.

Which translates to following TT:

```<code>$dirchk1   $dirchk2   process?

true       true       if-block
true       false      if-block
false      false      if-block
false      true       else-block
</code>```

which translates to:

```<code>if( ($dirchk1 && $dirchk2) || (!$dirchk2) ) {
  // if block
} else {
  // else block
}
</code>```

Or you could also do :

```<code>if(! (!$dirchk1 && $dirchk2) ) {
  // if block
} else {
  // else block
}
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
You mention: But if only $dirchk2 exist then process else statement.

Which translates to following TT:

$dirchk1   $dirchk2   process?

true       true       if-block
true       false      if-block
false      false      if-block
false      true       else-block

which translates to:

if( ($dirchk1 && $dirchk2) || (!$dirchk2) ) {
  // if block
} else {
  // else block
}

Or you could also do :

if(! (!$dirchk1 && $dirchk2) ) {
  // if block
} else {
  // else block
}


问:
Generating a Microsoft Word Report from Excel—Application Waiting for OLE Action? (VBA)
I'm trying to write a macro that will generate a Microsoft Word 'report' from an Excel file. I want for the macro to navigate to bookmarks in a Word template for the report, and insert at each certain content or a chart from the native Excel file. The macro works when running in piecemeal, but altogether fails to execute, with Excel repeating over and over that "[It] is waiting for another application to complete an OLE action."

To clarify also, the macro first clears a certain 'data dump' region in the workbook (its native file) and repopulates it with new data from a specified file. This file (its location path) and the various 'target row' and 'identifier' variables you see in the code are inputted by the user to a sort of interface (just a worksheet in the native workbook), where each is labeled manually as a (named) range to be easily fed into to be used by the code. The macro then creates the report by going through the different sheets of the workbook, copying certain content, and turning to Word to paste the copied content at template locations indicated by bookmarks.

I'm completely perplexed by the 'OLE error'. Any ideas about this/the code otherwise? Please share. Thanks for your help!

```<code>Sub GenerateReport()

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Dim myWorkbook As Excel.Workbook
Set myWorkbook = ThisWorkbook
Dim myWorksheet As Excel.Worksheet
Set myWorksheet = myWorkbook.Sheets("Sheet1")
Dim myWorksheet2 As Excel.Worksheet
Set myWorksheet2 = myWorkbook.Sheets("Sheet2")
Dim myWorksheet3 As Excel.Worksheet
Set myWorksheet3 = myWorkbook.Sheets("Sheet3")

Dim FileName As String
FileName = myWorksheet.Range("FileName")
Dim FilePath As String
FilePath = myWorksheet.Range("FilePath")
Dim TargetSheetName As String
TargetSheetName = myWorksheet.Range("TargetSheetName")
Dim PasteSheetName As String
PasteSheetName = myWorksheet.Range("PasteSheetName")

Dim Identifier As String
Identifier = myWorksheet.Range("Identifier")
Dim Identifier2 As String
Identifier2 = myWorksheet.Range("Identifier2")
Dim TargetRow As String
TargetRow = myWorksheet.Range("TargetRow")
Dim TargetRow2 As String
TargetRow2 = myWorksheet.Range("TargetRow2")
Dim PasteIdentifier As String
PasteIdentifier = myWorksheet.Range("PasteIdentifier")
Dim PasteIdentifier2 As String
PasteIdentifier2 = myWorksheet.Range("PasteIdentifier2")
Dim PasteTargetRow As String
PasteTargetRow = myWorksheet.Range("PasteTargetRow")
Dim PasteTargetRow2 As String
PasteTargetRow2 = myWorksheet.Range("PasteTargetRow2")

Dim Text As String
Text = myWorksheet.Range("Text")
Dim Text2 As String
Text2 = myWorksheet.Range("Text2")
Dim Text3 As String
Text3 = myWorksheet.Range("Text3")

Dim ReportTemplateFilePath As String
ReportTemplateFilePath = myWorksheet.Range("ReportTemplateFilePath")
Dim ReportTemplateFileName As String
ReportTemplateFileName = myWorksheet.Range("ReportTemplateFileName")
Dim SaveToLocation As String
SaveToLocation = myWorksheet.Range("SaveToLocation")

Dim SourceTargetSheet As Excel.Worksheet
Set SourceTargetSheet = myWorkbook.Sheets(PasteSheetName)
Dim TargetWorkbook As Excel.Workbook
Set TargetWorkbook = Workbooks.Open(FilePath)
Dim TargetSheet As Excel.Worksheet
Set TargetSheet = TargetWorkbook.Sheets(TargetSheetName)

'Clear old info
Dim UpperLeftHandCornerOfClear As String
UpperLeftHandCornerOfClear = "A" & PasteTargetRow
Dim LowerRightHandCornerOfClear As String
LowerRightHandCornerOfClear = "XFD" & PasteTargetRow2
SourceTargetSheet.Range(UpperLeftHandCornerOfClear, LowerRightHandCornerOfClear).ClearContents

'Copy new info for pasting
Dim StartingColumnAsRange As Range
Set StartingColumnAsRange = TargetSheet.Cells.Find(Identifier, LookIn:=xlValues, LookAt:=xlPart)
If Not StartingColumnAsRange Is Nothing Then
    Dim StartingColumn As String
    StartingColumn = Split(StartingColumnAsRange.Address, "$")(1)
End If
Dim EndingColumnAsRange As Range
Set EndingColumnAsRange = TargetSheet.Cells.Find(Identifier2, LookIn:=xlValues, LookAt:=xlPart)
If Not EndingColumnAsRange Is Nothing Then
    Dim EndingColumn As String
    EndingColumn = Split(EndingColumnAsRange.Address, "$")(1)
End If
Dim UpperLeftHandCornerOfCopy As String
UpperLeftHandCornerOfCopy = StartingColumn & TargetRow
Dim LowerRightHandCornerOfCopy As String
LowerRightHandCornerOfCopy = EndingColumn & TargetRow2
TargetSheet.Range(UpperLeftHandCornerOfCopy, LowerRightHandCornerOfCopy).Copy
Dim PastePasteTarget As String
PastePasteTarget = "A" & PasteTargetRow
SourceTargetSheet.Range(PastePasteTarget).PasteSpecial Paste:=xlPasteValues

'Create a Microsoft Word object (instance of Word to control)
Dim WordApplication As Word.Application
Set WordApplication = CreateObject("Word.Application")

'Error handle if Microsoft Word is open
On Error Resume Next
    Set WordApplication = GetObject(class:="Word.Application")
    Err.Clear
    If WordApplication Is Nothing Then
        Set WordApplication = CreateObject(class:="Word.Application")
    End If
On Error GoTo 0

'Error handle if report template is specifically already open
On Error Resume Next
Application.DisplayAlerts = False
Documents(ReportTemplateFileName).Close SaveChanges:=wdDoNotSaveChanges
On Error GoTo 0
Application.DisplayAlerts = True

Dim WordDocument As Word.Document
Set WordDocument = WordApplication.Documents.Open(ReportTemplateFilePath)

'Content from 'myWorksheet'
With WordDocument
    .Bookmarks("Bookmark1").Range.Text = myWorksheet.Range("Text1")
    .Bookmarks("Bookmark2").Range.Text = myWorksheet.Range("Text2")
    .Bookmarks("Bookmark3").Range.Text = myWorksheet.Range("Text3")
    .Bookmarks("Bookmark4").Range.Text = myWorksheet.Range("Text4")
End With

'Content from 'myWorksheet2'
With WordDocument
    .Bookmarks("Bookmark5").Range.Text = myWorksheet2.Range("Text5")
    .Bookmarks("Bookmark6").Range.Text = myWorksheet2.Range("Text6")
    .Bookmarks("Bookmark7").Range.Text = myWorksheet2.Range("Text7")
    .Bookmarks("Bookmark8").Range.Text = myWorksheet2.Range("Text8")
    .Bookmarks("Bookmark9").Range.Text = myWorksheet2.Range("Text9")
    .Bookmarks("Bookmark10").Range.Text = myWorksheet3.Range("Text10")
End With

'Chart (alone on worksheet)
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart1"
ThisWorkbook.Sheets("Chart 1 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

'Two charts grouped together
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart2"
ThisWorkbook.Sheets("Chart 2 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

With WordDocument
    .SaveAs FileName:=SaveToLocation & " " & Text3, _
            FileFormat:=wdFormatDocumentDefault
    .Close
End With

WordApplication.Quit
Set WordApplication = Nothing
Set WordDocument = Nothing

Application.ScreenUpdating = True
'Application.DisplayAlerts = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

myWorksheet.Activate
MsgBox "Report successfully generated.", vbInformation, "Completed!"

End Sub
</code>```

答:
Try modifying your Word application creation script - this is all you need:

```<code>On Error Resume Next
Set WordApplication = GetObject(class:="Word.Application")
On Error GoTo 0

If WordApplication Is Nothing Then
    Set WordApplication = CreateObject(class:="Word.Application")
End If
</code>```

It may be that Word is waiting for some input from you but you're not seeing it because you didn't make the instance visible, so try also adding:

```<code>WordApplication.Visible = True
</code>```

Body:
I'm trying to write a macro that will generate a Microsoft Word 'report' from an Excel file. I want for the macro to navigate to bookmarks in a Word template for the report, and insert at each certain content or a chart from the native Excel file. The macro works when running in piecemeal, but altogether fails to execute, with Excel repeating over and over that "[It] is waiting for another application to complete an OLE action."

To clarify also, the macro first clears a certain 'data dump' region in the workbook (its native file) and repopulates it with new data from a specified file. This file (its location path) and the various 'target row' and 'identifier' variables you see in the code are inputted by the user to a sort of interface (just a worksheet in the native workbook), where each is labeled manually as a (named) range to be easily fed into to be used by the code. The macro then creates the report by going through the different sheets of the workbook, copying certain content, and turning to Word to paste the copied content at template locations indicated by bookmarks.

I'm completely perplexed by the 'OLE error'. Any ideas about this/the code otherwise? Please share. Thanks for your help!

Sub GenerateReport()

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Dim myWorkbook As Excel.Workbook
Set myWorkbook = ThisWorkbook
Dim myWorksheet As Excel.Worksheet
Set myWorksheet = myWorkbook.Sheets("Sheet1")
Dim myWorksheet2 As Excel.Worksheet
Set myWorksheet2 = myWorkbook.Sheets("Sheet2")
Dim myWorksheet3 As Excel.Worksheet
Set myWorksheet3 = myWorkbook.Sheets("Sheet3")

Dim FileName As String
FileName = myWorksheet.Range("FileName")
Dim FilePath As String
FilePath = myWorksheet.Range("FilePath")
Dim TargetSheetName As String
TargetSheetName = myWorksheet.Range("TargetSheetName")
Dim PasteSheetName As String
PasteSheetName = myWorksheet.Range("PasteSheetName")

Dim Identifier As String
Identifier = myWorksheet.Range("Identifier")
Dim Identifier2 As String
Identifier2 = myWorksheet.Range("Identifier2")
Dim TargetRow As String
TargetRow = myWorksheet.Range("TargetRow")
Dim TargetRow2 As String
TargetRow2 = myWorksheet.Range("TargetRow2")
Dim PasteIdentifier As String
PasteIdentifier = myWorksheet.Range("PasteIdentifier")
Dim PasteIdentifier2 As String
PasteIdentifier2 = myWorksheet.Range("PasteIdentifier2")
Dim PasteTargetRow As String
PasteTargetRow = myWorksheet.Range("PasteTargetRow")
Dim PasteTargetRow2 As String
PasteTargetRow2 = myWorksheet.Range("PasteTargetRow2")

Dim Text As String
Text = myWorksheet.Range("Text")
Dim Text2 As String
Text2 = myWorksheet.Range("Text2")
Dim Text3 As String
Text3 = myWorksheet.Range("Text3")

Dim ReportTemplateFilePath As String
ReportTemplateFilePath = myWorksheet.Range("ReportTemplateFilePath")
Dim ReportTemplateFileName As String
ReportTemplateFileName = myWorksheet.Range("ReportTemplateFileName")
Dim SaveToLocation As String
SaveToLocation = myWorksheet.Range("SaveToLocation")

Dim SourceTargetSheet As Excel.Worksheet
Set SourceTargetSheet = myWorkbook.Sheets(PasteSheetName)
Dim TargetWorkbook As Excel.Workbook
Set TargetWorkbook = Workbooks.Open(FilePath)
Dim TargetSheet As Excel.Worksheet
Set TargetSheet = TargetWorkbook.Sheets(TargetSheetName)

'Clear old info
Dim UpperLeftHandCornerOfClear As String
UpperLeftHandCornerOfClear = "A" & PasteTargetRow
Dim LowerRightHandCornerOfClear As String
LowerRightHandCornerOfClear = "XFD" & PasteTargetRow2
SourceTargetSheet.Range(UpperLeftHandCornerOfClear, LowerRightHandCornerOfClear).ClearContents

'Copy new info for pasting
Dim StartingColumnAsRange As Range
Set StartingColumnAsRange = TargetSheet.Cells.Find(Identifier, LookIn:=xlValues, LookAt:=xlPart)
If Not StartingColumnAsRange Is Nothing Then
    Dim StartingColumn As String
    StartingColumn = Split(StartingColumnAsRange.Address, "$")(1)
End If
Dim EndingColumnAsRange As Range
Set EndingColumnAsRange = TargetSheet.Cells.Find(Identifier2, LookIn:=xlValues, LookAt:=xlPart)
If Not EndingColumnAsRange Is Nothing Then
    Dim EndingColumn As String
    EndingColumn = Split(EndingColumnAsRange.Address, "$")(1)
End If
Dim UpperLeftHandCornerOfCopy As String
UpperLeftHandCornerOfCopy = StartingColumn & TargetRow
Dim LowerRightHandCornerOfCopy As String
LowerRightHandCornerOfCopy = EndingColumn & TargetRow2
TargetSheet.Range(UpperLeftHandCornerOfCopy, LowerRightHandCornerOfCopy).Copy
Dim PastePasteTarget As String
PastePasteTarget = "A" & PasteTargetRow
SourceTargetSheet.Range(PastePasteTarget).PasteSpecial Paste:=xlPasteValues

'Create a Microsoft Word object (instance of Word to control)
Dim WordApplication As Word.Application
Set WordApplication = CreateObject("Word.Application")

'Error handle if Microsoft Word is open
On Error Resume Next
    Set WordApplication = GetObject(class:="Word.Application")
    Err.Clear
    If WordApplication Is Nothing Then
        Set WordApplication = CreateObject(class:="Word.Application")
    End If
On Error GoTo 0

'Error handle if report template is specifically already open
On Error Resume Next
Application.DisplayAlerts = False
Documents(ReportTemplateFileName).Close SaveChanges:=wdDoNotSaveChanges
On Error GoTo 0
Application.DisplayAlerts = True

Dim WordDocument As Word.Document
Set WordDocument = WordApplication.Documents.Open(ReportTemplateFilePath)

'Content from 'myWorksheet'
With WordDocument
    .Bookmarks("Bookmark1").Range.Text = myWorksheet.Range("Text1")
    .Bookmarks("Bookmark2").Range.Text = myWorksheet.Range("Text2")
    .Bookmarks("Bookmark3").Range.Text = myWorksheet.Range("Text3")
    .Bookmarks("Bookmark4").Range.Text = myWorksheet.Range("Text4")
End With

'Content from 'myWorksheet2'
With WordDocument
    .Bookmarks("Bookmark5").Range.Text = myWorksheet2.Range("Text5")
    .Bookmarks("Bookmark6").Range.Text = myWorksheet2.Range("Text6")
    .Bookmarks("Bookmark7").Range.Text = myWorksheet2.Range("Text7")
    .Bookmarks("Bookmark8").Range.Text = myWorksheet2.Range("Text8")
    .Bookmarks("Bookmark9").Range.Text = myWorksheet2.Range("Text9")
    .Bookmarks("Bookmark10").Range.Text = myWorksheet3.Range("Text10")
End With

'Chart (alone on worksheet)
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart1"
ThisWorkbook.Sheets("Chart 1 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

'Two charts grouped together
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart2"
ThisWorkbook.Sheets("Chart 2 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

With WordDocument
    .SaveAs FileName:=SaveToLocation & " " & Text3, _
            FileFormat:=wdFormatDocumentDefault
    .Close
End With

WordApplication.Quit
Set WordApplication = Nothing
Set WordDocument = Nothing

Application.ScreenUpdating = True
'Application.DisplayAlerts = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

myWorksheet.Activate
MsgBox "Report successfully generated.", vbInformation, "Completed!"

End Sub

Body:
Try modifying your Word application creation script - this is all you need:

On Error Resume Next
Set WordApplication = GetObject(class:="Word.Application")
On Error GoTo 0

If WordApplication Is Nothing Then
    Set WordApplication = CreateObject(class:="Word.Application")
End If

It may be that Word is waiting for some input from you but you're not seeing it because you didn't make the instance visible, so try also adding:

WordApplication.Visible = True


问:
For-comprehension for two arrays of the same length
I have two Seq[Array[Byte]] arrays:

```<code>var o1: Seq[Array[Byte]]
var o2: Seq[Array[Byte]]
//...
</code>```

I need to mutate the o1 Seq of Arrays  so that each array of o1 is replaced with Array of o2 of the same position iff the array of o2 has non-zero length.

Is it possible to do with for-comprehension?

答:
This seems like a better job for zip

```<code>o1 zip o2 map { case (l, r) => if(r.nonEmpty) r else l }
</code>```

If you don't like creating the intermediate seq with o1 zip o2, you could lazily build up the combination using iterators:

```<code>(o1.iterator zip o2.iterator map { case (l, r) => if(r.nonEmpty) r else l }).toList
</code>```

If you really want to mutate, first make sure to use a collection.mutable.IndexedSeq since its mutation method (update) takes an index. If you try to mutate a general Seq, you might get O(n) updates due to linked list-ish structures.

```<code>for {
  (replacement, index) <- o2.iterator.zipWithIndex
  if replacement.nonEmpty
} o1(index) = replacement
</code>```

This is actually just syntax sugar for something like:

```<code>o2.iterator.zipWithIndex.foreach {
  case (replacement, index) =>
    if(replacement.nonEmpty) o1.update(index, replacement)
}
</code>```

Body:
I have two Seq[Array[Byte]] arrays:

var o1: Seq[Array[Byte]]
var o2: Seq[Array[Byte]]
//...

I need to mutate the o1 Seq of Arrays  so that each array of o1 is replaced with Array of o2 of the same position iff the array of o2 has non-zero length.

Is it possible to do with for-comprehension?

Body:
This seems like a better job for zip

o1 zip o2 map { case (l, r) => if(r.nonEmpty) r else l }

If you don't like creating the intermediate seq with o1 zip o2, you could lazily build up the combination using iterators:

(o1.iterator zip o2.iterator map { case (l, r) => if(r.nonEmpty) r else l }).toList

If you really want to mutate, first make sure to use a collection.mutable.IndexedSeq since its mutation method (update) takes an index. If you try to mutate a general Seq, you might get O(n) updates due to linked list-ish structures.

for {
  (replacement, index) <- o2.iterator.zipWithIndex
  if replacement.nonEmpty
} o1(index) = replacement

This is actually just syntax sugar for something like:

o2.iterator.zipWithIndex.foreach {
  case (replacement, index) =>
    if(replacement.nonEmpty) o1.update(index, replacement)
}


问:
JS if else statement and a reset
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

```<code>   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>
</code>```

JS

```<code>function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}
</code>```

答:
you can add "disabled" attribute to "SEND TROOPS" button at first, it will disable this button which will prevent clicking it.
you can remove that attribute when "ATTACK" is clicked.

Add attribute

```<code>document.getElementsByClassName("troops")[0]).setAttribute("disabled","disabled")
</code>```

Remove attribute:

```<code>document.getElementsByClassName("troops")[0]).removeAttribute("disabled","disabled")
</code>```

Title: JS if else statement and a reset

Body:
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

Body:
you can add "disabled" attribute to "SEND TROOPS" button at first, it will disable this button which will prevent clicking it.
you can remove that attribute when "ATTACK" is clicked.

Add attribute

document.getElementsByClassName("troops")[0]).setAttribute("disabled","disabled")

Remove attribute:

document.getElementsByClassName("troops")[0]).removeAttribute("disabled","disabled")


问:
Java CSV Formatting Issues
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

```<code>HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
</code>```

It produces

```<code>Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,
</code>```

Expected Output (without comma at the end of each line):

```<code>Feature2,Feature1
2,1
</code>```

Which is  a wrong formatting

This is the code I use. How to fix it ?

```<code>public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}
</code>```

答:
One way to achieve that is doing something like this:

```<code>import java.io.IOException;
import java.util.HashMap;

public class HashMapToCSV {

   public static void main(String[] args) {

      HashMap<String, Integer> hmap = new HashMap<String, Integer>();
      hmap.put("Feature1", 1);
      hmap.put("Feature2", 2);

      try {
          System.out.println(appendCSV(hmap));
      } catch (IOException e){
         e.printStackTrace();
      }
   }

   public static String appendCSV(HashMap<String,Integer> featureset) throws IOException{

      StringBuilder csvReport = new StringBuilder();
      // loop through the keySet and append the keys
      for(String key: featureset.keySet()){
           csvReport.append(key+",");
      }
      // to remove the comma at the end
      csvReport.replace(csvReport.length()-1, csvReport.length(), "");
      csvReport.append("\n"); // append new line

      // then loop through the keySet and append the values
      for(String key: featureset.keySet()){
          csvReport.append(featureset.get(key)+",");
      }
      csvReport.replace(csvReport.length()-1, csvReport.length(), "");
      return csvReport.toString();
   }
}
</code>```

Output

```<code>Feature2,Feature1
2,1
</code>```

Title: Java CSV Formatting Issues

Body:
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);

It produces

Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,

Expected Output (without comma at the end of each line):

Feature2,Feature1
2,1

Which is  a wrong formatting

This is the code I use. How to fix it ?

public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}

Body:
One way to achieve that is doing something like this:

import java.io.IOException;
import java.util.HashMap;

public class HashMapToCSV {

   public static void main(String[] args) {

      HashMap<String, Integer> hmap = new HashMap<String, Integer>();
      hmap.put("Feature1", 1);
      hmap.put("Feature2", 2);

      try {
          System.out.println(appendCSV(hmap));
      } catch (IOException e){
         e.printStackTrace();
      }
   }

   public static String appendCSV(HashMap<String,Integer> featureset) throws IOException{

      StringBuilder csvReport = new StringBuilder();
      // loop through the keySet and append the keys
      for(String key: featureset.keySet()){
           csvReport.append(key+",");
      }
      // to remove the comma at the end
      csvReport.replace(csvReport.length()-1, csvReport.length(), "");
      csvReport.append("\n"); // append new line

      // then loop through the keySet and append the values
      for(String key: featureset.keySet()){
          csvReport.append(featureset.get(key)+",");
      }
      csvReport.replace(csvReport.length()-1, csvReport.length(), "");
      return csvReport.toString();
   }
}

Output

Feature2,Feature1
2,1


问:
radio buttons display form
I have in my form 3 radio buttons, when i click on each one a form appears and a parameter of my backtesting change. The problem is that when i click on save buttons nothing is saved. Before I added the check of radio buttons the save buttons was working. The click on radio buttons change the strategy of parameters. The error is with the save function when i check the radio buttons but i don't know how to resolve it.

Models.py

```<code>class Parameters(models.Model):

MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),)

SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),)

user = models.ForeignKey(User)
title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long")

#input characteristics
price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
stocks_num_2_min     = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
stocks_num_2_max     = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
    holding_period = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),])

    volume = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),])
    market = models.CharField('Market', max_length=30, null=True)
    sector = models.CharField('Sector', max_length=30, null=True)
</code>```

The html where the parameters are saved in a table:

```<code> {% extends 'base.html' %}
 {% block content %}

   <div> {% if user.is_authenticated %}
            {% if user.profile.is_active %}
                 Saved from "Backtesting"
                <ul>
                    {% for param in user.parameters_set.all %}
                        {% if param.type == "backtest" %}

                           <table style="width:100%">
                                    <tr>
                                         <th> Saved File </th>
                                         <th> Created at </th>
                                     <tr>

                                     <td> <a href='{{param.get_backtest_url}}'>{{param.title}}  </a> </td>
                                     <td> {{param.created_at}} </td>
                                     <td> {{param.strategy}} </td>

                              </tr>
                             </table>

                        {% endif %}
                    {% endfor %}
                </ul>
                            {% else %}
                <p>
                You are logged in but your account has expired. You can reactivate your account by buying one of <a href="{% url 'pricing' %}">our services</a>. You are welcome however to keep using our free services!
                </p>
            {% endif %}
{% else %}
                            <p>
If you “login” you can save your parameters for future use. Please <a href="{% url 'auth_login' %}">login</a>, or <a href="{% url 'registration_register' %}">register</a> and get <strong><span class = "greenText">1 Month free trial</span></strong>.
                            </p>
{% endif %}
    </div>

{% endblock %}
</code>```

View.py

```<code>def backtest(request, pk=None):

if pk is not None:
    param = get_object_or_404(Parameters, pk=pk, user=request.user)
    form = BacktestForm(request.POST or None, instance=param)
else:
    form = BacktestForm(request.POST or None)

    if request.method == 'POST':
    if form.is_valid():
        if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            if ('toggle-tab1').checked  in request.POST:
             obj.strategy="Long"
                            elif ('toggle-tab2').checked  in request.POST:
                             obj.strategy="Short"
                            else :
                             obj.strategy="Long and Short "

                obj.type = "backtest"

                obj.save()

                messages.info(request, 'Saved!')
            return redirect(obj.get_backtest_url())

                    else:
                            obj = ForecastQueue.create(request.user, 'backtest', json.dumps(request.POST))
            obj.save()
                            return redirect(obj.get_url())

            else:
        messages.info(request, 'Please check entered data')
        data = {
            'active_page': 'backtest',
            'form': form,}

else:
            data = {'active_page': 'backtest',
        'form': form,
    }
return render(request, 'backtest.html', data)
</code>```

The html of the template

```<code>   { % extends 'base.html' %}
   {% block title %}Backtesting{% endblock %}
   {% block content %}
<div class="page-header">
    <h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %} <a data-toggle="popover" data-content="
    <img src='{{STATIC_URL}}img/tutorial/documentation/img20.png'class='img-responsive img-rounded'/>
        "><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span></a></h1>
    </div>
    <div class="row">
    <div class='col-md-9'>
              <div id="tabs">

               <input type="radio" name="tabs" id="toggle-tab1"  checked="checked" />
               <label for="toggle-tab1">Long</label>

               <input type="radio" name="tabs" id="toggle-tab2"    />
               <label for="toggle-tab2">Short</label>

               <input type="radio" name="tabs" id="toggle-tab3"   />
               <label for="toggle-tab3">Long and Short</label>
               <div id="tab1" class="tab"  >
        <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}

            {% include 'tags/parameters_form.html' %}
            <br />
            {% include 'tags/parameters_backtest_form.html' %}
            <br/>

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}
                    <p>
                    Expired account! you need to reactivate in order to save parameters.
                    </p>
                {% endif %}
            {% else %}
                                     Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                 </br>
                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

                    </form>
</code>```

答:
Add all 3 radio field in form tag like below and add value of each radio button different value.

```<code><form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}
      <input type="radio" name="tabs" value="first" id="toggle-tab1"  checked="checked" />
               <label for="toggle-tab1">Long</label>

               <input type="radio" name="tabs" value="second" id="toggle-tab2"    />
               <label for="toggle-tab2">Short</label>

               <input type="radio" name="tabs" value="third"  id="toggle-tab3"   />
               <label for="toggle-tab3">Long and Short</label>

....
</code>```

When you submit this form you will get "tabs" in request.POST with value, So follow below code in view.

```<code> if form.is_valid():
    if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            tab_value = request.POST.get('tabs')
                            if tab_value == 'first':
             obj.strategy="Long"
                            elif tab_value == 'second':
                             obj.strategy="Short"
                            else :
                             obj.strategy="Long and Short
</code>```

Title: radio buttons display form

Body:
I have in my form 3 radio buttons, when i click on each one a form appears and a parameter of my backtesting change. The problem is that when i click on save buttons nothing is saved. Before I added the check of radio buttons the save buttons was working. The click on radio buttons change the strategy of parameters. The error is with the save function when i check the radio buttons but i don't know how to resolve it.

Models.py

class Parameters(models.Model):

MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),)

SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),)

user = models.ForeignKey(User)
title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long")

#input characteristics
price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
stocks_num_2_min     = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
stocks_num_2_max     = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
    holding_period = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),])

    volume = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),])
    market = models.CharField('Market', max_length=30, null=True)
    sector = models.CharField('Sector', max_length=30, null=True)

The html where the parameters are saved in a table:

 {% extends 'base.html' %}
 {% block content %}

 {% if user.is_authenticated %}
            {% if user.profile.is_active %}
                 Saved from "Backtesting"

                    {% for param in user.parameters_set.all %}
                        {% if param.type == "backtest" %}

                                          Saved File
                                          Created at

                                      {{param.title}}
                                      {{param.created_at}}
                                      {{param.strategy}}

                        {% endif %}
                    {% endfor %}

                            {% else %}

                You are logged in but your account has expired. You can reactivate your account by buying one of our services. You are welcome however to keep using our free services!

            {% endif %}
{% else %}

If you “login” you can save your parameters for future use. Please login, or register and get 1 Month free trial.

{% endif %}

{% endblock %}

View.py

def backtest(request, pk=None):

if pk is not None:
    param = get_object_or_404(Parameters, pk=pk, user=request.user)
    form = BacktestForm(request.POST or None, instance=param)
else:
    form = BacktestForm(request.POST or None)

    if request.method == 'POST':
    if form.is_valid():
        if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            if ('toggle-tab1').checked  in request.POST:
             obj.strategy="Long"
                            elif ('toggle-tab2').checked  in request.POST:
                             obj.strategy="Short"
                            else :
                             obj.strategy="Long and Short "

                obj.type = "backtest"

                obj.save()

                messages.info(request, 'Saved!')
            return redirect(obj.get_backtest_url())

                    else:
                            obj = ForecastQueue.create(request.user, 'backtest', json.dumps(request.POST))
            obj.save()
                            return redirect(obj.get_url())

            else:
        messages.info(request, 'Please check entered data')
        data = {
            'active_page': 'backtest',
            'form': form,}

else:
            data = {'active_page': 'backtest',
        'form': form,
    }
return render(request, 'backtest.html', data)

The html of the template

   { % extends 'base.html' %}
   {% block title %}Backtesting{% endblock %}
   {% block content %}

Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %} <a data-toggle="popover" data-content="

        ">

               <input type="radio" name="tabs" id="toggle-tab1"  checked="checked" />
               Long

               <input type="radio" name="tabs" id="toggle-tab2"    />
               Short

               <input type="radio" name="tabs" id="toggle-tab3"   />
               Long and Short

        <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}

            {% include 'tags/parameters_form.html' %}

            {% include 'tags/parameters_backtest_form.html' %}

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}

                    Expired account! you need to reactivate in order to save parameters.

                {% endif %}
            {% else %}
                                     Please login in order to Run backtesting!

                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

                    </form>

Body:
Add all 3 radio field in form tag like below and add value of each radio button different value.

<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}
      <input type="radio" name="tabs" value="first" id="toggle-tab1"  checked="checked" />
               <label for="toggle-tab1">Long</label>

               <input type="radio" name="tabs" value="second" id="toggle-tab2"    />
               <label for="toggle-tab2">Short</label>

               <input type="radio" name="tabs" value="third"  id="toggle-tab3"   />
               <label for="toggle-tab3">Long and Short</label>

....

When you submit this form you will get "tabs" in request.POST with value, So follow below code in view.

 if form.is_valid():
    if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            tab_value = request.POST.get('tabs')
                            if tab_value == 'first':
             obj.strategy="Long"
                            elif tab_value == 'second':
                             obj.strategy="Short"
                            else :
                             obj.strategy="Long and Short


问:
Error could not match type
I have a type:

```<code>newtype User = User
  { id :: String
  , email :: String
  , last_update :: String
  }
</code>```

and a function:

```<code>import Pux.DOM.HTML (HTML)
import Pux.DOM.HTML.Attributes (key)
import Text.Smolder.HTML as H
import Text.Smolder.HTML.Attributes as A

userRow :: User -> HTML Event
  userRow user =
    H.tr ! key user.id ! A.className "user-item" $ do
      H.td ! key ("email") $ text user.email
      H.td ! key ("last_update") $ text user.last_update
      H.td ! key ("actions") ! A.className "actions" $ do
        H.a ! key ("delete")  ! A.className "action-delete" #! onClick (pure $ OpenDeleteModal (show user.id)) $ do
          H.span
          ! A.className "dashicons dashicons-trash"
          ! A.alt "Delete"
          ! A.title "Delete"
          $ text ""
</code>```

But the types will not unify:

```<code>268    H.tr ! key user.id ! A.className "user-item" $ do
                  ^^^^

Could not match type

  { id :: String
  | t0
  }

with type

  User

while checking that type User
  is at least as general as type { id :: String
                                 | t0
                                 }
while checking that expression user
  has type { id :: String
           | t0
           }
while checking type of property accessor user.id
in value declaration userRow

where t0 is an unknown type
</code>```

I can't see what I am doing wrong. It seems to me that the user type has an "id" member which is a string, and therefore is at least as general as

```<code>type { id :: String
     | t0
     }
</code>```

答:
User is a newtype around a record, so it wraps the record up. In order to access the records fields you first need to unwrap it. The easiest way to do this in your situation is to pattern match on the user argument:

```<code>userRow :: User -> HTML Event
userRow (User user) =
  H.tr ! key user.id ! A.className "user-item" $ do
    ...
</code>```

Title: Error could not match type

Body:
I have a type:

newtype User = User
  { id :: String
  , email :: String
  , last_update :: String
  }

and a function:

import Pux.DOM.HTML (HTML)
import Pux.DOM.HTML.Attributes (key)
import Text.Smolder.HTML as H
import Text.Smolder.HTML.Attributes as A

userRow :: User -> HTML Event
  userRow user =
    H.tr ! key user.id ! A.className "user-item" $ do
      H.td ! key ("email") $ text user.email
      H.td ! key ("last_update") $ text user.last_update
      H.td ! key ("actions") ! A.className "actions" $ do
        H.a ! key ("delete")  ! A.className "action-delete" #! onClick (pure $ OpenDeleteModal (show user.id)) $ do
          H.span
          ! A.className "dashicons dashicons-trash"
          ! A.alt "Delete"
          ! A.title "Delete"
          $ text ""

But the types will not unify:

268    H.tr ! key user.id ! A.className "user-item" $ do
                  ^^^^

Could not match type

  { id :: String
  | t0
  }

with type

  User

while checking that type User
  is at least as general as type { id :: String
                                 | t0
                                 }
while checking that expression user
  has type { id :: String
           | t0
           }
while checking type of property accessor user.id
in value declaration userRow

where t0 is an unknown type

I can't see what I am doing wrong. It seems to me that the user type has an "id" member which is a string, and therefore is at least as general as

type { id :: String
     | t0
     }

Body:
User is a newtype around a record, so it wraps the record up. In order to access the records fields you first need to unwrap it. The easiest way to do this in your situation is to pattern match on the user argument:

userRow :: User -> HTML Event
userRow (User user) =
  H.tr ! key user.id ! A.className "user-item" $ do
    ...


问:
JSP+Tomcat: Single Sign-On
How the best way to create a single sign-on for many JSP applications using Tomcat server?</p>

答: Authenticating agains a Kerberos Server. You can do that with JAAS and Kerberos 5 JAAS Module.</p>

Title: JSP+Tomcat: Single Sign-On


问:
Basic bash script issue
Here is my first post on the forum, let me know if I may be more descriptif.
Yesterday, I script a lil' script to start, restart and stop my server in one, so I test 3 times the $1 argument to know if it's start, restart, stop string.

I take all the improvments if I can do it in another way :)

Here is my code :

```<code>#!/bin/bash
STA="start"
RES="restart"
STO="stop"
SERVERNAME="server_live"
if [ $1 -ge 1 ]
then
    echo "Entre un argument : start, stop, restart"
elif [ $1 = $STA ]
then
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
elif [ $1 = $RES ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
elif [ $1 = $STO ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
fi
</code>```

I got the following error :
My code here

It means : syntaxe error near inexpected symbol elif line 10

Thanks in advance.. I wanna add that

```<code>#!/bin/bash
echo "read smthg"
read name
</code>```

put an error too (on read) , how might I know if I got a version issue or something like that ?

答:
you should use case instead of if ... elif, and (almost) always quote your variables between " " :

Please try this version (close to yours, but using case...esac and with some quotes added):

```<code>#!/bin/bash
SERVERNAME="server_live"

case "$1" in
  start)
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
    ;;
  restart)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
    ;;
  stop)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
    ;;
  *)
    echo "argument: '$1' non reconnu..."
    exit 1
    ;;
esac
</code>```

If you encounter an error, your script may contain things before that part that interfere? Please first paste your script in : www.shellcheck.net  and see what it tells you (it will parse it and show a lot of common error, such as unclosed quotes, etc).

EDIT

The problem came from the fact that person was editing under windows (which uses 'CR-LF' line endings) and using it in linux/unix (which expected just LF, and thus took the CR as an additionnal character in the lines containing them).

To get rid of "everything non-printable" that isn't used for scripting in your script:

```<code>LC_ALL="C" tr -cd "[$(printf '\t')\$(printf '\n') -~]" <script.bash >script_without_nonprintables.bash
  # LC_ALL="C" just before tr makes tr use that environment, which gives "ascii" instead of whatever locale you use. This helps ensure the ranges given are the ascii ones, and not something else.
  # -c = complement, ie "whatever is not..."   -d="delete", so -cd= "delete whatever is not specified"
  #  [a-d] = from a to d in the current locale (ascii, here, thanks to LC_ALL="C", so it will be : a, b, c or d
  #   in ascii,  SPACE to ~  covers all the character you need to write scripts, except for TAB (\t) and Newline (\n), so I added those as well.
  #   for newline, I preceded it with an "\" to have it taken literally
chmod +x script_without_nonprintables.bash
</code>```

Title: Basic bash script issue

Body:
Here is my first post on the forum, let me know if I may be more descriptif.
Yesterday, I script a lil' script to start, restart and stop my server in one, so I test 3 times the $1 argument to know if it's start, restart, stop string.

I take all the improvments if I can do it in another way :)

Here is my code :

#!/bin/bash
STA="start"
RES="restart"
STO="stop"
SERVERNAME="server_live"
if [ $1 -ge 1 ]
then
    echo "Entre un argument : start, stop, restart"
elif [ $1 = $STA ]
then
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
elif [ $1 = $RES ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
elif [ $1 = $STO ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
fi

I got the following error :
My code here

It means : syntaxe error near inexpected symbol elif line 10

Thanks in advance.. I wanna add that

#!/bin/bash
echo "read smthg"
read name

put an error too (on read) , how might I know if I got a version issue or something like that ?

Body:
you should use case instead of if ... elif, and (almost) always quote your variables between " " :

Please try this version (close to yours, but using case...esac and with some quotes added):

#!/bin/bash
SERVERNAME="server_live"

case "$1" in
  start)
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
    ;;
  restart)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
    ;;
  stop)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
    ;;
  *)
    echo "argument: '$1' non reconnu..."
    exit 1
    ;;
esac

If you encounter an error, your script may contain things before that part that interfere? Please first paste your script in : www.shellcheck.net  and see what it tells you (it will parse it and show a lot of common error, such as unclosed quotes, etc).

EDIT

The problem came from the fact that person was editing under windows (which uses 'CR-LF' line endings) and using it in linux/unix (which expected just LF, and thus took the CR as an additionnal character in the lines containing them).

To get rid of "everything non-printable" that isn't used for scripting in your script:

LC_ALL="C" tr -cd "[$(printf '\t')\$(printf '\n') -~]" <script.bash >script_without_nonprintables.bash
  # LC_ALL="C" just before tr makes tr use that environment, which gives "ascii" instead of whatever locale you use. This helps ensure the ranges given are the ascii ones, and not something else.
  # -c = complement, ie "whatever is not..."   -d="delete", so -cd= "delete whatever is not specified"
  #  [a-d] = from a to d in the current locale (ascii, here, thanks to LC_ALL="C", so it will be : a, b, c or d
  #   in ascii,  SPACE to ~  covers all the character you need to write scripts, except for TAB (\t) and Newline (\n), so I added those as well.
  #   for newline, I preceded it with an "\" to have it taken literally
chmod +x script_without_nonprintables.bash


问:
How to render and append sub-views in Backbone.js
I have a nested-View setup which can get somewhat deep in my application. There are a bunch of ways I could think of initializing, rendering and appending the sub-views, but I'm wondering what common practice is.

Here are a couple I've thought of:

```<code>initialize : function () {

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template());

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}
</code>```

Pros: You don't have to worry about maintaining the right DOM order with appending. The views are initialized early on, so there isn't as much to do all at once in the render function.

Cons: You are forced to re-delegateEvents(), which might be costly? The parent view's render function is cluttered with all of the subview rendering that needs to happen? You don't have the ability to set the tagName of the elements, so the template needs to maintain the correct tagNames.

Another way:

```<code>initialize : function () {

},

render : function () {

    this.$el.empty();

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});

    this.$el.append(this.subView1.render().el, this.subView2.render().el);
}
</code>```

Pros: You don't have to re-delegate events. You don't need a template that just contains empty placeholders and your tagName's are back to being defined by the view.

Cons: You now have to make sure to append things in the right order. The parent view's render is still cluttered by the subview rendering.

With an onRender event:

```<code>initialize : function () {
    this.on('render', this.onRender);
    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}
</code>```

Pros: The subview logic is now separated from the view's render() method.

With an onRender event:

```<code>initialize : function () {
    this.on('render', this.onRender);
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {
    this.subView1 = new Subview();
    this.subView2 = new Subview();
    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}
</code>```

I've kind of mix and matched a bunch of different practices across all of these examples (so sorry about that) but what are the ones that you would keep or add? and what would you not do?

Summary of practices:

Instantiate subviews in initialize or in render?

Perform all sub-view rendering logic in render or in onRender?

Use setElement or append/appendTo?

答:
You could also inject the rendered subviews as variables into the main template as variables.

first render the subviews and convert them to html like this:

var subview1 = $(subview1.render.el).html();
var subview2 = $(subview2.render.el).html();

(that way you could also dynamically string concatenate the views like subview1 + subview2 when used in loops) and then pass it to the master template which looks like this:

... some header stuff ...
<%= sub1 %>
<%= sub2 %>
... some footer stuff ...

and inject it finally like this:

this.$el.html(_.template(MasterTemplate, { sub1: subview1, sub2: subview2 } ));

Regarding the Events within the subviews: They will be most likely have to be connected in the parent (masterView) with this approach not within the subviews.

Body:
I have a nested-View setup which can get somewhat deep in my application. There are a bunch of ways I could think of initializing, rendering and appending the sub-views, but I'm wondering what common practice is.

Here are a couple I've thought of:

initialize : function () {

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template());

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

Pros: You don't have to worry about maintaining the right DOM order with appending. The views are initialized early on, so there isn't as much to do all at once in the render function.

Cons: You are forced to re-delegateEvents(), which might be costly? The parent view's render function is cluttered with all of the subview rendering that needs to happen? You don't have the ability to set the tagName of the elements, so the template needs to maintain the correct tagNames.

Another way:

initialize : function () {

},

render : function () {

    this.$el.empty();

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});

    this.$el.append(this.subView1.render().el, this.subView2.render().el);
}

Pros: You don't have to re-delegate events. You don't need a template that just contains empty placeholders and your tagName's are back to being defined by the view.

Cons: You now have to make sure to append things in the right order. The parent view's render is still cluttered by the subview rendering.

With an onRender event:

initialize : function () {
    this.on('render', this.onRender);
    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

Pros: The subview logic is now separated from the view's render() method.

With an onRender event:

initialize : function () {
    this.on('render', this.onRender);
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {
    this.subView1 = new Subview();
    this.subView2 = new Subview();
    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

I've kind of mix and matched a bunch of different practices across all of these examples (so sorry about that) but what are the ones that you would keep or add? and what would you not do?

Summary of practices:

Instantiate subviews in initialize or in render?

Perform all sub-view rendering logic in render or in onRender?

Use setElement or append/appendTo?


问:
Using AWS S3 bucket as a sink in Spring Cloud Data Flow Server installed on local machine
I've a Spring Cloud Data Flow Server installed on my Local. while creating a stream from source(file) to AWS-S3 as sink, I get the following error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name     'org.springframework.cloud.aws.context.support.io.ResourceLoaderBeanPostProcessor#0': Cannot resolve reference to bean 'amazonS3' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonS3' defined in
org.springframework.cloud.stream.app.s3.AmazonS3Configuration: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.amazonaws.services.s3.AmazonS3]: Factory method 'amazonS3' threw exception;
nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
</code>```

Caused By:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'amazonS3' defined in org.springframework.cloud.stream.app.s3.AmazonS3Configuration: Bean instantiation via factory method failed; nested exception is
 org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.amazonaws.services.s3.AmazonS3]: Factory method 'amazonS3' threw exception;
 nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
</code>```

What I observe is, that S3 can only be used as a sink if Spring Cloud Dataflow server is installed on AWS EC2.

Is there, any way, by which a Spring Cloud Data Flow Server installed on Local machine can be used to connect to AWS S3 bucket and use the same as sink

答:
Maybe is a configuration issue in your dev env, As for version of spring cloud Brixton.SR7, to configure manually the region you would set in your application.properties (or .xml, .yml whatever you're using). This parameter should be ONLY for your dev env, unless you truly need to specify it in production.

```<code>cloud.aws.region.static=us-east-1
</code>```

I also had to set next property for dev, but maybe you dont need it.

```<code>cloud.aws.stack.auto=false
</code>```

Body:
I've a Spring Cloud Data Flow Server installed on my Local. while creating a stream from source(file) to AWS-S3 as sink, I get the following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name     'org.springframework.cloud.aws.context.support.io.ResourceLoaderBeanPostProcessor#0': Cannot resolve reference to bean 'amazonS3' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonS3' defined in
org.springframework.cloud.stream.app.s3.AmazonS3Configuration: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.amazonaws.services.s3.AmazonS3]: Factory method 'amazonS3' threw exception;
nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance

Caused By:

Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'amazonS3' defined in org.springframework.cloud.stream.app.s3.AmazonS3Configuration: Bean instantiation via factory method failed; nested exception is
 org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.amazonaws.services.s3.AmazonS3]: Factory method 'amazonS3' threw exception;
 nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance

What I observe is, that S3 can only be used as a sink if Spring Cloud Dataflow server is installed on AWS EC2.

Is there, any way, by which a Spring Cloud Data Flow Server installed on Local machine can be used to connect to AWS S3 bucket and use the same as sink

Body:
Maybe is a configuration issue in your dev env, As for version of spring cloud Brixton.SR7, to configure manually the region you would set in your application.properties (or .xml, .yml whatever you're using). This parameter should be ONLY for your dev env, unless you truly need to specify it in production.

cloud.aws.region.static=us-east-1

I also had to set next property for dev, but maybe you dont need it.

cloud.aws.stack.auto=false


问:
MySQL 'SHOW TABLES' Returns count instead of list (Python)
I'm troubleshooting a script I am using to query the database. To make sure I had everything working right I stripped it down to a simple 'SHOW TABLES' query. The problem is that it is returning a count of the tables instead of the list of names it should return.

```<code>import pymysql

connection = pymysql.connect(host='10.0.0.208', user='admin', passwd='Passwrd')

cursor = connection.cursor()
sqlstring = 'SHOW TABLES;'
cursor.execute('USE CustDB')
x = cursor.execute(sqlstring)

print(x)
</code>```

This is only returning '17'. What am I missing??

答:
Per the documentation, execute returns the number of rows affected

Returns: Number of affected rows

In order to get the desired results, you need to loop through the cursor

```<code>cursor.execute('USE CustDB')
tables = [c for c in cursor]
</code>```

or use fetchall

```<code>cursor.execute('USE CustDB')
tables = cursor.fetchall()
</code>```

Body:
I'm troubleshooting a script I am using to query the database. To make sure I had everything working right I stripped it down to a simple 'SHOW TABLES' query. The problem is that it is returning a count of the tables instead of the list of names it should return.

import pymysql

connection = pymysql.connect(host='10.0.0.208', user='admin', passwd='Passwrd')

cursor = connection.cursor()
sqlstring = 'SHOW TABLES;'
cursor.execute('USE CustDB')
x = cursor.execute(sqlstring)

print(x)

This is only returning '17'. What am I missing??

Body:
Per the documentation, execute returns the number of rows affected

Returns: Number of affected rows

In order to get the desired results, you need to loop through the cursor

cursor.execute('USE CustDB')
tables = [c for c in cursor]

or use fetchall

cursor.execute('USE CustDB')
tables = cursor.fetchall()


问:
Calling a stored procedure from another SQL Server Database Engine
From SQL Server Management Studio I have connected to an SQL Server database engine. This database engine has a lot of databases. From a store procedure defined in a database I am trying to call a store procedure in another database that it is in another SQL Server database engine. So I have done:

```<code>exec [MyDatabaseEngine].[MyDatabase].[MyStoreProcedure] param1, param2
</code>```

But it is not working.

I do not know if I have explained it correctly. If not, please let me know.

答:
You need to have linked server created with credentials access to the other database. More info

https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine

Once you have it, you can run queries on another server

```<code>SELECT name FROM [SRVR002\ACCTG].master.sys.databases ;
GO
</code>```

Body:
From SQL Server Management Studio I have connected to an SQL Server database engine. This database engine has a lot of databases. From a store procedure defined in a database I am trying to call a store procedure in another database that it is in another SQL Server database engine. So I have done:

exec [MyDatabaseEngine].[MyDatabase].[MyStoreProcedure] param1, param2

But it is not working.

I do not know if I have explained it correctly. If not, please let me know.

Body:
You need to have linked server created with credentials access to the other database. More info

https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine

Once you have it, you can run queries on another server

SELECT name FROM [SRVR002\ACCTG].master.sys.databases ;
GO


问:
Write some random numbers to the pipe?
my question is can I write an integer to pipe ? and how ?

I need to make 3 processes first one generate 2 numbers, second make sum of the numbers, third print the result (USING PIPE)

Thanks all

答:
Since a pipe is just a file, you can use the fprintf() function to convert a random number to text and write that to the pipe. For instance:</p>

```<code>FILE *pipe = popen("path/to/your/program", "w");
if (pipe != NULL) {
    fprintf(pipe, "%d\n", rand());
    pclose(pipe);
}
</code>```

Title: Write some random numbers to the pipe?

Body:
Since a pipe is just a file, you can use the fprintf() function to convert a random number to text and write that to the pipe. For instance:

FILE *pipe = popen("path/to/your/program", "w");
if (pipe != NULL) {
    fprintf(pipe, "%d\n", rand());
    pclose(pipe);
}