问:
8-bit binary addition
Can someone explain how to calculate checksum with 8-bit binary addition? This is an excerpt from the documentation:

This is the general form of the messages:

```<code>STX | TYPE | FS | DATA | FS | CHK | ETX
</code>```

STX is HEX 02

ETX is HEX 03

FS  is HEX 15

The "type" is a unique, 1-byte message identifier (e.g., 'P' for Poll message).
"Data" contains printable ASCII characters.

Checksum

The Checksum is computed on all characters, including all the <FS> characters, between <STX> and <CHK>. The Checksum is calculated by the 8-bit binary addition of all included characters with the 8th or parity bit assumed to be zero. Carries beyond the 8th bit are lost. The 8-bit result is converted into two printable ASCII Hex characters, ranging from 00 to FF, which are then inserted into the data stream as <CHK>. The Hex characters A-F are uppercase. The receiving device recalculates the checksum on the buffered message and compares it with the checksum it received. The comparison is the basis for subsequent acknowledgement (<ACK>) or negative acknowledgement (<NAK>) of the transmission.

答:
None of the answers above work, when the sum of the bytes crosses 256.

The OP was probably trying to interface a Siemens Dimension EXL200 chemistry analyzer with his _Lab information system.

The paragraph he's posted (about the spec for the checksum) is copy/paste from their manual.
I've been banging my head against this particular problem for the last 12 hours and cannot find any way around it.
I am including some of the strings mentioned in the Siemens Manual, as they have provided the checksums.

You will notice that all the answers above work, but only for some of the strings.
In others, the checksum in the manual is completely different from what we get by using the methods posted above.

I am posting two examples, 1 failure, and 1 success => same algorithm.

For convenience(as the protocol uses HEX characters, I'm including the actual byte arrays, so that anyone reading this can try it in his/her language of choice).
I hope someone can find a solution here:

Example One: @Just My Correct Opinion's Solution Fails:

```<code>/***

RAW STRING:
P<FS>9300<FS>1<FS>1<FS>0<FS>

BYTE ARRAY:
{80, 28, 57, 51, 48, 48, 28, 49, 28, 49, 28, 48, 28}

EXPECTED CHECKSUM :
6C

ACTUAL CHECKSUM :
3A

CODE TO REPRODUCE BELOW:
***/

byte[] byteArry = {80, 28, 57, 51, 48, 48, 28, 49, 28, 49, 28, 48, 28};
String ss = new String(byteArry);
int s = 0;

for(int i = 0; i < ss.length(); i++)
    {
        s += ss.charAt(i) & 0x7f;
        s &= 0xff;
    }
    System.out.println(s);
    System.out.format("Checksum: %02X\n", s);
}

</code>```

Example Two: @Just My Correct Opinion's Solution SUCCEEDS:

```<code>/***

RAW STRING:
M<FS>A<FS><FS>

BYTE ARRAY:
{77, 28, 65, 28, 28}

EXPECTED CHECKSUM :
E2

ACTUAL CHECKSUM :
E2

CODE TO REPRODUCE BELOW:
***/

byte[] byteArry = {77, 28, 65, 28, 28};
String ss = new String(byteArry);
int s = 0;

for(int i = 0; i < ss.length(); i++)
    {
        s += ss.charAt(i) & 0x7f;
        s &= 0xff;
    }
    System.out.println(s);
    System.out.format("Checksum: %02X\n", s);
}

</code>```

Given the above examples, I've noticed that it seems to fail as soon as the sum of the bytes crosses a certain value(what I cannot be sure), but I think its around 256. Anything above 256 gives a result different from whatever the people at Siemens seem to want.
The first example has crossed 256 by a big margin, but the second one is at 226. There is another example in the manual of an even smaller byte sum, where our code above seems to work, producing the expected checksum.
I'm not a very good programmer, but I'm sure this has something to do with overflows.

Bhargav R.

ContentLicense: CC BY-SA 2.5

Title: 8-bit binary addition

Body:
Can someone explain how to calculate checksum with 8-bit binary addition? This is an excerpt from the documentation:

This is the general form of the messages:

STX | TYPE | FS | DATA | FS | CHK | ETX

STX is HEX 02

ETX is HEX 03

FS  is HEX 15

The "type" is a unique, 1-byte message identifier (e.g., 'P' for Poll message).
"Data" contains printable ASCII characters.

Checksum

The Checksum is computed on all characters, including all the <FS> characters, between <STX> and <CHK>. The Checksum is calculated by the 8-bit binary addition of all included characters with the 8th or parity bit assumed to be zero. Carries beyond the 8th bit are lost. The 8-bit result is converted into two printable ASCII Hex characters, ranging from 00 to FF, which are then inserted into the data stream as <CHK>. The Hex characters A-F are uppercase. The receiving device recalculates the checksum on the buffered message and compares it with the checksum it received. The comparison is the basis for subsequent acknowledgement (<ACK>) or negative acknowledgement (<NAK>) of the transmission.

Body:
None of the answers above work, when the sum of the bytes crosses 256.

The OP was probably trying to interface a Siemens Dimension EXL200 chemistry analyzer with his _Lab information system.

The paragraph he's posted (about the spec for the checksum) is copy/paste from their manual.
I've been banging my head against this particular problem for the last 12 hours and cannot find any way around it.
I am including some of the strings mentioned in the Siemens Manual, as they have provided the checksums.

You will notice that all the answers above work, but only for some of the strings.
In others, the checksum in the manual is completely different from what we get by using the methods posted above.

I am posting two examples, 1 failure, and 1 success => same algorithm.

For convenience(as the protocol uses HEX characters, I'm including the actual byte arrays, so that anyone reading this can try it in his/her language of choice).
I hope someone can find a solution here:

Example One: @Just My Correct Opinion's Solution Fails:

/***

RAW STRING:
P<FS>9300<FS>1<FS>1<FS>0<FS>

BYTE ARRAY:
{80, 28, 57, 51, 48, 48, 28, 49, 28, 49, 28, 48, 28}

EXPECTED CHECKSUM :
6C

ACTUAL CHECKSUM :
3A

CODE TO REPRODUCE BELOW:
***/

byte[] byteArry = {80, 28, 57, 51, 48, 48, 28, 49, 28, 49, 28, 48, 28};
String ss = new String(byteArry);
int s = 0;

for(int i = 0; i < ss.length(); i++)
    {
        s += ss.charAt(i) & 0x7f;
        s &= 0xff;
    }
    System.out.println(s);
    System.out.format("Checksum: %02X\n", s);
}

Example Two: @Just My Correct Opinion's Solution SUCCEEDS:

/***

RAW STRING:
M<FS>A<FS><FS>

BYTE ARRAY:
{77, 28, 65, 28, 28}

EXPECTED CHECKSUM :
E2

ACTUAL CHECKSUM :
E2

CODE TO REPRODUCE BELOW:
***/

byte[] byteArry = {77, 28, 65, 28, 28};
String ss = new String(byteArry);
int s = 0;

for(int i = 0; i < ss.length(); i++)
    {
        s += ss.charAt(i) & 0x7f;
        s &= 0xff;
    }
    System.out.println(s);
    System.out.format("Checksum: %02X\n", s);
}

Given the above examples, I've noticed that it seems to fail as soon as the sum of the bytes crosses a certain value(what I cannot be sure), but I think its around 256. Anything above 256 gives a result different from whatever the people at Siemens seem to want.
The first example has crossed 256 by a big margin, but the second one is at 226. There is another example in the manual of an even smaller byte sum, where our code above seems to work, producing the expected checksum.
I'm not a very good programmer, but I'm sure this has something to do with overflows.

Bhargav R.


来源: stackexchange

问:
How to create a Variable with scope global and but should not be a STATIC
Need a variable to hold a value which will be assigned once and will be used by every method of a class

if I specify it as non static variable it is not holding the value

```<code>Class Test{

private String test;

public void method1(){
     test = "String1";
}

public void method2(){
     System.out.println(test.length());
}

}
</code>```

Getting Null Pointer exception. the value of the test will be used in every method.

Could anyone help me, how to fix the issue.

答:
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:

```<code>Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
</code>```

You should use this object "test1" as a parameter wherever you need it.

If you want to access the variable globally then create a Singletone class:

