问:
Full Calendar: Limit events per day in one cell
Is there a way to limit events per one cell on the bootstrap calendar as appears in attached image?
I want to show it as 2 events and "... X more" label in case there's more than 2 events with the same date and prevent stretching the whole calendar.

答:
According to the documentation: https://fullcalendar.io/docs/eventLimit,

You can use the following code and upgrade it, depending on your goal:

```<code>var calendar = new Calendar(calendarEl, {
  eventLimit: true, // for all non-TimeGrid views
    views: {
      timeGrid: {
      eventLimit: 6 // adjust to 6 only for timeGridWeek/timeGridDay
    }
  }
});
</code>```

In this case in the calendar will be shown only a few elements but at the bottom of each day will be a link +x more, with x representing the total number of your records for the current day which pops up a modal window with the rest of the information.

I hope I was helpful!

Edit:

Apparently eventLimit: true was enough for default functionality.

Body:
According to the documentation: https://fullcalendar.io/docs/eventLimit,

You can use the following code and upgrade it, depending on your goal:

var calendar = new Calendar(calendarEl, {
  eventLimit: true, // for all non-TimeGrid views
    views: {
      timeGrid: {
      eventLimit: 6 // adjust to 6 only for timeGridWeek/timeGridDay
    }
  }
});

In this case in the calendar will be shown only a few elements but at the bottom of each day will be a link +x more, with x representing the total number of your records for the current day which pops up a modal window with the rest of the information.

I hope I was helpful!

Edit:

Apparently eventLimit: true was enough for default functionality.


来源: stackexchange

问:
email sending via wso2 identity server fails
I am using wso2 identity server 5.9.0 on my linux machine.
I am getting the error below while doing account creation.

I get message Email sent successfully, but at backend it throws error after some time and the mail is never received.

[2020-02-15 13:09:22,241] [725c9824-a414-44f4-9b4f-e5f8da8db48c] ERROR

{org.wso2.carbon.event.output.adapter.email.EmailEventAdapter} - Event
  dropped at Output Adapter 'EmailPublisher' for tenant id '-1234',
  Error in message format, Exception reading response
  javax.mail.MessagingException: Exception reading response;   nested
  exception is:
          java.net.SocketException: Connection timed out (Read failed)
          at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2460)
          at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:1699)
          at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:744)
          at javax.mail.Service.connect(Service.java:366)
          at javax.mail.Service.connect(Service.java:246)
          at javax.mail.Service.connect(Service.java:195)
          at javax.mail.Transport.send0(Transport.java:254)
          at javax.mail.Transport.send(Transport.java:124)
          at org.wso2.carbon.event.output.adapter.email.EmailEventAdapter$EmailSender.run(EmailEventAdapter.java:306)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
          at java.lang.Thread.run(Thread.java:748) Caused by: java.net.SocketException: Connection timed out (Read failed)
          at java.net.SocketInputStream.socketRead0(Native Method)
          at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
          at java.net.SocketInputStream.read(SocketInputStream.java:171)
          at java.net.SocketInputStream.read(SocketInputStream.java:141)
          at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:126)
          at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
          at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
          at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:106)
          at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2440)
          ... 13 more

I already made changes in output-event-adapters.xml and axis2.xml for smtp details.

Any help on this?

output-event-adapters.xml configuration is as below:

        noreply@xyz.com
        noreply@xyz.com

        ABC.XXX.XXX.XXX
        25
        true
        false

        8
        100
        20000
        10000

答:
It seems like it is blocked by google. Refer to this doc

If you are using Gmail account you have to on "Allow less secure apps"
  in your account.

For more info refer this

ContentLicense: CC BY-SA 4.0


问:
How to interpret linux kernel trap error line?
I have a socket application written in C++ which runs on Linux. It crashed this morning and when I check the /var/log/messages I see the following line at the time of the crash:

```<code>kernel: traps: LogProcessor[9364] general protection ip:4f2555 sp:7fbd529b1670 error:0 in MyPrg[400000+21a000]
</code>```

I want to dig into the code and find the reason but I don't know how to interpret the values in the error line.

Does it mean the error is caused by LogProcessor? What are the values "ip", "sp", "error:0", MyPrg[400000+21a000] ?

答:
This is General Protection Fault. There are multiple reasons that can cause it. You can read more in the aforementioned link.

LogProcessor[9364] - thread name and pid

ip:4f2555 - instruction pointer (looks suspicious here)

sp:7fbd529b1670 - stack pointer

error:0 - error code (why 0?)

MyPrg[400000+21a000] - program name

Body:
I have a socket application written in C++ which runs on Linux. It crashed this morning and when I check the /var/log/messages I see the following line at the time of the crash:

kernel: traps: LogProcessor[9364] general protection ip:4f2555 sp:7fbd529b1670 error:0 in MyPrg[400000+21a000]

I want to dig into the code and find the reason but I don't know how to interpret the values in the error line.

Does it mean the error is caused by LogProcessor? What are the values "ip", "sp", "error:0", MyPrg[400000+21a000] ?


问:
Fahrenheit to Celsius convert and printing problem
Hi i was trying to create a function that printed out the statement f(variable)degrees Fahrenheit = c(variable) degrees Celsius in swift and I am having issues printing it mainly cause its a variable with numbers and im trying to put it into a string I tried some different types of decleratino but it hasnt worked. and sorry for repetitive questions</p>

```<code>var f = 68.0;
var c = (f - 32.0) * 5.0 / 9.0;
var conversion = "f degrees Fahrenheit = c degrees Celsius"

print(conversion)
</code>```

答:
You need to use String interpolation, otherwise it's just text.

Replace c with \(c) to actually get the value of variable c value.
Also f with \(f) for the same reason.

var conversion = "\(f) degrees Fahrenheit = \(c) degrees Celsius"

Body:
Hi i was trying to create a function that printed out the statement f(variable)degrees Fahrenheit = c(variable) degrees Celsius in swift and I am having issues printing it mainly cause its a variable with numbers and im trying to put it into a string I tried some different types of decleratino but it hasnt worked. and sorry for repetitive questions

var f = 68.0;
var c = (f - 32.0) * 5.0 / 9.0;
var conversion = "f degrees Fahrenheit = c degrees Celsius"

print(conversion)


问:
Static method override
```<code>class XYZ{
    public static void show(){
        System.out.println("inside XYZ");
    }
}

public class StaticTest extends XYZ {
    public static void  show() {
        System.out.println("inside statictest");

    }

    public static void main(String args[]){
        StaticTest st =new StaticTest();
        StaticTest.show();

    }

}
</code>```

though we know static methods cant be overridden. Then what actually is happening?

答:
// Java allows a static method to be called from an Instance/Object reference
// which is not the case in other pure OOP languages like C# Dot net.
// which causes this confusion.
// Technically, A static method is always tied to a Class and not instance.
// In other words, the binding is at compile-time for static functions. - Early Binding
//
// eg.</p>

```<code>class BaseClass
{
 public static void f1()
 {
  System.out.println("BaseClass::f1()...");
 } // End of f1().
}

public class SubClass extends BaseClass
{
  public static void f1()
  {
    System.out.println("SubClass::f1()...");
    // super.f1(); // non-static variable super cannot be referenced from a static context

  } // End of f1().

  public static void main(String[] args)
  {
f1();
SubClass obj1 = new SubClass();
obj1.f1();
BaseClass b1 = obj1;
b1.f1();

  } // End of main().

} // End of class.

// Output:
// SubClass::f1()...
// SubClass::f1()...
// BaseClass::f1()...
</code>```

<p>//
//
// So even though in this case, called with an instance b1 which is actually referring to
// an object of type SuperClass, it calls the BaseClass:f1 method.
// </p>

ContentLicense: CC BY-SA 3.0

Title: Static method override

Body:
class XYZ{
    public static void show(){
        System.out.println("inside XYZ");
    }
}

public class StaticTest extends XYZ {
    public static void  show() {
        System.out.println("inside statictest");

    }

    public static void main(String args[]){
        StaticTest st =new StaticTest();
        StaticTest.show();

    }

}

though we know static methods cant be overridden. Then what actually is happening?

Body:
// Java allows a static method to be called from an Instance/Object reference
// which is not the case in other pure OOP languages like C# Dot net.
// which causes this confusion.
// Technically, A static method is always tied to a Class and not instance.
// In other words, the binding is at compile-time for static functions. - Early Binding
//
// eg.

class BaseClass
{
 public static void f1()
 {
  System.out.println("BaseClass::f1()...");
 } // End of f1().
}

public class SubClass extends BaseClass
{
  public static void f1()
  {
    System.out.println("SubClass::f1()...");
    // super.f1(); // non-static variable super cannot be referenced from a static context

  } // End of f1().

  public static void main(String[] args)
  {
f1();
SubClass obj1 = new SubClass();
obj1.f1();
BaseClass b1 = obj1;
b1.f1();

  } // End of main().

} // End of class.

