问:
Node.js response headers are not set
I'm trying to set Nodejs headers to the returned packet, but when logging the response it's always empty.

Here is my middleware in node.js server. It's supposed to add "From" header to the response, but it doesn't appear in the client logging the response.

EDIT:

In addition to changing res.set() to res.setHeaders() I had to access them at the client side using response.headers() instead of response.headers

```<code>app.use(function(reg, res, next){
        var checkAdmin = false;
        var bearerToken;
        var bearerHeader = reg.headers.authorization;
        if(admin.indexOf(reg.url) > -1){
                console.log("varmistetaan onko admin");
                checkAdmin = true;
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else if(public.indexOf(reg.url) < 0){
                console.log("varmistetaan onko suojattu");
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else {
                bearerToken = decodeToken(bearerHeader);
                if(bearerToken !== false){
                        decoded = verifyToken(bearerToken);
                        if(decoded !== false){
                                if (checkIfExpired(decoded.expires)){
                                        res.setHeader('From','test@test.com');
                                        next();
                                }else{
                                        res.set('From','test@test.com');
                                        next();
                                }
                        }else{
                                res.set('From','test@test.com');
                                next();
                        }
                }else{
                        res.set('From','test@test.com');
                        next();
                }
        }
});
</code>```

Here is my angularjs interceptor, which is logging the response at the moment:

```<code>.factory('authInterceptorService', ['$q', '$window', '$localStorage', function($q, $window, $localStorage){
        return {
                'request': function (config){
                        config.headers = config.headers || {};
                        if ($localStorage.accessToken) {
                                config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                        }
                        return config;
                },
                'response' : function(response){
                        console.log(response);
                        return response
                },
                'responseError': function(responseError){
                        responseError = JSON.parse(responseError.data);
                        if(responseError.tokenstatus === "expired"){
                                delete $localStorage.accessToken
                                window.location = "/";
                        }
                        if(response.status === 401 || response.status === 403) {
                                window.location = "/";
                        }
                        window.location = "/";
                        return $q.reject(response);
                }
        };
}])
</code>```

This is what the response looks like:

```<code>{…}
config: {…}
cache: Object { put: put(), get: get(), remove: remove(), … }
headers: Object { Accept: "application/json, text/plain, */*", Authorization: "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcml2aWxlZ2VzIjp7ImFkbWluIjp0cnVlLCJhc3Vubm90IjpmYWxzZSwib3Bpbm5vdCI6ZmFsc2V9LCJvcHRpZXRvbWVtYmVyIjpmYWxzZSwiYXN1bm5vdG1lbWJlciI6ZmFsc2UsImV4cGlyZXMiOjE1MTYwNDA3MjksImlhdCI6MTUxNjAwNDcyOX0.hU8yT3G58ZtkJbBo-SUwLmcSMSX_8cHYxnX0GdmfJVM" }
jsonpCallbackParam: "callback"
method: "GET"
paramSerializer: function Ef/this.$get/<()
transformRequest: Array [ Df/this.defaults.transformRequest<() ]
transformResponse: Array []
url: "koti.html"
__proto__: Object { … }
data: "<h1>Tähän tulee kotisivun sisältö</h1>\n"
headers: wd/<() #Response headers should be here?
length: 1
name: ""
__proto__: function ()
status: 200
statusText: "OK"
__proto__: Object { … }
</code>```

答:
I realize that the original question indicated the use of AngularJS, and while the responses for that are probably helpful, they DO NOT seem to apply to later versions of Angular (i.e. version 2+).

I was using NodeJS/express middlewares to host a secure form of json-server, and I was trying to dump the contents of the headers collection to the console to see that they all came across correctly.  This is where I was going wrong, and here's why:

The headers property of the response object is not a method, but an object, and the headers are processed in a lazy-loaded manner.  This means that dumping the contents to the console yielded an entirely empty collection, making me believe I had a bug.  In order to access the full collection, you first need to call rsp.headers.init().

Now, if you do not need to see the full collection, feel free to make calls for the specific values you need, through calls such as rsp.headers.get("_returnCode").  When you make such calls, the init() method is called for you prior to attempting to return the first value, and all should work fine.

Hope this helps!

Title: Node.js response headers are not set

Body:
I'm trying to set Nodejs headers to the returned packet, but when logging the response it's always empty.

Here is my middleware in node.js server. It's supposed to add "From" header to the response, but it doesn't appear in the client logging the response.

EDIT:

In addition to changing res.set() to res.setHeaders() I had to access them at the client side using response.headers() instead of response.headers

app.use(function(reg, res, next){
        var checkAdmin = false;
        var bearerToken;
        var bearerHeader = reg.headers.authorization;
        if(admin.indexOf(reg.url) > -1){
                console.log("varmistetaan onko admin");
                checkAdmin = true;
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else if(public.indexOf(reg.url) < 0){
                console.log("varmistetaan onko suojattu");
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else {
                bearerToken = decodeToken(bearerHeader);
                if(bearerToken !== false){
                        decoded = verifyToken(bearerToken);
                        if(decoded !== false){
                                if (checkIfExpired(decoded.expires)){
                                        res.setHeader('From','test@test.com');
                                        next();
                                }else{
                                        res.set('From','test@test.com');
                                        next();
                                }
                        }else{
                                res.set('From','test@test.com');
                                next();
                        }
                }else{
                        res.set('From','test@test.com');
                        next();
                }
        }
});

Here is my angularjs interceptor, which is logging the response at the moment:

.factory('authInterceptorService', ['$q', '$window', '$localStorage', function($q, $window, $localStorage){
        return {
                'request': function (config){
                        config.headers = config.headers || {};
                        if ($localStorage.accessToken) {
                                config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                        }
                        return config;
                },
                'response' : function(response){
                        console.log(response);
                        return response
                },
                'responseError': function(responseError){
                        responseError = JSON.parse(responseError.data);
                        if(responseError.tokenstatus === "expired"){
                                delete $localStorage.accessToken
                                window.location = "/";
                        }
                        if(response.status === 401 || response.status === 403) {
                                window.location = "/";
                        }
                        window.location = "/";
                        return $q.reject(response);
                }
        };
}])

This is what the response looks like:

{…}
config: {…}
cache: Object { put: put(), get: get(), remove: remove(), … }
headers: Object { Accept: "application/json, text/plain, */*", Authorization: "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcml2aWxlZ2VzIjp7ImFkbWluIjp0cnVlLCJhc3Vubm90IjpmYWxzZSwib3Bpbm5vdCI6ZmFsc2V9LCJvcHRpZXRvbWVtYmVyIjpmYWxzZSwiYXN1bm5vdG1lbWJlciI6ZmFsc2UsImV4cGlyZXMiOjE1MTYwNDA3MjksImlhdCI6MTUxNjAwNDcyOX0.hU8yT3G58ZtkJbBo-SUwLmcSMSX_8cHYxnX0GdmfJVM" }
jsonpCallbackParam: "callback"
method: "GET"
paramSerializer: function Ef/this.$get/<()
transformRequest: Array [ Df/this.defaults.transformRequest<() ]
transformResponse: Array []
url: "koti.html"
__proto__: Object { … }
data: "
Tähän tulee kotisivun sisältö
\n"
headers: wd/<() #Response headers should be here?
length: 1
name: ""
__proto__: function ()
status: 200
statusText: "OK"
__proto__: Object { … }


来源: stackexchange

问:
how to handle SQL failer from asterisk dial plan
Im using

Asterisk certified/16.8-cert2

MSSQL Express 2014

unixODBC 2.3.1

freetds v1.1.20

Lua 5.1.4

CentOS7

I doing update statement in SQL with  func_odbc.so. The update statement is working fine with no issue. but I wanna away to be able to catch an error if it happens, like a disconnect or network interruption.

Here is my update statement

```<code>  UPDATE Customers SET AccountBalance = AccountBalance - ${VAL1} WHERE cif = ${ARG1}
</code>```

My dialPlan function call ( in extention.lua)

local  statues = channel.ODBC_ErrorTest(1499):set(10)

One of the thing that I  though I can make it work, is by adding TRY and CATCH blook in the SQL statement itself like below, so if there is an error it will return the error number

```<code>BEGIN TRY
  UPDATE Customers SET AccountBalance = AccountBalance - a WHERE cif = 17399
END TRY
BEGIN CATCH
 SELECT   ERROR_NUMBER() AS ErrorNumber
END CATCH
</code>```

But when I try to execute this it does not  return me an error number when there is a failer, just return an empty string.

So my question is simple, how to handle SQL failer from the dial plan?

答:
For update it should return -1 in case of writesql error.

However you should understand, asterisk is PBX, not something suitable for complex sql check.

Possible workarounds

1) create other table with command, create external script which check it for new "actions" and send back results/error. Check in asterisk after 0.5sec, 1sec etc.

2) create simple rest API and use func_CURL.

ContentLicense: CC BY-SA 4.0

Body:
Im using

Asterisk certified/16.8-cert2

MSSQL Express 2014

unixODBC 2.3.1

freetds v1.1.20

Lua 5.1.4

CentOS7

I doing update statement in SQL with  func_odbc.so. The update statement is working fine with no issue. but I wanna away to be able to catch an error if it happens, like a disconnect or network interruption.

Here is my update statement

  UPDATE Customers SET AccountBalance = AccountBalance - ${VAL1} WHERE cif = ${ARG1}

My dialPlan function call ( in extention.lua)

local  statues = channel.ODBC_ErrorTest(1499):set(10)

One of the thing that I  though I can make it work, is by adding TRY and CATCH blook in the SQL statement itself like below, so if there is an error it will return the error number

BEGIN TRY
  UPDATE Customers SET AccountBalance = AccountBalance - a WHERE cif = 17399
END TRY
BEGIN CATCH
 SELECT   ERROR_NUMBER() AS ErrorNumber
END CATCH

But when I try to execute this it does not  return me an error number when there is a failer, just return an empty string.

So my question is simple, how to handle SQL failer from the dial plan?


问:
Increase TCP disconnection time
I know TCP won't break an established TCP connection during a period of time. But is it possible to increase this time?