```<code>    class Test{

    private static Test single_instance = null;
    private String test;

    // private constructor restricted to this class itself
    private Test(){
    }

    // static method to create instance of Singleton class
    public static Test getInstance(){
        if (single_instance == null)
            single_instance = new Test();

        return single_instance;
    }

    public void setTest(String value){
        test = value;
    }

    public String getTest(){
        return test;
    }

  public static void main(String args[]){
        Test test = Test.getInstance();
        test.setTest("String1");
        test.getTest();
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Need a variable to hold a value which will be assigned once and will be used by every method of a class

if I specify it as non static variable it is not holding the value

Class Test{

private String test;

public void method1(){
     test = "String1";
}

public void method2(){
     System.out.println(test.length());
}

}

Getting Null Pointer exception. the value of the test will be used in every method.

Could anyone help me, how to fix the issue.

Body:
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:

Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();

You should use this object "test1" as a parameter wherever you need it.

If you want to access the variable globally then create a Singletone class:

    class Test{

    private static Test single_instance = null;
    private String test;

    // private constructor restricted to this class itself
    private Test(){
    }

    // static method to create instance of Singleton class
    public static Test getInstance(){
        if (single_instance == null)
            single_instance = new Test();

        return single_instance;
    }

    public void setTest(String value){
        test = value;
    }

    public String getTest(){
        return test;
    }

  public static void main(String args[]){
        Test test = Test.getInstance();
        test.setTest("String1");
        test.getTest();
    }

}


问:
jquery form validation ajaxSubmit()
I am getting very frustrated with this jquery form validation ajaxSubmit();

In chrome, it seems to fail silently without even hitting the submitHandler, firefox does, but still goes on to the action="contact.php" page. I was expecting it to just post in the background and possibly return results, but can't get it to work that way.

Edit: Found a fix for this if anyone else is interested, put this line of code somewhere in your dom ready.

```<code>// disable HTML5 native validation and let jquery handle it.
    $('form').attr('novalidate','novalidate');
</code>```

HTML form:

```<code><form method="post" action="contact.php" id="contact">
    <fieldset>
        <input type="text" id="email" class="required email" name="email"  maxlength="30" value="youremail @ example.com" />
        <input type="text" id="subject" class="required" name="subject" maxlength="24" value="Enter your subject" />
        <textarea id="msg" class="required textarea" name="msg" cols="30" rows="5">Reason for contact.</textarea>
        <input type="submit" class="formBtn" value="Punch me an Email" />
    </fieldset>