// Output:
// SubClass::f1()...
// SubClass::f1()...
// BaseClass::f1()...

//
//
// So even though in this case, called with an instance b1 which is actually referring to
// an object of type SuperClass, it calls the BaseClass:f1 method.
//


问:
Select two different Items if they meet different condition
I have a select problem with mssql which is;

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ
</code>```

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

```<code>SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)
</code>```

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition
</code>```

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

答:
Try this </p>

```<code>select * from [Table A] A
join [Table B]  B on A.ItemUniqueNo=B.ItemUniqueNo
where b.ItemGroup='XXX' or OR A.ItemUniqueNo = 3
</code>```

Body:
I have a select problem with mssql which is;

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

Body:
Try this

select * from [Table A] A
join [Table B]  B on A.ItemUniqueNo=B.ItemUniqueNo
where b.ItemGroup='XXX' or OR A.ItemUniqueNo = 3


问:
Migration from Angular 4 to 9
It is advisable to migrate Angular 4 to 9 directly, or it would be better to go from 4 to 7 and then from 7 to 9?</p>

答:
using this link https://update.angular.io/ to what you have to do for each version upgrade , i think you have to first upgrade you app from Angular 4 to 5 because of changing http and httpClient big changes come in version 5 after it i think the  other versions will be easy .
and don't forget if your not using Angular Cli first put your project based on it. </p>

Title: Migration from Angular 4 to 9


问:
Missing Anaconda Navigator and command prompt in the Start Menu
I am having multiple problem installing the anaconda on Windows 10.

First I cant see Anaconda Navigator in the Start Menu.

Second if I navigate to the installation Directory :

C:\Users\user-name\AppData\Local\Continuum\anaconda3 I can see the bin folder there.

Below is the Snapshot

I also cant see the Anaconda Prompt

C:\Users\user-name\conda
'conda' is not recognized as an internal or external command,
operable program or batch file.

I have tried re-installing the python,anaconda many times.

Do I need to install the Python before ?Which Version?3.7 or latest(3.8) .

Also I doubt the Installation is Complete (by looking at the anaconda3 folder.Can someone who has successfully installed Anaconda , please check)

答:
You can install any later version of Python 3
Install conda
set the environment variable for both Python and Anaconda </p>

<p>After setting the environment variable open a new command prompt and try conda install </p>

Body:
You can install any later version of Python 3
Install conda
set the environment variable for both Python and Anaconda

After setting the environment variable open a new command prompt and try conda install


问:
Unable to get execute result (SQL-Tools)
I have retrieve a record from my database (sqlite). When I ran the following code:

from sql_tools import sqlite
sqlite.connect("base.sqlite3")
names = sqlite.execute("SELECT * FROM NAMES")
print(names)
sqlite.disconnect()
```

It gives me an object instead of my result. How can I get my result instead of this object. Can anybody help me?

答:
You will need to use the .get property. From version 1.0.0, the execute command returns an Exec object instead of the result. This object has some properties & .get is one of them. This property will return you the result in the form of an np array.

Code:

names = sqlite.execute("SELECT * FROM NAMES").get
```

Body:
I have retrieve a record from my database (sqlite). When I ran the following code:

from sql_tools import sqlite
sqlite.connect("base.sqlite3")
names = sqlite.execute("SELECT * FROM NAMES")
print(names)
sqlite.disconnect()

It gives me an object instead of my result. How can I get my result instead of this object. Can anybody help me?


问:
Adding a counter
I'm trying to add a counter to this, so when a number is clicked, it should display "You've selected 1 out of 5" meaning the person has to select 5 numbers. But if the same number is clicked, it should deselect and then go back to "You've selected 0 out of 5". So you could essentially click 1,5,7 but then it should display "You've selected 3 out of 5"</p>

```<code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Gaarith</title>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <style>
         #feedback {
         font-size: 1.4em;
         }

         #selectable .ui-selecting {
           background: #FECA40;
         }

         #selectable .ui-selected {
           background: #F39814;
           color: white;
         }

         #selectable {
          list-style-type: none;
           margin: 0;
           padding: 0;
           width: 450px;
         }

         #selectable li {
         margin: 10px;
         padding: 1px;
         float: left;
         width: 100px;
         height: 80px;
         font-size: 4em;
         text-align: center;
         }

         .wrapper {
           display: flex;
           margin: auto;
           justify-content: center;
           align-items: center;
         }
      </style>
   </head>
   <body>
      <div class="wrapper">
         <div>
            <p id="feedback">
               <span>You've selected:</span> <span id="select-result">none</span>.
            </p>
            <ol id="selectable">
               <li class="ui-widget-content" text="car">1</li>
               <li class="ui-widget-content" text="truck">2</li>
               <li class="ui-widget-content" text="physics">3</li>
               <li class="ui-widget-content" text="maths">4</li>
               <li class="ui-widget-content" text="home automation">5</li>
               <li class="ui-widget-content" text="car6">6</li>
               <li class="ui-widget-content" text="car7">7</li>
               <li class="ui-widget-content" text="car8">8</li>
               <li class="ui-widget-content" text="car9">9</li>
               <li class="ui-widget-content" text="car10">10</li>
               <li class="ui-widget-content" text="car11">11</li>
               <li class="ui-widget-content" text="car12">12</li>
            </ol>
         </div>
      </div>
      <script>
         // this makes each box clickable and adds it to an array the title.
         let liSelected = [];
$("document").ready(function() {
    $(".ui-widget-content").on("click", function() {
        if($(this).hasClass('ui-selecting')){
            $(this).removeClass('ui-selecting');
            removeItem(liSelected, $(this).attr('text'));
        }else{
            $(this).addClass('ui-selecting');
            liSelected.push($(this).attr('text'))
        }
        $("#select-result").text(liSelected.length === 0 ? "none" : liSelected.join(", "));
    });
//   this checks if the existing title is in the array and then removes it
    function removeItem(array, item){
        for(var i in array){
            if(array[i]==item){
                array.splice(i,1);
                break;
            }
        }
    }
});
      </script>
   </body>
</html>
</code>```

答:
You are currently displaying the array of selected items. Just display the length instead.

You can just change

$("#select-result").text(liSelected.length === 0 ? "none" : liSelected.join(", "));

to

$("#select-result").text(liSelected.length === 0 ? "none" : (liSelected.length + ' out of 5'));

Title: Adding a counter

Body:
I'm trying to add a counter to this, so when a number is clicked, it should display "You've selected 1 out of 5" meaning the person has to select 5 numbers. But if the same number is clicked, it should deselect and then go back to "You've selected 0 out of 5". So you could essentially click 1,5,7 but then it should display "You've selected 3 out of 5"

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Gaarith</title>

               You've selected: none.

1

2

3

4

5

6

7

8

9

10

11

12


问:
How does type is submit work in javascript?
Type="Submit" and type="Button" in element input. How are they different? When I use type="button" then it submits successfully but type="Submit" does not? why is that?

```<code> <form class="crush-form">
    <div>
        <input class="name" type="text" name="name" required />
        <label for="">Name</label>
    </div>
    <div>
        <input class="address" type="text" name="address" required />
        <label for="">Address</label>
    </div>
    <div class="lol">
        <input
            type="submit"
            onclick="SubmitClickHandle()"
            name="huhu"
            value="ggg"
        />
        <button onclick="closeDialog()">Close Dialog</button>
    </div>
</form>
</code>```

答:
You have a JavaScript function SubmitClickHandle() that performs the form submission. If you use type="submit", then the form also submits using the default method, which reloads the page and cancels the SubmitClickHandle() code.

You should use type="button" when you've provided your own JavaScript to submit the form, and you don't need the default submission.

If you want to use type="submit", the onclick code should end with return false to prevent the default action:

```<code><button type="submit" onclick="SubmitClickHandle(); return false">
</code>```

Body:
Type="Submit" and type="Button" in element input. How are they different? When I use type="button" then it submits successfully but type="Submit" does not? why is that?

 <form class="crush-form">

        <input class="name" type="text" name="name" required />
        Name

        <input class="address" type="text" name="address" required />
        Address

        <input
            type="submit"
            onclick="SubmitClickHandle()"
            name="huhu"
            value="ggg"
        />
        <button onclick="closeDialog()">Close Dialog</button>

</form>

Body:
You have a JavaScript function SubmitClickHandle() that performs the form submission. If you use type="submit", then the form also submits using the default method, which reloads the page and cancels the SubmitClickHandle() code.

You should use type="button" when you've provided your own JavaScript to submit the form, and you don't need the default submission.

If you want to use type="submit", the onclick code should end with return false to prevent the default action:

<button type="submit" onclick="SubmitClickHandle(); return false">


