问:
How to listen to Webpage Events with a Chrome Extension
I have a webpage that has custom events that I would like to listen to with a chrome extension. Every time an order comes in, the webpage gets the order and updates a little notification number with how many orders are pending. I am looking to create a chrome extension to listen to this event and in future be able to select the order and perform actions on it.

First of all, is this possible?

In the website source code that I found through using F12 on Chrome I found the orderHandler.js file

```<code>var OrdersHandler=new(function(){this.getOrder=function(item_id,success,fail){try{$.ajax({url:'/api/orders/'+item_id,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.getOrdersList=function(listName,success,fail){try{$.ajax({url:'/api/orders-list/'+listName,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_items);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.getOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.takeOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/take",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.reprocessOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/reprocess",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.setSupplierOrderItem=function(item_id,supplier_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/change_supplier",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-Type":"application/json"},data:JSON.stringify({supplier_id:supplier_id}),success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.releaseOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/release",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.setOrderItemEarnPrice=function(item_id,price,success,fail){try{$.ajax({url:'/api/order_items/'+item_id,method:"PATCH",data:JSON.stringify({earn_price:price}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.confirmOrderItemDelivered=function(item_id,success,fail){try{$.ajax({url:"/api/order_items/"+item_id+"/confirm_delivered",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.markOrderItemDelivered=function(item_id,delivery_proof,files,success,fail){try{$.ajax({url:"/api/order_items/"+item_id+"/mark_delivered",method:"POST",data:JSON.stringify({delivery_proof:delivery_proof,files:files}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.addChatMessage=function(item_id,message,success,fail){if(message.length<3){return;}
try{$.ajax({url:'/api/order_items/'+item_id+"/chats",method:"POST",data:JSON.stringify({message:message}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};})();

</code>```

A lot of the Handler seems to be failure cases and what message to output depending on that. I was having a hard time deciphering what it is doing and how I can make a background.js to listen to the getOrder function.

Any help with these would be greatly appreciated! Ask for any clarification in the comments!

UPDATE

Via the helpful comments below. I can see that the window.OrdersHandler has functions available

Are these functions usable and how would I connect this to a Listener?
chrome.runtime.addListener()?

答:
Because OrdersHandler is global, and because it has the properties you're interested in directly assigned to the object, you can overwrite the properties you care about with your own logic. All of the properties look to be of the form:

```<code>this.getOrder = function (item_id, success, fail) {
    try {
        $.ajax({
            url: '/api/orders/' + item_id, method: "GET", headers: { "Authorization": "Bearer " + Cookies.getJSON("access_token").access_token }, success: function (response, status, xhr) {
                if (response.success) { if (typeof (success) == "function") { success(response.order); } }
                else { if (typeof (fail) == "function") { fail(status, response.message); } }
            }, error: function (response, status, statusName, xhr) {
                if (typeof (fail) == "function") {
                    if (typeof (response.responseJSON) === "object" && typeof (response.responseJSON.message) === "string") { fail(response.status, response.responseJSON.message); }
                    else { fail(response.status, response.status == 0 ? "Network error" : statusName); }
                }
            }
        });
    }
    catch (e) { console.log(e); onFailure(-1, "Script error"); }
};
</code>```

Once the parent OrdersHandler object is defined, simply overwrite the property (or properties) that you're interested in. Copy and paste the original code, and then add whatever custom logic you want. For example, to monkeypatch getOrder so that it logs the response.order when it succeeds, you could do:

```<code>OrdersHandler.getOrder = function (item_id, success, fail) {
    try {
        $.ajax({
            url: '/api/orders/' + item_id, method: "GET", headers: { "Authorization": "Bearer " + Cookies.getJSON("access_token").access_token }, success: function (response, status, xhr) {
                if (response.success) { if (typeof (success) == "function") {
                  console.log(response.order); // <--------------------------
                  success(response.order);
                } }
                else { if (typeof (fail) == "function") { fail(status, response.message); } }
            }, error: function (response, status, statusName, xhr) {
                if (typeof (fail) == "function") {
                    if (typeof (response.responseJSON) === "object" && typeof (response.responseJSON.message) === "string") { fail(response.status, response.responseJSON.message); }
                    else { fail(response.status, response.status == 0 ? "Network error" : statusName); }
                }
            }
        });
    }
    catch (e) { console.log(e); onFailure(-1, "Script error"); }
};
</code>```

You can paste that code into the browser console once the site has loaded. You could also write a userscript to run that code automatically whenever you load the page. (You could also write an extension, but an extension is overkill when you only want to inject some JS into a page, IMO)

Body:
I have a webpage that has custom events that I would like to listen to with a chrome extension. Every time an order comes in, the webpage gets the order and updates a little notification number with how many orders are pending. I am looking to create a chrome extension to listen to this event and in future be able to select the order and perform actions on it.

First of all, is this possible?

In the website source code that I found through using F12 on Chrome I found the orderHandler.js file