</form>
</code>```

JQuery:

```<code>$(window).load(function(){
    $('#contact').validate({
            rules:{
                email:{required: true, email:true},
                subject:{required: true, minlength: 5},
                msg:{required: true, minlength: 50}
            },
            messages:{
                email:'',
                subject: '',
                msg: ''
            },
            invalidHandler:function(){
                $('div.error').hide();
            },
            focusInvalid:true,
            onfocusout:false,
            submitHandler: function() {
               // never hits with chrome, and alert works in FF4,
               // but still goes to contact.php
               $('#contact').ajaxSubmit();
           }
        });
});
</code>```

答:
I'm not really familiar with the validation plugin, but I would try it the other way around, by validating the form in the form plugin's beforeSubmit event:</p>

```<code>$('#contact').ajaxForm({
  beforeSubmit: function() {
    $('#contact').validate({ /* ... */ });
    return $('#contact').valid();
  },
  success: function(resp) {
    alert(resp);
  }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery form validation ajaxSubmit()

Body:
I am getting very frustrated with this jquery form validation ajaxSubmit();

In chrome, it seems to fail silently without even hitting the submitHandler, firefox does, but still goes on to the action="contact.php" page. I was expecting it to just post in the background and possibly return results, but can't get it to work that way.

Edit: Found a fix for this if anyone else is interested, put this line of code somewhere in your dom ready.

// disable HTML5 native validation and let jquery handle it.
    $('form').attr('novalidate','novalidate');

HTML form:

<form method="post" action="contact.php" id="contact">
    <fieldset>
        <input type="text" id="email" class="required email" name="email"  maxlength="30" value="youremail @ example.com" />
        <input type="text" id="subject" class="required" name="subject" maxlength="24" value="Enter your subject" />
        <textarea id="msg" class="required textarea" name="msg" cols="30" rows="5">Reason for contact.</textarea>
        <input type="submit" class="formBtn" value="Punch me an Email" />
    </fieldset>
</form>

JQuery:

$(window).load(function(){
    $('#contact').validate({
            rules:{
                email:{required: true, email:true},
                subject:{required: true, minlength: 5},
                msg:{required: true, minlength: 50}
            },
            messages:{
                email:'',
                subject: '',
                msg: ''
            },
            invalidHandler:function(){
                $('div.error').hide();
            },
            focusInvalid:true,
            onfocusout:false,
            submitHandler: function() {
               // never hits with chrome, and alert works in FF4,
               // but still goes to contact.php
               $('#contact').ajaxSubmit();
           }
        });
});

Body:
I'm not really familiar with the validation plugin, but I would try it the other way around, by validating the form in the form plugin's beforeSubmit event:

$('#contact').ajaxForm({
  beforeSubmit: function() {
    $('#contact').validate({ /* ... */ });
    return $('#contact').valid();
  },
  success: function(resp) {
    alert(resp);
  }
});


问:
Segmentation fault in C
When I try to run the following C program in my VS code it shows segmentation fault core dumped. How can I fix it?</p>

```<code>#include <stdio.h>
#include <string.h>

void read(student);
void display(student);

struct student {
    int roll, result;
    char name[20], depart[20], sex;
    float percent, marks[5];
};

void main() {
    struct student s;
    read(s);
}

void read(struct student std) {
    int c = 0, i;
    printf("enter the roll no:");
    scanf("%d", &std.roll);
    printf("enter the name:\n");
    scanf("%s", std.name);
    printf("enter Sex:\n");
    scanf(" %c", &std.sex);
    printf("Enter the department:\n");
    scanf("%s", std.depart);
    printf("enter the marks in 5 subjects:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", std.marks[i]);
    }
}
</code>```

答:
The main problem as discussed in the comments is that when using scanf to read a value, you have to pass in a pointer to the variable and in the case of populating an array, you still need to pass in a pointer to each element. And you also need to specify the correct format - %d is for reading integers, %f is for reading floats.

So the following line of code...

```<code>scanf("%d", std.marks[i]);
</code>```

...should be

```<code>scanf("%f", &std.marks[i]);
</code>```

The other problem which you've not yet discovered is you aren't actually populating s - you're populating a local copy. To populate s you need to pass in a pointer to it like so:

```<code>read(&s);
</code>```

which means your function would look more like

```<code>void read(struct student *std) {
     int c=0,i;
     printf("enter the roll no:");
     scanf("%d",&std->roll);
</code>```

and you'd have to use std-> instead of std. to deference the struct elements properly.

As an aside, calling a function read is generally not a good idea as there is a C library called read - you'd be better off calling it read_student to also better indicate what it does.

OwnerDisplayName: Sudru

Title: Segmentation fault in C

Body:
When I try to run the following C program in my VS code it shows segmentation fault core dumped. How can I fix it?

#include <stdio.h>
#include <string.h>

void read(student);
void display(student);

struct student {
    int roll, result;
    char name[20], depart[20], sex;
    float percent, marks[5];
};

void main() {
    struct student s;
    read(s);
}

void read(struct student std) {
    int c = 0, i;
    printf("enter the roll no:");
    scanf("%d", &std.roll);
    printf("enter the name:\n");
    scanf("%s", std.name);
    printf("enter Sex:\n");
    scanf(" %c", &std.sex);
    printf("Enter the department:\n");
    scanf("%s", std.depart);
    printf("enter the marks in 5 subjects:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", std.marks[i]);
    }
}

Body:
The main problem as discussed in the comments is that when using scanf to read a value, you have to pass in a pointer to the variable and in the case of populating an array, you still need to pass in a pointer to each element. And you also need to specify the correct format - %d is for reading integers, %f is for reading floats.

So the following line of code...

scanf("%d", std.marks[i]);

...should be

scanf("%f", &std.marks[i]);

The other problem which you've not yet discovered is you aren't actually populating s - you're populating a local copy. To populate s you need to pass in a pointer to it like so:

read(&s);

which means your function would look more like

void read(struct student *std) {
     int c=0,i;
     printf("enter the roll no:");
     scanf("%d",&std->roll);

and you'd have to use std-> instead of std. to deference the struct elements properly.

As an aside, calling a function read is generally not a good idea as there is a C library called read - you'd be better off calling it read_student to also better indicate what it does.


问:
Convert entire column from integer to datetime using SQL
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

```<code>UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);
</code>```

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

答:
```<code>ALTER TABLE [dbo].[WORKER]
ALTER COLUMN [INT_TIME] DATETIME
</code>```

This statement alters the integer column to a datetime column and parses the values automatically.

Body:
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

Body:
ALTER TABLE [dbo].[WORKER]
ALTER COLUMN [INT_TIME] DATETIME

This statement alters the integer column to a datetime column and parses the values automatically.


问:
Using COUNTIFS with checking string and comparing values
I have the following excel sheet:

```<code>  Value
2 50
3 60
4 50
5 0
6 0
7 60
</code>```

I am trying to count the number of times when comparing 2 rows a time the first or second is bigger by Value and Value is not 0.

For example:

I am currently using:

```<code>=IFS(A2>A3;"Original";A2<A3;"Fake";A2=A3;"Equal")
</code>```

Which simply adds a text value to column B by checking 2 Values. What I'd like to add is a statement - & Value>0.

Expected output:

```<code>  Value   State
2 50      Fake
3 60
4 50      (empty because row 5 is 0)
5 0
6 0       (empty because row 6 is 0)
7 60
</code>```

In short - how can I count the number of occurrences when condition #1 is met and condition #2 is met, when the second condition is not a text value but a number comparison?

Thank you for your suggestions.

答:
Try following formula:

```<code>=IFERROR(CHOOSE((A2>A3)*(A3<>0)*1+(A2<A3)*(A2<>0)*2+(A2=A3)*(A2<>0)*3;"Original";"Fake";"Equal");"")
</code>```

Edit

With condition that the formula works every second row.

```<code>=IFERROR(CHOOSE(((A2>A3)*(A3<>0)*1 + (A2<A3)*(A2<>0)*2+(A2=A3)*(A2<>0)*3)*(MOD(ROW();2)=0);"Original";"Fake";"Equal");"")
</code>```

Body:
I have the following excel sheet:

  Value
2 50
3 60
4 50
5 0
6 0
7 60

I am trying to count the number of times when comparing 2 rows a time the first or second is bigger by Value and Value is not 0.

For example:

I am currently using:

=IFS(A2>A3;"Original";A2<A3;"Fake";A2=A3;"Equal")

Which simply adds a text value to column B by checking 2 Values. What I'd like to add is a statement - & Value>0.

Expected output:

  Value   State
2 50      Fake
3 60
4 50      (empty because row 5 is 0)
5 0
6 0       (empty because row 6 is 0)
7 60

In short - how can I count the number of occurrences when condition #1 is met and condition #2 is met, when the second condition is not a text value but a number comparison?

Thank you for your suggestions.

Body:
Try following formula:

=IFERROR(CHOOSE((A2>A3)*(A3<>0)*1+(A2<A3)*(A2<>0)*2+(A2=A3)*(A2<>0)*3;"Original";"Fake";"Equal");"")

Edit

With condition that the formula works every second row.

=IFERROR(CHOOSE(((A2>A3)*(A3<>0)*1 + (A2<A3)*(A2<>0)*2+(A2=A3)*(A2<>0)*3)*(MOD(ROW();2)=0);"Original";"Fake";"Equal");"")


问:
Java/Spring: initMocks a class which got @Value from yml file
I am writing unit tests on a Service class like below :

```<code>@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}
</code>```

My current test class for this test is like this:

```<code>@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }

    @Test
    public void shouldReturnException() {
        final Exception exception = assertThrows(ApiErrorException.class,
        () -> myService.myMethod(var));

    assertThat(exception).hasMessage("here the message");

    verify(otherService, never()).method();
    }
}
</code>```

With this two classes, I have an application.yml & application-dev.yml to set my.property.
I want to get the property from the application-dev file during my tests execution.
But, with @InjectMocks, property is null. Whereas, using @Autowired in place of/with @InjectMocks, the property variable is set with the value present in file.

Problem, using Autowired with/in place of InjectMock results in the otherService variable being initialized, so no mock is created.

How can I still use Mockito, while having the property variable set with the value in the file?
I saw about ReflectionTestUtils.setField, but using it mean having no use of a yml file (which i am not fan).

Have a nice day

With the help of @Deadpool, the tests can use the values written in the application.yml file.
But, using @MockBean and @Autowired, the tests get a behavior I do not understand.

Example:
I test that a method return an Exception, and I verify that others methods are not called after the exception was catch: verify(otherService, never()).otherMethod();
Writing this line returns the following error org.mockito.exceptions.verification.NeverWantedButInvoked.

The initial exception is correctly caught, but the test does not seem to acknowledge that no other services must be called.

答:
@SpringBootTest is used for integration testing which loads the ApplicationContext that will be utilized for test environment

The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

Since you are generating integration environment using @SpringBootTest you need to mock the bean using @MockBean annotation

```<code>@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {

   @MockBean
   private OtherService otherService;

   @Autowire
   private MyService myService;

   @BeforeEach
   public void init() {

    when(otherService.method()).thenReturn("a string");
   }
}
</code>```

Body:
I am writing unit tests on a Service class like below :

@Component
@Profile({"default", "dev"})
public class MyService {
    @Value("${my.property}")
    private String property;

    private OtherService otherService;

    public void MyMethod() {
        String myVar = otherService.method();

        return String.format("MyVar %s & MyProperty %s", myVar, property);
    }
}

My current test class for this test is like this:

@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {
    @Mock
    private OtherService otherService;

    @InjectMocks
    private MyService myService;

    @BeforeEach()
    public void init() {
        MockitoAnnotations.initMocks(this);

        when(otherService.method()).thenReturn("a string");
    }

    @Test
    public void shouldReturnException() {
        final Exception exception = assertThrows(ApiErrorException.class,
        () -> myService.myMethod(var));

    assertThat(exception).hasMessage("here the message");

    verify(otherService, never()).method();
    }
}

With this two classes, I have an application.yml & application-dev.yml to set my.property.
I want to get the property from the application-dev file during my tests execution.
But, with @InjectMocks, property is null. Whereas, using @Autowired in place of/with @InjectMocks, the property variable is set with the value present in file.

Problem, using Autowired with/in place of InjectMock results in the otherService variable being initialized, so no mock is created.

How can I still use Mockito, while having the property variable set with the value in the file?
I saw about ReflectionTestUtils.setField, but using it mean having no use of a yml file (which i am not fan).

Have a nice day

With the help of @Deadpool, the tests can use the values written in the application.yml file.
But, using @MockBean and @Autowired, the tests get a behavior I do not understand.

Example:
I test that a method return an Exception, and I verify that others methods are not called after the exception was catch: verify(otherService, never()).otherMethod();
Writing this line returns the following error org.mockito.exceptions.verification.NeverWantedButInvoked.

The initial exception is correctly caught, but the test does not seem to acknowledge that no other services must be called.

Body:
@SpringBootTest is used for integration testing which loads the ApplicationContext that will be utilized for test environment

The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

Since you are generating integration environment using @SpringBootTest you need to mock the bean using @MockBean annotation

@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
public class MyServiceTest {

   @MockBean
   private OtherService otherService;

   @Autowire
   private MyService myService;

   @BeforeEach
   public void init() {

    when(otherService.method()).thenReturn("a string");
   }
}


问:
Convert AM/PM time to 24 hours format?
I need to convert 12 hours format time (am/pm) to 24 hours format time, e.g. 01:00 PM to 13:00 using C#. How can I convert it?</p>

答:
```<code>using System;

class Solution
{
    static string timeConversion(string s)
    {
        return DateTime.Parse(s).ToString("HH:mm");
    }

    static void Main(string[] args)
    {
        Console.WriteLine(timeConversion("01:00 PM"));
        Console.Read();
    }
}
</code>```

Title: Convert AM/PM time to 24 hours format?


问:
Replace text stored in string
Using iText 5.5, I am trying to assign value from list to variable. Any professional eager to help amateur?

File I am parsing: https://slicedinvoices.com/pdf/wordpress-pdf-invoice-plugin-sample.pdf

Here is my code:

```<code>using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDF_file_reader
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> InvoiceNumbers = new List<string>();

            string filePath = @"C:\temp\parser\Invoice_Template.pdf";
            int pagesToScan = 2;

            string strText = string.Empty;
            try
            {
                PdfReader reader = new PdfReader(filePath);

                for (int page = 1; page <= pagesToScan; page++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
                {
                    ITextExtractionStrategy its = new LocationTextExtractionStrategy();
                    strText = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
                    //creating the string array and storing the PDF line by line
                    string[] lines = strText.Split('\n');
                    foreach (string line in lines)
                    {
                        if (line.Contains("Invoice Number"))
                        {
                            InvoiceNumbers.Add(line.Trim());
                            break;
                        }
                    }

                    var match = InvoiceNumbers.FirstOrDefault(stringToCheck => stringToCheck.Contains("Invoice Number"));

                    match.Replace("Invoice number", "").Trim();

                    Console.Write(match);

                    Console.Read();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }
    }
}
</code>```

I need match to be INV-3337 currently it seems to be Invoice Number INV-3337. Why this command:

match.Replace("Invoice number", "").Trim();?

does not perform Replace.

My output:

答:
It doesn't work because the match is case sensitive (capital N vs lower case n).</p>

```<code>match = match.Replace("Invoice Number", "").Trim();
</code>```

Title: Replace text stored in string

Body:
Using iText 5.5, I am trying to assign value from list to variable. Any professional eager to help amateur?

File I am parsing: https://slicedinvoices.com/pdf/wordpress-pdf-invoice-plugin-sample.pdf

Here is my code:

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDF_file_reader
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> InvoiceNumbers = new List<string>();

            string filePath = @"C:\temp\parser\Invoice_Template.pdf";
            int pagesToScan = 2;

            string strText = string.Empty;
            try
            {
                PdfReader reader = new PdfReader(filePath);

                for (int page = 1; page <= pagesToScan; page++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
                {
                    ITextExtractionStrategy its = new LocationTextExtractionStrategy();
                    strText = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
                    //creating the string array and storing the PDF line by line
                    string[] lines = strText.Split('\n');
                    foreach (string line in lines)
                    {
                        if (line.Contains("Invoice Number"))
                        {
                            InvoiceNumbers.Add(line.Trim());
                            break;
                        }
                    }

                    var match = InvoiceNumbers.FirstOrDefault(stringToCheck => stringToCheck.Contains("Invoice Number"));

                    match.Replace("Invoice number", "").Trim();

                    Console.Write(match);

                    Console.Read();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }
    }
}

I need match to be INV-3337 currently it seems to be Invoice Number INV-3337. Why this command:

match.Replace("Invoice number", "").Trim();?

does not perform Replace.

My output:

Body:
It doesn't work because the match is case sensitive (capital N vs lower case n).

match = match.Replace("Invoice Number", "").Trim();


问:
How to return a range of XML nodes with XQuery of FLWOR?
I'm interested in getting back a specific range of results, say from 99 to 199, or, perhaps, the last JSON object.  While this works for small numbers or ranges, how can it be generalized or expanded to a larger range?

```<code>xquery version "3.0";

for $i in (1,2,3)
for $line in db:open("json_people")
return $line/json/_[$i]
</code>```

答:
You can avoid the nested loop, use the position() function and specify a range:

```<code>db:open("json_people")/json/_[position() = 99 to 199]
</code>```

Body:
I'm interested in getting back a specific range of results, say from 99 to 199, or, perhaps, the last JSON object.  While this works for small numbers or ranges, how can it be generalized or expanded to a larger range?

xquery version "3.0";

for $i in (1,2,3)
for $line in db:open("json_people")
return $line/json/_[$i]

Body:
You can avoid the nested loop, use the position() function and specify a range:

db:open("json_people")/json/_[position() = 99 to 199]


问:
How to scrape data other then stock data from yahoo finance
I'm wanting to scrape data on different shoe companies. I am trying to scrape the EPS from yahoo-finance however I cant find anywhere how to do this. The only way I see so far is finding stock data as open,close etc. How can I scrape data from yahoo-fiance that is not stock data.</p>

答:
This will grab the metrics you want and write everything to a CSV file.</p>

```<code>import csv
import requests
from bs4 import BeautifulSoup

url_base = "https://finviz.com/quote.ashx?t="
tckr = ['SBUX','MSFT','AAPL']
url_list = [url_base + s for s in tckr]

with open('C:/your_path_here/metrics.csv', 'a', newline='') as f:
    writer = csv.writer(f)

    for url in url_list:
        try:
            fpage = requests.get(url)
            fsoup = BeautifulSoup(fpage.content, 'html.parser')

            # write header row
            writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2-cp'})))

            # write body row
            writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2'})))
        except HTTPError:
            print("{} - not found".format(url))
</code>```

Body:
This will grab the metrics you want and write everything to a CSV file.

import csv
import requests
from bs4 import BeautifulSoup

url_base = "https://finviz.com/quote.ashx?t="
tckr = ['SBUX','MSFT','AAPL']
url_list = [url_base + s for s in tckr]

with open('C:/your_path_here/metrics.csv', 'a', newline='') as f:
    writer = csv.writer(f)

    for url in url_list:
        try:
            fpage = requests.get(url)
            fsoup = BeautifulSoup(fpage.content, 'html.parser')

            # write header row
            writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2-cp'})))

            # write body row
            writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2'})))
        except HTTPError:
            print("{} - not found".format(url))


问:
Java and MySql connection problem
I am using Java+MySql. I am trying to add bulk data (around 40 million records). My application works fine for couple of hundred thousands records but after that it starts giving me following exception:

```<code>Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor5.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at net.jboss.Database.DatabaseConnection.getConnection(DatabaseConnection.java:48)
    at net.jboss.emp.idm.adta(mde.java:96)
    at net.jboss.emp.idm.main(mde.java:69)
Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
    ... 16 more
</code>```

I googled this problem and tried almost every option (updating windows registry, changing my.cnf file, changing mysql global parameters etc.) but its not working.

答:
It seems connection isn't being closed properly. I would recommend you to use connection-pooling

Also See

Connection pooling with MySQL Connector/J

Title: Java and MySql connection problem

Body:
I am using Java+MySql. I am trying to add bulk data (around 40 million records). My application works fine for couple of hundred thousands records but after that it starts giving me following exception:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor5.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at net.jboss.Database.DatabaseConnection.getConnection(DatabaseConnection.java:48)
    at net.jboss.emp.idm.adta(mde.java:96)
    at net.jboss.emp.idm.main(mde.java:69)
Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
    ... 16 more

I googled this problem and tried almost every option (updating windows registry, changing my.cnf file, changing mysql global parameters etc.) but its not working.


问:
BotFramework WebChat not sending messages
I am trying to run one of the botbuilders samples to check the opportunities of sending adaptive cards to several channels starting with webchat. The example can be found here: https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/javascript_nodejs/07.using-adaptive-cards

I managed to establish the connection with framework emulator, but when changing to test it in the azure console with the webChat test it seems that webChat is not able to send messages.

As I am using SDK V4 I understood that I do not have to care at all for the SSL Connection, neither I have to care about an A-category certificate - it's all done by the SDK/Framework.

So my bot is running as restify-server under the http protocol, but the configuration of the botservice indicates that the service endpoint should support https. Do I need to have worries about this?

Here the sample code:

```<code>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

const path = require('path');
const restify = require('restify');

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');

const { AdaptiveCardsBot } = require('./bots/adaptiveCardsBot');

// Read botFilePath and botFileSecret from .env file.
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create adapter. See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppID,
    appPassword: process.env.MicrosoftAppPassword
});

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    // NOTE: In production environment, you should consider logging this to Azure
    //       application insights.
    console.error(`\n [onTurnError] unhandled error: ${ error }`);

    // Send a trace activity, which will be displayed in Bot Framework Emulator
    await context.sendTraceActivity(
        'OnTurnError Trace',
        `${ error }`,
        'https://www.botframework.com/schemas/error',
        'TurnError'
    );

    // Send a message to the user
    await context.sendActivity('The bot encountered an error or bug.');
    await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};

// Create the AdaptiveCardsBot.
const bot = new AdaptiveCardsBot();

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
    console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        await bot.run(context);
    });
});```

```

答:
This likely doesn't have anything to do with HTTP(S)/SSL. It sounds like a deployment issue. Here is some common deployment troubleshooting:

Common Deployment Issues

Recommended Steps

Test to see if "Test in Web Chat" works from Azure Portal > Your Resource Group > Your Bot > Test in Web Chat.

If it works, your deployment was successful and you need to troubleshoot why your client cannot connect to your deployed bot

If it doesn't work, please follow additional troubleshooting steps from this document

If you ran into errors while executing deployment CLI commands, ensure you have the latest version of Azure CLI

Some CLI commands will fail without much explanation. This is usually a formatting error. For your CLI commands, ensure that:

The entire command has appropriate spacing

User-provided strings are surrounded by quotes

User-provided strings for resource names are free of special characters (this mostly applies to App Service Plan names). See Naming rules and restrictions for specific details.

Ensure that you ran the az bot prepare-deploy step prior to deployment. Missing this step often manifests in a bot not starting or 404 errors (due to missing/incorrect web.config) when visiting https://<yourBot>.azurewebsites.net

Ensure that the file/folder structure of https://<yourBot>.scm.azurewebsites.net/dev/wwwroot/ looks similar to your local bot. For Node bots, it will look mostly the same as your local bot files. For C# bots, it will have a lot of Microsoft.*.dll files along with <yourBot>.dll. All deployed bots should have a web.config file

For Node bots, you also need to have node_modules and .env deployed. For C# bots, you need appsettings.json. If your bot is missing .env or appsettings.json you need to either upload it, or copy the appropriate keys and values in Azure Portal > Your Resource Group > Your App Service > Configuration

Expanding on the code deployment step: When deploying, zip the contents of your project folder and not the folder by itself. Your zip file should have the structure:

code.zip/[each project file and folder] and not code.zip/myBot/[each project file and folder]

Ensure that the MicrosoftAppId and MicrosoftAppPassword that you have in appsettings.json/.env/App Service Configuration matches the ones found in your App Registration

Ensure that your App Registration can be accessed by "Accounts in any organizational directory" by following these steps

Go to https://<yourBot>.scm.azurewebsites.net/dev/wwwroot/:output, click Run, and see if any errors present themselves in the Output window

Recommended Documents

Deploy your bot

For Virtual Assistants and Skills: Manual Deployment

Set up continuous deployment

Please follow the document and let me know how it goes. If this turns out not to be a deployment issue, I will adjust this answer.

Body:
I am trying to run one of the botbuilders samples to check the opportunities of sending adaptive cards to several channels starting with webchat. The example can be found here: https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/javascript_nodejs/07.using-adaptive-cards

I managed to establish the connection with framework emulator, but when changing to test it in the azure console with the webChat test it seems that webChat is not able to send messages.

As I am using SDK V4 I understood that I do not have to care at all for the SSL Connection, neither I have to care about an A-category certificate - it's all done by the SDK/Framework.

So my bot is running as restify-server under the http protocol, but the configuration of the botservice indicates that the service endpoint should support https. Do I need to have worries about this?

Here the sample code:

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

const path = require('path');
const restify = require('restify');

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');

const { AdaptiveCardsBot } = require('./bots/adaptiveCardsBot');

// Read botFilePath and botFileSecret from .env file.
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create adapter. See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppID,
    appPassword: process.env.MicrosoftAppPassword
});

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    // NOTE: In production environment, you should consider logging this to Azure
    //       application insights.
    console.error(`\n [onTurnError] unhandled error: ${ error }`);

    // Send a trace activity, which will be displayed in Bot Framework Emulator
    await context.sendTraceActivity(
        'OnTurnError Trace',
        `${ error }`,
        'https://www.botframework.com/schemas/error',
        'TurnError'
    );

    // Send a message to the user
    await context.sendActivity('The bot encountered an error or bug.');
    await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};

// Create the AdaptiveCardsBot.
const bot = new AdaptiveCardsBot();

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
    console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        await bot.run(context);
    });
});```


问:
Django Execute a def at a time value
I'm searching for a method to make a def to execute at a time value when I run the server... Example once per day. One solution is to use Celery but i don't want to use it only for a simple def... Any suggestion? I'm using windows. Thanks!

答:
Look in to using the Windows Task Scheduler to run your django task via manage.py. You can schedule it once a day from here or as often as you need.

https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page

Use the simplest solution to solve your problem until you require a more complex solution.

Title: Django Execute a def at a time value


问:
copy a database within SQL Server Express?
I would like to make a copy of a database I have but keep it on the same server as a test database. However, everything I have found is to use the copy database wizard (I am using MS SQL Server Express).

The instructions always say: In SQL Server Management Studio, in Object Explorer, expand Databases, right-click a database, point to Tasks, and then click Copy Database.

I don't have the Copy Database option. I am running as an admin, so no clue why it is missing for me - is it something I have to install separately? I can't do the Detach/Attach since it is copying to the same server. I tried detaching, copying the MDF/LDF, renaming, attaching but as you can imagine that messed a ton up :) I am not great with SQL to do it all programatically. Is there a tool out there I could use?

答:
As for the first part of your question (why do you not see this Copy Database Wizard option under Tasks for your dbs), the answer is indeed in the fact that you are running SQL Server Express. SQL Server Express doesn't support the SQL Server Agent feature,    which this Copy DB feature relies upon, so the Copy DB feature is not shown (but many online resources fail to make that observation).

Fortunately, most everyone else has addressed the second part of your question (how to achieve the task otherwise), and nearly all point out using the existing backup and restore options (which DO exist in Express), or the export/import (which also exists in Express, I can confirm).


问:
How to take data from aspx page to stored procedure?
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

```<code>USE [PC_Rewrite]
</code>```

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

```<code>-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END
</code>```

END

Any help would be appreciated.

答:
if your stored procedure looks something like this:

```<code>Create PROCEDURE [dbo].[sp]
@ID int
AS
BEGIN
    Select ID, Display, GroupID
    From SystemTypes
    Where ID = @ID
END
</code>```

then you can set the ID parameter like this:

```<code>SqlCommand command = new SqlCommand("sp",connection);
command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("@ID, SqlDbType.Int).Value = **VALUE**;
conn.open();

SqlDataReader reader = command.ExecuteReader();
</code>```

if you want to use something like a comma seperated values string.. I found this link:

http://www.outsightinteractive.com/blog/comma_delimited_list_as_stored_procedure_parameter

https://web.archive.org/web/20211020153409/https://www.4guysfromrolla.com/webtech/031004-1.shtml

Passing List<> to SQL Stored Procedure

Body:
I have to create an RDLC report in asp.net. For which I am writing a stored procedure using different scalar functions.
I have a GUI from which I have to select a criteria and collect data according to that criteria. The GUI is here:

I have implemented all cases like "All Staff", "All services", etc but the problem comes when I have to select specific records from list box and bring data according to that. For example I select specfic Staff records from list and my report should display the records only having that selected records.
How can I handle this? I mean when I select some records from listbox, how can I take these records to the where clause of my stored procedure and how to use it there?

I am using SQL SERVER 2008.
My Stored Procedure is:

USE [PC_Rewrite]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetClients]
(
    @orderBy varchar(50)
)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