问:
Setting an environment variable for maven-driven integration tests
Is is possible to set an environment variable from within a Citrus Framework integration test? I am asking because my services use log4j to log console output and the configuration file (log4j2-spring.xml) uses environment variables to set log file names, etc. It would be convenient to be able to do this.</p>

答:
In general changing environment settings for the already running JVM instance and getting the changes updated in your running system (e.g. Log4J logging appenders) is not easy and might not work in all situations. So I am pretty sure this is not what you should try to do.

In terms of Citrus you can run any Java or Groovy code as part of the integration tests so you can also have all imaginable hacks as part of an integration test. But as I already said this is not what you really want.


问:
user-defined scalar function to generate computed column
I have databse having 2 tables i.e (Installment and InstallmentPlan).
In the installment table there are number of columns. I want to add one new computed column name SurchargeCalculated (SC). The calculation for SC is this

```<code>SC = (Installment.Amount * Installment.days * (InstallmentPlan.InstPercentage /365 /100))
</code>```

I have created user-defined function SurchargeCal having 3 parameters which are Amount, days and InstPercentage. The problem is that when i add computed column in installment table and call scalar function from there, the saclar func needs InstPercetage parameter of 2nd table (InstallmentPlan).
I know recommended ways is to use view but that will complicate my problem as i am using installment table in C#.

Any help will be extremely appreciated.

My scalar function is

```<code>USE [myDB]
GO
/****** Object:  UserDefinedFunction [dbo].[SurchargeCal]    Script Date: 17/02/2020 2:21:15 PM
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER FUNCTION [dbo].[SurchargeCal]
(
    -- Add the parameters for the function here
    @days as int,
    @amount as money,
    @surchargePerc as decimal
)
RETURNS decimal
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result as decimal =0;

    -- Add the T-SQL statements to compute the return value here
    --SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1>

        if  @days = 0
            set @result = 0
        else if (@days > 0 and @amount > 0)
            set @result = (@days * @amount * (@surchargePerc/ 365 / 100))
        else
            set @result = 0

    -- Return the result of the function
    RETURN @result

END
</code>```

then below ADD table command XXXX is the problem

```<code>USE [myDB]
GO
ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days,Amount, XXXX) --where XXX should be InstPercenatage
GO
</code>```

答:
Since you can't use a subquery directly on the computed column, you will need to do it on the scalar function itself :

```<code>CREATE FUNCTION SurchargeCal(@days as integer, @amount as money, @PlanKey as integer)
RETURNS decimal
AS
BEGIN
    DECLARE @result as decimal = 0;

    SELECT @result = @amount * @days * InstPercentage / 365 / 100
    FROM InstallMentPlan
    WHERE PlanKey = @PlanKey

    RETURN @result
END
</code>```

Now you can create the computed column, passing the PlanKey instead of its InstPercentage.

```<code>ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days, Amount, PlanKey)
</code>```

Body:
I have databse having 2 tables i.e (Installment and InstallmentPlan).
In the installment table there are number of columns. I want to add one new computed column name SurchargeCalculated (SC). The calculation for SC is this

SC = (Installment.Amount * Installment.days * (InstallmentPlan.InstPercentage /365 /100))

I have created user-defined function SurchargeCal having 3 parameters which are Amount, days and InstPercentage. The problem is that when i add computed column in installment table and call scalar function from there, the saclar func needs InstPercetage parameter of 2nd table (InstallmentPlan).
I know recommended ways is to use view but that will complicate my problem as i am using installment table in C#.

Any help will be extremely appreciated.

My scalar function is