I am developing a client-server application used to stream continuous data from one server to the client application using C#. I want to keep collecting data if the cable connection reconnected within one minute.

答:
There are three timeouts that you can use in the tcp client:https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netcore-3.1#properties

Connect timeout. The time it takes to establish the connection

Receive timeout. The timeout on the receiving side once the reading is initiated: https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.receivetimeout?view=netcore-3.1#System_Net_Sockets_TcpClient_ReceiveTimeout

Send timeout. The timeout on the sender side once the sending is initiated: https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.sendtimeout?view=netcore-3.1#System_Net_Sockets_TcpClient_SendTimeout

Those are the out of the box settings you can use. If you didn't mean one of these, please clarify in your question.

Title: Increase TCP disconnection time


问:
pl/sql function to find those customers who are eligible for LOAN and the amount of loan
Note:
the question has 2 table: customer(id,name,dept,designation,salary) and account(id,ACCOUNT_NUMBER,FIXED
DEPOSIT) .
i wrote the pl/sql function for that:

```<code>CREATE OR REPLACE FUNCTION loan_func (sal IN NUMBER,fd in NUMBER)
RETURN NUMBER
IS
loan NUMBER(6);
BEGIN
IF (sal>60000 AND fd>100000) THEN
loan := (sal*0.4)+100000;
ELSIF (sal>50000 AND sal<59999 AND fd>50000) THEN
loan := (sal*0.3)+90000;
END IF;
RETURN loan;
END;
</code>```

the function  in entered correctly but the cursor doesnot work! can you help me fix the problem to get the ans?

below is the cursor:

```<code>DECLARE
CURSOR CR IS
SELECT
    C_ID,
    A_ID,
    NAME,
    FIXED_DEPOSIT,
    SALARY
FROM
    CUSTOMER
join ACCOUNT
on     C_ID = A_ID;
I CUSTOMER.C_ID%TYPE;
N CUSTOMER.NAME%TYPE;
fd ACCOUNT.FIXED_DEPOSIT%TYPE;
sal CUSTOMER.SALARY%TYPE;
Loan NUMBER(6);
BEGIN
OPEN CR;
LOOP
EXIT WHEN CR%NOTFOUND;
FETCH CR INTO I,N,fd,sal;
DBMS_OUTPUT.PUTLINE(I || N);
Loan:=loan_func(sal,fd);
DBMS_OUTPUT.PUTLINE(loan);
END LOOP;
END;
</code>```

it shows the following error:

ORA-06550: line 22, column 2:
PLS-00394: wrong number of values in the INTO list of a FETCH statement

答:
Your original query was correct. That used the ANSI JOIN syntax, the preferred syntax. The correction reverted to the an obsolete (since 1992 SQL standard), yet still supported syntax. The ON clause provides the same function as the missing statement.

Your error is not necessary in the cursor but in the fetch. The cursor contains 5 columns, however the fetch only get 4 variables. Either c_id is not needed in the cursor OR you need to add it to the fetch. Even better would be switch to a cursor for loop where Oracle takes care the cursor handling.

```<code>declare
   loan number(6);
begin
   for cr in
       ( select a_id, name,fixed_deposit fd, salary sal
           from customer c
           join account  a
             on c_id = a_id
       )
   loop
      dbms_output.put ('id ='|| cr.a_id || 'name = ' ||cr.name n );
      loan:=loan_func(cr.sal,cr.fd);
      dbms_output.putline(' loan amount is =' || loan);
   end loop
end;
</code>```

I also corrected dbms_output statements.

Body:
Note:
the question has 2 table: customer(id,name,dept,designation,salary) and account(id,ACCOUNT_NUMBER,FIXED
DEPOSIT) .
i wrote the pl/sql function for that:

CREATE OR REPLACE FUNCTION loan_func (sal IN NUMBER,fd in NUMBER)
RETURN NUMBER
IS
loan NUMBER(6);
BEGIN
IF (sal>60000 AND fd>100000) THEN
loan := (sal*0.4)+100000;
ELSIF (sal>50000 AND sal<59999 AND fd>50000) THEN
loan := (sal*0.3)+90000;
END IF;
RETURN loan;
END;

the function  in entered correctly but the cursor doesnot work! can you help me fix the problem to get the ans?

below is the cursor:

DECLARE
CURSOR CR IS
SELECT
    C_ID,
    A_ID,
    NAME,
    FIXED_DEPOSIT,
    SALARY
FROM
    CUSTOMER
join ACCOUNT
on     C_ID = A_ID;
I CUSTOMER.C_ID%TYPE;
N CUSTOMER.NAME%TYPE;
fd ACCOUNT.FIXED_DEPOSIT%TYPE;
sal CUSTOMER.SALARY%TYPE;
Loan NUMBER(6);
BEGIN
OPEN CR;
LOOP
EXIT WHEN CR%NOTFOUND;
FETCH CR INTO I,N,fd,sal;
DBMS_OUTPUT.PUTLINE(I || N);
Loan:=loan_func(sal,fd);
DBMS_OUTPUT.PUTLINE(loan);
END LOOP;
END;

it shows the following error:

ORA-06550: line 22, column 2:
PLS-00394: wrong number of values in the INTO list of a FETCH statement

Body:
Your original query was correct. That used the ANSI JOIN syntax, the preferred syntax. The correction reverted to the an obsolete (since 1992 SQL standard), yet still supported syntax. The ON clause provides the same function as the missing statement.

Your error is not necessary in the cursor but in the fetch. The cursor contains 5 columns, however the fetch only get 4 variables. Either c_id is not needed in the cursor OR you need to add it to the fetch. Even better would be switch to a cursor for loop where Oracle takes care the cursor handling.

declare
   loan number(6);
begin
   for cr in
       ( select a_id, name,fixed_deposit fd, salary sal
           from customer c
           join account  a
             on c_id = a_id
       )
   loop
      dbms_output.put ('id ='|| cr.a_id || 'name = ' ||cr.name n );
      loan:=loan_func(cr.sal,cr.fd);
      dbms_output.putline(' loan amount is =' || loan);
   end loop
end;

I also corrected dbms_output statements.


问:
Yii::app()->user->isGuest always returns true even though login was successful
I started to make some differences between those users which have authenticated and those that not. For this, i am using

```<code>Yii::app()->user->id;
</code>```

However, in a determined view i put the following code:

```<code><?php
    if(Yii::app()->user->isGuest) {
        print("Welcome back Guest!");
        print("Your id is ".Yii::app()->user->id);
    } else {
        print("Welcome back ".Yii::app()->user->name);
        print("Your id is ".Yii::app()->user->id);
}?>
</code>```

And i always get the "welcome back guest!", whether i have logged in (successfully) or not. And if i have logged in, then it displays the welcome message together with the user's id!

EDIT

@briiC.lv
Hey.. sorry for the late reply, I hope you are still following this! I am not extending the given UserIdentity class. Is this mandatory? Since i still dont get very well the whole authorization issue, i thought it would be best to give a try with the class they provide, and then extend with my own functionality.. Anyway, next i post my UserIdentity class with its small tweaks.. maybe the problem lies here??

```<code><?php class UserIdentity extends CUserIdentity{
private $_id;

public function authenticate()
{
    $user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
    if(!isset($user[0]))
    {
        return false;
    }
    else
    {
        $this->setState('id', $user[0]->id);
        $this->username = $user[0]->username;
        $this->errorCode=self::ERROR_NONE;
        return true;
    }
}

public function getId()
{
    return $this->_id;
}
</code>```

}

Here is the output i got when i started to log as you suggested; i got this output immediately after successfully logging in.

```<code>[05:23:21.833][trace][vardump] CWebUser#1 (
[allowAutoLogin] => true
[guestName] => 'Guest'
[loginUrl] => array ( '0' => '/site/login' )
[identityCookie] => null
[authTimeout] => null
[autoRenewCookie] => false
[autoUpdateFlash] => true
[CWebUser:_keyPrefix] => '0f4431ceed8f17883650835e575b504b'
[CWebUser:_access] => array()
[behaviors] => array()
[CApplicationComponent:_initialized] => true
[CComponent:_e] => null
[CComponent:_m] => null
)
</code>```

Any help is much appreciated!

答:
Maybe you can try to debug harder:
change messages to something like this:

```<code>if(Yii::app()->user->isGuest) {
    print("Not logged");
} else {
    print_r(Yii::app()->user);
    print("Welcome ".Yii::app()->user->name);
    print("Your id is ".Yii::app()->user->id);

}
</code>```

And check session variable in your config/main.php file