-- Insert statements for procedure here
IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY c.LastName, c.FirstName, c.MiddleInit
END

ELSE IF(@orderBy = 'Consumer Address')
BEGIN
    SELECT c.Id, c.LastName, c.FirstName, c.MiddleInit,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex, cs.Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS InsuranceProvider FROM Client c
    LEFT OUTER JOIN ClientStatus cs ON cs.Id = c.StatusId
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca on c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    ORDER BY ca.Address
END

END

Any help would be appreciated.

Body:
if your stored procedure looks something like this:

Create PROCEDURE [dbo].[sp]
@ID int
AS
BEGIN
    Select ID, Display, GroupID
    From SystemTypes
    Where ID = @ID
END

then you can set the ID parameter like this:

SqlCommand command = new SqlCommand("sp",connection);
command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("@ID, SqlDbType.Int).Value = **VALUE**;
conn.open();

SqlDataReader reader = command.ExecuteReader();

if you want to use something like a comma seperated values string.. I found this link:

http://www.outsightinteractive.com/blog/comma_delimited_list_as_stored_procedure_parameter

https://web.archive.org/web/20211020153409/https://www.4guysfromrolla.com/webtech/031004-1.shtml

Passing List<> to SQL Stored Procedure


问:
doesn't java follow implicit type conversion?
I was solving the following problem on Hacker rank. The program is supposed to print "Weird" onto the screen when N is odd. I checked the condition for N to be odd with the bitwise and(&) operator. But, I was getting this message from the compiler. I recently switched to java from c++. This operation works in C++. I wonder why it's not supported by java.

```<code>public class Solution {
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int N = scanner.nextInt();
    if(N&1){
        System.out.println("Weird");
    }
    else if(N>=2&&N<=5)
    {
       System.out.println("Not Weird");
    }
    else if(N>=6&&N<=20){
        System.out.println("Weird");
    }
    else{
        System.out.println("Not Weird");
    }

    scanner.close();
}
</code>```

}