USE [myDB]
GO
/****** Object:  UserDefinedFunction [dbo].[SurchargeCal]    Script Date: 17/02/2020 2:21:15 PM
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER FUNCTION [dbo].[SurchargeCal]
(
    -- Add the parameters for the function here
    @days as int,
    @amount as money,
    @surchargePerc as decimal
)
RETURNS decimal
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result as decimal =0;

    -- Add the T-SQL statements to compute the return value here
    --SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1>

        if  @days = 0
            set @result = 0
        else if (@days > 0 and @amount > 0)
            set @result = (@days * @amount * (@surchargePerc/ 365 / 100))
        else
            set @result = 0

    -- Return the result of the function
    RETURN @result

END

then below ADD table command XXXX is the problem

USE [myDB]
GO
ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days,Amount, XXXX) --where XXX should be InstPercenatage
GO

Body:
Since you can't use a subquery directly on the computed column, you will need to do it on the scalar function itself :

CREATE FUNCTION SurchargeCal(@days as integer, @amount as money, @PlanKey as integer)
RETURNS decimal
AS
BEGIN
    DECLARE @result as decimal = 0;

    SELECT @result = @amount * @days * InstPercentage / 365 / 100
    FROM InstallMentPlan
    WHERE PlanKey = @PlanKey

    RETURN @result
END

Now you can create the computed column, passing the PlanKey instead of its InstPercentage.

ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days, Amount, PlanKey)


问:
Negative Slicing in Python
quiz question :

```<code>a=[1,2,3,4,5,6,7,8,9,10]
</code>```

result for :

```<code>print a([-1:-5])
</code>```

I don't know the actual output for this operation please update.

答:
To start with, it's invalid syntax.

But even if you had your syntax correct, it's going to give you an empty array. Because it is not going to slice between -1 to -5, but it will slice between -5 to -1. Imagine that slicing will only work from a smaller number: larger number.

so

```<code>print(a[-1:-5])
</code>```

will result in

```<code>[]
</code>```

Whereas

```<code>print(a[-5:-1])
</code>```

will result in the elements 5th position from the end of the list to the first position from the end of the list which is

```<code>[6, 7, 8, 9]
</code>```

Title: Negative Slicing in Python

Body:
quiz question :

a=[1,2,3,4,5,6,7,8,9,10]

result for :

print a([-1:-5])

I don't know the actual output for this operation please update.

Body:
To start with, it's invalid syntax.

But even if you had your syntax correct, it's going to give you an empty array. Because it is not going to slice between -1 to -5, but it will slice between -5 to -1. Imagine that slicing will only work from a smaller number: larger number.

so

print(a[-1:-5])

will result in

[]

Whereas

print(a[-5:-1])

will result in the elements 5th position from the end of the list to the first position from the end of the list which is

[6, 7, 8, 9]


问:
dropdown menu is hiding behind toolbar
i am using ionic4/angular. on-clicking on the ion-avatar a dropdown menu should display but the dropdown menu is hiding in the toolbar. i tried giving z-index but it is not working. Thanks.

stackblitz link

<ion-header>
  <ion-toolbar color="tertiary" >

    <ion-buttons slot="start">
      <ion-back-button defaultHref="/"></ion-back-button>
    </ion-buttons>

    <ion-buttons slot="end">
      <button class="btn btn-light">My Courses</button>
    </ion-buttons>

    <ion-buttons slot="end">
      <ion-button class="iconbell">
        <ion-icon name="notifications-outline" size="large"></ion-icon>
      </ion-button>
    </ion-buttons>

    <ion-buttons slot="end">

        <ion-avatar class="dropdown-toggle" style="margin-right:10px;height: 5vh;width: 5vh;" id="menu1" type="button" data-toggle="dropdown">

        </ion-avatar>

HTML

CSS

JavaScript

About Us

    </ion-buttons>

  </ion-toolbar>
</ion-header>```

答:
```<code>Please add or update css

.toolbar{
    contain: inherit;
    overflow: visible;
}
</code>```

Title: dropdown menu is hiding behind toolbar


问:
Which line in the code
Is there any way to get which line of the code is running?

E.g. in some method I ran another programm and I'm waiting to ending. Now I want to know which line called this program without using breakpoints

答: If you hit the "pause" button in the debugger, navigate to the right thread if necessary, and look at the stack, you'll see where you are. If that's not what you're looking for, please clarify your question.</p>

Title: Which line in the code


问:
How to optimize the Flutter App size?
I am a native Android developer and I started using flutter SDK. I developed a simple app by following official flutter doc. But I found that the debug app size is 46 MB which is too large for this simple app. Is there any way to optimize the app size? because Flutter app size is larger than the native Android App.</p>

答:
Follow the official doc - https://flutter.dev/docs/perf/app-size

Some of the obvious things you can do to make your app smaller are:

Remove unused resources

Minimize resource imported from libraries

Support a limited number of screen densities

Compress PNG and JPEG files

Title: How to optimize the Flutter App size?


问:
How to run Vue.js dev serve with https?
I'm using Vue-cli to create vue project with webpack template. how to run it with https in development using: npm run dev?

答:
You will still get the warning when running in Chrome or Edge, as the certificate is not a trusted certificate. But you can switch off the prompt when running the site by setting the following flag:

```<code>chrome://flags/#allow-insecure-localhost
</code>```

This also works also in the latest version Edge.

Title: How to run Vue.js dev serve with https?

Body:
You will still get the warning when running in Chrome or Edge, as the certificate is not a trusted certificate. But you can switch off the prompt when running the site by setting the following flag:

chrome://flags/#allow-insecure-localhost

This also works also in the latest version Edge.


问:
How to sort Properties in java?
I have a Properties object and sometimes I need to add other Properties to it.

```<code>Properties myBasicProps = this.getClass.getResourceAsStream(MY_PROPS_PATH);
...
Properties otherProps = new Properties();
otherProps.load(new StringReader(tempPropsString)); //tempPropsString contains my temporary properties
myBasicProps.putAll(otherProps);
</code>```

I want to sort myBasicProps after this. I don't want to get all keys and values, sort them with Collections.sort() and then put it all to a new object. Is there a better way?

答:
In Java 8 Properties.keys() was used for storing the properties , in Java 9 this changed and Properties.entrySet() was used:

Java 8

```<code>private void store0(BufferedWriter bw, String comments, boolean escUnicode)
    throws IOException
{
...
        for (Enumeration<?> e = keys(); e.hasMoreElements();) {
</code>```

Java 9

```<code>private void store0(BufferedWriter bw, String comments, boolean escUnicode)
    throws IOException
{
...
        for (Map.Entry<Object, Object> e : entrySet()) {
</code>```

I use this class to handle both java version:

```<code>public class SortedProperties extends Properties {

    /**
     * constructor
     *
     * @param unsortedProperties
     */
    public SortedProperties(Properties unsortedProperties) {
        putAll(unsortedProperties);
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public synchronized Enumeration keys() {
        Enumeration<Object> keysEnum = super.keys();
        Vector<String> keyList = new Vector<String>();
        while (keysEnum.hasMoreElements()) {
            keyList.add((String) keysEnum.nextElement());
        }
        Collections.sort(keyList);
        return keyList.elements();
    }

    @Override
    public Set<java.util.Map.Entry<Object, Object>> entrySet() {
        // use a TreeMap since in java 9 entrySet() instead of keys() is used in store()
        TreeMap<Object, Object> treeMap = new TreeMap<>();
        Set<Map.Entry<Object, Object>> entrySet = super.entrySet();
        for (Map.Entry<Object, Object> entry : entrySet) {
            treeMap.put(entry.getKey(), entry.getValue());
        }
        return Collections.synchronizedSet(treeMap.entrySet());
    }
}
</code>```

Title: How to sort Properties in java?

Body:
I have a Properties object and sometimes I need to add other Properties to it.

Properties myBasicProps = this.getClass.getResourceAsStream(MY_PROPS_PATH);
...
Properties otherProps = new Properties();
otherProps.load(new StringReader(tempPropsString)); //tempPropsString contains my temporary properties
myBasicProps.putAll(otherProps);

I want to sort myBasicProps after this. I don't want to get all keys and values, sort them with Collections.sort() and then put it all to a new object. Is there a better way?

Body:
In Java 8 Properties.keys() was used for storing the properties , in Java 9 this changed and Properties.entrySet() was used:

Java 8

private void store0(BufferedWriter bw, String comments, boolean escUnicode)
    throws IOException
{
...
        for (Enumeration<?> e = keys(); e.hasMoreElements();) {

Java 9

private void store0(BufferedWriter bw, String comments, boolean escUnicode)
    throws IOException
{
...
        for (Map.Entry<Object, Object> e : entrySet()) {

I use this class to handle both java version:

public class SortedProperties extends Properties {

    /**
     * constructor
     *
     * @param unsortedProperties
     */
    public SortedProperties(Properties unsortedProperties) {
        putAll(unsortedProperties);
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public synchronized Enumeration keys() {
        Enumeration<Object> keysEnum = super.keys();
        Vector<String> keyList = new Vector<String>();
        while (keysEnum.hasMoreElements()) {
            keyList.add((String) keysEnum.nextElement());
        }
        Collections.sort(keyList);
        return keyList.elements();
    }

    @Override
    public Set<java.util.Map.Entry<Object, Object>> entrySet() {
        // use a TreeMap since in java 9 entrySet() instead of keys() is used in store()
        TreeMap<Object, Object> treeMap = new TreeMap<>();
        Set<Map.Entry<Object, Object>> entrySet = super.entrySet();
        for (Map.Entry<Object, Object> entry : entrySet) {
            treeMap.put(entry.getKey(), entry.getValue());
        }
        return Collections.synchronizedSet(treeMap.entrySet());
    }
}


问:
Update table in foreach loop with filtered model with Ajax (asp.net mvc c#)
I've developed an asp.net MVC web app where I have a table that shows some items in a model.

I can filter it now with a dropdown list using ajax

The model that i pass to the table is correct (if i go to the model before the foreach there are 3 rows instead of 10 thanks to the filter)

The problem is that the table doesn't change, it always shows all the rows as the initial request.

It look like it works but the table won't update...

There's my jquery ajax call:

```<code>$("#Dropdown1Id").on('change', function () {
//console.log("onchange");
//console.log($("#Dropdown1Id").val());
var drpdown1 = $("#Dropdown1Id").val();
var submit = $("#submitButton");
    $.ajax({ // crea una chiamata AJAX
        data: { data: drpdown1 }, // prendi i dati del form in questo caso del primo dropdown
        type: "GET", // GET o POST
        url: "/Select/Filter", // li passa al controller
        success: function () { // se va con successo esegue il codice seguente
            submit.click();
            $("#frmId").submit();
        },
        error: function (error) {
            console.log("error")
        }
    });
});
</code>```

There's my controller action:

```<code>public ActionResult Filter(string data)
    {
        List<Card> cards = new List<Card>();
        ViewBag.stato = new SelectList(myApi.GetState(), "Name", "Name");

        if (data != null && data != "")
        {
            foreach (var card in model)
            {
                if (card.IdList == data || data == "")
                    cards.Add(card);
            }
            return View(cards);
        }
        return View(model);
    }
</code>```

There's my view with the daple and the dropdown:

```<code>@using (Html.BeginForm(new { id = "frmId"}))
{
@Html.AntiForgeryToken()
<table id="tb2">
    <tr>
        <th>
            <h4> LIST : @Html.DropDownList("stato", null, new { @id = "Dropdown1Id" })</h4>
        </th>
        @*<th>
            <h4>ARCHVIED : @Html.DropDownList("closed", null, new { @id = "Dropdown2Id" })</h4>
        </th>*@
        <th>
            <input type="submit" value="Filter" class="btn btn-info" id="submitButton" />
        </th>
    </tr>
</table>

<br />

<div id="risultato"></div>

<table class="table" id="tb1">
    <tr>
        <th style="text-align:center">
            TRELLO'S CARDS LIST
        </th>
        <th>LIST</th>
        <th>ARCHVIED</th>
        <th>Expiration date</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.IdList)
            </td>
            @if (item.Closed == "True")
            {
                <td>YES</td>
            }
            else
            {
                <td>NO</td>
            }

            @if (item.Due != null)
            {
                <td>
                    @Html.DisplayFor(modelItem => item.Due)
                </td>
            }
            else
            {
                <td>

                    Not Present
                </td>
            }
        </tr>

        idList.Add(item.Id);
    }