```<code>...
    'session' => array(
        'autoStart'=>true,
    ),
...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I started to make some differences between those users which have authenticated and those that not. For this, i am using

Yii::app()->user->id;

However, in a determined view i put the following code:

<?php
    if(Yii::app()->user->isGuest) {
        print("Welcome back Guest!");
        print("Your id is ".Yii::app()->user->id);
    } else {
        print("Welcome back ".Yii::app()->user->name);
        print("Your id is ".Yii::app()->user->id);
}?>

And i always get the "welcome back guest!", whether i have logged in (successfully) or not. And if i have logged in, then it displays the welcome message together with the user's id!

EDIT

@briiC.lv
Hey.. sorry for the late reply, I hope you are still following this! I am not extending the given UserIdentity class. Is this mandatory? Since i still dont get very well the whole authorization issue, i thought it would be best to give a try with the class they provide, and then extend with my own functionality.. Anyway, next i post my UserIdentity class with its small tweaks.. maybe the problem lies here??

<?php class UserIdentity extends CUserIdentity{
private $_id;

public function authenticate()
{
    $user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
    if(!isset($user[0]))
    {
        return false;
    }
    else
    {
        $this->setState('id', $user[0]->id);
        $this->username = $user[0]->username;
        $this->errorCode=self::ERROR_NONE;
        return true;
    }
}

public function getId()
{
    return $this->_id;
}

}

Here is the output i got when i started to log as you suggested; i got this output immediately after successfully logging in.

[05:23:21.833][trace][vardump] CWebUser#1 (
[allowAutoLogin] => true
[guestName] => 'Guest'
[loginUrl] => array ( '0' => '/site/login' )
[identityCookie] => null
[authTimeout] => null
[autoRenewCookie] => false
[autoUpdateFlash] => true
[CWebUser:_keyPrefix] => '0f4431ceed8f17883650835e575b504b'
[CWebUser:_access] => array()
[behaviors] => array()
[CApplicationComponent:_initialized] => true
[CComponent:_e] => null
[CComponent:_m] => null
)

Any help is much appreciated!

Body:
Maybe you can try to debug harder:
change messages to something like this:

if(Yii::app()->user->isGuest) {
    print("Not logged");
} else {
    print_r(Yii::app()->user);
    print("Welcome ".Yii::app()->user->name);
    print("Your id is ".Yii::app()->user->id);

}

And check session variable in your config/main.php file

...
    'session' => array(
        'autoStart'=>true,
    ),
...


问:
Show the Progress Percentage of an operation running inside a FOR-loop in Label.Text
I have the following C# Code:

```<code>for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }
</code>```

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.

答:
You can calculate one hundred percent and then just delete current iteration:

```<code>var oneHundred = Rows.Count - 1;
for (int i = 0; i < dgItems.Rows.Count - 1; i++)
{
     SqlCommand cmd = new SqlCommand(/*The code is omitted for the brevity*/);
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
     var currentPercent = ((100 * i) / oneHundred )
     progressBar1.Value = currentPercent ;
     LB_ProgText.Text = "Progress :%" + currentPercent;
     LB_ProgText.Invalidate();
     LB_ProgText.Update();
 }
</code>```

In addition, you need to use parameterized SQL to avoid SQL injections.

UPDATE:

As we have sign < in i < dgItems.Rows.Count - 1, then it means, that i never become equal to dgItems.Rows.Count - 1. So we can slightly modify our condition to:

```<code>i < dgItems.Rows.Count
</code>```

The whole code will looks like this:

```<code>var rowsCount = 8001;
var oneHundred = rowsCount - 1;
for (int i = 0; i < rowsCount; i++)
{
    var currentPercent = ((100 * i) / oneHundred);
    if (currentPercent > 97)
    {
        Console.WriteLine(currentPercent);
    }
}
</code>```

Body:
I have the following C# Code:

for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.

Body:
You can calculate one hundred percent and then just delete current iteration:

var oneHundred = Rows.Count - 1;
for (int i = 0; i < dgItems.Rows.Count - 1; i++)
{
     SqlCommand cmd = new SqlCommand(/*The code is omitted for the brevity*/);
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
     var currentPercent = ((100 * i) / oneHundred )
     progressBar1.Value = currentPercent ;
     LB_ProgText.Text = "Progress :%" + currentPercent;
     LB_ProgText.Invalidate();
     LB_ProgText.Update();
 }

In addition, you need to use parameterized SQL to avoid SQL injections.

UPDATE:

As we have sign < in i < dgItems.Rows.Count - 1, then it means, that i never become equal to dgItems.Rows.Count - 1. So we can slightly modify our condition to:

i < dgItems.Rows.Count

The whole code will looks like this:

var rowsCount = 8001;
var oneHundred = rowsCount - 1;
for (int i = 0; i < rowsCount; i++)
{
    var currentPercent = ((100 * i) / oneHundred);
    if (currentPercent > 97)
    {
        Console.WriteLine(currentPercent);
    }
}


问:
Tomcat v9.0 Server Starting Error In Eclipse
I'm trying to run my dynamic web project , but the server won't to start and the only message i get is this "Server Tomcat v9.0 Server at localhost failed to start".
Note : the server was working normally before that. </p>

答:
NOTE : before you try to do anything try to run your servlet(or jsp) and check if there is no exception.

i found the answer here : ""Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal"

first if the server was working normally before that and you're sure that you don't touch anything on the server settings or something like that ,don't try to delete the server or .snap file or .tmp file or playing with setting, the problem may be on the web.xml file.

so i found two solutions :

the first one is you have to delete the servlet mapping on your web.xml file

file before editing :

```<code>...

<display-name>something<display-name>
<servlet>
<servlet-name>Welcome<servlet-name>
<servlet-class>DemoServlet<servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Welcome <servlet-name>
<url-pattern>/welcome</url-pattern>

<welcome-file-list>
...
</welcome-file-list>
...
</code>```

after :

```<code> <display-name>something<display-name>

<welcome-file-list>
...
</welcome-file-list>
...

</code>```

or the best thing is your just need to add <element> tag just below <?xml version="1.0" encoding="UTF-8"?> (and don't forget to close the tag by </element>).
so your xml file will be like that :

```<code>...
<?xml version="1.0" encoding="UTF-8"?>
<element>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 <display-name>something<display-name>
<servlet>
<servlet-name>Welcome<servlet-name>
<servlet-class>DemoServlet<servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Welcome <servlet-name>
<url-pattern>/welcome</url-pattern>

<welcome-file-list>
...
</welcome-file-list>
</web-app>
</element>
</code>```

Body:
NOTE : before you try to do anything try to run your servlet(or jsp) and check if there is no exception.

i found the answer here : ""Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal"

first if the server was working normally before that and you're sure that you don't touch anything on the server settings or something like that ,don't try to delete the server or .snap file or .tmp file or playing with setting, the problem may be on the web.xml file.

so i found two solutions :

the first one is you have to delete the servlet mapping on your web.xml file

file before editing :

...

<display-name>something<display-name>
<servlet>
<servlet-name>Welcome<servlet-name>
<servlet-class>DemoServlet<servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Welcome <servlet-name>
<url-pattern>/welcome</url-pattern>

<welcome-file-list>
...
</welcome-file-list>
...

after :

 <display-name>something<display-name>

<welcome-file-list>
...
</welcome-file-list>
...

or the best thing is your just need to add <element> tag just below <?xml version="1.0" encoding="UTF-8"?> (and don't forget to close the tag by </element>).
so your xml file will be like that :

...
<?xml version="1.0" encoding="UTF-8"?>
<element>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 <display-name>something<display-name>
<servlet>
<servlet-name>Welcome<servlet-name>
<servlet-class>DemoServlet<servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Welcome <servlet-name>
<url-pattern>/welcome</url-pattern>

<welcome-file-list>
...
</welcome-file-list>
</web-app>
</element>


问:
Is it possible to filter for multiple strings in AG-Grid?
I have been using

```<code>myTable.api.setQuickFilter(string1);
</code>```

with great success for a while, but I would like to be able to filter for string1, string2, or string3 at the same time and see all the results at once. Is this possible? I cannot find anything on the ag-grid docs.

答:
Since the custom filter example here focuses on individual column, using External filter seems to be the ideal solution.

You need to implement 2 methods - on gridOptions: isExternalFilterPresent() and doesExternalFilterPass(node).

```<code>  isExternalFilterPresent() {
    return true; // to indicate external filtering is on
  }

  doesExternalFilterPass(node) {

// filter only if searchtext is there
   if (this.searchText) {
        return Object.values(node.data).includes(this.searchText.split(' ')[0]) // 'string1'
         || Object.values(node.data).includes(this.searchText.split(' ')[1]) // 'string2'
         || Object.values(node.data).includes(this.searchText.split(' ')[2]); // 'string3'
    }
   return true;
}

// assuming this is bound to your input field
  externalFilterChanged(newValue) {
    this.searchText = newValue;
    this.gridApi.onFilterChanged(); // letting the grid know filter has changed
  }
</code>```

From docs -

isExternalFilterPresent

  is called exactly once every time the grid senses a filter change. It should return true if external filtering is active or false otherwise. If you return true,
  doesExternalFilterPass() will be called while filtering, otherwise doesExternalFilterPass() will not be called.

doesExternalFilterPass

  is called once for each row node in the grid. If you return false, the node will be excluded from the final
  set.

If the external filter changes, you need to call api.onFilterChanged()
  to tell the grid.

Body:
I have been using

myTable.api.setQuickFilter(string1);

with great success for a while, but I would like to be able to filter for string1, string2, or string3 at the same time and see all the results at once. Is this possible? I cannot find anything on the ag-grid docs.

Body:
Since the custom filter example here focuses on individual column, using External filter seems to be the ideal solution.

You need to implement 2 methods - on gridOptions: isExternalFilterPresent() and doesExternalFilterPass(node).

  isExternalFilterPresent() {
    return true; // to indicate external filtering is on
  }

  doesExternalFilterPass(node) {

// filter only if searchtext is there
   if (this.searchText) {
        return Object.values(node.data).includes(this.searchText.split(' ')[0]) // 'string1'
         || Object.values(node.data).includes(this.searchText.split(' ')[1]) // 'string2'
         || Object.values(node.data).includes(this.searchText.split(' ')[2]); // 'string3'
    }
   return true;
}

// assuming this is bound to your input field
  externalFilterChanged(newValue) {
    this.searchText = newValue;
    this.gridApi.onFilterChanged(); // letting the grid know filter has changed
  }

From docs -

isExternalFilterPresent

  is called exactly once every time the grid senses a filter change. It should return true if external filtering is active or false otherwise. If you return true,
  doesExternalFilterPass() will be called while filtering, otherwise doesExternalFilterPass() will not be called.

doesExternalFilterPass

  is called once for each row node in the grid. If you return false, the node will be excluded from the final
  set.

If the external filter changes, you need to call api.onFilterChanged()
  to tell the grid.


问:
How to remove box from new Google Maps embeds?
Google appear to have changed how their iFrames work. There is now an infobox at the top left that tries to display the place name. The problem is that here in Ireland it's often impossible to use the name of the business to pinpoint a map, and often you need to use the street name etc etc, which makes the box functionaly useless as the name of the street is right there on the map, as well as on the page beside the map!

How can I get rid of this thing? In this example the business is in the same building as Irish Coaches. Maps insists that by putting in the address, this solicitor for some reason want's to inform its prospective clients of where Irish Coaches is!

I've tried iwloc but it does nothing, and I can't effect it via CSS and jQuery because it's on another domain!

Any ideas?

答:
Update_2020:

1.find your location in google map

2.right click on your target and select What's here?

3.down the screen you can see a coordinate like this: 29.586525, 52.546173

4.now paste the coordinate into the search box

5.click on share button and choose Embed a map and copy the iframe tag


问:
Duplicate data when working with multiple tables. Clarification needed
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

```<code>DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'
</code>```

答:
these duplicate data are because of records that are (AAPL,Annual) but are not (Revenues).you should move the condition of statementitem in where cluse or in join condition:

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,isnull(a.value,0)  as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
</code>```