答:
Java is not C, you can't coerce an int to a boolean. This

```<code>if(N&1){
</code>```

should be

```<code>if ((N & 1) == 1) {
</code>```

Body:
I was solving the following problem on Hacker rank. The program is supposed to print "Weird" onto the screen when N is odd. I checked the condition for N to be odd with the bitwise and(&) operator. But, I was getting this message from the compiler. I recently switched to java from c++. This operation works in C++. I wonder why it's not supported by java.

public class Solution {
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int N = scanner.nextInt();
    if(N&1){
        System.out.println("Weird");
    }
    else if(N>=2&&N<=5)
    {
       System.out.println("Not Weird");
    }
    else if(N>=6&&N<=20){
        System.out.println("Weird");
    }
    else{
        System.out.println("Not Weird");
    }

    scanner.close();
}

}

Body:
Java is not C, you can't coerce an int to a boolean. This

if(N&1){

should be

if ((N & 1) == 1) {


问:
How to keep margin(Positions) same while resizing objects

What is issue?

I don't want to confuse the community with my question so I'll tell that my question is Javascript based (Photoshop's DOM particularly). So if someone can help me on function/logic which requires basic javascript than they can take effort on reading further, Thanks.

Now; The situation is that I'm making a freebie of Photoshop Plugin (HTML Panel) named "PS Blender" which will simulate the same functionality of Illustrator's Blend Tool although Illustrator have very complex and powerful Blending options while I'm only planning to make basic blends with Positions, Rotations, Scales and Transparency. First prototype is ready and I've tested where everything worked fine except scale blendings. Before we continue, Please watch below GIFs so that you can understand the case.

First try with positions and transparency, which seems working perfectly

Second try with scaling included, which doesn't works well (The result should be like I brushed in the end of GIF)

My code regarding issue

So whole function of generating Blend is....

```<code>function generateBlend(data) {
    //Get user's input from panel
    var newLayerPositionX = data.split("&&&&")[0];
    var newLayerPositionY = data.split("&&&&")[1];
    var newLayerScaleX = data.split("&&&&")[2];
    var newLayerScaleY = data.split("&&&&")[3];
    var newLayerRotation = data.split("&&&&")[4];
    var newLayerTransparency = data.split("&&&&")[5];
    var steps = parseInt(data.split("&&&&")[6]);
    //calculates the difference between values where start values are the real data and new values are user input
    var xTransform = parseFloat(newLayerPositionX) - parseFloat(startLayerPositionX);
    var yTransform = parseFloat(newLayerPositionY) - parseFloat(startLayerPositionY);
    var xScale = parseFloat(newLayerScaleX) - parseFloat(startScaleX); //if positive then increase size and on negative decrease
    var yScale = parseFloat(newLayerScaleY) - parseFloat(startScaleY);
    var rot = parseFloat(newLayerRotation) - parseFloat(startRotation);
    var trans = parseFloat(newLayerTransparency) - parseFloat(startTransparency);
    //dummy variables to call after every increment in for loop
    var masterScaleX = parseFloat(startScaleX);
    var masterScaleY = parseFloat(startScaleY);
    var masterRotation = parseFloat(startRotation);
    var masterTransparency = parseFloat(startTransparency);
    //create a new smart object to start copying and cloning layers (steps)
    editSmartObject();
    duplicateLayer();
    moveLayerBelow();
    convertToSmart();
    renameLayer("SmartObject");
    //define masterPositionX and Y because startPositionX is the value of layers bound which lies in original document while our current layer lies in the smart object of original document so bounds need to be updated
    var docRef = app.activeDocument;
    var curLayer = docRef.activeLayer;
    var curLayerBounds = curLayer.bounds;
    var curLayerPositionX = curLayerBounds[0].value + ((curLayerBounds[2].value - curLayerBounds[0].value) / 2);
    var curLayerPositionY = curLayerBounds[1].value + ((curLayerBounds[3].value - curLayerBounds[1].value) / 2);
    var masterPositionX = parseFloat(curLayerPositionX);
    var masterPositionY = parseFloat(curLayerPositionY);
    //generates incremental values i.e. 50px move in 5 steps gives 10px per step.
    var splitPositionX = parseFloat(xTransform) / steps;
    var splitPositionY = parseFloat(yTransform) / steps;
    var splitScaleX = parseFloat(xScale) / steps;
    var splitScaleY = parseFloat(yScale) / steps;
    var splitRotation = parseFloat(rot) / steps;
    var splitTransparency = parseFloat(trans) / steps;
    //the main code for generating blends starts here
    for (var i = 0; i < steps; i++) {
        //updates masterPositing by adding splits
        masterPositionX = masterPositionX + parseFloat(splitPositionX);
        masterPositionY = masterPositionY + parseFloat(splitPositionY);
        //Photoshop DOM Scale method is relative rather than absolute so if we will change scale to 50 then it won't resize object by 50% but it will resize objects half by it's current size so we need to tweak resize method
        var masterScaleX = parseFloat(((masterScaleX + splitScaleX) * 100) / masterScaleX);
        var masterScaleY = parseFloat(((masterScaleY + splitScaleY) * 100) / masterScaleY);
        var masterRotation = masterRotation + parseFloat(splitRotation);
        var masterTransparency = masterTransparency + parseFloat(splitTransparency);
        //starts looping in where order will be duplicate SO-clear mask-move downside-apply transformation-select above layer-select bound-below layer mask (This all steps are what makes blend layers)
        try {
            duplicateLayer();
            moveLayerBelow();
            if (hasMask() == true) {
                selectLayerMask();
                deleteLayerMask();
            }
            transformLayer(parseFloat(splitPositionX), parseFloat(splitPositionY))
            resizeLayer(masterScaleX, masterScaleY);
            rotateLayer(masterRotation);
            changeTransparency(masterTransparency);
            revealAll();
            selectAboveLayer();
            selectBoundOfLayer()
            selectBelowLayer();
            createMask();
            invert();
            trim();
        } catch (e) {
            alert(e);
        }
    }
}
</code>```

As you can see above in try segment I do all stuffs by calling separate methods; Now all you might be interested are in Resize method which code is....

function resizeLayer(xScale, yScale) {
    app.activeDocument.activeLayer.resize(xScale, yScale, AnchorPosition.MIDDLECENTER);
}
```

See this is very basic function directly forked from Official JS reference.

What I've tried?

Well I've tried some various method like changing the AnchorPosition and etc but since the blending direction can be any I can't really find a way to make it work. Well the function is doing it's work. Let's take a simple example: Think that layer should move 10px on every step and should resize by 5%, Now if there wouldn't any resize then it'll move clones by every 10 px but if we will now resize it then we need to move clones 10px+the area reduced due to resize and that area seems impossible to figure out since I'm not a developer at all and know very basic on JS.

What I need?

All I need is some guidance on how should I code the logic of resize to solve this problem. All of yours contribution will be very helpful since this is freebie which I'm making for community, I can share source code if you needed too. Thanks for taking your time on my question.

Best Regard!

答:
The process was pretty simple and the question itself had answer but I never thought it from that perspective. the issue was how to maintain the margin even when object gets scaled down and all I had to do was add scaled down pixels to the xDisplacement and that worked perfectly.

And here is even a good thing, I've decided to don't make the plugin on my own since I'm fear that I might get hundreds of questions since I'm newbie in development thing, The updated code and the first prototype is available on PS Blender GitHub page. (I released it as open source maybe I can post the link)

Body:
What is issue?

I don't want to confuse the community with my question so I'll tell that my question is Javascript based (Photoshop's DOM particularly). So if someone can help me on function/logic which requires basic javascript than they can take effort on reading further, Thanks.

Now; The situation is that I'm making a freebie of Photoshop Plugin (HTML Panel) named "PS Blender" which will simulate the same functionality of Illustrator's Blend Tool although Illustrator have very complex and powerful Blending options while I'm only planning to make basic blends with Positions, Rotations, Scales and Transparency. First prototype is ready and I've tested where everything worked fine except scale blendings. Before we continue, Please watch below GIFs so that you can understand the case.

First try with positions and transparency, which seems working perfectly

Second try with scaling included, which doesn't works well (The result should be like I brushed in the end of GIF)

My code regarding issue

So whole function of generating Blend is....

function generateBlend(data) {
    //Get user's input from panel
    var newLayerPositionX = data.split("&&&&")[0];
    var newLayerPositionY = data.split("&&&&")[1];
    var newLayerScaleX = data.split("&&&&")[2];
    var newLayerScaleY = data.split("&&&&")[3];
    var newLayerRotation = data.split("&&&&")[4];
    var newLayerTransparency = data.split("&&&&")[5];
    var steps = parseInt(data.split("&&&&")[6]);
    //calculates the difference between values where start values are the real data and new values are user input
    var xTransform = parseFloat(newLayerPositionX) - parseFloat(startLayerPositionX);
    var yTransform = parseFloat(newLayerPositionY) - parseFloat(startLayerPositionY);
    var xScale = parseFloat(newLayerScaleX) - parseFloat(startScaleX); //if positive then increase size and on negative decrease
    var yScale = parseFloat(newLayerScaleY) - parseFloat(startScaleY);
    var rot = parseFloat(newLayerRotation) - parseFloat(startRotation);
    var trans = parseFloat(newLayerTransparency) - parseFloat(startTransparency);
    //dummy variables to call after every increment in for loop
    var masterScaleX = parseFloat(startScaleX);
    var masterScaleY = parseFloat(startScaleY);
    var masterRotation = parseFloat(startRotation);
    var masterTransparency = parseFloat(startTransparency);
    //create a new smart object to start copying and cloning layers (steps)
    editSmartObject();
    duplicateLayer();
    moveLayerBelow();
    convertToSmart();
    renameLayer("SmartObject");
    //define masterPositionX and Y because startPositionX is the value of layers bound which lies in original document while our current layer lies in the smart object of original document so bounds need to be updated
    var docRef = app.activeDocument;
    var curLayer = docRef.activeLayer;
    var curLayerBounds = curLayer.bounds;
    var curLayerPositionX = curLayerBounds[0].value + ((curLayerBounds[2].value - curLayerBounds[0].value) / 2);
    var curLayerPositionY = curLayerBounds[1].value + ((curLayerBounds[3].value - curLayerBounds[1].value) / 2);
    var masterPositionX = parseFloat(curLayerPositionX);
    var masterPositionY = parseFloat(curLayerPositionY);
    //generates incremental values i.e. 50px move in 5 steps gives 10px per step.
    var splitPositionX = parseFloat(xTransform) / steps;
    var splitPositionY = parseFloat(yTransform) / steps;
    var splitScaleX = parseFloat(xScale) / steps;
    var splitScaleY = parseFloat(yScale) / steps;
    var splitRotation = parseFloat(rot) / steps;
    var splitTransparency = parseFloat(trans) / steps;
    //the main code for generating blends starts here
    for (var i = 0; i < steps; i++) {
        //updates masterPositing by adding splits
        masterPositionX = masterPositionX + parseFloat(splitPositionX);
        masterPositionY = masterPositionY + parseFloat(splitPositionY);
        //Photoshop DOM Scale method is relative rather than absolute so if we will change scale to 50 then it won't resize object by 50% but it will resize objects half by it's current size so we need to tweak resize method
        var masterScaleX = parseFloat(((masterScaleX + splitScaleX) * 100) / masterScaleX);
        var masterScaleY = parseFloat(((masterScaleY + splitScaleY) * 100) / masterScaleY);
        var masterRotation = masterRotation + parseFloat(splitRotation);
        var masterTransparency = masterTransparency + parseFloat(splitTransparency);
        //starts looping in where order will be duplicate SO-clear mask-move downside-apply transformation-select above layer-select bound-below layer mask (This all steps are what makes blend layers)
        try {
            duplicateLayer();
            moveLayerBelow();
            if (hasMask() == true) {
                selectLayerMask();
                deleteLayerMask();
            }
            transformLayer(parseFloat(splitPositionX), parseFloat(splitPositionY))
            resizeLayer(masterScaleX, masterScaleY);
            rotateLayer(masterRotation);
            changeTransparency(masterTransparency);
            revealAll();
            selectAboveLayer();
            selectBoundOfLayer()
            selectBelowLayer();
            createMask();
            invert();
            trim();
        } catch (e) {
            alert(e);
        }
    }
}

As you can see above in try segment I do all stuffs by calling separate methods; Now all you might be interested are in Resize method which code is....

function resizeLayer(xScale, yScale) {
    app.activeDocument.activeLayer.resize(xScale, yScale, AnchorPosition.MIDDLECENTER);
}

See this is very basic function directly forked from Official JS reference.

What I've tried?

Well I've tried some various method like changing the AnchorPosition and etc but since the blending direction can be any I can't really find a way to make it work. Well the function is doing it's work. Let's take a simple example: Think that layer should move 10px on every step and should resize by 5%, Now if there wouldn't any resize then it'll move clones by every 10 px but if we will now resize it then we need to move clones 10px+the area reduced due to resize and that area seems impossible to figure out since I'm not a developer at all and know very basic on JS.

What I need?

All I need is some guidance on how should I code the logic of resize to solve this problem. All of yours contribution will be very helpful since this is freebie which I'm making for community, I can share source code if you needed too. Thanks for taking your time on my question.

Best Regard!


问:
How do you completely close an SQLConnection string in vb.net?
I'm running a multithreaded application that connects to a database, the connections are closed when I'm done with them (and I dispose of all the threads).  I've tried clearing the connection pools, setting pooling=false and I've used both .dispose and .close.

I get the error "cannot drop the database X because it is currently in use" if I try to drop the database I connected to after the connections have all been closed.  Below is my code:

```<code>Dim comExecuteInsert As New SqlCommand
Dim comm As New SqlConnection
If (Not comm Is Nothing) Then
    comm = Nothing
End If
comExecuteInsert.Connection = comm
comExecuteInsert.CommandType = CommandType.StoredProcedure
comExecuteInsert.CommandText = strProcedureName
comExecuteInsert.CommandTimeout = 26000
comExecuteInsert.Parameters.Add("@tableName", SqlDbType.VarChar, 100).Value = strTableName
comExecuteInsert.Parameters.Add("@filename", SqlDbType.VarChar, 500).Value = strFileName
comExecuteInsert.ExecuteScalar()
comExecuteInsert.Parameters.Clear()

comExecuteInsert = Nothing
comm.Close()
SqlConnection.ClearPool(comm)
</code>```

The stored procedure creates temporary tables which it later drops and inserts data into tables existing in the database.

答:
You are not disposing your command object.

Instead of

```<code>comExecuteInsert = Nothing
</code>```

try

```<code>comExecuteInsert.Dispose
</code>```

Or try the following:

```<code>Using comm As New SqlConnection
  Using comExecuteInsert As New SqlCommand
    comExecuteInsert.Connection = comm
    comExecuteInsert.CommandType = CommandType.StoredProcedure
    comExecuteInsert.CommandText = strProcedureName
    comExecuteInsert.CommandTimeout = 26000
    comExecuteInsert.Parameters.Add("@tableName", SqlDbType.VarChar, 100).Value = strTableName
    comExecuteInsert.Parameters.Add("@filename", SqlDbType.VarChar, 500).Value = strFileName
    comExecuteInsert.ExecuteScalar()
    comExecuteInsert.Parameters.Clear()
    comm.Close()
  End Using
End Using
</code>```

Body:
I'm running a multithreaded application that connects to a database, the connections are closed when I'm done with them (and I dispose of all the threads).  I've tried clearing the connection pools, setting pooling=false and I've used both .dispose and .close.

I get the error "cannot drop the database X because it is currently in use" if I try to drop the database I connected to after the connections have all been closed.  Below is my code:

Dim comExecuteInsert As New SqlCommand
Dim comm As New SqlConnection
If (Not comm Is Nothing) Then
    comm = Nothing
End If
comExecuteInsert.Connection = comm
comExecuteInsert.CommandType = CommandType.StoredProcedure
comExecuteInsert.CommandText = strProcedureName
comExecuteInsert.CommandTimeout = 26000
comExecuteInsert.Parameters.Add("@tableName", SqlDbType.VarChar, 100).Value = strTableName
comExecuteInsert.Parameters.Add("@filename", SqlDbType.VarChar, 500).Value = strFileName
comExecuteInsert.ExecuteScalar()
comExecuteInsert.Parameters.Clear()

comExecuteInsert = Nothing
comm.Close()
SqlConnection.ClearPool(comm)

The stored procedure creates temporary tables which it later drops and inserts data into tables existing in the database.

Body:
You are not disposing your command object.

Instead of

comExecuteInsert = Nothing

try

comExecuteInsert.Dispose

Or try the following:

Using comm As New SqlConnection
  Using comExecuteInsert As New SqlCommand
    comExecuteInsert.Connection = comm
    comExecuteInsert.CommandType = CommandType.StoredProcedure
    comExecuteInsert.CommandText = strProcedureName
    comExecuteInsert.CommandTimeout = 26000
    comExecuteInsert.Parameters.Add("@tableName", SqlDbType.VarChar, 100).Value = strTableName
    comExecuteInsert.Parameters.Add("@filename", SqlDbType.VarChar, 500).Value = strFileName
    comExecuteInsert.ExecuteScalar()
    comExecuteInsert.Parameters.Clear()
    comm.Close()
  End Using
End Using


问:
How do I disable the sign up link for the aws amplify vue authenticator?
I'm using the amplify-authenticator component from the aws-amplify-vue library to enable authentication for my app. I'm trying to figure out how to disable the "Create Account" link on the front end and I can't seem to find anything in the documentation or online.  I've seen a few places where users disabled it by hiding it with css and a few places where users were able to disable it with the react library, but I haven't found anything specific for the vue library. It's possible I'm just missing the documentation, but does anyone know how to remove the sign up functionality from the vue amplify authenticator?

Component

```<code><template>
  <v-container>
    <amplify-authenticator></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  async created() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      logger.silly("No user currently logged in");

      AmplifyEventBus.$on("authState", async info => {
        logger.silly("signedIn");
        logger.silly(info);
        if (info === "signedIn") {
          const user = await Auth.currentAuthenticatedUser({
            bypassCache: true
          });
          this.$router.push("/instruments");
        } else {
          logger.error(`Failed to login`);
          alert("Failed to login");
        }
      });
    }
  }
}
</script>