</table>
</code>```

答:
Let me get you through the execution stack and you'll understand why:

Your MVC view is loaded. When the view is returned to the frontend it is already in Html format. Check Server side rendering here

Basically it means that @foreach (var item in Model) will only execute on the server side and will not re-run when you hit an ajax call. This will only happen on a full post.

While in your page you fire up change dropdown event and the following happens:

An ajax call hit your controller

Data are being returned to the success function

Your success: function () is being executed.

A new form post occurs. See that you didn't do anything with the return data that was returned in the success: function(). You just posted back to the controller

After the post, the full view has returned ignoring any changes in the dropdown and in the data returned.

There are 2 solutions for your problem:

Do a full post and return a new view with the proper data

Write some more javascript to change the DOM inside your sucess function

Body:
I've developed an asp.net MVC web app where I have a table that shows some items in a model.

I can filter it now with a dropdown list using ajax

The model that i pass to the table is correct (if i go to the model before the foreach there are 3 rows instead of 10 thanks to the filter)

The problem is that the table doesn't change, it always shows all the rows as the initial request.

It look like it works but the table won't update...

There's my jquery ajax call:

$("#Dropdown1Id").on('change', function () {
//console.log("onchange");
//console.log($("#Dropdown1Id").val());
var drpdown1 = $("#Dropdown1Id").val();
var submit = $("#submitButton");
    $.ajax({ // crea una chiamata AJAX
        data: { data: drpdown1 }, // prendi i dati del form in questo caso del primo dropdown
        type: "GET", // GET o POST
        url: "/Select/Filter", // li passa al controller
        success: function () { // se va con successo esegue il codice seguente
            submit.click();
            $("#frmId").submit();
        },
        error: function (error) {
            console.log("error")
        }
    });
});

There's my controller action:

public ActionResult Filter(string data)
    {
        List<Card> cards = new List<Card>();
        ViewBag.stato = new SelectList(myApi.GetState(), "Name", "Name");

        if (data != null && data != "")
        {
            foreach (var card in model)
            {
                if (card.IdList == data || data == "")
                    cards.Add(card);
            }
            return View(cards);
        }
        return View(model);
    }

There's my view with the daple and the dropdown:

@using (Html.BeginForm(new { id = "frmId"}))
{
@Html.AntiForgeryToken()

 LIST : @Html.DropDownList("stato", null, new { @id = "Dropdown1Id" })

        @*

ARCHVIED : @Html.DropDownList("closed", null, new { @id = "Dropdown2Id" })

        	*@

            <input type="submit" value="Filter" class="btn btn-info" id="submitButton" />

            TRELLO'S CARDS LIST

        LIST
        ARCHVIED
        Expiration date

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.IdList)

            @if (item.Closed == "True")
            {
                YES
            }
            else
            {
                NO
            }

            @if (item.Due != null)
            {

                    @Html.DisplayFor(modelItem => item.Due)

            }
            else
            {

                    Not Present

            }

        idList.Add(item.Id);
    }


问:
SQLITE DISTINCT COUNT within a strftime statement throwing error
I have a query in SQLite through Pandas in a jupyter notebook.

The below query runs as expected except I want the dayofweek_count to count the number of occurences of each weekday.  There can be more than one entry for each day (i.e. Monday 2/17/20 could have 4 entries but I only want Monday 2/17/20 counted once)

```<code>df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)"
    "when 0 then 'Sunday'"
    "when 1 then 'Monday'"
    "when 2 then 'Tuesday'"
    "when 3 then 'Wednesday'"
    "when 4 then 'Thursday'"
    "when 5 then 'Friday'"
    "else 'Saturday' end as dayofweek"
    ",COUNT(strftime('%w', event_date)) as dayofweek_count"
    ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])
</code>```

But this query throws a syntax error near DISTINCT, but I cannot seem to figure out why.  I have tried DISTINCT (event_date) as well as DISTINCT event_date.

```<code>df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)"
        "when 0 then 'Sunday'"
        "when 1 then 'Monday'"
        "when 2 then 'Tuesday'"
        "when 3 then 'Wednesday'"
        "when 4 then 'Thursday'"
        "when 5 then 'Friday'"
        "else 'Saturday' end as dayofweek"
        ",COUNT(strftime('%w',DISTINCT event_date)) as dayofweek_count"
        ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])
</code>```

What am I missing?

答:
```<code>COUNT(strftime('%w',DISTINCT event_date))
</code>```

That's a syntax error because strftime() doesn't understand DISTINCT; it's not an aggregate function (And with aggregate functions, it only works on ones with a single argument). COUNT(strftime(...)) doesn't make much sense anyways unless some of your event_date values are't accepted date/time strings (Which would make strftime() return NULL).

Body:
I have a query in SQLite through Pandas in a jupyter notebook.

The below query runs as expected except I want the dayofweek_count to count the number of occurences of each weekday.  There can be more than one entry for each day (i.e. Monday 2/17/20 could have 4 entries but I only want Monday 2/17/20 counted once)

df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)"
    "when 0 then 'Sunday'"
    "when 1 then 'Monday'"
    "when 2 then 'Tuesday'"
    "when 3 then 'Wednesday'"
    "when 4 then 'Thursday'"
    "when 5 then 'Friday'"
    "else 'Saturday' end as dayofweek"
    ",COUNT(strftime('%w', event_date)) as dayofweek_count"
    ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])

But this query throws a syntax error near DISTINCT, but I cannot seem to figure out why.  I have tried DISTINCT (event_date) as well as DISTINCT event_date.

df_total_weekday=pd.read_sql_query("SELECT CASE cast(strftime('%w', event_date) as integer)"
        "when 0 then 'Sunday'"
        "when 1 then 'Monday'"
        "when 2 then 'Tuesday'"
        "when 3 then 'Wednesday'"
        "when 4 then 'Thursday'"
        "when 5 then 'Friday'"
        "else 'Saturday' end as dayofweek"
        ",COUNT(strftime('%w',DISTINCT event_date)) as dayofweek_count"
        ",SUM(quantity) as total_quantity FROM subscription_data GROUP BY 1 ORDER BY strftime('%w', event_date)",conn,parse_dates=['event_date'])

What am I missing?

Body:
COUNT(strftime('%w',DISTINCT event_date))

That's a syntax error because strftime() doesn't understand DISTINCT; it's not an aggregate function (And with aggregate functions, it only works on ones with a single argument). COUNT(strftime(...)) doesn't make much sense anyways unless some of your event_date values are't accepted date/time strings (Which would make strftime() return NULL).


问:
What is the most efficent way to get a Range "set difference" in Excel Automation?
Given a pair of ranges, where one is known to contain elements of another:

```<code>src = ActiveSheet.UsedRange
sel = src.SpecialCells(xlCellTypeVisible)
</code>```

what is the most efficient way to get a new range that represents the set difference
between these two ranges, i.e., the cells in src that are not in sel?

This can be done using a loop over the cells in src, but this requires m * n Automation calls for an m by n range, which does not have very good performance, and I'm hoping for something that involves fewer remote API calls.

答:
I don't think there is any better way than looping through each cell in src.  The Excel.Application object has the Intersect function, which tells you what cells are contained in two or more ranges, but not the opposite.  You can also perform a union which just gives you a range with all the cells in two or more ranges...

But I think you're going to have to go through each cell in src and see if it's in sel...

```<code>Function GetInvisibleCells() As Range
    Dim src As Range, sel As Range

    Set src = ActiveSheet.UsedRange
    Set sel = src.SpecialCells(xlCellTypeVisible)

    Dim Isection As Range
    Set Isection = Application.Intersect(src, sel)

    Dim Result As Range

    Dim cl As Range
    For Each cl In src ' Go find all the cells in range2 that aren't in Isection
        If Application.Intersect(cl, Isection) Is Nothing Then
            ' Cl is not in sel
            If Not Result Is Nothing Then
                Set Result = Range(Result, cl)
            Else
                Set Result = cl
            End If
            ' Debug.Print Cl.Address & " is in " & src.Address & " and not in " & sel.Address
        End If
    Next cl
    Application.Intersect
    Set GetInvisibleCells = Result

End Function
</code>```

There are a few approaches detailed here

OwnerDisplayName: Christopher Currie

ContentLicense: CC BY-SA 2.5

Body:
Given a pair of ranges, where one is known to contain elements of another:

src = ActiveSheet.UsedRange
sel = src.SpecialCells(xlCellTypeVisible)

what is the most efficient way to get a new range that represents the set difference
between these two ranges, i.e., the cells in src that are not in sel?

This can be done using a loop over the cells in src, but this requires m * n Automation calls for an m by n range, which does not have very good performance, and I'm hoping for something that involves fewer remote API calls.

Body:
I don't think there is any better way than looping through each cell in src.  The Excel.Application object has the Intersect function, which tells you what cells are contained in two or more ranges, but not the opposite.  You can also perform a union which just gives you a range with all the cells in two or more ranges...

But I think you're going to have to go through each cell in src and see if it's in sel...

Function GetInvisibleCells() As Range
    Dim src As Range, sel As Range

    Set src = ActiveSheet.UsedRange
    Set sel = src.SpecialCells(xlCellTypeVisible)

    Dim Isection As Range
    Set Isection = Application.Intersect(src, sel)

    Dim Result As Range

    Dim cl As Range
    For Each cl In src ' Go find all the cells in range2 that aren't in Isection
        If Application.Intersect(cl, Isection) Is Nothing Then
            ' Cl is not in sel
            If Not Result Is Nothing Then
                Set Result = Range(Result, cl)
            Else
                Set Result = cl
            End If
            ' Debug.Print Cl.Address & " is in " & src.Address & " and not in " & sel.Address
        End If
    Next cl
    Application.Intersect
    Set GetInvisibleCells = Result

End Function

There are a few approaches detailed here

OwnerDisplayName: Jon Fournier

LastEditorDisplayName: Jon Fournier


问:
Distributed and replicated data storage for small amounts of data under Windows
We're looking for a good solution to a caching problem.  We'd like to distribute a relatively small amount of data (perhaps 10's of GBs) among a cluster of web servers such that:

The data is replicated to all nodes

The data is persistent

The data can be accessed locally

Our motivation for a caching solution is that we currently have a single point of failure: a SQL Server database.  We're unable to set up a fail-over cluster for this database, unfortunately.  We're already using Memcached to a large extent, but we want to avoid the problem where if a Memcached node goes down, we'd suddenly have a large amount of cache misses and therefore experience a massive amount of requests to one endpoint.

We'd prefer instead to have local persistent caches on each web server node so that the resulting load would be distributed.  When a retrieval is made, it would pass through the following:

Check for data in Memcached.  If it's not there...

Check for data in local persistent storage.  If it's not there...

Retrieve data from the database.

When data changes, the cache key is invalidated at both caching layers.

We've been looking at a bunch of potential solutions, but none of them seem to match exactly what we need:

CouchDB

This is pretty close; the data model we'd like to cache is very document-oriented.  However, its replication model isn't exactly what we're looking for.  It seems to me as though replication is an action you have to perform rather than a permanent relationship among nodes.  You can set up continuous replication, but this doesn't persist between restarts.

Cassandra

This solution seems to be mostly geared toward those with large storage requirements.  We have a large amount of users, but small amounts of data.  Cassandra looks to be able to support n number of fail-over nodes, but 100% replication among nodes doesn't seem to be what it's intended for; instead, it seems more geared toward distribution only.

SAN

One attractive idea is that we can store a bunch of files on a SAN or similar type of appliance.  I haven't worked with these before, but it seems like this would still be a single point of failure; if the SAN goes down, we'd suddenly be going to the database for all cache misses.

DFS Replication

A simple Google search revealed this.  It seems to do what we want; it synchronizes files across all nodes in a replication cluster.  But the marketing text makes it look like it's more of a system for ensuring documents are copied to different office locations.  Also, it has limits, like a file count maximum, that wouldn't work well for us.

Have any of you had similar requirements to ours and found a good solution that meets your needs?

答:
We've been using Riak successfully in production for several months now for a problem that's somewhat similar to what you describe. We too have evaluated CouchDB and Cassandra before.

The advantage of Riak in this sort of problems imo is that distribution and data replication are at the core of the system. You define how many replicas of the data across the cluster you want and it takes care of the rest (it's a bit more complicated than that of course, but that's the essence). We went through adding nodes, removing nodes, had nodes crush, and it's proven surprisingly resilient.

It's a lot like Couch in other matters - document oriented, REST interface, Erlang.


问:
How to set input date from ajax laravel
I have a date form that I want to fill in the value of ajax response, on the server side I use laravel and the data form becomes like this 2020-02-18 i try with this code, but it doesn't work. How do I fix it?

$.ajax({
    type: "get",
    url: "{{route('santri-edit-perijinan')}}" + "?id=" + id + "&type=" + type,
    success: function(data) {
        console.log(data.mulai_ijin);
        $("#tanggal_ijin").val(data.mulai_ijin);
    }
});
and this my html
  <input type="date" class="form-control" id="tanggal_ijin" name="tanggal">
```