or

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,isnull(a.value,0) as revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
   and a.statementitem = 'Revenues' and a.periodtype = 'Annual'
</code>```

Body:
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'

Body:
these duplicate data are because of records that are (AAPL,Annual) but are not (Revenues).you should move the condition of statementitem in where cluse or in join condition:

SELECT distinct a.yearmonth, a.symbol, periodtype,isnull(a.value,0)  as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'

or

SELECT distinct a.yearmonth, a.symbol, periodtype,isnull(a.value,0) as revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
   and a.statementitem = 'Revenues' and a.periodtype = 'Annual'


问:
Blazor access to hardware
I currently use inject IJSRuntime along with navigator.geolocation, navigator.mediaDevices
But is it correct? Isn't it possible to access these functions without javascript using only C#?
What do you think about it ?
Thank you for your feedback.
Daniel Kminek

答:
I'm am researching this question right now, and the answer is No you have to use JSInterop.  And Yes it can be done through Interop.  For an example of GeoLocation, see Ed Charbeneau's ebook Blazor: A Beginners Guide and I've linked to the backing source code.  Also checkout AspNetMonsters/Blazor.Geolocation  I've used it for months and it is great.

Regarding MediaDevices: I've written some JS Interop/Blazor code and verified Blazor can see it, but not much further progress.  Can't find any examples, unlike Geolocation.

I can't really shed any light why you can't access the devices from C#.  Above my pay grade.  But I guess it could be API's not available from the Browser (which is really what has access to the hardware), or the underlying Blazor circuit.  If I make any headway, I'l update.

Title: Blazor access to hardware


问:
Window.matchMedia in JavaScript not functioning
I have an HTML, CSS and JavaScript files. The HTML contains three quotes which shuffles every two seconds. I have written the JavaScript code to show these quotes only when the screen width is at most 600px. The problem is that the quote continues to display across every screen width. I've tried using the media query in CSS, but to no avail. What might be the issue? Please, see code below.

HTML Code:

```<code><div class="preNavBar">
        <div class="quoteWrapper">
            <span class="quote">The roots of education are bitter, but the fruit is sweet.  </span>
            <span class="quoteAuthor">— Aristotle</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">To teach is to learn twice.  </span>
            <span class="quoteAuthor">— Unknown</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">A person who won't read has no advantage over one who can't read.  </span>
            <span class="quoteAuthor">— Mark Twain</span>
        </div>
    </div>
</code>```

CSS Code:

```<code>body {
    padding: 0 !important;
    margin: 0 !important;
    font-size: 16pxm;
    background: rgb(53, 54, 58);
}

* {
    box-sizing: border-box;
    /* margin: 0; */
    padding: 0;
}

/* PRE-NAVIGATION BAR */
.preNavBar {
    background-color: navy;
    color: white;
    padding: 10px 30px;
    display: grid;
    justify-content: center;
}

.preNavBar .quoteAuthor {
    font-weight: bolder;
    float: right;
}

@media only screen and (min-width: 768px) {
    /* .preNavBar .quoteWrapper{
        display: none;
    } */
}
</code>```

JavaScript Code:

```<code><script>
        let x = window.matchMedia("(max-width: 600px)");
        if (x.matches) {
            showQuote();
            function showQuote() {
                let slides = document.getElementsByClassName("quoteWrapper");
                let i;
                for (i = 0; i < slides.length; i++) {
                    slides[i].style.display = "none";
                }

                let min = 0;
                let max = slides.length - 1;
                let randNum = Math.floor(Math.random() * (max - min + 1)) + min;

                slides[randNum].style.display = "block";

                setTimeout(showQuote, 2000); // change every 2 seconds
            }
        }
    </script>
</code>```

答:
That's because you set the variable on start and never change it on resize

let timeout;
function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
        function showQuote() {
            let slides = document.getElementsByClassName("quoteWrapper");

            for (let i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
            }

            //the min was 0 so it was useless, if you do slides.length-1,
            //you wont be able to access the last index
            let randNum = Math.floor(Math.random() * slides.length);
            slides[randNum].style.display = "block";
            //set it so you can clear if user changes to > 600px
            timeout = setTimeout(showQuote, 2000); // change every 2 seconds
        }

        showQuote();
    } else if (timeout) {
        clearTimeout(timeout);
    }
}

testMatch();
addEventListener("resize", testMatch);
```

<p>Also this could be a lot more efficiently done by using an id to signify which quote is not hidden.</p>

<pre class="lang-js prettyprint-override"><code>(function () {
  const slides = document.getElementsByClassName("quoteWrapper");
  let timeout;

  function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
      function showQuote() {
        //the min was 0 so it was useless, if you do slides.length-1,
        //you wont be able to access the last index
        let randNum = Math.floor(Math.random() * slides.length);

        const prev = document.getElementById("current-quote");
        if (prev) prev.removeAttribute("id");
        slides[randNum].setAttribute("id", "current-quote");
        timeout = setTimeout(showQuote, 2000); // change every 2 seconds
      }

      showQuote();
    } else if (timeout) {
      clearTimeout(timeout);
    }
  }

  testMatch();
  addEventListener("resize", testMatch);
})();
</code>```

.quoteWrapper {
  display: none;
}

#current-quote {
  display: block;
}
```

Body:
I have an HTML, CSS and JavaScript files. The HTML contains three quotes which shuffles every two seconds. I have written the JavaScript code to show these quotes only when the screen width is at most 600px. The problem is that the quote continues to display across every screen width. I've tried using the media query in CSS, but to no avail. What might be the issue? Please, see code below.

HTML Code:

            The roots of education are bitter, but the fruit is sweet.
            — Aristotle

            To teach is to learn twice.
            — Unknown

            A person who won't read has no advantage over one who can't read.
            — Mark Twain

CSS Code:

body {
    padding: 0 !important;
    margin: 0 !important;
    font-size: 16pxm;
    background: rgb(53, 54, 58);
}

* {
    box-sizing: border-box;
    /* margin: 0; */
    padding: 0;
}

/* PRE-NAVIGATION BAR */
.preNavBar {
    background-color: navy;
    color: white;
    padding: 10px 30px;
    display: grid;
    justify-content: center;
}

.preNavBar .quoteAuthor {
    font-weight: bolder;
    float: right;
}

@media only screen and (min-width: 768px) {
    /* .preNavBar .quoteWrapper{
        display: none;
    } */
}

JavaScript Code:

Body:
That's because you set the variable on start and never change it on resize

let timeout;
function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
        function showQuote() {
            let slides = document.getElementsByClassName("quoteWrapper");

            for (let i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
            }

            //the min was 0 so it was useless, if you do slides.length-1,
            //you wont be able to access the last index
            let randNum = Math.floor(Math.random() * slides.length);
            slides[randNum].style.display = "block";
            //set it so you can clear if user changes to > 600px
            timeout = setTimeout(showQuote, 2000); // change every 2 seconds
        }

        showQuote();
    } else if (timeout) {
        clearTimeout(timeout);
    }
}

testMatch();
addEventListener("resize", testMatch);

Also this could be a lot more efficiently done by using an id to signify which quote is not hidden.

(function () {
  const slides = document.getElementsByClassName("quoteWrapper");
  let timeout;

  function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
      function showQuote() {
        //the min was 0 so it was useless, if you do slides.length-1,
        //you wont be able to access the last index
        let randNum = Math.floor(Math.random() * slides.length);

        const prev = document.getElementById("current-quote");
        if (prev) prev.removeAttribute("id");
        slides[randNum].setAttribute("id", "current-quote");
        timeout = setTimeout(showQuote, 2000); // change every 2 seconds
      }

      showQuote();
    } else if (timeout) {
      clearTimeout(timeout);
    }
  }

  testMatch();
  addEventListener("resize", testMatch);
})();

.quoteWrapper {
  display: none;
}

#current-quote {
  display: block;
}


问:
pandas lagged value of time series (previous year) for cohort
For a dataframe of:

```<code>import pandas as pd

df = pd.DataFrame({
    'dt':[
        '2019-01-01',
        '2019-01-02',
        '2019-01-03',
        '2020-01-01',
        '2020-01-02',
        '2020-01-03',
        '2019-01-01',
        '2019-01-02',
        '2019-01-03',
        '2020-01-01',
        '2020-01-02',
        '2020-01-03'
    ],
    'foo': [1,2,3, 4,5,6, 1,5,3, 4,10,6],

    'category': [1,1,1,1,1,1,  2,2,2,2,2,2]
})
</code>```

How can I find the lagged value from the previous year for each category?

```<code>df['dt'] = pd.to_datetime(df['dt'])
display(df)
</code>```

Shifting the index only returns an empty result, and thus fails assignment.

```<code>df['last_year'] = df[df.dt == df.dt - pd.offsets.Day(365)]
</code>```

Obviously, a join with the data from 2019 on the month and day would work - but seem rahter cumbersome. Is there a better way?

edit

the desired result:

```<code>dt  foo     category  last_year
2020-01-01  4   1      1
2020-01-02  5   1      2
2020-01-03  6   1      3
2020-01-01  4   2      1
2020-01-02  10  2      5
2020-01-03  6   2      3
</code>```

Body:
For a dataframe of:

import pandas as pd

df = pd.DataFrame({
    'dt':[
        '2019-01-01',
        '2019-01-02',
        '2019-01-03',
        '2020-01-01',
        '2020-01-02',
        '2020-01-03',
        '2019-01-01',
        '2019-01-02',
        '2019-01-03',
        '2020-01-01',
        '2020-01-02',
        '2020-01-03'
    ],
    'foo': [1,2,3, 4,5,6, 1,5,3, 4,10,6],

    'category': [1,1,1,1,1,1,  2,2,2,2,2,2]
})