<style scoped></style>
</code>```

Update 1

Based on @asimpledevice's answer I tried the below without success:

```<code><template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="authConfiguration"
    ></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import StoreTypes from "../store-types";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  async mounted() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      const self = this;
      AmplifyEventBus.$on("authState", async info => {
        if (info === "signedIn") {
          this.$store.dispatch(StoreTypes.types.LOAD_CURRENT_USER);
          const nextLocation =
            self.$route.query.redirect !== null &&
            self.$route.query.redirect !== undefined
              ? (self.$route.query.redirect as string)
              : "/instruments";
          this.$router.push(nextLocation).catch(err => {});
        }
      });
    }
  }

  authConfiguration() {
    return {
      signInConfig: {
        isSignUpDisplayed: false
      }
    };
  }
}
</script>
</code>```

答:
You can hide the "sign up" section via the "signInConfig" object.

```<code>  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };
</code>```

You can then pass this object in as a prop to the  component:

```<code>    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>
</code>```

NOTE: You must make the config object a local property.  The config will not work if it is a function or computed property. Your full solution would be the following:

```<code><template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import StoreTypes from "../store-types";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };

  async mounted() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      const self = this;
      AmplifyEventBus.$on("authState", async info => {
        if (info === "signedIn") {
          this.$store.dispatch(StoreTypes.types.LOAD_CURRENT_USER);
          const nextLocation =
            self.$route.query.redirect !== null &&
            self.$route.query.redirect !== undefined
              ? (self.$route.query.redirect as string)
              : "/instruments";
          this.$router.push(nextLocation).catch(err => {});
        }
      });
    }
  }
}
</script>