答:
HTML input type=date accept yyyy-MM-dd format as input, So as long as your backend returns the date in the said format, your .val() function won't have any issue in setting the date.
If your date is being converted in Y-m-d H:i:s format as per PHP formats, you should convert the format using carbon.
Carbon::parse($date)->format('Y-m-d');

PHP date format Y-m-d is equivalent to yyyy-MM-dd format.

Title: How to set input date from ajax laravel


问:
No DB commits after message consumption in Spring cloud stream Azure Event Hub binder
I have an event listener Spring boot application which performs the operation Read from Azure Event Hub Topic -> Persist the event into DB.
I used the spring-cloud-azure-eventhubs-stream-binder(Version - 1.2.1)'s Sink to listen for events from my topic, and it works perfectly fine. However, that event is not persisted in DB. When I looked at the JPA created sql's there is no insert operation at all. I could only see the Select query being executed on JPA save.

I just followed the example in the link eventhubs-binder-sample.

```<code>@StreamListener(Sink.INPUT)
public void handleMessage(String message, @Header(AzureHeaders.CHECKPOINTER) Checkpointer checkpointer) {
    System.out.println(String.format("New message received: '%s'", message));
    myRepository.save(message); // No Insert operation triggered
}
</code>```

Any JPA save operation performed inside the @StreamListener annotated method is not inserting the data into the DB..

Any hints are highly appreciated.. I have to do something with Transaction Synchronisation(KafkaTransactionManager + JPATransactionManager) I suppose, but not sure..

答:
Got it working after spending a day on it.. Created a new JpaTransactionManager and used it to create a TransactionTemplate.

And performed my DB operations within a new Transaction created from the TransactionTemplate.

```<code>TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult()
        {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status)
            {
                myRepository.save(message);
            }
        });
</code>```

Body:
I have an event listener Spring boot application which performs the operation Read from Azure Event Hub Topic -> Persist the event into DB.
I used the spring-cloud-azure-eventhubs-stream-binder(Version - 1.2.1)'s Sink to listen for events from my topic, and it works perfectly fine. However, that event is not persisted in DB. When I looked at the JPA created sql's there is no insert operation at all. I could only see the Select query being executed on JPA save.

I just followed the example in the link eventhubs-binder-sample.

@StreamListener(Sink.INPUT)
public void handleMessage(String message, @Header(AzureHeaders.CHECKPOINTER) Checkpointer checkpointer) {
    System.out.println(String.format("New message received: '%s'", message));
    myRepository.save(message); // No Insert operation triggered
}

Any JPA save operation performed inside the @StreamListener annotated method is not inserting the data into the DB..

Any hints are highly appreciated.. I have to do something with Transaction Synchronisation(KafkaTransactionManager + JPATransactionManager) I suppose, but not sure..

Body:
Got it working after spending a day on it.. Created a new JpaTransactionManager and used it to create a TransactionTemplate.

And performed my DB operations within a new Transaction created from the TransactionTemplate.

TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult()
        {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status)
            {
                myRepository.save(message);
            }
        });


问:
Escaping a forwardslash in a text string regex python
Trying to obtain the numerical value and it appears the forward slash along with the second word boundary if giving me some problems.  Any help would be greatly appreciated.

This is coming from a text file and it should return about a hundred or so values into a list so it needs to be dynamic

```<code>#Here is the text of interest, I am trying to obtain just the numerical value of 268
Average Price/Square Foot\n$268

#I've tried these different methods for escaping the backslash but they are not working
avg_sqft_price = re.findall(r'\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price[\b]/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\B/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\/\bSquare Foot\n$268\n\$(d\*)',data)
</code>```

答:
The forward / is just a forward /, it has no specific meaning to re and there's nothing to escape. The issue is that you're trying to match things twice over:

```<code>\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)
</code>```

\W is already going to match /, so you're trying to match it twice, then you're matching $268 however unlike /, $ is a regex metacharacter (matches an end of string / end of line) so you do need to escape it, then you're trying to match  again except instead of \$\d+ you're matching a literal $ (this one's good), a literal d and a literal *. Since the latter is repeated in all your attempts nothing can ever work no matter what mess you make of earlier bits.

Also all your \b are pretty much useless though they're at least harmless. Which the \B is not since you're trying to match a non-word-boundary right at very explicit word boundary.

Average Price/Square Foot\n\$(\d+) seems to be what you're looking for: https://regex101.com/r/NyuTh7/2

Body:
Trying to obtain the numerical value and it appears the forward slash along with the second word boundary if giving me some problems.  Any help would be greatly appreciated.

This is coming from a text file and it should return about a hundred or so values into a list so it needs to be dynamic

#Here is the text of interest, I am trying to obtain just the numerical value of 268
Average Price/Square Foot\n$268

#I've tried these different methods for escaping the backslash but they are not working
avg_sqft_price = re.findall(r'\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price[\b]/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\B/\bSquare Foot\n$268\n\$(d\*)',data)
avg_sqft_price = re.findall(r'\bAverage Price\/\bSquare Foot\n$268\n\$(d\*)',data)

Body:
The forward / is just a forward /, it has no specific meaning to re and there's nothing to escape. The issue is that you're trying to match things twice over:

\bAverage Price\W/\bSquare Foot\n$268\n\$(d\*)

\W is already going to match /, so you're trying to match it twice, then you're matching $268 however unlike /, $ is a regex metacharacter (matches an end of string / end of line) so you do need to escape it, then you're trying to match  again except instead of \$\d+ you're matching a literal $ (this one's good), a literal d and a literal *. Since the latter is repeated in all your attempts nothing can ever work no matter what mess you make of earlier bits.

Also all your \b are pretty much useless though they're at least harmless. Which the \B is not since you're trying to match a non-word-boundary right at very explicit word boundary.

Average Price/Square Foot\n\$(\d+) seems to be what you're looking for: https://regex101.com/r/NyuTh7/2


问:
Angular Mat drag and drop detect when stop dragging over a div
I am using angular material drag and drop and I have two lists like the drag and drag example from the docs. I would like to be able to drag one of the items over one of two divs and then snap back to the original list but detect which div it dropped over. I tried using the material dragEnded function but it only gives you X and Y coordinates. Is there anyway to get the id of the div the item was ended dragging over?</p>

```<code><div class="example-container">
  <h2>To do</h2>

  <div
    cdkDropList
    #todoList="cdkDropList"
    [cdkDropListData]="todo"
    [cdkDropListConnectedTo]="[doneList, div1, div2]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of todo" cdkDrag>{{item.value}}</div>

</div>
</div>

<div class="example-container">
  <h2>Done</h2>
  <div
    cdkDropList
    #doneList="cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[todoList,  div1, div2]"
    class="example-list"
    (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of done" cdkDrag (cdkDragEnded)="dragEnded($event)">
      {{item.value}}
    </div>
  </div>
</div>
<br />
<br />
<div cdkDropList
     #div1="cdkDropList"
     [cdkDropListConnectedTo]="[doneList]"
     style="background-color: red; width: 300px; height: 100px"
     id="div1"
>Div 1</div>
<br />
<div cdkDropList
     #div2="cdkDropList"
     [cdkDropListConnectedTo]="[doneList]"
     style="background-color: red; width: 300px; height: 100px"
     id="div2"
>Div 2</div>
</code>```

答:
in the event (cdkDropListDropped)="drop($event) you has an event CdkDrapDop

In event.container.dataand event.currentIndex you has the "data", you can add a "fool data" [cdkDropListData]="'one'", [cdkDropListData]="'two'" and make a

```<code>drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
       if (event.container.data=='one'){...}
       if (event.container.data=='two'){...}
    }
  }
</code>```

If you has real data -an array, you can use if (event.container.data==myarrayOne)

Body:
I am using angular material drag and drop and I have two lists like the drag and drag example from the docs. I would like to be able to drag one of the items over one of two divs and then snap back to the original list but detect which div it dropped over. I tried using the material dragEnded function but it only gives you X and Y coordinates. Is there anyway to get the id of the div the item was ended dragging over?

To do

{{item.value}}

Done

      {{item.value}}

Div 1

Div 2

Body:
in the event (cdkDropListDropped)="drop($event) you has an event CdkDrapDop

In event.container.dataand event.currentIndex you has the "data", you can add a "fool data" [cdkDropListData]="'one'", [cdkDropListData]="'two'" and make a

drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
       if (event.container.data=='one'){...}
       if (event.container.data=='two'){...}
    }
  }