How can I find the lagged value from the previous year for each category?

df['dt'] = pd.to_datetime(df['dt'])
display(df)

Shifting the index only returns an empty result, and thus fails assignment.

df['last_year'] = df[df.dt == df.dt - pd.offsets.Day(365)]

Obviously, a join with the data from 2019 on the month and day would work - but seem rahter cumbersome. Is there a better way?

edit

the desired result:

dt  foo     category  last_year
2020-01-01  4   1      1
2020-01-02  5   1      2
2020-01-03  6   1      3
2020-01-01  4   2      1
2020-01-02  10  2      5
2020-01-03  6   2      3

Body:
you can merge df with itself after you assign the column dt with the difference you want with pd.DateOffset.

print (df.merge(df.assign(dt=lambda x: x['dt']+pd.DateOffset(years=1)),
                on=['dt', 'category'],
                suffixes=('','_lastYear'),
                how='left'))
           dt  foo  category  foo_lastYear
0  2019-01-01    1         1           NaN
1  2019-01-02    2         1           NaN
2  2019-01-03    3         1           NaN
3  2020-01-01    4         1           1.0
4  2020-01-02    5         1           2.0
5  2020-01-03    6         1           3.0
6  2019-01-01    1         2           NaN
7  2019-01-02    5         2           NaN
8  2019-01-03    3         2           NaN
9  2020-01-01    4         2           1.0
10 2020-01-02   10         2           5.0
11 2020-01-03    6         2           3.0


问:
R: Substituting missing values (NAs) with two different values
I might be overcomplicating things - would love to know if if there is an easier way to solve this. I have a data frame (df) with 5654 observations - 1332 are foreign-born, and 4322 Canada-born subjects.

The variable df$YR_IMM captures: "In what year did you come to live in Canada?"
See the following distribution of observations per immigration year table(df$YR_IMM) :

```<code>1920 1926 1928 1930 1939 1942 1944 1946 1947 1948 1949 1950 1951 1952 1953 1954
2    1    1    2    1    2    1    1    1    9    5    1    7   13    3    5
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
10    5    8    6    6    1    5    1    6    3    7   16   18   12   15   13
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
10   17    8   18   25   16   15   12   16   27   13   16   11    9   17   16
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
24   21   31   36   26   30   26   24   22   30   29   26   47   52   53   28   9
</code>```

Naturally these are only foreign-born individuals (mean = 1985) - however, 348 foreign-borns are missing. There are a total of 4670 NAs that also include Canada-borns subjects.

How can I code these df$YR_IMM NAs in such a way that

```<code>348 (NA) --> 1985
4322(NA) --> 100
</code>```

Additionally, the status is given by df$Brthcoun with 0 = "born in Canada" and 1 = "born outside of Canada.

Hope this makes sense - thank you!

EDIT: This was the solution ->

df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985

答:
Something like this should also work:</p>

```<code>df$YR_IMM <- ifelse(is.na(df$YR_IMM) & df$Brthcoun == 0, 100, 1985)
</code>```

Body:
I might be overcomplicating things - would love to know if if there is an easier way to solve this. I have a data frame (df) with 5654 observations - 1332 are foreign-born, and 4322 Canada-born subjects.

The variable df$YR_IMM captures: "In what year did you come to live in Canada?"
See the following distribution of observations per immigration year table(df$YR_IMM) :

1920 1926 1928 1930 1939 1942 1944 1946 1947 1948 1949 1950 1951 1952 1953 1954
2    1    1    2    1    2    1    1    1    9    5    1    7   13    3    5
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
10    5    8    6    6    1    5    1    6    3    7   16   18   12   15   13
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
10   17    8   18   25   16   15   12   16   27   13   16   11    9   17   16
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
24   21   31   36   26   30   26   24   22   30   29   26   47   52   53   28   9

Naturally these are only foreign-born individuals (mean = 1985) - however, 348 foreign-borns are missing. There are a total of 4670 NAs that also include Canada-borns subjects.

How can I code these df$YR_IMM NAs in such a way that

348 (NA) --> 1985
4322(NA) --> 100

Additionally, the status is given by df$Brthcoun with 0 = "born in Canada" and 1 = "born outside of Canada.

Hope this makes sense - thank you!

EDIT: This was the solution ->

df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985

Body:
Something like this should also work:

df$YR_IMM <- ifelse(is.na(df$YR_IMM) & df$Brthcoun == 0, 100, 1985)


问:
Ngx-Chart does not display data
I am currently using Ngx-Charts in my angular project. The data for my charts comes from a Node.js web service that gives the following response:

```<code>[{name: "ALB", value: 2188679.1133568},{name: "OFF", value: 1440804.2389714},{name: "SL1", value: 971553.8710496},{name: "HDS", value: 793200.8299244},{name: "YAC", value: 183228.7398208},{name: "DWK", value: 104339.702865},{name: "SS1", value: 54080.201656},{name: "SIM", value: 44772.373923},{name: "ELS", value: 755.211371}]
</code>```

I am trying to parse this into an array in my component.ts file and then pass the array into the chart canvas in my component.html file. However though I am able to display the response onto the console, I am unable to display the data onto the chart. All I see are blank charts with the x and y axes but not data on them. I don’t understand where I am going wrong.

My component.ts file:

```<code>export class DashboardComponent implements OnInit{

  isBrowser: boolean;

  verticalBarOptions = {
    showXAxis: true,
    showYAxis: true,
    gradient: false,
    showLegend: true,
    showGridLines: true,
    barPadding: 25,
    showXAxisLabel: false,
    xAxisLabel: 'Country',
    showYAxisLabel: true,
    yAxisLabel: 'Sales'
  };

  locWData: any[];

  colorScheme = {
    domain: ['#0000FF', '#154360', '#17202A', '#21618C', '#2E86C1', '#85C1E9', '#2E86C1', '#34495E', '#21618C', '#154360']
  };

  constructor(@Inject(PLATFORM_ID) private platformId: object, private service: ReportsService) {
    this.locWData = [];
    this.isBrowser = isPlatformBrowser(platformId);
  }

  ngOnInit(): void {
    this.service.getAllLocWiseStock().subscribe((response : any) => {
      //console.log(response.recordset);
      for (let i = 0; i < response.recordset.length; i++) {
        this.locWData.push({name: response.recordset[i].LOCATION_ID, value: response.recordset[i].AMOUNT})
      }
      console.log(this.locWData);
    });
  }
}
</code>```

And component.html file:

```<code><div class="col-12 chart-card”>
  <div>
    <div class="chart-card-header">
      <span>Location-wise Sales</span>
    </div>
    <div class="chart-card-body bar-vertical">
      <ngx-charts-bar-vertical *ngIf="isBrowser"
        [scheme]="colorScheme"
        [results]="locWData"
        [gradient]="verticalBarOptions.gradient"
        [xAxis]="verticalBarOptions.showXAxis"
        [yAxis]="verticalBarOptions.showYAxis"
        [legend]="verticalBarOptions.showLegend"
        [showXAxisLabel]="verticalBarOptions.showXAxisLabel"
        [showYAxisLabel]="verticalBarOptions.showYAxisLabel"
        [xAxisLabel]="verticalBarOptions.xAxisLabel"
        [yAxisLabel]=“verticalBarOptions.yAxisLabel"
        [barPadding]="verticalBarOptions.barPadding"
        [showGridLines]="verticalBarOptions.showGridLines">
      </ngx-charts-bar-vertical>
    </div>
  </div>
</div>
<div class="col-12 chart-card">
  <div>
    <div class="chart-card-header">
      <span>Location-wise Sales Distribution</span>
    </div>
    <div class="chart-card-body pie-grid">
      <ngx-charts-advanced-pie-chart *ngIf="isBrowser"
        [label]="'Points'"
        [scheme]="colorScheme"
        [results]="locWData">
      </ngx-charts-advanced-pie-chart>
    </div>
  </div>
</div>
</code>```

答:
In this stackblitz it seems to fill the charts. even if you change the data for advance-pie-chart:

https://stackblitz.com/edit/angular-ivy-em7rez?file=src%2Fapp%2Fdashboard%2Fdashboard.component.ts

Title: Ngx-Chart does not display data

Body:
I am currently using Ngx-Charts in my angular project. The data for my charts comes from a Node.js web service that gives the following response:

[{name: "ALB", value: 2188679.1133568},{name: "OFF", value: 1440804.2389714},{name: "SL1", value: 971553.8710496},{name: "HDS", value: 793200.8299244},{name: "YAC", value: 183228.7398208},{name: "DWK", value: 104339.702865},{name: "SS1", value: 54080.201656},{name: "SIM", value: 44772.373923},{name: "ELS", value: 755.211371}]

I am trying to parse this into an array in my component.ts file and then pass the array into the chart canvas in my component.html file. However though I am able to display the response onto the console, I am unable to display the data onto the chart. All I see are blank charts with the x and y axes but not data on them. I don’t understand where I am going wrong.

My component.ts file:

export class DashboardComponent implements OnInit{

  isBrowser: boolean;

  verticalBarOptions = {
    showXAxis: true,
    showYAxis: true,
    gradient: false,
    showLegend: true,
    showGridLines: true,
    barPadding: 25,
    showXAxisLabel: false,
    xAxisLabel: 'Country',
    showYAxisLabel: true,
    yAxisLabel: 'Sales'
  };

  locWData: any[];

  colorScheme = {
    domain: ['#0000FF', '#154360', '#17202A', '#21618C', '#2E86C1', '#85C1E9', '#2E86C1', '#34495E', '#21618C', '#154360']
  };

  constructor(@Inject(PLATFORM_ID) private platformId: object, private service: ReportsService) {
    this.locWData = [];
    this.isBrowser = isPlatformBrowser(platformId);
  }