<style></style>
</code>```

Body:
I'm using the amplify-authenticator component from the aws-amplify-vue library to enable authentication for my app. I'm trying to figure out how to disable the "Create Account" link on the front end and I can't seem to find anything in the documentation or online.  I've seen a few places where users disabled it by hiding it with css and a few places where users were able to disable it with the react library, but I haven't found anything specific for the vue library. It's possible I'm just missing the documentation, but does anyone know how to remove the sign up functionality from the vue amplify authenticator?

Component

<template>
  <v-container>
    <amplify-authenticator></amplify-authenticator>
  </v-container>
</template>

Update 1

Based on @asimpledevice's answer I tried the below without success:

<template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="authConfiguration"
    ></amplify-authenticator>
  </v-container>
</template>

Body:
You can hide the "sign up" section via the "signInConfig" object.

  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };

You can then pass this object in as a prop to the  component:

    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>

NOTE: You must make the config object a local property.  The config will not work if it is a function or computed property. Your full solution would be the following:

<template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import StoreTypes from "../store-types";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };

  async mounted() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      const self = this;
      AmplifyEventBus.$on("authState", async info => {
        if (info === "signedIn") {
          this.$store.dispatch(StoreTypes.types.LOAD_CURRENT_USER);
          const nextLocation =
            self.$route.query.redirect !== null &&
            self.$route.query.redirect !== undefined
              ? (self.$route.query.redirect as string)
              : "/instruments";
          this.$router.push(nextLocation).catch(err => {});
        }
      });
    }
  }
}
</script>

<style></style>


问:
Unexpected Vaadin Session Expired and parallel spring boot applications
I am using Vaadin 8.9.4 and Spring boot 2.2.4.RELEASE. I have 2 spring boot applications, FirstApplication (server.port=8083) and SecondApplication (server.port=8084). Both the application have @SpringUI annotated class extending UI Class, as given below. The session for FirstApplication is expired as soon as I click on the button in the SecondApplication and vice versa. This happens only when I use two chorme tabs in parallel. If I use two different browsers, everything is working as expected.

Is this some kind of a bug as I expect no relation between the sessions of the two applications simply because they are running independently on different port.

Note: I am new to the spring boot and I am trying to build 2 micorservices communicating with each other via Rest API.

```<code>@SpringUI
@Theme("valo")
public class FirstApplicationUI extends UI {