If you has real data -an array, you can use if (event.container.data==myarrayOne)


问:
How to disable stripe pay button when payment is processing using reactjs?

I have created using reactjs stripe card section and in card section, adding card element and in the checkout form render it and in checkout form pay button is also there but I want to disable the pay button unless response gets from backend?
  Here is my code:-

```<code>class CheckoutForm extends React.Component {
  handleCallback = status => {
    if (status === "success") {
      message.success("Payment is successfull");
      this.props.history.push("/main");
    } else {
      message.error("Some error occoured");
    }
  };

  handleSubmit = ev => {
    ev.preventDefault();
    const { userDetails, user, tempPassDate } = this.props;
    const { paymentId } = this.props;
    this.props.stripe
      .createPaymentMethod("card", { billing_details: { name: "Jenny Rosen" } })
      .then(({ paymentMethod }) => {
        console.log("Received Stripe PaymentMethod:", paymentMethod.id);
        this.props.payment(
          {
            paymentMethodId: paymentMethod.id,
            paymentId: paymentId,

          },

        );
      })
      .catch(err => console.log(err));
  };
  render() {

    return (
          <form onSubmit={this.handleSubmit}>
            <CardSection/>
            <button>
              Pay
            </button>
          </form>
    );
  }
}
</code>```

答:
Manage that in state like:</p>

```<code>class CheckoutForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      disableBtn: false;
    }
  }
  handleCallback = status => {
    if (status === "success") {
      message.success("Payment is successfull");
      this.props.history.push("/main");
    } else {
      message.error("Some error occoured");
    }
  };

  handleSubmit = ev => {
    ev.preventDefault();
    this.setState({ disableBtn: true });
    const { userDetails, user, tempPassDate } = this.props;
    const { paymentId } = this.props;
    this.props.stripe
      .createPaymentMethod("card", { billing_details: { name: "Jenny Rosen" } })
      .then(({ paymentMethod }) => {
        console.log("Received Stripe PaymentMethod:", paymentMethod.id);
        this.props.payment(
          {
            paymentMethodId: paymentMethod.id,
            paymentId: paymentId,

          },

        );
        this.setState({ disableBtn: false });
      })
      .catch(err => console.log(err));
  };
  render() {

    return (
          <form onSubmit={this.handleSubmit}>
            <CardSection/>
            <button disabled={this.state.disableBtn}>
              Pay
            </button>
          </form>
    );
  }
}
</code>```

Body:
I have created using reactjs stripe card section and in card section, adding card element and in the checkout form render it and in checkout form pay button is also there but I want to disable the pay button unless response gets from backend?
  Here is my code:-

class CheckoutForm extends React.Component {
  handleCallback = status => {
    if (status === "success") {
      message.success("Payment is successfull");
      this.props.history.push("/main");
    } else {
      message.error("Some error occoured");
    }
  };

  handleSubmit = ev => {
    ev.preventDefault();
    const { userDetails, user, tempPassDate } = this.props;
    const { paymentId } = this.props;
    this.props.stripe
      .createPaymentMethod("card", { billing_details: { name: "Jenny Rosen" } })
      .then(({ paymentMethod }) => {
        console.log("Received Stripe PaymentMethod:", paymentMethod.id);
        this.props.payment(
          {
            paymentMethodId: paymentMethod.id,
            paymentId: paymentId,

          },

        );
      })
      .catch(err => console.log(err));
  };
  render() {

    return (
          <form onSubmit={this.handleSubmit}>
            <CardSection/>
            <button>
              Pay
            </button>
          </form>
    );
  }
}

Body:
Manage that in state like:

class CheckoutForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      disableBtn: false;
    }
  }
  handleCallback = status => {
    if (status === "success") {
      message.success("Payment is successfull");
      this.props.history.push("/main");
    } else {
      message.error("Some error occoured");
    }
  };

  handleSubmit = ev => {
    ev.preventDefault();
    this.setState({ disableBtn: true });
    const { userDetails, user, tempPassDate } = this.props;
    const { paymentId } = this.props;
    this.props.stripe
      .createPaymentMethod("card", { billing_details: { name: "Jenny Rosen" } })
      .then(({ paymentMethod }) => {
        console.log("Received Stripe PaymentMethod:", paymentMethod.id);
        this.props.payment(
          {
            paymentMethodId: paymentMethod.id,
            paymentId: paymentId,

          },

        );
        this.setState({ disableBtn: false });
      })
      .catch(err => console.log(err));
  };
  render() {

    return (
          <form onSubmit={this.handleSubmit}>
            <CardSection/>
            <button disabled={this.state.disableBtn}>
              Pay
            </button>
          </form>
    );
  }
}


问:
Firebase Functions Error - firebase.functions is not a function
I am importing all the correct parts, but am getting an error that functions doesn't exist in firebase.

```<code><script src="https://www.gstatic.com/firebasejs/7.8.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-functions.js"></script>
</code>```

When I call:

```<code>firebaseConfig = {My App details};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
db = firebase.firestore();
functions = firebase.functions();
</code>```

The error is:

Uncaught TypeError: firebase.functions is not a function

答:
This type of error has very similar others that might occur on calling Firestore functions. For your error specifically, it seems that to fix your error you need to add require("firebase/functions") - as per the question Cloud functions with firebase: firebase.functions is not a function on the Community.

Let me know if the information helped you!

Body:
I am importing all the correct parts, but am getting an error that functions doesn't exist in firebase.

When I call:

firebaseConfig = {My App details};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
db = firebase.firestore();
functions = firebase.functions();

The error is:

Uncaught TypeError: firebase.functions is not a function


问:
Django - Issue with Dynamic URL Redirect using Reverse in Model
I am attempting to set up dynamic URL redirecting using the method outlined in my tutorial. However, it always mangles the actual URL.

For example, it should redirect to http://127.0.0.1:8000/products/3/, but rather redirected to http://127.0.0.1:8000/products/=/products/3/

My redirect function in models is

```<code>def get_absolute_url(self):
       return reverse("product-detail", args=[self.id])
</code>```

Note: My tutorial said I should pass in `kwargs={"id": self.id}, however, that created a whole other list of issues, and other posts I've seen pass in args, instead.

My urlpattern is path('products/<int:my_id>/', dynamic_lookup_view, name='product-detail'),

I've been puttering around for a while trying to figure this out. Would appreciate any help.

答:
Try this. It should work.</p>

```<code>def get_absolute_url(self):
    return reverse("product-detail", kwargs={"pk": self.pk})
</code>```

Body:
I am attempting to set up dynamic URL redirecting using the method outlined in my tutorial. However, it always mangles the actual URL.

For example, it should redirect to http://127.0.0.1:8000/products/3/, but rather redirected to http://127.0.0.1:8000/products/=/products/3/

My redirect function in models is

def get_absolute_url(self):
       return reverse("product-detail", args=[self.id])

Note: My tutorial said I should pass in `kwargs={"id": self.id}, however, that created a whole other list of issues, and other posts I've seen pass in args, instead.