  ngOnInit(): void {
    this.service.getAllLocWiseStock().subscribe((response : any) => {
      //console.log(response.recordset);
      for (let i = 0; i < response.recordset.length; i++) {
        this.locWData.push({name: response.recordset[i].LOCATION_ID, value: response.recordset[i].AMOUNT})
      }
      console.log(this.locWData);
    });
  }
}

And component.html file:

      Location-wise Sales

      <ngx-charts-bar-vertical *ngIf="isBrowser"
        [scheme]="colorScheme"
        [results]="locWData"
        [gradient]="verticalBarOptions.gradient"
        [xAxis]="verticalBarOptions.showXAxis"
        [yAxis]="verticalBarOptions.showYAxis"
        [legend]="verticalBarOptions.showLegend"
        [showXAxisLabel]="verticalBarOptions.showXAxisLabel"
        [showYAxisLabel]="verticalBarOptions.showYAxisLabel"
        [xAxisLabel]="verticalBarOptions.xAxisLabel"
        [yAxisLabel]=“verticalBarOptions.yAxisLabel"
        [barPadding]="verticalBarOptions.barPadding"
        [showGridLines]="verticalBarOptions.showGridLines">
      </ngx-charts-bar-vertical>

      Location-wise Sales Distribution

      <ngx-charts-advanced-pie-chart *ngIf="isBrowser"
        [label]="'Points'"
        [scheme]="colorScheme"
        [results]="locWData">
      </ngx-charts-advanced-pie-chart>


问:
Reducer: getting information about value changes at the store
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

```<code>ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}
</code>```

Reducer action:

```<code>export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.
</code>```

Reducer:

```<code>const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}
</code>```

答:
I have the solution: I'm using componentWillReceiveProps(nextProps) and can receive a result from the reducer.
Thanks all for the answers.

Body:
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}

Reducer action:

export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.

Reducer:

const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}


问:
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 0 updates, 1 removal
  - Removing genealabs/laravel-caffeine (0.3.12)
Writing lock file
Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
  @php artisan package:discover

[Symfony\Component\Debug\Exception\FatalThrowableError]

  Class 'GeneaLabs\LaravelCaffeine\LaravelCaffeineServiceProvider' not found

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

答:
in this case, I use space for APP_NAME key in .env file.

and have below error :

```<code>The environment file is invalid!
Failed to parse dotenv file due to unexpected whitespace. Failed at [my name].
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1
</code>```

Don't use space in APP_NAME key !!

Body:
in this case, I use space for APP_NAME key in .env file.

and have below error :

The environment file is invalid!
Failed to parse dotenv file due to unexpected whitespace. Failed at [my name].
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Don't use space in APP_NAME key !!


问:
Does adding [DataContract] and [DataMember] to all classes impact performance
Lets say we got a code generating tool that creates thousands of C# classes, and we sometimes need to add those attributes to them.

We are considering whether it is better to put [DataContract] and [DataMember] on all appropriate classes or we need to create a special strategy that will determine whether to do so in order to save up some possible? performance lost in AtribbuteAll approach.

In the end the question is whether adding attributes can somehow affect performance?

I am thinking that adding an attribute on a class will simply stay with its type information and should not affect any performance but would like to be 100% certain here

答: Adding attributes would impact in performance if these are inspected in some part of the code, if not, classes would have more metadata, but this doesn't impact performance.</p>


问:
jQuery - clone() is not a function
I'm trying to copy some of my elements from this block and paste them in the end:

```<code><div class="brands">
    <img src="brand1.png" alt="1" />
    <img src="brand2.png" alt="2" />
    <img src="brand3.png" alt="3" />
</div>
</code>```

That's what I'm doing:

```<code>for (var i = 0; i < 2; i++) {
    $('.brands img')[i].clone().appendTo('.brands');
}
</code>```

But then I see this in console: TypeError: $(...)[i].clone is not a function, jQuery is uncluded. What's wrong with my code?

答:
For all img elements, clone() and appendTo('.brands') will work.

```<code>$('.brands img').clone().appendTo('.brands');
</code>```

Title: jQuery - clone() is not a function

Body:
I'm trying to copy some of my elements from this block and paste them in the end:

That's what I'm doing:

for (var i = 0; i < 2; i++) {
    $('.brands img')[i].clone().appendTo('.brands');
}

But then I see this in console: TypeError: $(...)[i].clone is not a function, jQuery is uncluded. What's wrong with my code?

Body:
For all img elements, clone() and appendTo('.brands') will work.

$('.brands img').clone().appendTo('.brands');


问:
Dropzone.js not showing in vue-js-modal
In a project, I am using the vue-js-modal plugin by euvl and dropzone.js for multiple file uploads.

I know want to combine both libraries and let the user open a modal and upload files. Unfortunately, it looks like the dropzone.js library is not initialized properly, the modal pops up, but I can't upload photos through the dropzone container.

Unfortunately, I don't get an error on the console, but the file upload window doesn't open and drag and drop of files is also not possible.

This is my vue component file:

```<code><template>
<modal name="upload-files-modal" classses="p-4 bg-card rounded-lg" height="auto">
        <div class="card mt-3">
        <h3 class="font-normal text-xl py-4 -ml-5 mb-3 border-l-4 border-blue-light pl-4">
           Upload some pictures
        </h3>
            <form id="newForm" method="POST" action="" class="dropzone" >
            </form>
        </div>
</modal>
</template>

<script>
import Dropzone from 'dropzone'
import 'dropzone/dist/dropzone.css'

Dropzone.autoDiscover = false;
Dropzone.options.newForm = {
        paramName: 'photo',
        maxFilesize: 3,
        acceptedFiles: '.jpg, .jpeg, .png .bmp',
        init: function () {
        // Set up any event handlers
        this.on('queuecomplete', function (file) {
                location.reload();
        });
    }
}

export default {
    props: ['uploadurl']
}
</script>
</code>```

This is how I use the vue component in my laravel blade file:

```<code><upload-files-modal uploadurl="{{ $project->path() . '/photos' }}" ></upload-files-modal>

<a href="" @click.prevent=$modal.show('upload-files-modal')>Upload Photo</a>
</code>```

答:
I think you should initialize Dropzone after modal opens up.

Example

Dropzone.autoDiscover = false;

const VModal = window["vue-js-modal"].default;

Vue.use(VModal)

const dropForm = Vue.component('drop-form', {

  template: `

  <modal name="modal" @opened="afterOpen">

  </modal>
  <button @click="showModal()">Upload files</button>
`,
  methods: {
    showModal() {
      this.$modal.show('modal')
    },
    afterOpen() {
      const dropZone = new Dropzone(this.$refs.dropZoneRef, {
        url: "/file/post"
      });
    }
  },
  mounted() {
  }
});