    private static final long serialVersionUID = 9197592298697220144L;

    @Override
    protected void init(final VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        final Label label = new Label("First Application");
        final Button button = new Button("click");

        button.addClickListener(e -> Notification.show("First Application"));

        layout.addComponents(label, button);

        setContent(layout);
    }
}

@SpringUI
@Theme("valo")
public class SecondApplicationUI extends UI {

    private static final long serialVersionUID = 9059755286859361908L;

    @Override
    protected void init(final VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        final Label label = new Label("Second Application");
        final Button button = new Button("click");

        button.addClickListener(e -> Notification.show("Second Application"));

        layout.addComponents(label, button);

        setContent(layout);
    }
}
</code>```

答:
This is your two applications battling over the same cookie; both use the same name and your browser happily sends both backends the same cookie as the port is not considered.

Change the name in at least one of your applications; see server.servlet.session.cookie.name in https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html

Body:
I am using Vaadin 8.9.4 and Spring boot 2.2.4.RELEASE. I have 2 spring boot applications, FirstApplication (server.port=8083) and SecondApplication (server.port=8084). Both the application have @SpringUI annotated class extending UI Class, as given below. The session for FirstApplication is expired as soon as I click on the button in the SecondApplication and vice versa. This happens only when I use two chorme tabs in parallel. If I use two different browsers, everything is working as expected.

Is this some kind of a bug as I expect no relation between the sessions of the two applications simply because they are running independently on different port.

Note: I am new to the spring boot and I am trying to build 2 micorservices communicating with each other via Rest API.

@SpringUI
@Theme("valo")
public class FirstApplicationUI extends UI {

    private static final long serialVersionUID = 9197592298697220144L;

    @Override
    protected void init(final VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        final Label label = new Label("First Application");
        final Button button = new Button("click");

        button.addClickListener(e -> Notification.show("First Application"));

        layout.addComponents(label, button);

        setContent(layout);
    }
}

@SpringUI
@Theme("valo")
public class SecondApplicationUI extends UI {

    private static final long serialVersionUID = 9059755286859361908L;

    @Override
    protected void init(final VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        final Label label = new Label("Second Application");
        final Button button = new Button("click");

        button.addClickListener(e -> Notification.show("Second Application"));

        layout.addComponents(label, button);

        setContent(layout);
    }
}