My urlpattern is path('products/<int:my_id>/', dynamic_lookup_view, name='product-detail'),

I've been puttering around for a while trying to figure this out. Would appreciate any help.

Body:
Try this. It should work.

def get_absolute_url(self):
    return reverse("product-detail", kwargs={"pk": self.pk})


问:
Need to parse a Json object and append it to a table
```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function myFunction() {
            var abc, obj, i, j;
            abc = {
                "cars": [
                    '{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
                    '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
                    '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
                ]
            }
            var obj = JSON.parse(abc);
            var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
            document.getElementById("dtable").appendChild(theader);
            var x;
            for (i = 0; i < abc.cars.length; i++) {
                x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors + "</td><td>" + obj.cars[i].lol[0] + "</td></tr>";
                document.getElementById("dtable").appendChild(x);
            }
        };
    </script>
</head>
<body>
    <div class="container" ,id="dsjson">
        <button type="button" onclick="myFunction()">display json</button>
        <br><br>
        <table id="dtable"></table>
    </div>
</body>
</html>
</code>```

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

答:
Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.

If you want to add content using html strings, you can use insertAdjacentHTML in Vanilla.js

const dtable = document.getElementById("dtable");
const obj = {
  "cars": [{
      "model": "Sentra",
      "doors": 4,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    },
    {
      "model": "Maxima",
      "doors": 4,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    },
    {
      "model": "Skyline",
      "doors": 2,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    }
  ]
};
const cars = obj.cars;
const theader = "
Title	Author	year
";

function myFunction() {
  for (let i = 0; i < cars.length; i++) {
    if (i == 0) {
      dtable.insertAdjacentHTML('beforeend', theader);
    }
    let row = `

    ${cars[i].model}
    ${cars[i].doors}
    ${cars[i].lol[0]}

`;
    dtable.insertAdjacentHTML('beforeend', row);
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div class="container" ,id="dsjson">
    <button type="button" onclick="myFunction()">display json</button>
    <br><br>
    <table id="dtable"></table>
  </div>
</body>
</html></code>```

Body:
<!DOCTYPE html>

        <button type="button" onclick="myFunction()">display json</button>

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

Body:
Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.

If you want to add content using html strings, you can use insertAdjacentHTML in Vanilla.js

const dtable = document.getElementById("dtable");
const obj = {
  "cars": [{
      "model": "Sentra",
      "doors": 4,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    },
    {
      "model": "Maxima",
      "doors": 4,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    },
    {
      "model": "Skyline",
      "doors": 2,
      "lol": [
        "hi",
        "hello",
        "hahahaha"
      ]
    }
  ]
};
const cars = obj.cars;
const theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";

function myFunction() {
  for (let i = 0; i < cars.length; i++) {
    if (i == 0) {
      dtable.insertAdjacentHTML('beforeend', theader);
    }
    let row = `<tr>
    <td>${cars[i].model}</td>
    <td>${cars[i].doors}</td>
    <td>${cars[i].lol[0]}</td>
    </tr>`;
    dtable.insertAdjacentHTML('beforeend', row);
  }
};

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div class="container" ,id="dsjson">
    <button type="button" onclick="myFunction()">display json</button>
    <br><br>
    <table id="dtable"></table>
  </div>
</body>
</html>


问:
Best way to implement dynamic array of inputs in React
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}
```

<p><strong>UPDATE</strong></p>

<p>I tried using <code>immutable-js</code> <code>OrderedMap</code>. Now <code>key</code> property of elements won't change and <code>onChange</code> and <code>onDelete</code> won't iterate over everything. Is this better than before?</p>

```import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
```

<p><strong>UPDATE: 2</strong>
Also tried using plain javascript <code>Map</code>.</p>

<pre class="lang-js prettyprint-override"><code>import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(
            <div key={k}>
                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>
            </div>
        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

UPDATE 3
Using plain array but with key property.

```<code>import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (
                    <div key={key}>
                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>
                    </div>
                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

答:
Instead of using external js, i just do the little modification of the code, instead of doing the map or filter, you can use directly with splice,

the below code will help to do the deletion fast and it will keep the same index after deletion also.

```<code>import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
      const {value} = e.target;
      setRows(prev => {
          prev[i] = value;
          return [...prev];
        });
    };

    const onDelete = i => {
        setRows(prev => {
          prev.splice(i,1, undefined);
          return [...prev];
        });
    };
    return (
        <>
            {rows.map((row, index) => (typeof row !== "undefined") && (
              <div key={index}>
                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}
                    </div>
            ))}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}
</code>```

Body:
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}

UPDATE

I tried using immutable-js OrderedMap. Now key property of elements won't change and onChange and onDelete won't iterate over everything. Is this better than before?

import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE: 2
Also tried using plain javascript Map.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(

                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>

        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE 3
Using plain array but with key property.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (

                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

Body:
Instead of using external js, i just do the little modification of the code, instead of doing the map or filter, you can use directly with splice,

the below code will help to do the deletion fast and it will keep the same index after deletion also.

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
      const {value} = e.target;
      setRows(prev => {
          prev[i] = value;
          return [...prev];
        });
    };

    const onDelete = i => {
        setRows(prev => {
          prev.splice(i,1, undefined);
          return [...prev];
        });
    };
    return (
        <>
            {rows.map((row, index) => (typeof row !== "undefined") && (
              <div key={index}>
                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}
                    </div>
            ))}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}


问:
How to invoke a million Lambdas efficiently?
I have a Lambda function which I'm currently invoking from EC2. But I'm invoking it sequentially in a loop. So, if there are 1000 items to be processed, I'm using a simple loop to iterate over them and invoke the Lambda function for each item.

If this were to be done for a million items, this will not be efficient. What options do I have to reduce the time taken for this process.

The process for all items are independent; so, I can invoke, say, 1000 Lambdas in 1000 threads. But is that appropriate? I don't know much about Celery, SQS, redis, etc. but will those be useful in this scenario?

Just in case it's relevant, each Lambda takes around 5 minutes to complete.

答: Using a message broker would be more efficient. You can got with Redis or RabbitMQ


问:
How to load Northwind into SQLite3 -- Error 'File is not a database'
I am trying to load the Northwind.Sqlite3.create.sql hosted on https://github.com/jpwhite3/northwind-SQLite3 into SQLite3 on Ubuntu.

I have tried using: sqlite3 Northwind.Sqlite3.create.sql to import the database.
However when I try to view the data using SELECT * FROM CUSTOMERS; I get an error saying Error: file is not a database

Any suggestions as to how to open the database file and use it?

答:
That's just a text file full of DDL statements, not a sqlite3 database. You'd have to import it into a database with something like</p>

```<code>sqlite3 mydatabase.db < Northwind.Sqlite3.create.sql
</code>```

Body:
That's just a text file full of DDL statements, not a sqlite3 database. You'd have to import it into a database with something like

sqlite3 mydatabase.db < Northwind.Sqlite3.create.sql


问:
How do I keep the camera from changing its size?
I have attached two screenshots to my problem. Basically on resizing the Game view window the camera size also gets resized and the objects get moved when pressing play. How do I solve this?

答:
For anybody who is suffering form the same problem, I found the solution.
You just have to download and import a free unity asset.
Auto Letterbox</p>


问:
Does Liquibase runs before registering all the beans in spring boot application?
I have integrated Liquibase with my spring Boot application. The one confusion which I have is that - does Liquibase run before registering all the beans. If we want to fetch some property from the DB in the bean declaration method and that property is written by the sql script which will be executed by Liquibase. So, which of the two things will happen first?

I do know that liquibase automatically gets integrated to the startup of the spring boot application i.e, it runs everytime, the application runs. But, does it get loaded before loading other beans of the same application?

My liquibase dependency :

```<code><dependency>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-core</artifactId>
            <version>3.8.2</version>
</dependency>
</code>```

答:
So, which of the two things will happen first?

Liquibase runs it's scripts.

Spring-Boot initializes your beans.

So you should be able to get data (which Liquibase has just inserted) from database during bean initialization.

But as was suggested in the comments, you should try it yourself and add logs to your bean initialization methods. This will give you a way better understanding of Spring-Boot applications start-up process.

Body:
I have integrated Liquibase with my spring Boot application. The one confusion which I have is that - does Liquibase run before registering all the beans. If we want to fetch some property from the DB in the bean declaration method and that property is written by the sql script which will be executed by Liquibase. So, which of the two things will happen first?

I do know that liquibase automatically gets integrated to the startup of the spring boot application i.e, it runs everytime, the application runs. But, does it get loaded before loading other beans of the same application?

My liquibase dependency :

<dependency>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-core</artifactId>
            <version>3.8.2</version>
</dependency>