new Vue({
  el: '#root',
  template: `<drop-form></drop-form>`
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  padding: 1rem;
  border: 1px solid black;
  height: 200px;
}

#dropZone {
  height: 100px
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/basic.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.css">

```

Title: Dropzone.js not showing in vue-js-modal

Body:
In a project, I am using the vue-js-modal plugin by euvl and dropzone.js for multiple file uploads.

I know want to combine both libraries and let the user open a modal and upload files. Unfortunately, it looks like the dropzone.js library is not initialized properly, the modal pops up, but I can't upload photos through the dropzone container.

Unfortunately, I don't get an error on the console, but the file upload window doesn't open and drag and drop of files is also not possible.

This is my vue component file:

<template>
<modal name="upload-files-modal" classses="p-4 bg-card rounded-lg" height="auto">

           Upload some pictures

            <form id="newForm" method="POST" action="" class="dropzone" >
            </form>

</modal>
</template>

This is how I use the vue component in my laravel blade file:

<upload-files-modal uploadurl="{{ $project->path() . '/photos' }}" ></upload-files-modal>

Upload Photo

Body:
I think you should initialize Dropzone after modal opens up.

Example

Dropzone.autoDiscover = false;

const VModal = window["vue-js-modal"].default;

Vue.use(VModal)

const dropForm = Vue.component('drop-form', {

  template: `<div class="content">
  <modal name="modal" @opened="afterOpen">
    <div ref="dropZoneRef" class="dropzone"></div>
  </modal>
  <button @click="showModal()">Upload files</button></div>`,
  methods: {
    showModal() {
      this.$modal.show('modal')
    },
    afterOpen() {
      const dropZone = new Dropzone(this.$refs.dropZoneRef, {
        url: "/file/post"
      });
    }
  },
  mounted() {
  }
});

new Vue({
  el: '#root',
  template: `<drop-form></drop-form>`
})

.content {
  padding: 1rem;
  border: 1px solid black;
  height: 200px;
}

#dropZone {
  height: 100px
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/basic.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.js"></script>
<script src="https://unpkg.com/vue-js-modal@2.0.0-rc.3/dist/index.js"></script>
<div id="root"></div>


问:
Extending WebFormView in MVC
I want to extend the WebFormViewEngine so that I can perform some post-processing - I want it to do it's stuff, then hand me the Html back, so I can do put some final touches to it.  It needs to be done as a View/ViewEngine because I need access to the ViewData.

Unfortunately there seems to be no way to get the Html back from the WebFormView, and no way to hand a custom HtmlTextWriter to the WebFormView or ViewPage.

Surely there's a way to do this? No?

Littlecharva

答:
You can use Action Filters to do this.  Check out this tutorial at asp.net/mvc.  You want to use a ResultsFilter.

As an alternate, you can override the virtual OnResultExecuted method of the Controller.

OwnerDisplayName: littlecharva

ContentLicense: CC BY-SA 2.5

Title: Extending WebFormView in MVC

OwnerDisplayName: Matthew

LastEditorDisplayName: Matthew


问:
Django 3 admin link is coming without css
The Admin link is missing css, returns 404 when doing view source.
The .conf file is

```<code><VirtualHost *:80>

ServerAdmin webmaster@example.com
DocumentRoot /var/www/django/medicalai
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /static /var/www/django/medicalai
<Directory /var/www/django/medicalai/static>
Require all granted
</Directory>

<Directory /var/www/django/medicalai>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

WSGIDaemonProcess medicalai python-path=/var/www/django/medicalai python-home=/var/www/django/venv
WSGIProcessGroup medicalai
WSGIScriptAlias / /var/www/django/medicalai/medicalai/wsgi.py
WSGIPassAuthorization On

</VirtualHost>
</code>```

The Static file contains.

```<code>STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
</code>```

The static folder and files are here.
/var/www/django/medicalai/static/admin/css

All the files and folders are downloaded by using
python manage.py collectstatic.

But there is no CSS when I open http://example.com/admin/login/?next=/admin/
Please help to point the mistake.

答:
This issue could happen because you do not have  STATIC_ROOT configured when you run

```<code>python manage.py collectstatic
</code>```

What this setting does is to copy all the static files from all the STATICFILES_DIRS directories into a single ROOT prepared for production serving.

```<code>STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATIC_ROOT = '/var/www/django/medicalai/static/'
</code>```

Body:
The Admin link is missing css, returns 404 when doing view source.
The .conf file is

<VirtualHost *:80>

ServerAdmin webmaster@example.com
DocumentRoot /var/www/django/medicalai
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /static /var/www/django/medicalai
<Directory /var/www/django/medicalai/static>
Require all granted
</Directory>

<Directory /var/www/django/medicalai>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

WSGIDaemonProcess medicalai python-path=/var/www/django/medicalai python-home=/var/www/django/venv
WSGIProcessGroup medicalai
WSGIScriptAlias / /var/www/django/medicalai/medicalai/wsgi.py
WSGIPassAuthorization On

</VirtualHost>

The Static file contains.

STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]

The static folder and files are here.
/var/www/django/medicalai/static/admin/css

All the files and folders are downloaded by using
python manage.py collectstatic.

But there is no CSS when I open http://example.com/admin/login/?next=/admin/
Please help to point the mistake.

Body:
This issue could happen because you do not have  STATIC_ROOT configured when you run

python manage.py collectstatic

What this setting does is to copy all the static files from all the STATICFILES_DIRS directories into a single ROOT prepared for production serving.

STATIC_DIR = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATIC_ROOT = '/var/www/django/medicalai/static/'


问:
Sorting SQL results by date on the CLIENT instead of in the QUERY
suppose I have some table that is tracking a users weight over time.

```<code>CREATE TABLE `userWeights` (
  `weight_id` int PRIMARY KEY AUTO_INCREMENT,
  `user_id` int,
  `weight` float,
  `date_created` timestamp
);
</code>```

The obvious use-case here is some REST endpoint getWeights(user_id) and then display it as a graph on the UI.
The standard query I would write would be something like:

```<code>SELECT * FROM userWeights WHERE user_id=user_id ORDER BY date_created ASC
</code>```

but seeing as as we're sorting by date, business logic that would never change for this use-case, could the sorting computational load be outsourced to the client's device and thus improve the performance of the SQL query? would this be a mostly insignificant improvement for, say, a table of 1000 users where we store 6 months of daily weight measurements?

```<code>SELECT * FROM userWeights WHERE user_id=user_id
results.sort(date_created, ASCENDING); //e.g. code on android device
</code>```

EDIT: I ask because many cloud function/cloud database hosts charge based on computation time per invocation.

答:
KISS.

Adding an ORDER BY to the query is simple and hard to screw up.

Adding sorting to the client takes more keystrokes and is more error-prone.

Furthermore, it is possible to eat-your-cake without even paying for it!  The sort can be "free":

```<code>CREATE TABLE `userWeights` (
  `user_id` int,
  `weight` float,
  `date_created` timestamp,
  PRIMARY KEY(user_id, date_created)
);
</code>```

You still need the ORDER BY clause on the SELECT, but notice that it will take zero effort on either the server or the client.

The way you had the table definition, it had to scan the entire table to find the rows for the requested user_id; this change avoids that, too.  Also, this saves space of the useless weight_id.

My suggestion has one problem:  You can't record two different weights taken in the same second.  (That seems like a bug to even try!)

Cost savings...

The Optimizer will not charge anything for discovering that the data is already sorted.  (Above)

Don't say SELECT *, that returns all the columns; you need only two:  SELECT date_created, weight.

Syntax problem:  WHERE user_id=user_id -- One of those needs to be the parameter coming in.  Else, it is equivalent to "TRUE".

Body:
suppose I have some table that is tracking a users weight over time.

CREATE TABLE `userWeights` (
  `weight_id` int PRIMARY KEY AUTO_INCREMENT,
  `user_id` int,
  `weight` float,
  `date_created` timestamp
);

The obvious use-case here is some REST endpoint getWeights(user_id) and then display it as a graph on the UI.
The standard query I would write would be something like:

SELECT * FROM userWeights WHERE user_id=user_id ORDER BY date_created ASC

but seeing as as we're sorting by date, business logic that would never change for this use-case, could the sorting computational load be outsourced to the client's device and thus improve the performance of the SQL query? would this be a mostly insignificant improvement for, say, a table of 1000 users where we store 6 months of daily weight measurements?

SELECT * FROM userWeights WHERE user_id=user_id
results.sort(date_created, ASCENDING); //e.g. code on android device

EDIT: I ask because many cloud function/cloud database hosts charge based on computation time per invocation.

Body:
KISS.

Adding an ORDER BY to the query is simple and hard to screw up.

Adding sorting to the client takes more keystrokes and is more error-prone.

Furthermore, it is possible to eat-your-cake without even paying for it!  The sort can be "free":

CREATE TABLE `userWeights` (
  `user_id` int,
  `weight` float,
  `date_created` timestamp,
  PRIMARY KEY(user_id, date_created)
);

You still need the ORDER BY clause on the SELECT, but notice that it will take zero effort on either the server or the client.

The way you had the table definition, it had to scan the entire table to find the rows for the requested user_id; this change avoids that, too.  Also, this saves space of the useless weight_id.

My suggestion has one problem:  You can't record two different weights taken in the same second.  (That seems like a bug to even try!)

Cost savings...

The Optimizer will not charge anything for discovering that the data is already sorted.  (Above)

Don't say SELECT *, that returns all the columns; you need only two:  SELECT date_created, weight.

Syntax problem:  WHERE user_id=user_id -- One of those needs to be the parameter coming in.  Else, it is equivalent to "TRUE".


问:
How to scroll horizontally using selenium chromedriver in python
I am doing web-scraping using Selenium Chromedriver in Python. My link is below: https://www.macrotrends.net/stocks/charts/AAPL/apple/balance-sheet

I want to get data of table in the link. But The table has a scrollbar so I can only get the data in visible columns of the table. I want to get all data of table.

ex)

driver.find_element_by_css_selector('#columntablejqxgrid').text

My goal)

```<code>Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30
2013-09-30
2012-09-30
2011-09-30
2010-09-30
2009-09-30
2008-09-30
2007-09-30
2006-09-30
2005-09-30
</code>```

The result)

```<code>Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30
</code>```

So, I have to scroll the table horizontally and get the rest of data. How can I achieve that?

答:
For the scrolling you can use the ActionChains Class

```<code>from selenium.webdriver.common.action_chains import ActionChains
</code>```

Then you can move the slider using somthing like

```<code>ActionChains(driver).click_and_hold(slider).move_by_offset(x , 0).release().perform()
</code>```

Here's a working solution for you case:

```<code>horizontal_bar_width = driver.find_element_by_id('jqxScrollOuterWraphorizontalScrollBarjqxgrid').rect['width']
slider = driver.find_element_by_id('jqxScrollThumbhorizontalScrollBarjqxgrid')
    header_columns = []

# Using iteration as span values won't show went they are hidden
for _ in range(4):
    for el in driver.find_elements_by_css_selector('#columntablejqxgrid [role="columnheader"] span'):
        if el.text not in header_columns and el.text != '':
            header_columns.append(el.text)
    # Ensure the slider is in view
    slider.location_once_scrolled_into_view
    ActionChains(driver).click_and_hold(slider).move_by_offset(horizontal_bar_width/4, 0).release().perform()
</code>```

Output

```<code>['Annual Data | Millions of US $ except per share data',
 '2019-09-30',
 '2018-09-30',
 '2017-09-30',
 '2016-09-30',
 '2015-09-30',
 '2014-09-30',
 '2013-09-30',
 '2012-09-30',
 '2011-09-30',
 '2010-09-30',
 '2009-09-30',
 '2008-09-30',
 '2007-09-30',
 '2006-09-30',
 '2005-09-30']
</code>```

Body:
I am doing web-scraping using Selenium Chromedriver in Python. My link is below: https://www.macrotrends.net/stocks/charts/AAPL/apple/balance-sheet

I want to get data of table in the link. But The table has a scrollbar so I can only get the data in visible columns of the table. I want to get all data of table.

ex)

driver.find_element_by_css_selector('#columntablejqxgrid').text

My goal)

Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30
2013-09-30
2012-09-30
2011-09-30
2010-09-30
2009-09-30
2008-09-30
2007-09-30
2006-09-30
2005-09-30

The result)

Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30

So, I have to scroll the table horizontally and get the rest of data. How can I achieve that?

Body:
For the scrolling you can use the ActionChains Class

from selenium.webdriver.common.action_chains import ActionChains

Then you can move the slider using somthing like

ActionChains(driver).click_and_hold(slider).move_by_offset(x , 0).release().perform()

Here's a working solution for you case:

horizontal_bar_width = driver.find_element_by_id('jqxScrollOuterWraphorizontalScrollBarjqxgrid').rect['width']
slider = driver.find_element_by_id('jqxScrollThumbhorizontalScrollBarjqxgrid')
    header_columns = []

# Using iteration as span values won't show went they are hidden
for _ in range(4):
    for el in driver.find_elements_by_css_selector('#columntablejqxgrid [role="columnheader"] span'):
        if el.text not in header_columns and el.text != '':
            header_columns.append(el.text)
    # Ensure the slider is in view
    slider.location_once_scrolled_into_view
    ActionChains(driver).click_and_hold(slider).move_by_offset(horizontal_bar_width/4, 0).release().perform()

Output

['Annual Data | Millions of US $ except per share data',
 '2019-09-30',
 '2018-09-30',
 '2017-09-30',
 '2016-09-30',
 '2015-09-30',
 '2014-09-30',
 '2013-09-30',
 '2012-09-30',
 '2011-09-30',
 '2010-09-30',
 '2009-09-30',
 '2008-09-30',
 '2007-09-30',
 '2006-09-30',
 '2005-09-30']


问:
amazon cloud web service - how to locate/manage it
I am thinking of implementing a service on the amazon cloud.  Basic idea is:

client has some files (client can be on a the user's amazon cloud, or on a regular machine)

files are uploaded to a machine on the cloud, along with instructions for how to process the files

cloud machine performs the file processing

output file(s) are sent back to the client

Ideally I wouldn't want my service to run at all unless someone is requesting its use.  Also, if many clients want to use it, I want to spawn more machines to run my service.  Does this mean that I should implement my own server (off-cloud), that the client should first connect to, and my server would spawn some cloud machines and let the client know that cloud machine's IP address?

What is the best way to transfer files to the cloud?  Is FTP a good solution?  What if the client's file are on Amazon S3 cloud, should I use the S3 cloud interface for the file transfer?

答:
Interesting..

You need the following:

Auto-scaling - to spawn one or more servers + remove them when not in use.
http://www.techmasala.com/2009/04/06/dynamically-scale-web-applications-in-amazon-ec2/

Amazon S3 for transferring and storing files - 99% redundancy + distributed.
RequestTimeout uploading to S3 using PHP

I would suggest you to use S3FS where you can mount a bucket as a drive on a machine and the rest (uploading to the actual bucket) will be taken care by the FS command.


问:
Java: two threads summing numbers in a given range simultaneously: when just one thread is joined the second thread's sum is too big
I  have two threads that sum values in a single array of integers: [0; 100_000].
Each thread is an object that has min, max and sum fields and I later get the total sum by summing the result of both threads.
Thread 1 sums numbers in [0, 20_000] range, while thread 2 sums numbers in [20_001, 100_000] range. The correct thread1's sum is 200,010,000, the correct thread2's sum is 505,072,704, the correct total sum of numbers in [0, 100_000] range is 705,082,704.

It works fine when both threads are joined inside the main method's thread. However if I only join the first thread, the main method proceeds to print the results before the second thread is finished. I understand this behavior. However, I don't understand why in those results (at which point thread1's finished and its sum is correct, while thread2 is not finished yet and its sum is not correct) the thread2's sum exceeds the maximum possible sum for it (505,072,704). I don't understand how it's possible.

```<code>public class SumNumbers {
    public static void main(String[] args) throws Exception {
        int min = 0;
        int max = 100_000;

        int left = 20_000;
        int right = 100_000;

        int usualSum = 0;
        for (int i = min; i<= max; i++)  {
            usualSum += i;
        }
        System.out.printf("usual sum: %,d\n", usualSum);

        SummerThread s1 = new SummerThread(0, left);
        SummerThread s2 = new SummerThread(left + 1, right);

        Thread thread1 = new Thread(s1, "left thread");
        Thread thread2 = new Thread(s2, "right thread");

        thread1.start();
        thread2.start();

        thread1.join();
       // thread2.join();

        System.out.printf("left sum: %,d\n", s1.getSum());
        System.out.printf("right sum: %,d\n", s2.getSum());
        System.out.printf("left + right: %,d\n", s1.getSum() + s2.getSum());

        thread2.join();
        System.out.printf("right sum: %,d\n", s2.getSum());
        System.out.printf("left + right: %,d\n", s1.getSum() + s2.getSum());

    }
}

class SummerThread implements Runnable  {

    private int sum;
    private int min;
    private int max;

    private int id;
    private static int count;

    public SummerThread(int min, int max)  {
        this.min = min;
        this.max = max;

        count++;
        id = count;
    }

    @Override
    public void run()  {
        for (int i = min; i <= max; i++)  {
           // System.out.println("thread: " + id);
            sum += i;
        }
    }

    public int getSum()  {return sum;}
}
</code>```

The output is different accross the runs:

```<code>usual sum: 705,082,704
left sum: 200,010,000
right sum: 645,520,003
left + right: 1,020,729,153
right sum: 505,072,704
left + right: 705,082,704
</code>```

```<code>usual sum: 705,082,704
left sum: 200,010,000
right sum: 168,890,703
left + right: 1,049,163,528
right sum: 505,072,704
left + right: 705,082,704
</code>```

```<code>usual sum: 705,082,704
left sum: 200,010,000
right sum: 1,625,006,320
left + right: 1,825,016,320
right sum: 505,072,704
left + right: 705,082,704
</code>```

The correct output (if all .join are uncommented) is:

```<code>usual sum: 705,082,704
left sum: 200,010,000
right sum: 505,072,704
left + right: 705,082,704
right sum: 505,072,704
left + right: 705,082,704
</code>```

答:
Aren't your maths off here? The sum from 1 to n is n(n+1)/2, which, if you replace n with 100,000, gives you 5,000,050,000. This exceeds the maximum number you can store in an int, which is about 2 billion. The reason why the partial sum is higher than the final sum is likely because you experienced an integer overflow.

To illustrate this, the snippet below is useful:

```<code>System.out.println((int) 5_000_050_000L); // prints 705082704
</code>```

As you can see, we find your 705,082,704 sum again, but it is incorrect and only results from the integer overlow.

Body:
I  have two threads that sum values in a single array of integers: [0; 100_000].
Each thread is an object that has min, max and sum fields and I later get the total sum by summing the result of both threads.
Thread 1 sums numbers in [0, 20_000] range, while thread 2 sums numbers in [20_001, 100_000] range. The correct thread1's sum is 200,010,000, the correct thread2's sum is 505,072,704, the correct total sum of numbers in [0, 100_000] range is 705,082,704.

It works fine when both threads are joined inside the main method's thread. However if I only join the first thread, the main method proceeds to print the results before the second thread is finished. I understand this behavior. However, I don't understand why in those results (at which point thread1's finished and its sum is correct, while thread2 is not finished yet and its sum is not correct) the thread2's sum exceeds the maximum possible sum for it (505,072,704). I don't understand how it's possible.

public class SumNumbers {
    public static void main(String[] args) throws Exception {
        int min = 0;
        int max = 100_000;

        int left = 20_000;
        int right = 100_000;

        int usualSum = 0;
        for (int i = min; i<= max; i++)  {
            usualSum += i;
        }
        System.out.printf("usual sum: %,d\n", usualSum);

        SummerThread s1 = new SummerThread(0, left);
        SummerThread s2 = new SummerThread(left + 1, right);

        Thread thread1 = new Thread(s1, "left thread");
        Thread thread2 = new Thread(s2, "right thread");

        thread1.start();
        thread2.start();

        thread1.join();
       // thread2.join();

        System.out.printf("left sum: %,d\n", s1.getSum());
        System.out.printf("right sum: %,d\n", s2.getSum());
        System.out.printf("left + right: %,d\n", s1.getSum() + s2.getSum());

        thread2.join();
        System.out.printf("right sum: %,d\n", s2.getSum());
        System.out.printf("left + right: %,d\n", s1.getSum() + s2.getSum());

    }
}

class SummerThread implements Runnable  {

    private int sum;
    private int min;
    private int max;

    private int id;
    private static int count;

    public SummerThread(int min, int max)  {
        this.min = min;
        this.max = max;

        count++;
        id = count;
    }

    @Override
    public void run()  {
        for (int i = min; i <= max; i++)  {
           // System.out.println("thread: " + id);
            sum += i;
        }
    }

    public int getSum()  {return sum;}
}

The output is different accross the runs:

usual sum: 705,082,704
left sum: 200,010,000
right sum: 645,520,003
left + right: 1,020,729,153
right sum: 505,072,704
left + right: 705,082,704

usual sum: 705,082,704
left sum: 200,010,000
right sum: 168,890,703
left + right: 1,049,163,528
right sum: 505,072,704
left + right: 705,082,704

usual sum: 705,082,704
left sum: 200,010,000
right sum: 1,625,006,320
left + right: 1,825,016,320
right sum: 505,072,704
left + right: 705,082,704

The correct output (if all .join are uncommented) is:

usual sum: 705,082,704
left sum: 200,010,000
right sum: 505,072,704
left + right: 705,082,704
right sum: 505,072,704
left + right: 705,082,704

Body:
Aren't your maths off here? The sum from 1 to n is n(n+1)/2, which, if you replace n with 100,000, gives you 5,000,050,000. This exceeds the maximum number you can store in an int, which is about 2 billion. The reason why the partial sum is higher than the final sum is likely because you experienced an integer overflow.

To illustrate this, the snippet below is useful:

System.out.println((int) 5_000_050_000L); // prints 705082704

As you can see, we find your 705,082,704 sum again, but it is incorrect and only results from the integer overlow.


问:
Bulma installation on laravel project failed on laravel 7
Just try to install Bulma on a fresh new laravel project and get this error,
my steps is :
Install this preset via composer require laravel-frontend-presets/bulma. No need to register the service provider. Laravel 5.5 & up can auto detect the package.
Use php artisan ui bulma for basic Bulma preset
npm install
npm run dev </p>

```<code>ERROR in ./resources/sass/app.scss
Module build failed (from ./node_modules/css-loader/index.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
8 │ @import "node_modules/bulma/sass/utilities/_all"
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  resources/sass/bulma.sass 8:9
</code>```

<p>Someone know how fix this ? </p>

答:
At first view bulma is not compatible with laravel 7,
So if you want to use it you have this repo that give you a solution :
https://github.com/Norbertho/laravel-7-bulma-frontend-preset</p>

Body:
Just try to install Bulma on a fresh new laravel project and get this error,
my steps is :
Install this preset via composer require laravel-frontend-presets/bulma. No need to register the service provider. Laravel 5.5 & up can auto detect the package.
Use php artisan ui bulma for basic Bulma preset
npm install
npm run dev

ERROR in ./resources/sass/app.scss
Module build failed (from ./node_modules/css-loader/index.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
8 │ @import "node_modules/bulma/sass/utilities/_all"
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  resources/sass/bulma.sass 8:9

Someone know how fix this ?