var OrdersHandler=new(function(){this.getOrder=function(item_id,success,fail){try{$.ajax({url:'/api/orders/'+item_id,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.getOrdersList=function(listName,success,fail){try{$.ajax({url:'/api/orders-list/'+listName,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_items);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.getOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id,method:"GET",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.takeOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/take",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.reprocessOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/reprocess",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.setSupplierOrderItem=function(item_id,supplier_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/change_supplier",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-Type":"application/json"},data:JSON.stringify({supplier_id:supplier_id}),success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.releaseOrderItem=function(item_id,success,fail){try{$.ajax({url:'/api/order_items/'+item_id+"/release",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.setOrderItemEarnPrice=function(item_id,price,success,fail){try{$.ajax({url:'/api/order_items/'+item_id,method:"PATCH",data:JSON.stringify({earn_price:price}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.confirmOrderItemDelivered=function(item_id,success,fail){try{$.ajax({url:"/api/order_items/"+item_id+"/confirm_delivered",method:"POST",headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.markOrderItemDelivered=function(item_id,delivery_proof,files,success,fail){try{$.ajax({url:"/api/order_items/"+item_id+"/mark_delivered",method:"POST",data:JSON.stringify({delivery_proof:delivery_proof,files:files}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response.order_item);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};this.addChatMessage=function(item_id,message,success,fail){if(message.length<3){return;}
try{$.ajax({url:'/api/order_items/'+item_id+"/chats",method:"POST",data:JSON.stringify({message:message}),headers:{"Authorization":"Bearer "+Cookies.getJSON("access_token").access_token,"Content-type":"application/json"},success:function(response,status,xhr){if(response.success){if(typeof(success)=="function"){success(response);}}
else{if(typeof(fail)=="function"){fail(status,response.message);}}},error:function(response,status,statusName,xhr){if(typeof(fail)=="function"){if(typeof(response.responseJSON)==="object"&&typeof(response.responseJSON.message)==="string"){fail(response.status,response.responseJSON.message);}
else{fail(response.status,response.status==0?"Network error":statusName);}}}});}
catch(e){console.log(e);onFailure(-1,"Script error");}};})();

A lot of the Handler seems to be failure cases and what message to output depending on that. I was having a hard time deciphering what it is doing and how I can make a background.js to listen to the getOrder function.

Any help with these would be greatly appreciated! Ask for any clarification in the comments!

UPDATE

Via the helpful comments below. I can see that the window.OrdersHandler has functions available

Are these functions usable and how would I connect this to a Listener?
chrome.runtime.addListener()?

Body:
Because OrdersHandler is global, and because it has the properties you're interested in directly assigned to the object, you can overwrite the properties you care about with your own logic. All of the properties look to be of the form:

this.getOrder = function (item_id, success, fail) {
    try {
        $.ajax({
            url: '/api/orders/' + item_id, method: "GET", headers: { "Authorization": "Bearer " + Cookies.getJSON("access_token").access_token }, success: function (response, status, xhr) {
                if (response.success) { if (typeof (success) == "function") { success(response.order); } }
                else { if (typeof (fail) == "function") { fail(status, response.message); } }
            }, error: function (response, status, statusName, xhr) {
                if (typeof (fail) == "function") {
                    if (typeof (response.responseJSON) === "object" && typeof (response.responseJSON.message) === "string") { fail(response.status, response.responseJSON.message); }
                    else { fail(response.status, response.status == 0 ? "Network error" : statusName); }
                }
            }
        });
    }
    catch (e) { console.log(e); onFailure(-1, "Script error"); }
};

Once the parent OrdersHandler object is defined, simply overwrite the property (or properties) that you're interested in. Copy and paste the original code, and then add whatever custom logic you want. For example, to monkeypatch getOrder so that it logs the response.order when it succeeds, you could do:

OrdersHandler.getOrder = function (item_id, success, fail) {
    try {
        $.ajax({
            url: '/api/orders/' + item_id, method: "GET", headers: { "Authorization": "Bearer " + Cookies.getJSON("access_token").access_token }, success: function (response, status, xhr) {
                if (response.success) { if (typeof (success) == "function") {
                  console.log(response.order); // <--------------------------
                  success(response.order);
                } }
                else { if (typeof (fail) == "function") { fail(status, response.message); } }
            }, error: function (response, status, statusName, xhr) {
                if (typeof (fail) == "function") {
                    if (typeof (response.responseJSON) === "object" && typeof (response.responseJSON.message) === "string") { fail(response.status, response.responseJSON.message); }
                    else { fail(response.status, response.status == 0 ? "Network error" : statusName); }
                }
            }
        });
    }
    catch (e) { console.log(e); onFailure(-1, "Script error"); }
};

You can paste that code into the browser console once the site has loaded. You could also write a userscript to run that code automatically whenever you load the page. (You could also write an extension, but an extension is overkill when you only want to inject some JS into a page, IMO)


来源: stackexchange

问:
java database connectivity error with mysql
i am trying to do java database connectivity in eclipse juno using eclipse but i am getting the following error comes

```<code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
</code>```

suggest me some solutions..........
this is my code :

```<code>package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Connect {

public static Connection getConnection()
{
    String url="jdbc:mysql://localhost:3306/demo";
    String drive="com.mysql.jdbc.Driver";
    //String databse="demo";
    String user="root";
    String password="abc";
    Connection conn=null;
    try
    {
        Class.forName(drive);
        conn=DriverManager.getConnection(url, user, password);
    }
    catch (Exception e)
    {
        System.out.println(""+e);
    }
    return conn;
}
public static void main(String[] args)
{
    Connection conn=null;
    PreparedStatement pstmt=null;
    try
    {
        conn=getConnection();
        conn.setAutoCommit(false);
        pstmt=conn.prepareStatement("insert into testlongtele(address,name)values(?,?)");
        pstmt.setString(0, "NIRAV");
        pstmt.setString(1, "KAMANI");
        pstmt.executeUpdate();
        pstmt.close();
        conn.commit();
        conn.close();
    }
    catch(Exception e)
    {
        System.out.println(""+e);
    }
}

}
</code>```

答:
```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mindtree.kalinga.exception.ConnectionfailedException;
public class JdbcConnection {
    private static JdbcConnection jdbcConnection;
    private static Connection dbConnection;
    private JdbcConnection() {
    }
    public static JdbcConnection getInstance() {
        if (jdbcConnection == null)
            jdbcConnection = new JdbcConnection();
        return jdbcConnection;
    }
    public static void createConnection() throws ConnectionfailedException {
        try {
            dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mindtree", "root", "Welcome123");
        } catch (SQLException e) {
            throw new ConnectionfailedException("Error creating the connection to database", e);
        }
        System.out.println("Connection to db Established!");
    }
    public static Connection getConnection() {
        return dbConnection;
    }
    public static void closeConnection() throws ConnectionfailedException {
        try {
            dbConnection.close();
        } catch (SQLException e) {
            throw new ConnectionfailedException("connection  not closed properly", e);
        }
    }
}
--------------------------------------
Main
--------------------------------------
package com.mindtree.kalinga.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.exception.ConnectionfailedException;
import com.mindtree.kalinga.service.Mindtreeservice;
import com.mindtree.kalinga.serviceimp.Mindtreeserviceimp;
import com.mindtree.kalinga.utility.JdbcConnection;
public class MindtreeMain {
    static Scanner in = new Scanner(System.in);
    static Mindtreeservice ms = new Mindtreeserviceimp();
    public static void main(String[] args) {
        try {
            JdbcConnection.createConnection();
        } catch (ConnectionfailedException e) {
            System.out.println("Not able to connect to database! Terminating application!");
            e.printStackTrace();
        }
        MindtreeMain mm = new MindtreeMain();
        int i = 1;
        while (i == 1) {
            System.out.println("1. to enter the detail\n" + "2. fetch the detail\n" + "3. to exit");
            int key = in.nextInt();
            switch (key) {
            case 1:
                Mindtree m = mm.createminds();
                break;
            case 2:
                List<Mindtree> ml = new ArrayList<>();
                mm.display(ml);
                break;
            case 3:
                i = 0;
                break;
            default:
                break;
            }
        }
    }
    private Mindtree createminds() {
        // TODO Auto-generated method stub
        System.out.println("enter the id of mind");
        int id = in.nextInt();
        in.nextLine();
        System.out.println("enter the name of mind");
        String name = in.nextLine();
        System.out.println("ente the address of minds");
        String address = in.nextLine();
        Mindtree m = new Mindtree(id, name, address);
        return m;
    }
    private void display(List<Mindtree> mind) {
        for (Mindtree i : mind) {
            System.out.println(i.getMid());
            System.out.println(i.getName());
            System.out.println(i.getAddress());
        }
    }
}
-------------------------------------------------
service
-------------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreeservice {
    public void insertmind(Mindtree m);
    public List<Mindtree> getAllminds();
}
---------------------------------------------
serviceimp
---------------------------------------------
package com.mindtree.kalinga.serviceimp;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.daoimp.Mindtreedaoimp;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.service.Mindtreeservice;
public class Mindtreeserviceimp implements Mindtreeservice {
    Mindtreedao md = new Mindtreedaoimp();
    @Override
    public void insertmind(Mindtree m) {
        // TODO Auto-generated method stub
        md.insertMindToDb(m);
    }
    @Override
    public List<Mindtree> getAllminds() {
        // TODO Auto-generated method stub
        return md.getAllMindFromDb();
    }
}
--------------------------------------------
dao
--------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreedao {
    public void insertMindToDb(Mindtree m);
    public List<Mindtree> getAllMindFromDb();
}
-------------------------------------------
daoimp
-------------------------------------------
package com.mindtree.kalinga.daoimp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.utility.JdbcConnection;
import com.mysql.jdbc.Statement;
public class Mindtreedaoimp implements Mindtreedao {
    @Override
    public void insertMindToDb(Mindtree m) {
        Connection con = JdbcConnection.getConnection();
        String query = "insert into mindtree values(?,?,?);";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(query);
            ps.setInt(1, m.getMid());
            ps.setString(2, m.getName());
            ps.setString(3, m.getAddress());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }
    }
    @Override
    public List<Mindtree> getAllMindFromDb() {
        // TODO Auto-generated method stub
        List<Mindtree> mtl = new ArrayList<Mindtree>();
        Connection con = JdbcConnection.getConnection();
        String query = "select * from mindtree;";
        Statement st = null;
        ResultSet rs = null;
        try {
            st = (Statement) con.createStatement();
            rs = st.executeQuery(query);
            while (rs.next()) {
                Mindtree m = new Mindtree(rs.getInt(1), rs.getString(2), rs.getString(3));
                mtl.add(m);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mtl;
    }
}
-----------------------------------------------
exception
package com.mindtree.kalinga.exception;
public class ConnectionfailedException extends Exception {
    public ConnectionfailedException() {
        super();
        // TODO Auto-generated constructor stub
    }
    public ConnectionfailedException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
        super(arg0, arg1, arg2, arg3);
        // TODO Auto-generated constructor stub
    }
    public ConnectionfailedException(String arg0, Throwable arg1) {
        super(arg0, arg1);
        // TODO Auto-generated constructor stub
    }
    public ConnectionfailedException(String arg0) {
        super(arg0);
        // TODO Auto-generated constructor stub
    }
    public ConnectionfailedException(Throwable arg0) {
        super(arg0);
        // TODO Auto-generated constructor stub
    }
}
-----------------------------
entity
-----------------------------
package com.mindtree.kalinga.entity;
public class Mindtree {
    int Mid;
    String name;
    String address;
    public Mindtree(int mid, String name, String address)
{

        Mid = mid;
        this.name = name;
        this.address = address;
    }
    public int getMid() {
        return Mid;
    }
    public void setMid(int mid) {
        Mid = mid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to do java database connectivity in eclipse juno using eclipse but i am getting the following error comes

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException

suggest me some solutions..........
this is my code :

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Connect {

public static Connection getConnection()
{
    String url="jdbc:mysql://localhost:3306/demo";
    String drive="com.mysql.jdbc.Driver";
    //String databse="demo";
    String user="root";
    String password="abc";
    Connection conn=null;
    try
    {
        Class.forName(drive);
        conn=DriverManager.getConnection(url, user, password);
    }
    catch (Exception e)
    {
        System.out.println(""+e);
    }
    return conn;
}
public static void main(String[] args)
{
    Connection conn=null;
    PreparedStatement pstmt=null;
    try
    {
        conn=getConnection();
        conn.setAutoCommit(false);
        pstmt=conn.prepareStatement("insert into testlongtele(address,name)values(?,?)");
        pstmt.setString(0, "NIRAV");
        pstmt.setString(1, "KAMANI");
        pstmt.executeUpdate();
        pstmt.close();
        conn.commit();
        conn.close();
    }
    catch(Exception e)
    {
        System.out.println(""+e);
    }
}

}

ContentLicense: CC BY-SA 4.0


问:
':app:lintVitalRelease' error when generating signed apk
I've tried to upload my apk on google play and encountered an error message: "You uploaded a debuggable APK. For security reasons you need to disable debugging before it can be published in Google Play. Learn more about debuggable APKs."

Then I wrote android:debuggable="false" in my manifest and tried again. I've encountered the same error, so I've set the build variant from my module to release and tried generated an apk again, but this time, this error is generated:

```<code>Error:Gradle: Execution failed for task ':app:lintVitalRelease'.
Lint found fatal errors while assembling a release target.
  To proceed, either fix the issues identified by lint, or modify your build script as follows:
  ...
  android {
      lintOptions {
          checkReleaseBuilds false
          // Or, if you prefer, you can continue to check for errors in release builds,
          // but continue the build even when errors are found:
          abortOnError false
      }
  }
  ...
</code>```

答:
Add this inside android {}
build.gradle(Module:App)

```<code>lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
}
</code>```

Body:
I've tried to upload my apk on google play and encountered an error message: "You uploaded a debuggable APK. For security reasons you need to disable debugging before it can be published in Google Play. Learn more about debuggable APKs."

Then I wrote android:debuggable="false" in my manifest and tried again. I've encountered the same error, so I've set the build variant from my module to release and tried generated an apk again, but this time, this error is generated:

Error:Gradle: Execution failed for task ':app:lintVitalRelease'.
Lint found fatal errors while assembling a release target.
  To proceed, either fix the issues identified by lint, or modify your build script as follows:
  ...
  android {
      lintOptions {
          checkReleaseBuilds false
          // Or, if you prefer, you can continue to check for errors in release builds,
          // but continue the build even when errors are found:
          abortOnError false
      }
  }
  ...

Body:
Add this inside android {}
build.gradle(Module:App)

lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
}


问:
Package signatures do not match the previously installed version
This my project: https://github.com/kenpeter/my_hak_news, which is a direct copy of https://github.com/grigio/HAgnostic-News.

Git clone https://github.com/kenpeter/my_hak_news, then run react-native run-android

Got this error:

```<code>* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.hagnosticnews signatures do not match the previously installed version; ignoring!
</code>```

Relevant issue: https://github.com/grigio/HAgnostic-News/issues/1, I follow various ways, but not able to resolve this issue.

答:
This occurs due to the availability of the previous version of the Application, that is not installed on the device but its data is present in the device memory. So it fails to upgrade this uninstalled application data on the device

Try this :

Go to Device Settings ==> Apps(All Apps) ==> search your App OR search for 'client' ==> In App info screen , press the triple dots option on top right corner ==> select 'Uninstall for All Users' ==> a promt appears select 'OK'

It works for me every time this error occurs

Body:
This my project: https://github.com/kenpeter/my_hak_news, which is a direct copy of https://github.com/grigio/HAgnostic-News.

Git clone https://github.com/kenpeter/my_hak_news, then run react-native run-android

Got this error:

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to finalize session : INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.hagnosticnews signatures do not match the previously installed version; ignoring!

Relevant issue: https://github.com/grigio/HAgnostic-News/issues/1, I follow various ways, but not able to resolve this issue.


问:
Keep hover effect when moved out of the element
I have a navbar with an item that when a user hovers on it, a panel will open, like a dropdown menu. And when user clicks on an item on the panel, a small popup will open near it for information, and user can click things on that popup (such as links, button,...).

My problem is when the user moves the pointer to the popup, the panel will disappear because the popup is not in the same element with a navbar item, so it lost the hover effect.

Is there any solution to keep hovering item while mouse moved to the popup, and still keep the DOM structure (popup separates with navbar items)

答: As you use mouseover event, you need to use mouseout event to reset the default values.</p>


问:
Custom status change events in Javascript
I have an asynchronous function that performs various await tasks. I am trying to inform my UI in React when the status of the function changes or when one of the tasks is completed.

```<code>const foo = async () => {
    // trigger on load event

    await task1();
    // trigger task1 done event

    await task2();
    // trigger task2 done event

    await task3();
    // trigger on done event
}
</code>```

I also want to be able to specify callbacks for each event, like so:

```<code>const bar = foo();
foo.on_load(() => {
    // some code goes here
});
foo.on_done(() => {
    // some code goes here
});
</code>```

Another alternative would be something like this:

```<code>const bar = foo();
foo.on('status_change', status => {
    // read the status here and do something depending on the status
})
</code>```

I have been reading about custom events in JS but not sure how to use them for this. Or maybe there's another way to do this in React.

Any ideas would be helpful. Thanks!

EDIT

```<code>var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});
</code>```

I was trying to achieve something like the above code, taken from the firebase documentation on uploading files

This is where I've gotten so far:

```<code>class Task {
  constructor() {
    this.first = null;
    this.second = null;
  }

  on(keyword, callback) {
    switch (keyword) {
      case "first":
        this.first = callback;
        break;
      case "second":
        this.second = callback;
        break;
      default:
        // throw new error
        break;
    }
  }
}

const timeout = async time => {
  return new Promise(resolve => setTimeout(resolve, time));
};

const foo = () => {
  const task = new Task();

  timeout(2000).then(async () => {
    task.first && task.first();
    await timeout(2000);
    task.second && task.second();
  });

  console.log("returning");
  return task;
};

const taskObject = foo();
taskObject.on("first", () => console.log("executing first callback"));
taskObject.on("second", () => console.log("executing second callback"));
</code>```

Is there a better way to do this - without having the nested thens? Which approach would be better and when? EDIT - removed nested then clauses and replaced with then and await

PS: for my requirements, having callbacks would be sufficient. This is just so I can understand the concept better. Thanks!

答:
The best option would be to make use of promises, which means every time a promise is resolved, you will get notified and then cascading promise will get executed.

an example below of chaining promises

```<code>var function3 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function3 called');
     resolve('function3 success');
   }
   catch(err)
   {
      reject(err);
   }
}

var function2 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function2 called');
     resolve('function2 success');
     //return new Promise(function3);
   }
   catch(err)
   {
      reject(err);
   }
}

var function1 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function1 called');
     resolve('function1 success');
   }
   catch(err)
   {
      reject(err);
   }
}

var promise = new Promise(function1);

promise
.then(function(response){
  console.log(response);
   return new Promise(function2);
}, function(error)
{
   console.log(error);
})
.then(function(response)
{
  console.log(response);
  return new Promise(function3);
},
function(err)
{
  console.log(error);
})
.then(function(response)
{
  console.log(response);
},
function(err)
{
  console.log(error);
})

//output
"function1 called"
"function1 success"
"function2 called"
"function2 success"
"function3 called"
"function3 success"

</code>```

Body:
I have an asynchronous function that performs various await tasks. I am trying to inform my UI in React when the status of the function changes or when one of the tasks is completed.

const foo = async () => {
    // trigger on load event

    await task1();
    // trigger task1 done event

    await task2();
    // trigger task2 done event

    await task3();
    // trigger on done event
}

I also want to be able to specify callbacks for each event, like so:

const bar = foo();
foo.on_load(() => {
    // some code goes here
});
foo.on_done(() => {
    // some code goes here
});

Another alternative would be something like this:

const bar = foo();
foo.on('status_change', status => {
    // read the status here and do something depending on the status
})

I have been reading about custom events in JS but not sure how to use them for this. Or maybe there's another way to do this in React.

Any ideas would be helpful. Thanks!

EDIT

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});

I was trying to achieve something like the above code, taken from the firebase documentation on uploading files

This is where I've gotten so far:

class Task {
  constructor() {
    this.first = null;
    this.second = null;
  }

  on(keyword, callback) {
    switch (keyword) {
      case "first":
        this.first = callback;
        break;
      case "second":
        this.second = callback;
        break;
      default:
        // throw new error
        break;
    }
  }
}

const timeout = async time => {
  return new Promise(resolve => setTimeout(resolve, time));
};

const foo = () => {
  const task = new Task();

  timeout(2000).then(async () => {
    task.first && task.first();
    await timeout(2000);
    task.second && task.second();
  });

  console.log("returning");
  return task;
};

const taskObject = foo();
taskObject.on("first", () => console.log("executing first callback"));
taskObject.on("second", () => console.log("executing second callback"));

Is there a better way to do this - without having the nested thens? Which approach would be better and when? EDIT - removed nested then clauses and replaced with then and await

PS: for my requirements, having callbacks would be sufficient. This is just so I can understand the concept better. Thanks!

Body:
The best option would be to make use of promises, which means every time a promise is resolved, you will get notified and then cascading promise will get executed.

an example below of chaining promises

var function3 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function3 called');
     resolve('function3 success');
   }
   catch(err)
   {
      reject(err);
   }
}

var function2 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function2 called');
     resolve('function2 success');
     //return new Promise(function3);
   }
   catch(err)
   {
      reject(err);
   }
}

var function1 = function(resolve, reject)
{
   try
   {
     //do some thing
     console.log('function1 called');
     resolve('function1 success');
   }
   catch(err)
   {
      reject(err);
   }
}

var promise = new Promise(function1);

promise
.then(function(response){
  console.log(response);
   return new Promise(function2);
}, function(error)
{
   console.log(error);
})
.then(function(response)
{
  console.log(response);
  return new Promise(function3);
},
function(err)
{
  console.log(error);
})
.then(function(response)
{
  console.log(response);
},
function(err)
{
  console.log(error);
})

//output
"function1 called"
"function1 success"
"function2 called"
"function2 success"
"function3 called"
"function3 success"


问:
How to select two attributes from the same node with one expression in XPath?
For example:

```<code>//person[@id='abc123']/@haircolor|/@weight"
</code>```

PS. there are lots of "person" records

答:
Are you wanting to search for person nodes based on the value of multiple attributes.  If that's the question then you can just use ands e.g.

```<code>//person[@id='abc123' and @haircolor='blue' and @weight='...']
</code>```

If you want to search on a single attribute, but return the values of the other attributes, I would do something like this:

```<code> <xsl:template match="person[@id='abc123']">
     <xsl:value-of select="@haircolor"/>
     <xsl:value-of select="@weight"/>
  </xsl:template>
</code>```

Body:
For example:

//person[@id='abc123']/@haircolor|/@weight"

PS. there are lots of "person" records

Body:
Are you wanting to search for person nodes based on the value of multiple attributes.  If that's the question then you can just use ands e.g.

//person[@id='abc123' and @haircolor='blue' and @weight='...']

If you want to search on a single attribute, but return the values of the other attributes, I would do something like this:

 <xsl:template match="person[@id='abc123']">
     <xsl:value-of select="@haircolor"/>
     <xsl:value-of select="@weight"/>
  </xsl:template>


问:
Error check user input with integers in C
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

```<code>char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);
</code>```

I just need to check if these are in fact integers

答:
An approach that should be at least a bit more robust:

char input[100];
/* use fgets - it's the safer way to read a line.
   scanf("%[^\n]", input); can result in a buffer overflow! */
fgets(input, sizeof(input), stdin);

int c1, c2, c3, end;
/* Check the return value of sscanf to ensure we read exactly three ints.
   We then use %n to check that we read up to the end of the string.
   The \n before the %n skips all whitespace at the end of the string.
*/
if(sscanf(input, "%d,%d,%d\n%n", &c1, &c2, &c3, &end) != 3 || input[end] != '\0') {
    printf("invalid input!\n");
}
...
```

What this does: read a line using fgets (safer and no buffer overflow, unlike your scanf), then parses it using sscanf. Here I used the %n format option, which writes the number of characters read so far into the corresponding int parameter (here, end). Then we simply check that we hit the end of the string - if not, there must be trailing garbage so we can reject the input. Also, we check the return value of sscanf to ensure it has read exactly three numbers (%n doesn't count).

Body:
I am trying to take RGB codes entered by a user in the format #1, #2, #3. I error check the input to make sure it matches the ', ' format and can extract the numbers from the string. However, I am having trouble checking if the input is a number after that.

Ex: If the user enters: 255, 0, 0f the program still runs.

Any help would be appreciated!

char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);

//function to error check ', ' format

int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);

I just need to check if these are in fact integers

Body:
An approach that should be at least a bit more robust:

char input[100];
/* use fgets - it's the safer way to read a line.
   scanf("%[^\n]", input); can result in a buffer overflow! */
fgets(input, sizeof(input), stdin);

int c1, c2, c3, end;
/* Check the return value of sscanf to ensure we read exactly three ints.
   We then use %n to check that we read up to the end of the string.
   The \n before the %n skips all whitespace at the end of the string.
*/
if(sscanf(input, "%d,%d,%d\n%n", &c1, &c2, &c3, &end) != 3 || input[end] != '\0') {
    printf("invalid input!\n");
}
...

What this does: read a line using fgets (safer and no buffer overflow, unlike your scanf), then parses it using sscanf. Here I used the %n format option, which writes the number of characters read so far into the corresponding int parameter (here, end). Then we simply check that we hit the end of the string - if not, there must be trailing garbage so we can reject the input. Also, we check the return value of sscanf to ensure it has read exactly three numbers (%n doesn't count).


问:
Converting bitwise if condition to usual if condition
I have found this if condition using bitwise, I don't know how to convert it to work with normal logical operator.

```<code>if (out[currentState] & (1 << j))
</code>```

How to provide an equivalent condition that doesn't use bitwise?

答:
Bitwise operations aren't that difficult to learn, in fact they're much faster than other data type operations. However, you can use a function, to hide the complicated computation, like so:</p>

```<code> bool Check( const Foo& foo, int pos) {
     return foo & 1 << pos;

if(Check(out[currentState], j)) dosomething();
</code>```

Body:
I have found this if condition using bitwise, I don't know how to convert it to work with normal logical operator.

if (out[currentState] & (1 << j))

How to provide an equivalent condition that doesn't use bitwise?

Body:
Bitwise operations aren't that difficult to learn, in fact they're much faster than other data type operations. However, you can use a function, to hide the complicated computation, like so:

 bool Check( const Foo& foo, int pos) {
     return foo & 1 << pos;

if(Check(out[currentState], j)) dosomething();


问:
How can I set an AppleScript to run when a given file is modified?
I know that applescripts can be set to run as folder actions, but is there a way to get them to run as file actions? Yes, I know I can work around this by just making a new folder, putting the script in it, and running as a folder action, but I want to know if this can be done.

答: This is an old question, but the Apple Automator tool in MacOS does exactly this. You can set it to watch a folder and execute an Applescript, Shell Script, etc.

ContentLicense: CC BY-SA 2.5


问:
Created a Quiz using React, trying to create bookmarking system where users can bookmark questions from quiz
Using React, I created a Quiz where users get questions and can select answers:
https://codesandbox.io/s/quiz-1cf1m

I'm trying to add a bookmark functionality where the user can "bookmark" questions they want to get back to later. And once the quiz ends, can display the list of questions they bookmarked in the Result Summary (and hopefully click to get to that specific question).

In my Question Component, I added isBookMarked set to false and bookmarkedQuestions set to an empty array. Then created a handleBookmark function that toggles the bookmark icon.

```<code>class Question extends React.Component {
  state = {
    pick: false,
    correct: false,
    isBookmarked: false,
    bookmarkedQuestions: []
  };

  correctOrIncorrect = pick => {
    if (pick === this.state.pick) {
      return this.state.correct ? "correct" : "incorrect";
    } else if (
      pick === !this.state.correct &&
      this.props.currentQuestion.correctAnswer
    ) {
      return "correct";
    } else {
      return "clear";
    }
  };

  handleSelect = pick => {
    if (pick === this.props.currentQuestion.correctAnswer) {
      this.setState({ pick, correct: true });
    } else {
      this.setState({ pick });
    }
  };

  moveToNextQuestion = () => {
    this.setState({ pick: false, correct: false });
    this.props.nextQuestionHandler(this.state.correct);
  };

  handleBookmark = () => {
    console.log(this.props.currentQuestion);

    this.setState({
      isBookmarked: !this.state.isBookmarked
    });
  };

  render() {
    const { currentQuestion, shuffledAnswerChoices } = this.props;

    return (
      <div className={this.props.animation ? this.props.animation : null}>
        <span>
          <i
            id={currentQuestion}
            className={
              this.state.isBookmarked ? "fa fa-bookmark" : "fa fa-bookmark-o"
            }
            onClick={() => this.handleBookmark()}
          />
        </span>
        <p>{currentQuestion.text}</p>
        <ol type="A">
          {shuffledAnswerChoices.map((pick, idx) => {
            return (
              <li
                key={idx}
                className={this.state.pick ? this.correctOrIncorrect(pick) : null}
                onClick={() => this.handleSelect(pick)}
              >
                {pick}
              </li>
            );
          })}
        </ol>
        {this.state.pick && (
          <div>
            {this.state.correct ? (
              <p>
                <i>Correct!</i>
              </p>
            ) : (
              <p>
                <i>Incorrect</i>
              </p>
            )}
            <button className="next-btn" onClick={this.moveToNextQuestion}>
              Next
            </button>
          </div>
        )}
      </div>
    );
  }
}

export default Question;
</code>```

I realized with the current code I have, when I bookmark the icon stays bookmarked throughout the quiz unless I click again to unbookmark it. I have added a console log and can grab the current question I am on. I'm stuck with being able to only bookmark the selected questions and once the user moves to the next question, it "resets." I am also trying to push the question into the empty bookmarkedQuestions array when bookmarked, which I want to display at the end of the quiz (but just realized that the Result Component is a sibling not a child of the Question Component, and therefore, cannot pass down as props...).

Any React Pros out there who can teach me how to approach this problem...?

Additional question expanding from this bookmark system: any approach suggestions on how to repeat all the incorrect questions again until all questions have been correctly answered with the summary showing how many questions were answered correctly the first time?

答:
Definitely not a React Pro but I think I can be of help!

In my opinion, I think you should move the bookmark state to the Quiz level so that it persists for the duration of the quiz. This means passing down a function to the question from the quiz to control the state of the currently bookmarked questions. This also means that the 'isBookmarked' flag is passed down as a prop as well.

This may mean creating logic that overcomplicates what you are aiming to do.

LONG EXAMPLE (Some parts are overcomplicated for what it needs to do)- feel free to not use any of this, but I got into it so felt like adding it:
 https://codesandbox.io/s/quiz-x8wpv?fontsize=14&hidenavigation=1&theme=dark

I messed around with your code and created an example of how it would work. The data structure I chose for the bookmarks is a an object that has top level key of the quiz, [quizNumber], the value being another object with keys being each question. Which would then have a boolean flag which will indicate if bookmarked or not. To achieve this adding a field id for each question would be helpful

To avoid storing lots of data I omitted the actual question from the data structure as it can then be looked up with the quizNumber and question ID.

So I took the liberty of updating the questions to match this style

```<code>  {
        qID: 1,
        text: "What is the capital of United States?",
        correctAnswer: "Washington, D.C.",
        incorrectAnswers: ["Philadelphia", "Annapolis", "New York City"]
      }
</code>```

So an example of what the structure of the bookmarkedQuestions object could be is,

```<code>{
 '0':{1:true},
 '2':{1:false, 2:true , 3:true}
}
</code>```

This example would mean quiz 0 question 1 has been bookmarked as well as quiz 2 question 2 and 3. If the key does not exist or is false it can be assumed that the question has not been bookmarked.

To set this a function at the quiz level would need to be created. The function I created is most likely way overcomplicated for what it needs to do but is as follows

```<code>  bookmarkQuestion = () => {
    const { currentQuiz, numOfQuestions, quizQuestionBookmarks } = this.state;
    const { questions } = quizzes[currentQuiz];
    const { qID } = questions[numOfQuestions];
    // Can be simplified by creating a function to update nested values, or by using lodash
    // The destructuring is required so other parts of the object are not modified when updated deeper keys
    this.setState({
      quizQuestionBookmarks: {
        ...quizQuestionBookmarks,
        [currentQuiz]: {
          ...quizQuestionBookmarks[currentQuiz],
          [qID]: quizQuestionBookmarks[currentQuiz]
            ? !quizQuestionBookmarks[currentQuiz][qID]
            : true
        }
      }
    });
  };
</code>```

The idea is that this can now be used on the currentQuizQuestions to get the list of questions that are currently bookmarked.

```<code>  getBookmarkedQuestions = () => {
    const { currentQuiz, quizQuestionBookmarks } = this.state;
    const { questions } = quizzes[currentQuiz];
    const boorkmarkedQuestions = questions.filter(question =>
      quizQuestionBookmarks[currentQuiz]
        ? quizQuestionBookmarks[currentQuiz][question.qID]
        : false
    );
    return boorkmarkedQuestions;
  };
</code>```

In my example I also pass the bookmarkedQuestions to the Results page as a prop to demonstrate how the data can be passed to it to be used.

Body:
Using React, I created a Quiz where users get questions and can select answers:
https://codesandbox.io/s/quiz-1cf1m

I'm trying to add a bookmark functionality where the user can "bookmark" questions they want to get back to later. And once the quiz ends, can display the list of questions they bookmarked in the Result Summary (and hopefully click to get to that specific question).

In my Question Component, I added isBookMarked set to false and bookmarkedQuestions set to an empty array. Then created a handleBookmark function that toggles the bookmark icon.

class Question extends React.Component {
  state = {
    pick: false,
    correct: false,
    isBookmarked: false,
    bookmarkedQuestions: []
  };

  correctOrIncorrect = pick => {
    if (pick === this.state.pick) {
      return this.state.correct ? "correct" : "incorrect";
    } else if (
      pick === !this.state.correct &&
      this.props.currentQuestion.correctAnswer
    ) {
      return "correct";
    } else {
      return "clear";
    }
  };

  handleSelect = pick => {
    if (pick === this.props.currentQuestion.correctAnswer) {
      this.setState({ pick, correct: true });
    } else {
      this.setState({ pick });
    }
  };

  moveToNextQuestion = () => {
    this.setState({ pick: false, correct: false });
    this.props.nextQuestionHandler(this.state.correct);
  };

  handleBookmark = () => {
    console.log(this.props.currentQuestion);

    this.setState({
      isBookmarked: !this.state.isBookmarked
    });
  };

  render() {
    const { currentQuestion, shuffledAnswerChoices } = this.props;

    return (

           this.handleBookmark()}
          />

{currentQuestion.text}

          {shuffledAnswerChoices.map((pick, idx) => {
            return (

 this.handleSelect(pick)}
              >
                {pick}

            );
          })}

        {this.state.pick && (

            {this.state.correct ? (

                Correct!

            ) : (

                Incorrect

            )}
            <button className="next-btn" onClick={this.moveToNextQuestion}>
              Next
            </button>

        )}

    );
  }
}

export default Question;

I realized with the current code I have, when I bookmark the icon stays bookmarked throughout the quiz unless I click again to unbookmark it. I have added a console log and can grab the current question I am on. I'm stuck with being able to only bookmark the selected questions and once the user moves to the next question, it "resets." I am also trying to push the question into the empty bookmarkedQuestions array when bookmarked, which I want to display at the end of the quiz (but just realized that the Result Component is a sibling not a child of the Question Component, and therefore, cannot pass down as props...).

Any React Pros out there who can teach me how to approach this problem...?

Additional question expanding from this bookmark system: any approach suggestions on how to repeat all the incorrect questions again until all questions have been correctly answered with the summary showing how many questions were answered correctly the first time?

Body:
Definitely not a React Pro but I think I can be of help!

In my opinion, I think you should move the bookmark state to the Quiz level so that it persists for the duration of the quiz. This means passing down a function to the question from the quiz to control the state of the currently bookmarked questions. This also means that the 'isBookmarked' flag is passed down as a prop as well.

This may mean creating logic that overcomplicates what you are aiming to do.

LONG EXAMPLE (Some parts are overcomplicated for what it needs to do)- feel free to not use any of this, but I got into it so felt like adding it:
 https://codesandbox.io/s/quiz-x8wpv?fontsize=14&hidenavigation=1&theme=dark

I messed around with your code and created an example of how it would work. The data structure I chose for the bookmarks is a an object that has top level key of the quiz, [quizNumber], the value being another object with keys being each question. Which would then have a boolean flag which will indicate if bookmarked or not. To achieve this adding a field id for each question would be helpful

To avoid storing lots of data I omitted the actual question from the data structure as it can then be looked up with the quizNumber and question ID.

So I took the liberty of updating the questions to match this style

  {
        qID: 1,
        text: "What is the capital of United States?",
        correctAnswer: "Washington, D.C.",
        incorrectAnswers: ["Philadelphia", "Annapolis", "New York City"]
      }

So an example of what the structure of the bookmarkedQuestions object could be is,

{
 '0':{1:true},
 '2':{1:false, 2:true , 3:true}
}

This example would mean quiz 0 question 1 has been bookmarked as well as quiz 2 question 2 and 3. If the key does not exist or is false it can be assumed that the question has not been bookmarked.

To set this a function at the quiz level would need to be created. The function I created is most likely way overcomplicated for what it needs to do but is as follows

  bookmarkQuestion = () => {
    const { currentQuiz, numOfQuestions, quizQuestionBookmarks } = this.state;
    const { questions } = quizzes[currentQuiz];
    const { qID } = questions[numOfQuestions];
    // Can be simplified by creating a function to update nested values, or by using lodash
    // The destructuring is required so other parts of the object are not modified when updated deeper keys
    this.setState({
      quizQuestionBookmarks: {
        ...quizQuestionBookmarks,
        [currentQuiz]: {
          ...quizQuestionBookmarks[currentQuiz],
          [qID]: quizQuestionBookmarks[currentQuiz]
            ? !quizQuestionBookmarks[currentQuiz][qID]
            : true
        }
      }
    });
  };

The idea is that this can now be used on the currentQuizQuestions to get the list of questions that are currently bookmarked.

  getBookmarkedQuestions = () => {
    const { currentQuiz, quizQuestionBookmarks } = this.state;
    const { questions } = quizzes[currentQuiz];
    const boorkmarkedQuestions = questions.filter(question =>
      quizQuestionBookmarks[currentQuiz]
        ? quizQuestionBookmarks[currentQuiz][question.qID]
        : false
    );
    return boorkmarkedQuestions;
  };

In my example I also pass the bookmarkedQuestions to the Results page as a prop to demonstrate how the data can be passed to it to be used.


问:
Provide SSH Access on AWS EC2 Instance with a private key
I have a AWS EC2 Instance running with a PEM file kept at a safe place.
Now I want to give sftp access to one of the user to a particular directory. For this they have given me the private key file of their system. Is it possible to somehow import that private key on AWS Instance?</p>

答:
Create public key and placed in ~/.ssh/authorized_keys file for anyone user need to access.
You should using sftp instead of scp for secure purpose. </p>


问:
Gluon Mobile project does not work with gradle 6
I'm have a Gluon mobile project with a build.gradle like this:

```<code>buildscript {
    repositories {
        jcenter()
        google()
        mavenCentral()
        maven {
            url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
        }
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:2.0.30'
        classpath 'com.google.gradle:osdetector-gradle-plugin:1.6.0'
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.2'
    }
}

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

apply plugin: 'application'
apply plugin: 'org.javafxports.jfxmobile'
apply plugin: 'com.google.osdetector'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'eclipse'

compileJava {
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
                '--add-modules', 'javafx.controls'
        ]
    }
}

run {
    doFirst {
        jvmArgs = [
                '--module-path', classpath.asPath,
                '--add-modules', 'javafx.controls'
        ]
    }
}

sourceCompatibility = 13
targetCompatibility = 13

ext.platform = osdetector.os == 'osx' ? 'mac' : osdetector.os == 'windows' ? 'win' : osdetector.os

dependencies {
    compile "org.openjfx:javafx-base:13:$platform"
    compile "org.openjfx:javafx-graphics:13:$platform"
    compile "org.openjfx:javafx-controls:13:$platform"
    compile "org.openjfx:javafx-fxml:13:$platform"

    compile "org.openjfx:javafx-graphics:13:win"
    compile "org.openjfx:javafx-graphics:13:mac"
    compile "org.openjfx:javafx-graphics:13:linux"

    compile 'com.gluonhq:charm:5.0.0-jdk9'
    compile 'org.reactfx:reactfx:2.0-M5'
    compileOnly 'org.projectlombok:lombok:1.18.6'

    compile project(':GameClientLogic')
}

jfxmobile {
    downConfig {
        version = '3.8.6'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        compileSdkVersion = 23
        minSdkVersion = 23
//      manifest = 'src/android/AndroidManifest.xml'
        packagingOptions {
            pickFirst 'META-INF/*'
            pickFirst 'META-INF/**'
            pickFirst 'META-INF/INDEX.LIST'
            pickFirst 'META-INF/LICENSE'
            pickFirst 'META-INF/LICENSE.txt'
            pickFirst 'META-INF/NOTICE'
            pickFirst 'META-INF/DEPENDENCIES'
            pickFirst 'META-INF/NOTICE.txt'
            pickFirst 'META-INF/services/javax.ws.rs.ext.Providers'
        }
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

mainClassName = 'com.my.clientGUI.Main'
jar {
    manifest {
        attributes 'Main-Class': 'com.my.clientGUI.Main'
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

wrapper {
    gradleVersion = '6.0.1'
}
</code>```

When I try to execute a gradle build I get the error:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'ClientGUI'.
> Could not create task ':debug'.
   > Unnecessarily replacing a task that does not exist is not supported.  Use create() or register() directly instead.  You attempted to replace a task named 'debug', but there is no existing task with that name.
</code>```

I did not replace debug anywhere. Where is the problem? I already tried to delete the .gradle folder, did not help. Using Eclipse 4.14.

I want gradle 6 so I can use JDK 13.

答:
The issue is that the plugin org.javafxports.jfxmobile is not compatible with Gradle 6. Downgrade Gradle version 5.

Since Gradle 5 do not support Java 13 you should also downgrade Java to Java 11.

Body:
I'm have a Gluon mobile project with a build.gradle like this:

buildscript {
    repositories {
        jcenter()
        google()
        mavenCentral()
        maven {
            url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
        }
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:2.0.30'
        classpath 'com.google.gradle:osdetector-gradle-plugin:1.6.0'
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.2'
    }
}

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

apply plugin: 'application'
apply plugin: 'org.javafxports.jfxmobile'
apply plugin: 'com.google.osdetector'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'eclipse'

compileJava {
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
                '--add-modules', 'javafx.controls'
        ]
    }
}

run {
    doFirst {
        jvmArgs = [
                '--module-path', classpath.asPath,
                '--add-modules', 'javafx.controls'
        ]
    }
}

sourceCompatibility = 13
targetCompatibility = 13

ext.platform = osdetector.os == 'osx' ? 'mac' : osdetector.os == 'windows' ? 'win' : osdetector.os

dependencies {
    compile "org.openjfx:javafx-base:13:$platform"
    compile "org.openjfx:javafx-graphics:13:$platform"
    compile "org.openjfx:javafx-controls:13:$platform"
    compile "org.openjfx:javafx-fxml:13:$platform"

    compile "org.openjfx:javafx-graphics:13:win"
    compile "org.openjfx:javafx-graphics:13:mac"
    compile "org.openjfx:javafx-graphics:13:linux"

    compile 'com.gluonhq:charm:5.0.0-jdk9'
    compile 'org.reactfx:reactfx:2.0-M5'
    compileOnly 'org.projectlombok:lombok:1.18.6'

    compile project(':GameClientLogic')
}

jfxmobile {
    downConfig {
        version = '3.8.6'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        compileSdkVersion = 23
        minSdkVersion = 23
//      manifest = 'src/android/AndroidManifest.xml'
        packagingOptions {
            pickFirst 'META-INF/*'
            pickFirst 'META-INF/**'
            pickFirst 'META-INF/INDEX.LIST'
            pickFirst 'META-INF/LICENSE'
            pickFirst 'META-INF/LICENSE.txt'
            pickFirst 'META-INF/NOTICE'
            pickFirst 'META-INF/DEPENDENCIES'
            pickFirst 'META-INF/NOTICE.txt'
            pickFirst 'META-INF/services/javax.ws.rs.ext.Providers'
        }
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

mainClassName = 'com.my.clientGUI.Main'
jar {
    manifest {
        attributes 'Main-Class': 'com.my.clientGUI.Main'
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

wrapper {
    gradleVersion = '6.0.1'
}

When I try to execute a gradle build I get the error:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'ClientGUI'.
> Could not create task ':debug'.
   > Unnecessarily replacing a task that does not exist is not supported.  Use create() or register() directly instead.  You attempted to replace a task named 'debug', but there is no existing task with that name.

I did not replace debug anywhere. Where is the problem? I already tried to delete the .gradle folder, did not help. Using Eclipse 4.14.

I want gradle 6 so I can use JDK 13.


问:
How to create an object based on filtering two arrays with a filter criteria from one array in Javascript/ES6?
Let's assume I have two arrays of the same length:

```<code>const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];
</code>```

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

```<code>const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}
</code>```

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

```<code>let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};
</code>```

How can I achieve this with a minimal number of code lines?

答:
Your code looks optimal, here is an another version to your solution:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

let arr_final={}
arr_one.map((itm,indx)=>{
  if(itm!==null){
    arr_final[arr_two[indx]]=itm
  }
})
    console.log(arr_final)```

Body:
Let's assume I have two arrays of the same length:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};

How can I achieve this with a minimal number of code lines?


问:
Is there another way pushing data to array in js
here is my code pushing data to an array variable, but I am getting a blank array. what am I doing wrong?

```<code>let users = []

//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
  users.push(response[i].user_name)
}
</code>```

when I run console.log this is what I got

```<code>console.log(users) // Array[]
</code>```

答:
You can use the map function also of Javascript Array like below but before that you need to make sure that response has data in array type.

First we are checking response is not undefined and after that we are looping from response if response has data.

```<code>//looping ajax response here
let users = response && response.map(x => {
  return x.user_name;
});
</code>```

Body:
here is my code pushing data to an array variable, but I am getting a blank array. what am I doing wrong?

let users = []

//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
  users.push(response[i].user_name)
}

when I run console.log this is what I got

console.log(users) // Array[]

Body:
You can use the map function also of Javascript Array like below but before that you need to make sure that response has data in array type.

First we are checking response is not undefined and after that we are looping from response if response has data.

//looping ajax response here
let users = response && response.map(x => {
  return x.user_name;
});


答:
Bit shifts are basically multiplications and divisions by 2. The above condition is equivalent to

```<code>if ((out[currentState] >> j) & 1)
</code>```

which can be converted to

```<code>if ((int)(out[currentState] / pow(2, j)) % 2)
</code>```

Title: Converting bitwise if condition to usual if condition

Body:
Bit shifts are basically multiplications and divisions by 2. The above condition is equivalent to

if ((out[currentState] >> j) & 1)

which can be converted to

if ((int)(out[currentState] / pow(2, j)) % 2)


问:
Is there anyway not to use optional for conditional assignment?
I find myself in this situation a lot

```<code>func method() -> expensiveObj {
var x: expensiveObj?    //this has to be optional or compiler complains not initialized

    if someCondition {
      x = expensiveObj()
    } else P {
      x = expensiveObj()
    }

    return x // <---this is not allowed, need to unwrap with !
}
</code>```

my function doesnt want to return optional. And I dont like using ! all the time, overriding the compiler. And also I know there x is not optional to begin with. It's either one value or another, never nil.

How do I overcome this?

答:
Actually, that's not true. This is legal, and (little-known fact) you can even use let instead of var:

```<code>func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else {
        x = "2"
    }
    return x
}
</code>```

The trick is that you must cover all possibilities in your if/else series. In other words, there must be no circumstances under which x goes uninitialized. If there are such circumstances, the compiler rightly stops you.

For example, this will not compile:

```<code>func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else if anotherCondition {
        x = "2"
    }
    return x // error
}
</code>```

And rightly so, because what if neither condition is true? You need a catch-all:

```<code>func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else if anotherCondition {
        x = "2"
    } else {
        x = "3"
    }
    return x
}
</code>```

Body:
I find myself in this situation a lot

func method() -> expensiveObj {
var x: expensiveObj?    //this has to be optional or compiler complains not initialized

    if someCondition {
      x = expensiveObj()
    } else P {
      x = expensiveObj()
    }

    return x // <---this is not allowed, need to unwrap with !
}

my function doesnt want to return optional. And I dont like using ! all the time, overriding the compiler. And also I know there x is not optional to begin with. It's either one value or another, never nil.

How do I overcome this?

Body:
Actually, that's not true. This is legal, and (little-known fact) you can even use let instead of var:

func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else {
        x = "2"
    }
    return x
}

The trick is that you must cover all possibilities in your if/else series. In other words, there must be no circumstances under which x goes uninitialized. If there are such circumstances, the compiler rightly stops you.

For example, this will not compile:

func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else if anotherCondition {
        x = "2"
    }
    return x // error
}

And rightly so, because what if neither condition is true? You need a catch-all:

func method() -> String {
    let x:String
    if someCondition {
        x = "1"
    } else if anotherCondition {
        x = "2"
    } else {
        x = "3"
    }
    return x
}


问:
Change VSCode Default Language for new files?
Is there a way in Visual Studio Code to change the default language that is used for new files?

By default if you open a new file, it's set for "Plain Text", I want this to be "HTML" instead.

I am often copy pasting HTML into VSC, editing a bit, then copying it back to a CMS I am using (the CMS editor is horrible). I don't want to save the code on my computer at all, just edit it a bit with HTML syntax highlighting, but I want that to be the default.

答:
With v1.42 you can either set

```<code>"files.defaultLanguage": "${activeEditorLanguage}"
</code>```

and when you open a new untitled file with an html file as the last active file, the new file will automatically be assigned a languageMode of HTML.

Alternatively, pasting any html code into a new untitled file from a vscode editor will automatically be detected and the languageMode set to HTML.  Unless you have specifically set

```<code>"files.defaultLanguage": "plaintext"
</code>```

then the languageMode will not be automatically detected as of v1.43.

Also see https://stackoverflow.com/a/68596936/836330 for a preview language detection feature in vscode 1.59.

Body:
With v1.42 you can either set

"files.defaultLanguage": "${activeEditorLanguage}"

and when you open a new untitled file with an html file as the last active file, the new file will automatically be assigned a languageMode of HTML.

Alternatively, pasting any html code into a new untitled file from a vscode editor will automatically be detected and the languageMode set to HTML.  Unless you have specifically set

"files.defaultLanguage": "plaintext"

then the languageMode will not be automatically detected as of v1.43.

Also see https://stackoverflow.com/a/68596936/836330 for a preview language detection feature in vscode 1.59.


问:
Pandas rolling, resample and apply function
I am looking for a way to create on a daily timeindexed dataframe, a rolling window over last two years, resample it every 5th Day and then run functions on the resampled dataframe.

FYI,In this case I want to run regression y~X (as per the dataframe below).

So the output will be a timeindexed series with Beta values for each day(ignoring first 2 years)

Currently I am using a row based loop, but it is extremely slow

Feel there should be easier way to accomplish this.

Thanks in advance

```<code>date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

</code>```

Code I am currently using

```<code>
def rolling_stats(X,y,years_window=2):

    idx=X.index

    assert len(X)==len(y)

    x_idx=np.isnan(X).argmin()

    y_idx=np.isnan(y).argmin()

    out_dates = []
    out_beta = []
    out_rsq = []
    out_stderr = []

    df=pd.DataFrame(np.nan,columns=['Beta','RSQ','StdErr'],index=idx)

    for date in idx:

        start_date=date-DateOffset(years=years_window)

        date_range=pd.bdate_range(start_date,date,freq='5D')

        try:

            X_reg=X.loc[X.index.isin(date_range)]
            y_reg=y.loc[y.index.isin(date_range)]

            assert len(X_reg)==len(y_reg)

            X_c=sm.add_constant(X_reg)

            model=sm.OLS(y_reg,X_c)

            result=model.fit()

            df.loc[date,'RSQ']=result.rsquared
            df.loc[date,'Beta']=result.params[1]
            df.loc[date,'StdErr']=np.sqrt(result.mse_resid)

        except Exception:

            df.loc[date,'RSQ']=np.nan
            df.loc[date,'Beta']=np.nan
            df.loc[date,'StdErr']=np.nan

    return df

</code>```

答:
Doing a rolling.apply with several columns (here X, y) as input and returning 3 outputs is not possible with the implemented methods. The best way is to use the rolling method from piRSquared.

```<code>from numpy.lib.stride_tricks import as_strided as stride
import pandas as pd

def roll(df, w, **kwargs):
    v = df.values
    d0, d1 = v.shape
    s0, s1 = v.strides

    a = stride(v, (d0 - (w - 1), w, d1), (s0, s0, s1))

    rolled_df = pd.concat({
        row: pd.DataFrame(values, columns=df.columns)
        for row, values in zip(df.index[w-1:], a) #small difference to get the right date later
    })

    return rolled_df.groupby(level=0, **kwargs)
</code>```

Then define the function to apply per view to get the result from OLS. So here it is how to do:

```<code>def result_tup (df_roll):
    result = sm.OLS( df_roll['y'],
                     df_roll[['one','X']]).fit()
    return ( df_roll.index.get_level_values(0)[-1], result.rsquared,
             result.params[1], result.mse_resid)
</code>```

Now what you want is to apply this function over groups with 5days intervals, so you can do:

```<code># input and fix a seed for random
date_range=pd.date_range('2015-01-01','2019-12-31')
np.random.seed(1)
df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

#the two parameters and add the column with a 1 instead of doing it each time with sm.add_constant
years_windows = 2
day_freq = 5
df['one'] = 1

#calculate the length of the window
len_window = len(pd.date_range(pd.Timestamp.today().date() - pd.DateOffset(years=2),
                               pd.Timestamp.today().date(), freq=f'{day_freq}D'))

# groupby every day_freq rows and do the calculation:
df_res = pd.concat([ pd.DataFrame( roll(dfg, len_window).apply(result_tup).tolist(),
                                   columns=['date', 'RSQ', 'Beta','StdErr'])
                 for _, dfg in df.groupby(np.arange(len(df))%day_freq)])\
           .set_index('date').sort_index()
#and apply the np.sqrt on the column:
df_res['StdErr'] = np.sqrt(df_res['StdErr'])
</code>```

and you get way faster:

```<code>                 RSQ        Beta    StdErr
date
2016-12-31  0.000107    0.010800    0.300927
2017-01-01  0.001380    0.036603    0.291804
2017-01-02  0.000870    -0.030364   0.294584
2017-01-03  0.003308    0.056052    0.280171
2017-01-04  0.005622    -0.081809   0.303257
... ... ... ...
2019-12-27  0.000147    0.012609    0.287182
2019-12-28  0.001144    -0.031921   0.268274
2019-12-29  0.000120    0.010720    0.289787
2019-12-30  0.000280    0.014995    0.278135
2019-12-31  0.018433    0.137605    0.293537
</code>```

Body:
I am looking for a way to create on a daily timeindexed dataframe, a rolling window over last two years, resample it every 5th Day and then run functions on the resampled dataframe.

FYI,In this case I want to run regression y~X (as per the dataframe below).

So the output will be a timeindexed series with Beta values for each day(ignoring first 2 years)

Currently I am using a row based loop, but it is extremely slow

Feel there should be easier way to accomplish this.

Thanks in advance

date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

Code I am currently using

def rolling_stats(X,y,years_window=2):

    idx=X.index

    assert len(X)==len(y)

    x_idx=np.isnan(X).argmin()

    y_idx=np.isnan(y).argmin()

    out_dates = []
    out_beta = []
    out_rsq = []
    out_stderr = []

    df=pd.DataFrame(np.nan,columns=['Beta','RSQ','StdErr'],index=idx)

    for date in idx:

        start_date=date-DateOffset(years=years_window)

        date_range=pd.bdate_range(start_date,date,freq='5D')

        try:

            X_reg=X.loc[X.index.isin(date_range)]
            y_reg=y.loc[y.index.isin(date_range)]

            assert len(X_reg)==len(y_reg)

            X_c=sm.add_constant(X_reg)

            model=sm.OLS(y_reg,X_c)

            result=model.fit()

            df.loc[date,'RSQ']=result.rsquared
            df.loc[date,'Beta']=result.params[1]
            df.loc[date,'StdErr']=np.sqrt(result.mse_resid)

        except Exception:

            df.loc[date,'RSQ']=np.nan
            df.loc[date,'Beta']=np.nan
            df.loc[date,'StdErr']=np.nan

    return df

Body:
Doing a rolling.apply with several columns (here X, y) as input and returning 3 outputs is not possible with the implemented methods. The best way is to use the rolling method from piRSquared.

from numpy.lib.stride_tricks import as_strided as stride
import pandas as pd

def roll(df, w, **kwargs):
    v = df.values
    d0, d1 = v.shape
    s0, s1 = v.strides

    a = stride(v, (d0 - (w - 1), w, d1), (s0, s0, s1))

    rolled_df = pd.concat({
        row: pd.DataFrame(values, columns=df.columns)
        for row, values in zip(df.index[w-1:], a) #small difference to get the right date later
    })

    return rolled_df.groupby(level=0, **kwargs)

Then define the function to apply per view to get the result from OLS. So here it is how to do:

def result_tup (df_roll):
    result = sm.OLS( df_roll['y'],
                     df_roll[['one','X']]).fit()
    return ( df_roll.index.get_level_values(0)[-1], result.rsquared,
             result.params[1], result.mse_resid)

Now what you want is to apply this function over groups with 5days intervals, so you can do:

# input and fix a seed for random
date_range=pd.date_range('2015-01-01','2019-12-31')
np.random.seed(1)
df=pd.DataFrame(np.random.rand(len(date_range),2),index=date_range,columns=['X','y'])

#the two parameters and add the column with a 1 instead of doing it each time with sm.add_constant
years_windows = 2
day_freq = 5
df['one'] = 1

#calculate the length of the window
len_window = len(pd.date_range(pd.Timestamp.today().date() - pd.DateOffset(years=2),
                               pd.Timestamp.today().date(), freq=f'{day_freq}D'))

# groupby every day_freq rows and do the calculation:
df_res = pd.concat([ pd.DataFrame( roll(dfg, len_window).apply(result_tup).tolist(),
                                   columns=['date', 'RSQ', 'Beta','StdErr'])
                 for _, dfg in df.groupby(np.arange(len(df))%day_freq)])\
           .set_index('date').sort_index()
#and apply the np.sqrt on the column:
df_res['StdErr'] = np.sqrt(df_res['StdErr'])

and you get way faster:

                 RSQ        Beta    StdErr
date
2016-12-31  0.000107    0.010800    0.300927
2017-01-01  0.001380    0.036603    0.291804
2017-01-02  0.000870    -0.030364   0.294584
2017-01-03  0.003308    0.056052    0.280171
2017-01-04  0.005622    -0.081809   0.303257
... ... ... ...
2019-12-27  0.000147    0.012609    0.287182
2019-12-28  0.001144    -0.031921   0.268274
2019-12-29  0.000120    0.010720    0.289787
2019-12-30  0.000280    0.014995    0.278135
2019-12-31  0.018433    0.137605    0.293537