问:
difference between interface and abstract contract in solidity
I am learning solidity and got to know that interface and abstract are both classes that may contain unused functions.
My doubt is: What is the difference between interface and abstract contract in a solidity smart contract?

答:
Extensibility is key when building larger, more complex distributed applications. Solidity offers two ways to facilitate this:

Abstract Contract

Contracts are identified as abstract contracts if at least one of their functions lacks an implementation. This is the only requirement for abstract class. As a result, they cannot be compiled. They can however be used as base contracts from which other contracts can inherit from.

Unlike other languages, Solidity contracts do not need an abstract keyword to be marked as abstract. Rather, any contract that has at least one unimplemented function is treated as abstract in Solidity. An abstract contract can be neither compiled nor deployed unless it has an implementing contract

```<code>contract MyAbstractContract {
  function myAbstractFunction() public pure returns (string);
}
</code>```

if a contract inherits an abstract contract and does not implement all the unimplemented functions, then that contract will be considered abstract as well

```<code> //MyContract is also abstract
  contract MyContract is MyAbstractContract {
      function myAbstractFunction() public pure returns (string)
 }
</code>```

But this is not abstract because we are implementing the function.

```<code>contract MyContract is MyAbstractContract {
        function myAbstractFunction() public pure returns (string)
         { return "string value to return"; }
    }
</code>```

An abstract contract can have both implemented and unimplemented functions.

Interfaces

interfaces can have only unimplemented functions.  Also, they are neither compiled nor deployed. They are also called pure abstract contracts.

Interfaces cannot implement any of their functions. All interface functions are implicitly virtual

Interfaces are defined with the keyword Interface.

Interfaces cannot inherit other contracts or interfaces (after solidity 6.0.0 interfaces can inherit from interfaces) but other contracts can inherit from interfaces.

Interfaces cannot define a constructor

Functions of an interface can be only of type external.

Interfaces cannot have state variables

As of now Interfaces cannot define structs and enums but might change soon.

Body:
Extensibility is key when building larger, more complex distributed applications. Solidity offers two ways to facilitate this:

Abstract Contract

Contracts are identified as abstract contracts if at least one of their functions lacks an implementation. This is the only requirement for abstract class. As a result, they cannot be compiled. They can however be used as base contracts from which other contracts can inherit from.

Unlike other languages, Solidity contracts do not need an abstract keyword to be marked as abstract. Rather, any contract that has at least one unimplemented function is treated as abstract in Solidity. An abstract contract can be neither compiled nor deployed unless it has an implementing contract

contract MyAbstractContract {
  function myAbstractFunction() public pure returns (string);
}

if a contract inherits an abstract contract and does not implement all the unimplemented functions, then that contract will be considered abstract as well

 //MyContract is also abstract
  contract MyContract is MyAbstractContract {
      function myAbstractFunction() public pure returns (string)
 }

But this is not abstract because we are implementing the function.

contract MyContract is MyAbstractContract {
        function myAbstractFunction() public pure returns (string)
         { return "string value to return"; }
    }

An abstract contract can have both implemented and unimplemented functions.

Interfaces

interfaces can have only unimplemented functions.  Also, they are neither compiled nor deployed. They are also called pure abstract contracts.

Interfaces cannot implement any of their functions. All interface functions are implicitly virtual

Interfaces are defined with the keyword Interface.

Interfaces cannot inherit other contracts or interfaces (after solidity 6.0.0 interfaces can inherit from interfaces) but other contracts can inherit from interfaces.

Interfaces cannot define a constructor

Functions of an interface can be only of type external.

Interfaces cannot have state variables

As of now Interfaces cannot define structs and enums but might change soon.


来源: stackexchange

问:
Office JS API - Get add-in version at runtime
I'm developing an Excel taskpane using the new javascript api from Microsoft, and I would like to get the "Version" property from the loaded add-in from my script.

I see that the add-in displays its version when clicking on the information button, under "Security Info", but I can't find a way in the api reference to access this information from my javascript.

Does anybody know how and if it's possible to access to the security infos programmatically?

答:
The version element is located in the manifest file. But OfficeJS doesn't provide any property or method for reading the manifest content. The best what you could do is to define a version variable in the code of your add-in and update it with the manifest file accordingly. Also, if you host a copy of the manifest file on any web server, you could get it like any XML file and then parse it for getting the version info.

Feature requests on Tech Community are considered, when the dev team go through the planning process. Use the github label: “Type: product feature request” at https://aka.ms/M365dev-suggestions .

ContentLicense: CC BY-SA 4.0


问:
Access Laravel HTTP client status code in catch block
I need to be able to access the status code and response time in my catch block as not every error from the HTTP client results in no status code.

I've tried the following:

/**
* HTTP type
*
* @return object
*/
public function checkWithHttp($url, $timeout)
{
    try {
        $startResponseTime = microtime(true);
        $response = Http::withHeaders([
            'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
        ])->timeout($timeout)->get($url);
        $stopResponseTime = microtime(true);

        $responseTime = ($stopResponseTime - $startResponseTime) * 1000;

        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => $response->ok(),
            'json' => $response->json(),
            'headers' => $response->headers()
        ];
    } catch (\Exception $e) {
        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => false,
            'json' => null,
            'headers' => null
        ];
    }
}
```

But the results in $responseTime being undefined.

答:
You can get the estimated time the request was being transferred by the handler via getTransferTime() :

```<code>$response = Http::withHeaders(['User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'])
    ->timeout($timeout)
    ->get($url);
$responseTime = $response->transferStats->getTransferTime();
$return = [
    'response_time' => round($responseTime),
    'code' => $response->getStatusCode(),
    'ok' => $response->successful(),
    'json' => $response->json(),
    'headers' => $response->headers()
];
</code>```

FYI, unlike Guzzle's default behavior, Laravel's HTTP client wrapper does not throw exceptions on client or server errors (400 and 500 level responses from servers). So, you don't need to make a try-catch. You may determine if one of these errors was returned using the successful, clientError, or serverError methods.

Body:
I need to be able to access the status code and response time in my catch block as not every error from the HTTP client results in no status code.

I've tried the following:

/**
* HTTP type
*
* @return object
*/
public function checkWithHttp($url, $timeout)
{
    try {
        $startResponseTime = microtime(true);
        $response = Http::withHeaders([
            'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
        ])->timeout($timeout)->get($url);
        $stopResponseTime = microtime(true);

        $responseTime = ($stopResponseTime - $startResponseTime) * 1000;

        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => $response->ok(),
            'json' => $response->json(),
            'headers' => $response->headers()
        ];
    } catch (\Exception $e) {
        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => false,
            'json' => null,
            'headers' => null
        ];
    }
}

But the results in $responseTime being undefined.

Body:
You can get the estimated time the request was being transferred by the handler via getTransferTime() :

$response = Http::withHeaders(['User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'])
    ->timeout($timeout)
    ->get($url);
$responseTime = $response->transferStats->getTransferTime();
$return = [
    'response_time' => round($responseTime),
    'code' => $response->getStatusCode(),
    'ok' => $response->successful(),
    'json' => $response->json(),
    'headers' => $response->headers()
];

FYI, unlike Guzzle's default behavior, Laravel's HTTP client wrapper does not throw exceptions on client or server errors (400 and 500 level responses from servers). So, you don't need to make a try-catch. You may determine if one of these errors was returned using the successful, clientError, or serverError methods.


问:
RuntimeError: Model class xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I refer to following GitHub repo which is based on Django 2.0 and cookiecutter-django: github.com/Apfelschuss/apfelschuss/tree/c8851430201daeb7d1d81c5a6b3c8a639ea27b02

I am getting the following error when trying to run the app:

RuntimeError: Model class votes.models.Author doesn't declare an
  explicit app_label and isn't in an application in INSTALLED_APPS.

Error appeared with this line of code.

I tried to do as described in https://stackoverflow.com/a/40206661/5894988 but without success:

config/settings/base.py

```<code>LOCAL_APPS = [
    "apfelschuss.votes.apps.VotesConfig"
]
</code>```

apfelschuss/votes/apps.py

```<code>from django.apps import AppConfig

class VotesConfig(AppConfig):

    name = "apfelschuss.votes"
    verbose_name = "Votes"
</code>```

Any idea what I am doing wrong?

If anyone is interested how to run the docker container of the repo. It is described here.

答:
In file apps.py we see:

```<code>class ArticlesConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Django.apps.articles'
</code>```

We need name 'Django.apps.articles'

Now write in terminal:

```<code>from Django.apps.articles.models import Article
</code>```

And all working! I ran into this problem in PyCharm.

Body:
I refer to following GitHub repo which is based on Django 2.0 and cookiecutter-django: github.com/Apfelschuss/apfelschuss/tree/c8851430201daeb7d1d81c5a6b3c8a639ea27b02

I am getting the following error when trying to run the app:

RuntimeError: Model class votes.models.Author doesn't declare an
  explicit app_label and isn't in an application in INSTALLED_APPS.

Error appeared with this line of code.

I tried to do as described in https://stackoverflow.com/a/40206661/5894988 but without success:

config/settings/base.py

LOCAL_APPS = [
    "apfelschuss.votes.apps.VotesConfig"
]

apfelschuss/votes/apps.py

from django.apps import AppConfig

class VotesConfig(AppConfig):

    name = "apfelschuss.votes"
    verbose_name = "Votes"

Any idea what I am doing wrong?

If anyone is interested how to run the docker container of the repo. It is described here.

Body:
In file apps.py we see:

class ArticlesConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Django.apps.articles'

We need name 'Django.apps.articles'

Now write in terminal:

from Django.apps.articles.models import Article

And all working! I ran into this problem in PyCharm.


问:
Is the 2nd and 3rd byte of a JPEG image always the APP0 or APP1 marker?
I have a few different JPEG images I've been testing with.  As far as I've seen the 0th and first bytes are always 0xFF and 0xD8.

The second and third are usually either 0xFF and 0xE0 ( APP0 ) indicating either a JFIF segment or JFIF extension segment or 0xFF and 0xE1 ( APP1 ) indicating an EXIF segment.

My question: is this always the case?  Are the 2nd and 3rd bytes always APP0 or APP1?

答:
In theory, yes. According to the JFIF spec (pdf), its APP0 section should come first in the file. And the Exif spec (pdf) requires the same for its APP1 section.

But you shouldn't count on the order (or even the existance of) APPn sections; there are crazy JPEG writers out there. Start with the SOI and read the sections as they come by.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
is there any way to connect amazon aws opensearch to nodejs?
hi am newbie in aws and don't have any idea regarding how to connect to aws opensearch service and how to put data there using node and have created a domain on opensearch but want to put some data there using node please let me know if anybody can help
please provide the answer in code format</p>

答:
There are several ways to upload data to an OpenSearch Service, using services  like Lambda, using the command line or developing your service with most programming languages.

With the OpenSearch Service you can send HTTP requests to the domain of your service, so a curl request like this one would work to you:

```<code>curl -XPUT -u 'master-user:master-user-password' 'domain-endpoint/movies/_doc/1' -d '{"director": "Burton, Tim", "genre": ["Comedy","Sci-Fi"], "year": 1996, "actor": ["Jack Nicholson","Pierce Brosnan","Sarah Jessica Parker"], "title": "Mars Attacks!"}' -H 'Content-Type: application/json'
</code>```

For more information about sending curl requests to OpenSearch, take a look on this doc.

In Node.js we can do something like this:

```<code>var req = new AWS.HttpRequest(endpoint);

req.method = 'POST';
req.path = path.join('/', esDomain.index, esDomain.doctype);
req.region = esDomain.region;
req.headers['presigned-expires'] = false;
req.headers['Host'] = endpoint.host;
req.body = doc;

var signer = new AWS.Signers.V4(req , 'es');  // es: service code
signer.addAuthorization(creds, new Date());

var send = new AWS.NodeHttpClient();
send.handleRequest(req, null, function(httpResp) {
    var respBody = '';
    httpResp.on('data', function (chunk) {
        respBody += chunk;
    });
    httpResp.on('end', function (chunk) {
        console.log('Response: ' + respBody);
        context.succeed('Lambda added document ' + doc);
    });
}, function(err) {
    console.log('Error: ' + err);
    context.fail('Lambda failed with error ' + err);
});
</code>```

More examples can be found here: aws-samples
/
amazon-elasticsearch-lambda-samples

Body:
There are several ways to upload data to an OpenSearch Service, using services  like Lambda, using the command line or developing your service with most programming languages.

With the OpenSearch Service you can send HTTP requests to the domain of your service, so a curl request like this one would work to you:

curl -XPUT -u 'master-user:master-user-password' 'domain-endpoint/movies/_doc/1' -d '{"director": "Burton, Tim", "genre": ["Comedy","Sci-Fi"], "year": 1996, "actor": ["Jack Nicholson","Pierce Brosnan","Sarah Jessica Parker"], "title": "Mars Attacks!"}' -H 'Content-Type: application/json'

For more information about sending curl requests to OpenSearch, take a look on this doc.

In Node.js we can do something like this:

var req = new AWS.HttpRequest(endpoint);

req.method = 'POST';
req.path = path.join('/', esDomain.index, esDomain.doctype);
req.region = esDomain.region;
req.headers['presigned-expires'] = false;
req.headers['Host'] = endpoint.host;
req.body = doc;

var signer = new AWS.Signers.V4(req , 'es');  // es: service code
signer.addAuthorization(creds, new Date());

var send = new AWS.NodeHttpClient();
send.handleRequest(req, null, function(httpResp) {
    var respBody = '';
    httpResp.on('data', function (chunk) {
        respBody += chunk;
    });
    httpResp.on('end', function (chunk) {
        console.log('Response: ' + respBody);
        context.succeed('Lambda added document ' + doc);
    });
}, function(err) {
    console.log('Error: ' + err);
    context.fail('Lambda failed with error ' + err);
});

More examples can be found here: aws-samples
/
amazon-elasticsearch-lambda-samples


问:
How to share the same X axis in a combined plot without ggplot2?
I'm trying to combine two time series into a plot sharing the same values of the X axis. When I use the code below I got these goals. However, I'd like to display just one X axis for both the series and I also would like to remove the Y axis in the right side of the plot. My dataset is two financial variables from Yahoo Finance. I use the 'quantmod' package to extract the data and the default function 'plot' to visualize the series in the way that I want to.

PS: I got some results using the package 'ggplot2', but they don't fit well to my aim.

```<code>install.packages('quantmod')
library(quantmod)

## Get the data

# OVX
getSymbols(Symbols = "^OVX", from = "2007-05-10",
           to = "2020-01-01", src = "yahoo")

# USO
getSymbols(Symbols = "USO", from = "2007-05-10",
           to = "2020-01-01", src = "yahoo")

## PLOTS

par(mfcol=2:1, xaxt = "s")
plot(USO[, "USO.Adjusted"], main="USO", type = "l", lwd = 0.7, grid.col = NA, axes = F)

plot(OVX[, "OVX.Adjusted"], main="OVX", type = "l", lwd = 0.2, grid.col = NA)

</code>```

I'm not allowed to insert images here yet, then there is a link below to see my plot.

答:
plot.xts becomes aware of your "xts" class. To avoid this, use plot.default and lines.default, then you may easily add axis, mtext etc.

```<code>plot.default(USO$USO.Adjusted, col=2, type="l", xaxt='n',
             main='My TS PLot', xlab='Date', ylab='Unit',
             ylim=c(-10, max(USO[, "USO.Adjusted"])))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
lines.default(OVX$OVX.Adjusted, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))
</code>```

However, the added OVX is tiny and almost invisible. You could magnify the values and use a secondary y-axis, e.g.:

```<code>plot.default(USO$USO.Adjusted, col=2, type="l", axes=F,
             main='My TS PLot', xlab='Date', ylab='Unit',
             ylim=c(-10, max(USO[, "USO.Adjusted"]) + 100))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
axis(2, axTicks(2), labels=F, col=2)
mtext(axTicks(2), 2, 1, at=axTicks(2), col=2)
axis(4, axTicks(2), labels=F, col=3)
mtext((0:5)*20, 4, 1, at=(0:5)*200, col=3)
lines.default(OVX$OVX.Adjusted*10, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))
box()
</code>```

Body:
I'm trying to combine two time series into a plot sharing the same values of the X axis. When I use the code below I got these goals. However, I'd like to display just one X axis for both the series and I also would like to remove the Y axis in the right side of the plot. My dataset is two financial variables from Yahoo Finance. I use the 'quantmod' package to extract the data and the default function 'plot' to visualize the series in the way that I want to.

PS: I got some results using the package 'ggplot2', but they don't fit well to my aim.

install.packages('quantmod')
library(quantmod)

## Get the data

# OVX
getSymbols(Symbols = "^OVX", from = "2007-05-10",
           to = "2020-01-01", src = "yahoo")

# USO
getSymbols(Symbols = "USO", from = "2007-05-10",
           to = "2020-01-01", src = "yahoo")

## PLOTS

par(mfcol=2:1, xaxt = "s")
plot(USO[, "USO.Adjusted"], main="USO", type = "l", lwd = 0.7, grid.col = NA, axes = F)

plot(OVX[, "OVX.Adjusted"], main="OVX", type = "l", lwd = 0.2, grid.col = NA)

I'm not allowed to insert images here yet, then there is a link below to see my plot.

Body:
plot.xts becomes aware of your "xts" class. To avoid this, use plot.default and lines.default, then you may easily add axis, mtext etc.

plot.default(USO$USO.Adjusted, col=2, type="l", xaxt='n',
             main='My TS PLot', xlab='Date', ylab='Unit',
             ylim=c(-10, max(USO[, "USO.Adjusted"])))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
lines.default(OVX$OVX.Adjusted, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))

However, the added OVX is tiny and almost invisible. You could magnify the values and use a secondary y-axis, e.g.:

plot.default(USO$USO.Adjusted, col=2, type="l", axes=F,
             main='My TS PLot', xlab='Date', ylab='Unit',
             ylim=c(-10, max(USO[, "USO.Adjusted"]) + 100))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
axis(2, axTicks(2), labels=F, col=2)
mtext(axTicks(2), 2, 1, at=axTicks(2), col=2)
axis(4, axTicks(2), labels=F, col=3)
mtext((0:5)*20, 4, 1, at=(0:5)*200, col=3)
lines.default(OVX$OVX.Adjusted*10, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))
box()


问:
How to use youtube-dl from a python program?
I would like to access the result of the following shell command,

```<code>youtube-dl -g "www.youtube.com/..."
</code>```

to print its output direct url to a file, from within a python program. This is what I have tried:

```<code>import youtube-dl
fromurl="www.youtube.com/..."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)
</code>```

Is that possible?
I tried to understand the mechanism in the source but got lost: youtube_dl/__init__.py, youtube_dl/youtube_DL.py, info_extractors ...

答:
```<code>from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['Your youtube url'])
</code>```

You can use 'format', 'continue', 'outtmpl' in ydl_opts
As example;

```<code>ydl_opts= {
           'format': '22',
           'continue': True,
           'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
           'progress_hooks': [my_hook],
          }

def my_hook(d):
    if d['status'] == 'downloading':
        print('Downloading video!')
    if d['status'] == 'finished':
        print('Downloaded!')
</code>```

When you need to stop playlist downloading, Just add this code into ydl_opts.

```<code>'noplaylist': True;
</code>```

Body:
I would like to access the result of the following shell command,

youtube-dl -g "www.youtube.com/..."

to print its output direct url to a file, from within a python program. This is what I have tried:

import youtube-dl
fromurl="www.youtube.com/..."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)

Is that possible?
I tried to understand the mechanism in the source but got lost: youtube_dl/__init__.py, youtube_dl/youtube_DL.py, info_extractors ...

Body:
from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['Your youtube url'])

You can use 'format', 'continue', 'outtmpl' in ydl_opts
As example;

ydl_opts= {
           'format': '22',
           'continue': True,
           'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
           'progress_hooks': [my_hook],
          }

def my_hook(d):
    if d['status'] == 'downloading':
        print('Downloading video!')
    if d['status'] == 'finished':
        print('Downloaded!')

When you need to stop playlist downloading, Just add this code into ydl_opts.

'noplaylist': True;


问:
How can I get this ASP.NET MVC SelectList to work?
I create a selectList in my controller, to display in the view.

I'm trying to create it on the fly, sorta thing .. like this...

```<code>myViewData.PageOptionsDropDown =
   new SelectList(new [] {"10", "15", "25", "50", "100", "1000"}, "15");
</code>```

It compiles, but the output is bad...

```<code><select id="PageOptionsDropDown" name="PageOptionsDropDown">
    <option>10</option>
    <option>15</option>
    <option>25</option>
    <option>50</option>
    <option>100</option>
    <option>1000</option>
</select>
</code>```

Notice how no item is selected?

How can I fix this??

答:
Simple:</p>

```<code>string[] someName = new string[] {"10", "15", "25", "50", "100", "1000"};
myViewData.PageOptionsDropDown = new SelectList(someName, "15");
</code>```

Body:
I create a selectList in my controller, to display in the view.

I'm trying to create it on the fly, sorta thing .. like this...

myViewData.PageOptionsDropDown =
   new SelectList(new [] {"10", "15", "25", "50", "100", "1000"}, "15");

It compiles, but the output is bad...

<select id="PageOptionsDropDown" name="PageOptionsDropDown">
    <option>10</option>
    <option>15</option>
    <option>25</option>
    <option>50</option>
    <option>100</option>
    <option>1000</option>
</select>

Notice how no item is selected?

How can I fix this??

Body:
Simple:

string[] someName = new string[] {"10", "15", "25", "50", "100", "1000"};
myViewData.PageOptionsDropDown = new SelectList(someName, "15");


问:
Octave (or MATLAB) / operator
I wonder what / operator does in Octave. (I am not sure whether it works the same way in MATLAB)

```<code>V = [1; 2; 3]
</code>```

then

```<code>1 / V = [0.071429 0.142857 0.214286]
</code>```

I know that ./ operator does element-wise division of vectors or matrices.
Then what does / operator do?

答:
This behavior is described in the documentation:

x / y

Right division. This is conceptually equivalent to the expression

```<code>(inverse (y') * x')'
</code>```

but it is computed without forming the inverse of y’.

If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.

MATLAB has exactly the same behavior, see its documentation.

Title: Octave (or MATLAB) / operator

Body:
I wonder what / operator does in Octave. (I am not sure whether it works the same way in MATLAB)

V = [1; 2; 3]

then

1 / V = [0.071429 0.142857 0.214286]

I know that ./ operator does element-wise division of vectors or matrices.
Then what does / operator do?

Body:
This behavior is described in the documentation:

x / y

Right division. This is conceptually equivalent to the expression

(inverse (y') * x')'

but it is computed without forming the inverse of y’.

If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.

MATLAB has exactly the same behavior, see its documentation.


问:
Remove newline on separate print statements
Here's an example on what I'm trying to achieve :

```<code>print("Hi!")
print("Hello!")
>> Hi! Hello!
</code>```

Whats really happening :

```<code>print("Hi!")
print("Hello!")
>> Hi!
>> Hello!
</code>```

I've tried stuff like sep=" " and print("Hi!"), but those didn't work.

Please don't mark this as duplicate since all the answers for this question don't work for my situation.

https://pastebin.com/57xyqb8C : For my full code.

答:
I think this solves your problem:

print("Hi!", end='')
print("Hello!")

Hi! Hello!
```

Body:
Here's an example on what I'm trying to achieve :

print("Hi!")
print("Hello!")
>> Hi! Hello!

Whats really happening :

print("Hi!")
print("Hello!")
>> Hi!
>> Hello!

I've tried stuff like sep=" " and print("Hi!"), but those didn't work.

Please don't mark this as duplicate since all the answers for this question don't work for my situation.

https://pastebin.com/57xyqb8C : For my full code.


问:
Why does my function that type words out produce garbled output?
In the following code, I expect that it gets the words in all of the .auto-type elements as input, then starts typing them out character-by-character automatically. However, the code I have doesn't work, but it also doesn't produce any errors in the console. What have I missed?

window.onload = () => {
  let elements = document.getElementsByClassName("auto-type");
  for (element of elements) {
    const text = element.innerHTML.toString();
    element.innerHTML = "";
    let charIndex = 0;
    const typing = () => {
      element.innerHTML += text.charAt(charIndex);
      if (charIndex < text.length) {
        setTimeout(typing, 100);
        charIndex++;
      }
    };
    typing();
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}</code>```

hello!

some text

some other text

here is a better text```

答:
The code works but because it's asynchronous, it just happens to be trying to type it all out at the same time. The other reason that it isn't making sense is because it is also trying to type it into the same element.

Investigating the problem

Once rendered, you see this in the HTML of the page:

h

s

s

heooelmmrleeeo   !toietsxh tear  bteetxtter text
```
<p>Focussing on that last line, you can see that each message has been typed into the last element. This can be made more obvious by replacing each character in your original messages with a number:</p>
<pre class="lang-html prettyprint-override"><code><span class="auto-type code">111111</span>
<br />
<span class="auto-type code">222222222</span>
<br />
<div class="auto-type">333333333333333</div>
<span class="auto-type code">444444444444444444444</span>
</code>```

Which renders:

1

2

3

412341234123412341234234234234343434343434444444
```
<p>So that last line is built up like this:</p>
<pre class="lang-none prettyprint-override"><code>heooelmmrleeeo   !toietsxh tear  bteetxtter text
 │││└ the 'e' from "here" in the fourth element
 ││└ the 'o' from "some" in the third element
 │└ the 'o' from "some" in the second element
 └ the 'e' from "hello" in the first element
</code>```

The reason this happens is because of this for-loop, where the variable element is not scoped to the for-loop, meaning that it gets shared by each typing function, and will refer to the last element in elements:

```<code>for (element of elements) { // <- this element variable is a global!
    /* ... */
}
</code>```

You can solve your primary issue by simply redefining that element variable with let or const instead:

```<code>for (const element of elements) { // <- this element variable is now scoped to this for-loop
    /* ... */
}
</code>```

The effect of this change can be seen in the below StackSnippet:

window.onload = () => {
  let elements = document.getElementsByClassName("auto-type");
  for (const element of elements) {
    const text = element.innerHTML.toString();
    element.innerHTML = "";
    let charIndex = 0;
    const typing = () => {
      element.innerHTML += text.charAt(charIndex);
      if (charIndex < text.length) {
        setTimeout(typing, 100);
        charIndex++;
      }
    };
    typing();
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}</code>```

hello!

some text

some other text

here is a better text```
</div>
</div>
</p>
<h2>Other problems</h2>
<p>Because of the nature of JavaScript, it can take a while to load your page and all your dependencies. This means your messages would be visible to the user while the page is loading which probably isn't what you are looking for. So you should hide the messages with CSS and then reveal them when you are ready.</p>
<pre class="lang-css prettyprint-override"><code>.auto-type {
  visibility: hidden; /* like display:none; but still consumes space on the screen */
}
</code>```

Then when you empty the text out, make the element visible again:

const text = element.innerHTML.toString();
element.innerHTML = "";
element.style.visibility = "visible";
```
<h2>Correcting the code</h2>
<p>You need to rework your "type into" function to not fire off until the previous message has been typed out. We can do this by updating each "type into" function to return a Promise and then by chaining those Promises together.</p>
<pre class="lang-js prettyprint-override"><code>/**
 * Types text into the given element, returning a Promise
 * that resolves when all the text has been typed out.
 */
function typeTextInto(element, text, typeDelayMs = 100) {
    return new Promise(resolve => {
        let charIndex = 0;
        const typeNextChar = () => {
            element.innerHTML += text.charAt(charIndex);
            if (charIndex < text.length) {
                setTimeout(typeNextChar, typeDelayMs);
                charIndex++;
            } else {
                resolve(); // finished typing
            }
        };
        typeNextChar(); // start typing
    });
}

window.onload = () => {
    const elements = document.getElementsByClassName("auto-type");
    const elementTextPairs = [];

    // pass 1: empty out the contents
    for (element of elements) {
        const text = element.innerHTML.toString();
        element.innerHTML = "";
        element.style.visibility = "visible";
        elementTextPairs.push({ element, text });
    }

    // pass 2: type text into each element
    let chain = Promise.resolve(); // <- empty Promise to start the chain
    for (elementTextPair of elementTextPairs) {
        const { element, text } = elementTextPair; // unwrap pair
        chain = chain // <- add onto the chain
            .then(() => typeTextInto(element, text));
    }

    // basic error handling
    chain.catch(err => console.error("failed to type all messages:", err));
};
</code>```

This can be futher cleaned up using async/await and splitting the typing logic out into its own function. This is shown in the working StackSnippet below:

/**
 * Types text into the given element, returning a Promise
 * that resolves when all the text has been typed out.
 */
function typeTextInto(element, text, typeDelayMs = 100) {
    return new Promise(resolve => {
        let charIndex = 0;
        const typeNextChar = () => {
            element.innerHTML += text.charAt(charIndex);
            if (charIndex < text.length) {
                setTimeout(typeNextChar, typeDelayMs);
                charIndex++;
            } else {
                resolve(); // finished typing
            }
        };
        typeNextChar(); // start typing
    });
}

window.onload = async () => {
    try {
        const elements = document.getElementsByClassName("auto-type");
        const elementTextPairs = [];

        // pass 1: empty out the contents
        for (element of elements) {
            const text = element.innerHTML.toString();
            element.innerHTML = "";
            element.style.visibility = "visible";
            elementTextPairs.push({ element, text });
        }

        // pass 2: type text into each element
        for (elementTextPair of elementTextPairs) {
            const { element, text } = elementTextPair; // unwrap pair
            await typeTextInto(element, text); // await in a for-loop makes the asynchronous work run one-after-another
        }
    } catch (err) {
        // basic error handling
        console.error("failed to type all messages:", err);
    }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}

.auto-type {
  visibility: hidden;
}</code>```

hello!

some text

some other text

here is a better text```

Body:
In the following code, I expect that it gets the words in all of the .auto-type elements as input, then starts typing them out character-by-character automatically. However, the code I have doesn't work, but it also doesn't produce any errors in the console. What have I missed?

window.onload = () => {
  let elements = document.getElementsByClassName("auto-type");
  for (element of elements) {
    const text = element.innerHTML.toString();
    element.innerHTML = "";
    let charIndex = 0;
    const typing = () => {
      element.innerHTML += text.charAt(charIndex);
      if (charIndex < text.length) {
        setTimeout(typing, 100);
        charIndex++;
      }
    };
    typing();
  }
};

body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}

hello!

some text

some other text

here is a better text

Body:
The code works but because it's asynchronous, it just happens to be trying to type it all out at the same time. The other reason that it isn't making sense is because it is also trying to type it into the same element.

Investigating the problem

Once rendered, you see this in the HTML of the page:

<span class="auto-type code">h</span>
<br>
<span class="auto-type code">s</span>
<br>
<div class="auto-type">s</div>
<span class="auto-type code">heooelmmrleeeo   !toietsxh tear  bteetxtter text</span>

Focussing on that last line, you can see that each message has been typed into the last element. This can be made more obvious by replacing each character in your original messages with a number:

<span class="auto-type code">111111</span>
<br />
<span class="auto-type code">222222222</span>
<br />
<div class="auto-type">333333333333333</div>
<span class="auto-type code">444444444444444444444</span>

Which renders:

<span class="auto-type code">1</span>
<br>
<span class="auto-type code">2</span>
<br>
<div class="auto-type">3</div>
<span class="auto-type code">412341234123412341234234234234343434343434444444</span>

So that last line is built up like this:

heooelmmrleeeo   !toietsxh tear  bteetxtter text
 │││└ the 'e' from "here" in the fourth element
 ││└ the 'o' from "some" in the third element
 │└ the 'o' from "some" in the second element
 └ the 'e' from "hello" in the first element

The reason this happens is because of this for-loop, where the variable element is not scoped to the for-loop, meaning that it gets shared by each typing function, and will refer to the last element in elements:

for (element of elements) { // <- this element variable is a global!
    /* ... */
}

You can solve your primary issue by simply redefining that element variable with let or const instead:

for (const element of elements) { // <- this element variable is now scoped to this for-loop
    /* ... */
}

The effect of this change can be seen in the below StackSnippet:

window.onload = () => {
  let elements = document.getElementsByClassName("auto-type");
  for (const element of elements) {
    const text = element.innerHTML.toString();
    element.innerHTML = "";
    let charIndex = 0;
    const typing = () => {
      element.innerHTML += text.charAt(charIndex);
      if (charIndex < text.length) {
        setTimeout(typing, 100);
        charIndex++;
      }
    };
    typing();
  }
};

body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}

<span class="auto-type code">hello!</span>
<br />
<span class="auto-type code">some text</span>
<br />
<div class="auto-type">some other text</div>
<span class="auto-type code">here is a better text</span>

Other problems

Because of the nature of JavaScript, it can take a while to load your page and all your dependencies. This means your messages would be visible to the user while the page is loading which probably isn't what you are looking for. So you should hide the messages with CSS and then reveal them when you are ready.

.auto-type {
  visibility: hidden; /* like display:none; but still consumes space on the screen */
}

Then when you empty the text out, make the element visible again:

const text = element.innerHTML.toString();
element.innerHTML = "";
element.style.visibility = "visible";

Correcting the code

You need to rework your "type into" function to not fire off until the previous message has been typed out. We can do this by updating each "type into" function to return a Promise and then by chaining those Promises together.

/**
 * Types text into the given element, returning a Promise
 * that resolves when all the text has been typed out.
 */
function typeTextInto(element, text, typeDelayMs = 100) {
    return new Promise(resolve => {
        let charIndex = 0;
        const typeNextChar = () => {
            element.innerHTML += text.charAt(charIndex);
            if (charIndex < text.length) {
                setTimeout(typeNextChar, typeDelayMs);
                charIndex++;
            } else {
                resolve(); // finished typing
            }
        };
        typeNextChar(); // start typing
    });
}

window.onload = () => {
    const elements = document.getElementsByClassName("auto-type");
    const elementTextPairs = [];

    // pass 1: empty out the contents
    for (element of elements) {
        const text = element.innerHTML.toString();
        element.innerHTML = "";
        element.style.visibility = "visible";
        elementTextPairs.push({ element, text });
    }

    // pass 2: type text into each element
    let chain = Promise.resolve(); // <- empty Promise to start the chain
    for (elementTextPair of elementTextPairs) {
        const { element, text } = elementTextPair; // unwrap pair
        chain = chain // <- add onto the chain
            .then(() => typeTextInto(element, text));
    }

    // basic error handling
    chain.catch(err => console.error("failed to type all messages:", err));
};

This can be futher cleaned up using async/await and splitting the typing logic out into its own function. This is shown in the working StackSnippet below:

/**
 * Types text into the given element, returning a Promise
 * that resolves when all the text has been typed out.
 */
function typeTextInto(element, text, typeDelayMs = 100) {
    return new Promise(resolve => {
        let charIndex = 0;
        const typeNextChar = () => {
            element.innerHTML += text.charAt(charIndex);
            if (charIndex < text.length) {
                setTimeout(typeNextChar, typeDelayMs);
                charIndex++;
            } else {
                resolve(); // finished typing
            }
        };
        typeNextChar(); // start typing
    });
}

window.onload = async () => {
    try {
        const elements = document.getElementsByClassName("auto-type");
        const elementTextPairs = [];

        // pass 1: empty out the contents
        for (element of elements) {
            const text = element.innerHTML.toString();
            element.innerHTML = "";
            element.style.visibility = "visible";
            elementTextPairs.push({ element, text });
        }

        // pass 2: type text into each element
        for (elementTextPair of elementTextPairs) {
            const { element, text } = elementTextPair; // unwrap pair
            await typeTextInto(element, text); // await in a for-loop makes the asynchronous work run one-after-another
        }
    } catch (err) {
        // basic error handling
        console.error("failed to type all messages:", err);
    }
};

body {
  background-color: black;
  color: lime;
  font-family: consolas, monospace;
}

.auto-type {
  visibility: hidden;
}

<span class="auto-type code">hello!</span>
<br />
<span class="auto-type code">some text</span>
<br />
<div class="auto-type">some other text</div>
<span class="auto-type code">here is a better text</span>


问:
`java` command is not found from this Python process. Please ensure Java is installed and PATH is set for `java`
I don't know how to fix this error when I'm trying to run the following code:

```<code>df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')
</code>```

Log:

```<code>FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
    107     try:
--> 108         output = subprocess.check_output(args)
    109

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    335     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 336                **kwargs).stdout
    337

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    402
--> 403     with Popen(*popenargs, **kwargs) as process:
    404         try:

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
    996                                          os.fspath(cwd) if cwd is not None else None,
--> 997                                          startupinfo)
    998             finally:

FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

JavaNotFoundError                         Traceback (most recent call last)
<ipython-input-3-010e34a004ec> in <module>()
----> 1 df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')

~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
    109
    110     except FileNotFoundError as e:
--> 111         raise JavaNotFoundError(JAVA_NOT_FOUND_ERROR)
    112
    113     except subprocess.CalledProcessError as e:

JavaNotFoundError: `java` command is not found from this Python process. Please ensure Java is installed and PATH is set for `java`
</code>```

I tried changing and creating the path in the environmental variables but did not work. Here is the screenshot:

Does anyone know how to fix this? I have java version 8 (Checked through about java)

答:
I am also facing the same issue based on my experience, I am sharing here.

Step 1 - After download and completed installation of Java (copy a bin path location and add into environment variables)

Step2 - Add Java PATH location in the environment variable.

Still you are getting same error restart your anaconda and Chrome or restart you pc.

Check below code in command prompt

```<code>java --version
</code>```

Complete Java installation and environment variable path setting up guidance video - link.

Body:
I don't know how to fix this error when I'm trying to run the following code:

df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')

Log:

FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
    107     try:
--> 108         output = subprocess.check_output(args)
    109

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    335     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 336                **kwargs).stdout
    337

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    402
--> 403     with Popen(*popenargs, **kwargs) as process:
    404         try:

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
    996                                          os.fspath(cwd) if cwd is not None else None,
--> 997                                          startupinfo)
    998             finally:

FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

JavaNotFoundError                         Traceback (most recent call last)
<ipython-input-3-010e34a004ec> in <module>()
----> 1 df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')

~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
    109
    110     except FileNotFoundError as e:
--> 111         raise JavaNotFoundError(JAVA_NOT_FOUND_ERROR)
    112
    113     except subprocess.CalledProcessError as e:

JavaNotFoundError: `java` command is not found from this Python process. Please ensure Java is installed and PATH is set for `java`

I tried changing and creating the path in the environmental variables but did not work. Here is the screenshot:

Does anyone know how to fix this? I have java version 8 (Checked through about java)

Body:
I am also facing the same issue based on my experience, I am sharing here.

Step 1 - After download and completed installation of Java (copy a bin path location and add into environment variables)

Step2 - Add Java PATH location in the environment variable.

Still you are getting same error restart your anaconda and Chrome or restart you pc.

Check below code in command prompt

java --version

Complete Java installation and environment variable path setting up guidance video - link.


问:
Recent gyroscope support from Corona SDK seems to be non-responsive
I'm using a recent daily build of the Corona SDK (version 2001.562) to add gyroscope support to an existing application. Unfortunately, I can't seem to get the event-handling function for the gyroscope to fire. The application is running on an iPod touch, version 4.3.3.

I attach the gyroscope to an event handler like so:

```<code>if system.hasEventSource("gyroscope") then
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope on\n");
    io.close(feedbackFile);
    Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
else
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope off\n");
    io.close(feedbackFile);
end
</code>```

When I launch the application on the device, then close it and download the resource files, I find that log.txt contains the line with a timestamp and "gyroscope on". Good so far!

On to the event-handling function:

```<code>local function onGyroscopeDataReceived(event)

    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope reading delta="..event.deltaRotation..",x="..event.xRotation..",y="..event.yRotation..",z="..event.zRotation.."\n");
    io.close(feedbackFile);
end
</code>```

This line of information never appears in the log.txt file!

Please advise. Thanks in advance!

答: Just a wild guess but it may be your listener is never called --- I noticed your onGyroscopeDataReceived function is local.  If that's the case, then you need to make sure the variable is declared prior to the addEventListener call.  </p>

Body:
I'm using a recent daily build of the Corona SDK (version 2001.562) to add gyroscope support to an existing application. Unfortunately, I can't seem to get the event-handling function for the gyroscope to fire. The application is running on an iPod touch, version 4.3.3.

I attach the gyroscope to an event handler like so:

if system.hasEventSource("gyroscope") then
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope on\n");
    io.close(feedbackFile);
    Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
else
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope off\n");
    io.close(feedbackFile);
end

When I launch the application on the device, then close it and download the resource files, I find that log.txt contains the line with a timestamp and "gyroscope on". Good so far!

On to the event-handling function:

local function onGyroscopeDataReceived(event)

    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope reading delta="..event.deltaRotation..",x="..event.xRotation..",y="..event.yRotation..",z="..event.zRotation.."\n");
    io.close(feedbackFile);
end

This line of information never appears in the log.txt file!

Please advise. Thanks in advance!


问:
Check list element parts for mandatory array
I have a string list of files with the same names but different extensions and an array of extensions.
Every file name must have every extension and I want to output all missing pairs.
Is there good LINQ for it?

var files = new List<string>() { "file2.jpg", "file1.jpg", "file1.png", "file2.bmp", "file3.png", "file1.bmp" };
var exts = new[] { ".png", ".bmp", ".jpg" };
```
<p>The result must be like this</p>
```file2 missing .png
file3 missing .bmp, .jpg
```

答:
```<code> var files = new List<string>() { "file2.jpg", "file1.jpg", "file1.png", "file2.bmp", "file3.png", "file1.bmp" };
        var exts = new[] { ".png", ".bmp", ".jpg" };

        var fileGroups = files
            .GroupBy(c => Path.GetFileNameWithoutExtension(c), v => Path.GetExtension(v))
            .Select(x => new { File = x.Key, MissingExts = exts.Except(x) })
            .Where(x=> x.MissingExts.Any());

        foreach(var group in fileGroups)
        {
            Console.WriteLine($"{group.File} {string.Join(' ', group.MissingExts)}");
        }
</code>```

Body:
I have a string list of files with the same names but different extensions and an array of extensions.
Every file name must have every extension and I want to output all missing pairs.
Is there good LINQ for it?

var files = new List<string>() { "file2.jpg", "file1.jpg", "file1.png", "file2.bmp", "file3.png", "file1.bmp" };
var exts = new[] { ".png", ".bmp", ".jpg" };

The result must be like this

file2 missing .png
file3 missing .bmp, .jpg


问:
Why can't I access port 80 when I can access port 8080?
I have deployed my web application via AWS EC2. I have made inbound rules as below.

Inbound Rules

I can now access through myIP:8080 but I get an error with myIP or myIP:80. The error message I get is: This site can’t be reached. refused to connect. Try: Checking the connection. Checking the proxy and the firewall. ERR_CONNECTION_REFUSED

What am I doing wrong in here?

答:
I have managed to resolve the issue by port forwarding with the following command:

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080


问:
How to access specific information in json?
I made an authentication method in a WEB API and I'm getting the answer below:

```<code>I/Response
{
"login": "teste@teste.com",
"senha": "12345dxkjs",
"token":"kjqwdjqwdjlqkwjqkwdjqwdjwdqkwjlqjwkdqwjl", ....
}
</code>```

I use the code below to read the information:

```<code>String data = response.body().string();
Log.e("response", data);
</code>```

How can I access only the token that is in the array?
How do I do this using java/android?

答:
Use this command

String data = response.body().string();
JSONObject Jobject = new JSONObject(data);
Log.e("response", Jobject.getString("token"));
```

After parsing the string to the JSONObject you can access any item in the JSON, like 'token'.

Body:
I made an authentication method in a WEB API and I'm getting the answer below:

I/Response
{
"login": "teste@teste.com",
"senha": "12345dxkjs",
"token":"kjqwdjqwdjlqkwjqkwdjqwdjwdqkwjlqjwkdqwjl", ....
}

I use the code below to read the information:

String data = response.body().string();
Log.e("response", data);

How can I access only the token that is in the array?
How do I do this using java/android?

Body:
Use this command

String data = response.body().string();
JSONObject Jobject = new JSONObject(data);
Log.e("response", Jobject.getString("token"));

After parsing the string to the JSONObject you can access any item in the JSON, like 'token'.


问:
Is there a way to get corresponding index value in a 2nd array using the 1st array as a reference in Javascript?
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

```<code>function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}
</code>```

答:
Another option is to make use of the Map object, which allows the creation of a list of key-value pairs.  Then, if the key is known, the value can immediately be gotten.

Under the hood this usually done via a hashing algorithm on the key, in which case the lookup for the key does not involve looping through all keys, but instead generates the hash from the key, a hash which is then used to directly find the value in the list.  (It's a bit more complicated than that, but you can find out more by searching on array hashing techniques.)

So, the first step is to initialize the Map object by mapping the written version of the number as the key to the actual value of the number.

Then, once this mapping is created, for every instance where the lookup is required, it simply involves getting the value from the map.

function createMap( keyArray, valueArray ) {
  let map = new Map();
  for ( let i = 0; i < keyArray.length; i++ ) {
    map.set( keyArray[ i ], valueArray[ i ] );
  }
  return map;
}

let myMap = createMap(
  ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"],
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
)

console.log( myMap.get( "four" ) );
console.log( myMap.get( "two" ) );```

This then has the distinct advantage of directly returning the value corresponding to the key without having to search the list of keys every time...

Body:
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}

Body:
Another option is to make use of the Map object, which allows the creation of a list of key-value pairs.  Then, if the key is known, the value can immediately be gotten.

Under the hood this usually done via a hashing algorithm on the key, in which case the lookup for the key does not involve looping through all keys, but instead generates the hash from the key, a hash which is then used to directly find the value in the list.  (It's a bit more complicated than that, but you can find out more by searching on array hashing techniques.)

So, the first step is to initialize the Map object by mapping the written version of the number as the key to the actual value of the number.

Then, once this mapping is created, for every instance where the lookup is required, it simply involves getting the value from the map.

function createMap( keyArray, valueArray ) {
  let map = new Map();
  for ( let i = 0; i < keyArray.length; i++ ) {
    map.set( keyArray[ i ], valueArray[ i ] );
  }
  return map;
}

let myMap = createMap(
  ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"],
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
)

console.log( myMap.get( "four" ) );
console.log( myMap.get( "two" ) );

This then has the distinct advantage of directly returning the value corresponding to the key without having to search the list of keys every time...


答:
The end keyword is used for this in python. You could have any value for it:

```<code>print("Hi!", end=' ')
print("Hello!")

>>> Hi! Hello!

print("Hi!", end = ' This is a string \n')
print("Hello!")

>>> Hi! This is a string
>>> Hello!
</code>```

Title: Remove newline on separate print statements

Body:
The end keyword is used for this in python. You could have any value for it:

print("Hi!", end=' ')
print("Hello!")

>>> Hi! Hello!

print("Hi!", end = ' This is a string \n')
print("Hello!")

>>> Hi! This is a string
>>> Hello!


答:
You can use a JSON path function:

```<code>select qualif_id,
       jsonb_path_query_array(qualif_assessment_formats,
                              '$[*] ? (@.af_branch == "BR0000000000005")')
from the_table
</code>```

The function iterates through all array elements and returns those that match the condition specified after the ? operator.

Title: Postgresql remove object from jsonb array of objects by key value

Body:
So I've got this table, with formats text and jsonb respectively.

    qualif_id    |                                                                                qualif_assessment_formats
-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 QL0000000000003 | [{"af_sum": 432, "af_branch": "BR0000000000001", "af_currency": "EUR", "af_app_deadline": "25-10-2022 12:00:00", "af_acquire_datetime": "10-11-2022"}]
 QL0000000000004 | [{"af_sum": 432, "af_branch": "BR0000000000001", "af_currency": "EUR", "af_app_deadline": "25-10-2022 12:00:00", "af_acquire_datetime": "10-11-2022"}, {"af_sum": 432, "af_branch": "BR0000000000005", "af_currency": "EUR", "af_app_deadline": "25-10-2022 12:00:00", "af_acquire_datetime": "10-11-2022"}]

What I'm trying to do is to make a query, which would remove the object from each array, which contains a specific af_branch value, for example 'BR0000000000001'. So the result would look like that:

    qualif_id    |                                                                                qualif_assessment_formats
-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 QL0000000000003 | []
 QL0000000000004 | [{"af_sum": 432, "af_branch": "BR0000000000005", "af_currency": "EUR", "af_app_deadline": "25-10-2022 12:00:00", "af_acquire_datetime": "10-11-2022"}]

Again, having only 'BR0000000000001' for entry. Tried both using jsonb_to_recodset, then filter by it, then jsonb_agg to bring it back to the state... And also with jsonb_query_path_array, but all seems not working.

Body:
You can use a JSON path function:

select qualif_id,
       jsonb_path_query_array(qualif_assessment_formats,
                              '$[*] ? (@.af_branch == "BR0000000000005")')
from the_table

The function iterates through all array elements and returns those that match the condition specified after the ? operator.


问:
Move backdrop filter element behind absolute positioned element
Here's the problem

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blur">
This is the blurred container
  <div class="must-be-top">This div must be on top</div>
</div>
<div class="v-space"></div>
<div class="must-be-behind blur">This div must be behind</div></code>```

I'm looking for a workaround to make the red div go over the blurred div. I've already read about stacking order and painting order but couldn't come up with any solution. Any ideas?

UPDATE

I need the red div to be on top of any element regardless of what they are, and I'm not in control of editing them.

答:
Add this line to your CSS and you will get what you want:

.must-be-behind {z-index:-1; position:relative;}
```
<p>The reason is without any <code>z-index</code> defined, your <code>.blur</code> div will treat the second one higher than the first one. What I did is set the <code>.must-be-behind</code> always be behind, and to have <code>z-index</code> to work, we need a positioned element.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}
.must-be-behind {z-index:-1; position:relative;}</code>```

This is the blurred container

This div must be on top

This div must be behind
```

Body:
Here's the problem

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}

This is the blurred container

This div must be on top

This div must be behind

I'm looking for a workaround to make the red div go over the blurred div. I've already read about stacking order and painting order but couldn't come up with any solution. Any ideas?

UPDATE

I need the red div to be on top of any element regardless of what they are, and I'm not in control of editing them.

Body:
Add this line to your CSS and you will get what you want:

.must-be-behind {z-index:-1; position:relative;}

The reason is without any z-index defined, your .blur div will treat the second one higher than the first one. What I did is set the .must-be-behind always be behind, and to have z-index to work, we need a positioned element.

* {
  color: white;
}

.must-be-top {
  background-color: red;
  height: 200px;
  width: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 1999;
}

.v-space {
  height: 10px;
}

.blur {
  height: 50px;
  width: 400px;
  background-color: rgba(0, 0, 0, .8);
  backdrop-filter: blur(10px);
}
.must-be-behind {z-index:-1; position:relative;}

<div class="blur">
This is the blurred container
  <div class="must-be-top">This div must be on top</div>
</div>
<div class="v-space"></div>
<div class="must-be-behind blur">This div must be behind</div>


问:
Python code to remove records with two or more empty fields
I want to remove records which have 2 or more NaNs, but so far all the code I have found online is either for removing one NaN or not relevant to this situation (e.g. Thresh, any and all).

The code I use for at least 1 NaN is df_exercise.isnull().any(axis=1).

I’m not sure how to adapt this specifically to 2 or more NaNs.

答:
You count the number of empty fields per row and only keep those with fewer than 2 empty fields.

keep = df_exercise.isnull().sum(axis=1).lt(2)
df_exercise[keep]
```


问:
Hint oracle to use indexes on the subquery -- Oracle SQl
I have a query as follows

```<code>select *
from
( select id,sum(amt) amt from table_t group by id
) t inner join table_v v on (v.id = t.id)
order by t.amt desc;
</code>```

table_t has no index and has 738,000 rows and table_v has an index on id and has 158,000 rows.

The query currently fetches the results in 10 seconds.

The explain query plan shows a full table scan.. How can I improve the performance here ?

If I add an index on id for table_t will it help. Because I am using it in a subquery ?

答:
If you have an index on (id,amt) you would minimise the work in the group by/summation process (as it could read the index). If both columns are nullable then you may need to add a "where id is not null" so it will use the index. [That's implied by the later join on id, but may not get inferred by the optimizer.]

Next step would be to use a materialized view for the summation, maybe with an index on (amt,id) (which it could use to avoid the sort). But that is refreshed either at a commit or on request or at scheduled intervals. It doesn't help if you need to do this query as part of a transaction.

Both the index and the materialized view would add work to inserts/updates/deletes on the table but save work in this query.

Body:
I have a query as follows

select *
from
( select id,sum(amt) amt from table_t group by id
) t inner join table_v v on (v.id = t.id)
order by t.amt desc;

table_t has no index and has 738,000 rows and table_v has an index on id and has 158,000 rows.

The query currently fetches the results in 10 seconds.

The explain query plan shows a full table scan.. How can I improve the performance here ?

If I add an index on id for table_t will it help. Because I am using it in a subquery ?


问:
Create a conditional function if 502 Bad Gateway happens
I would like to create a conditional function in python, which return something else if 502 Bad Gateway happens.

def getData(request):
   url = "https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/resource/d1bfe1ad-
          6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv"

   if not 502 Bad Gateway:
       return pd.read_csv(url)
   else:
       return 'None'
```

502-Bad-Gateway

I would highly appreciate it if you could please help me to write that function.

答:
```<code>import pandas as pd
from urllib.error import HTTPError

def getEpiPhu():
    ROOT_DIR = Path(__file__).parent.parent
    path = os.path.join(ROOT_DIR, "data", "epi_phu.csv") # path of the earlier servion of data
    epi_data = pd.read_csv(path) # read the data
    try:
        # download the current version of data
        epi_phu = pd.read_csv("https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/d1bfe1ad-6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv")
        epi_phu.columns = [x.lower() for x in epi_phu.columns.values]
        epi_data.columns = [x.lower() for x in epi_data.columns.values]
        today = datetime.date.today().strftime("%Y-%m-%d")
        # check if the earlier version of data was updated to the current date.
        if epi_data['file_date'].unique()[-1] < today:
            epi_phu.to_csv(path) # save the current version of data and replace the earlier data to local drive for later use as the latter was not up-to-date.
            return epi_phu
        else:
            return epi_phu # use the current data

    except HTTPError as e:
        if e.code == 502 or 404: # 502 for bad gateway; 404 for not found
            return epi_data # use the most updated version of data
        else:
            return HttpResponse('Failure: ' + str(e.reason)) # show reason for failure

</code>```

Body:
I would like to create a conditional function in python, which return something else if 502 Bad Gateway happens.

def getData(request):
   url = "https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/resource/d1bfe1ad-
          6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv"

   if not 502 Bad Gateway:
       return pd.read_csv(url)
   else:
       return 'None'

502-Bad-Gateway

I would highly appreciate it if you could please help me to write that function.


问:
How to change the selected text background highlight color in vscode editor?
I want to change the selected text background highlight color in the vscode code editor.

The default seem to be some kind of light-blue for the selected word, and some kind of gray for the other words with same text.

How do I change the background color of these selected items?

For example, I would like the gray shade to be Goldenrod (#FFDAA520).

答:
I found it after a lot of trial & error:

    "workbench.colorCustomizations": {
        //"editor.findMatchHighlightBackground": "#DAA520",
        //"editor.findRangeHighlightBackground": "#DAA520",
        "editor.selectionHighlightBackground": "#DAA520",
        //"editor.inactiveSelectionBackground": "#DAA520",
        //"editor.findMatchBackground": "#DAA520",
    }

```


问:
How to make camera movement in a pygame 3d engine from scratch?
I am new to matrices and matrix transformations and other things. I am making a 3d engine of my own in pygame using 2d, but I ran into a problem. I can't get my engine to implement camera movement and it only does camera rotation. Here is my code:

window.py: The custom window class

```<code>from .general_imports import *

class Py3dWindow:
    def __init__(self, title=None, width=800, height=600,):
        self.title = title
        self.window = None
        self.width = width
        self.height = height
        self.meshes = []
        self.events_assinged = False

        self.projection_matrix = np.matrix([
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ])
        print(self.projection_matrix)

        self.camera = [
            [0, 0, 0, 0],
            [0, 0, 0],
            75, # fov
            1, # near
            1000 # far
        ]

    def add_mesh(self, mesh):
        self.meshes.append(mesh)

    def translate_matrix(self):
        angle_x = math.radians(self.camera[1][0])
        angle_y = math.radians(self.camera[1][1])
        angle_z = math.radians(self.camera[1][2])

        pos_x = self.camera[0][0]
        pos_y = self.camera[0][1]
        pos_z = self.camera[0][2]

        rotation_z = np.matrix([
            [int(np.cos(angle_z)), -int(np.sin(angle_z)), 0, 0],
            [int(np.sin(angle_z)), int(np.cos(angle_z)), 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ],)

        rotation_y = np.matrix([
            [int(np.cos(angle_y)), 0, int(np.sin(angle_y))],
            [0, 1, 0, 0],
            [-int(np.sin(angle_y)), 0, int(np.cos(angle_y))],
            [0, 0, 0, 1]
        ])

        rotation_x = np.matrix([
            [1, 0, 0, 0],
            [0, int(np.cos(angle_x)), -int(np.sin(angle_x)), 0],
            [0, int(np.sin(angle_x)), int(np.cos(angle_x)), 0],
            [0, 0, 0, 1],
        ])

        position_matrix = np.matrix([
            [1, 0, 0, pos_x],
            [0, 1, 0, pos_y],
            [0, 0, 1, pos_z],
            [0, 0, 0, 1],
        ])

        self.projection_matrix = np.dot(rotation_z, np.dot(rotation_y, rotation_x)) * position_matrix

        print(self.projection_matrix)

    def init_window(self):
        pygame.init()
        self.window = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
        pygame.display.set_caption(self.title)
        self.running = False

    def run(self,):
        self.running = True
        while self.running:
            self.draw()
            self.events(pygame.event.get())
            self.update()
            self.translate_matrix()
        pygame.quit()

    def events(self, events):
        for event in events:
            if event.type == pygame.QUIT:
                self.running = False
        if self.events_assinged:
            self._events(events)

    def update(self,):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

    def draw(self,):
        self.window.fill((0, 0, 0))
        for mesh in self.meshes:
            mesh.draw(self.window)
        pygame.display.update()
        time.sleep(0.001)

    def on_events(self, func):
        self._events = func
        self.events_assinged = True

    def on_update(self, func):
        self.update = lambda: func()

    def on_draw(self, func):
        self.draw = lambda: func()

</code>```

mesh.py: Mesh class

```<code>from .general_imports import *

class Mesh:
    def __init__(self, parnet):
        self.points = []
        self.parent = parnet

    def add_point(self, position):
        position = [position[0] * 100, position[1] * 100, position[2] * 100, 1]
        self.points.append(np.matrix(position))

    def draw(self, window):
        for point in self.points:
            p = (point - self.parent.camera[0])
            p = np.reshape(p, (4, 1))
            projection = np.dot(self.parent.projection_matrix, p)
            projection = projection.tolist()
            x = projection[0][0]
            y = projection[1][0]
            pygame.draw.circle(window, (255, 255, 255), (int(x) + window.get_width() / 2 - 100, int(y) + window.get_width() / 2- 100) , 1)

</code>```

demo.py: The demo

```<code># Py3D demo

from Py3D.__init__ import *
import random

win = Py3dWindow(title="Py3D")
win.init_window()

mesh_ = Mesh(win)

side = 1

for i in range(-side, side):
    for j in range(-side, side):
        for k in range(-side, side):
            mesh_.add_point((i, j, k))

win.add_mesh(mesh_)

def move(events):
    for i in events:
        if i.type == 771:
            if i.text == 'w':
                win.camera[0][2] -= 1
            if i.text == 's':
                win.camera[0][2] += 1
            if i.text == 'a':
                win.camera[0][0] -= 1
            if i.text == 'd':
                win.camera[0][0] += 1

def rotate():
    win.camera[1][0] = 45
    win.camera[1][1] = 45
    win.camera[1][2] = 45

win.on_events(move)
win.on_update(rotate)
win.run()

</code>```

Errors

```<code>ValueError: shapes (4,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)
</code>```

答:
The solution I found

In the translate_matrix function, I forgot to add four indexes to the whole array in rotation_y. That's it! It worked fine!

Body:
I am new to matrices and matrix transformations and other things. I am making a 3d engine of my own in pygame using 2d, but I ran into a problem. I can't get my engine to implement camera movement and it only does camera rotation. Here is my code:

window.py: The custom window class

from .general_imports import *

class Py3dWindow:
    def __init__(self, title=None, width=800, height=600,):
        self.title = title
        self.window = None
        self.width = width
        self.height = height
        self.meshes = []
        self.events_assinged = False

        self.projection_matrix = np.matrix([
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ])
        print(self.projection_matrix)

        self.camera = [
            [0, 0, 0, 0],
            [0, 0, 0],
            75, # fov
            1, # near
            1000 # far
        ]

    def add_mesh(self, mesh):
        self.meshes.append(mesh)

    def translate_matrix(self):
        angle_x = math.radians(self.camera[1][0])
        angle_y = math.radians(self.camera[1][1])
        angle_z = math.radians(self.camera[1][2])

        pos_x = self.camera[0][0]
        pos_y = self.camera[0][1]
        pos_z = self.camera[0][2]

        rotation_z = np.matrix([
            [int(np.cos(angle_z)), -int(np.sin(angle_z)), 0, 0],
            [int(np.sin(angle_z)), int(np.cos(angle_z)), 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ],)

        rotation_y = np.matrix([
            [int(np.cos(angle_y)), 0, int(np.sin(angle_y))],
            [0, 1, 0, 0],
            [-int(np.sin(angle_y)), 0, int(np.cos(angle_y))],
            [0, 0, 0, 1]
        ])

        rotation_x = np.matrix([
            [1, 0, 0, 0],
            [0, int(np.cos(angle_x)), -int(np.sin(angle_x)), 0],
            [0, int(np.sin(angle_x)), int(np.cos(angle_x)), 0],
            [0, 0, 0, 1],
        ])

        position_matrix = np.matrix([
            [1, 0, 0, pos_x],
            [0, 1, 0, pos_y],
            [0, 0, 1, pos_z],
            [0, 0, 0, 1],
        ])

        self.projection_matrix = np.dot(rotation_z, np.dot(rotation_y, rotation_x)) * position_matrix

        print(self.projection_matrix)

    def init_window(self):
        pygame.init()
        self.window = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
        pygame.display.set_caption(self.title)
        self.running = False

    def run(self,):
        self.running = True
        while self.running:
            self.draw()
            self.events(pygame.event.get())
            self.update()
            self.translate_matrix()
        pygame.quit()

    def events(self, events):
        for event in events:
            if event.type == pygame.QUIT:
                self.running = False
        if self.events_assinged:
            self._events(events)

    def update(self,):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

    def draw(self,):
        self.window.fill((0, 0, 0))
        for mesh in self.meshes:
            mesh.draw(self.window)
        pygame.display.update()
        time.sleep(0.001)

    def on_events(self, func):
        self._events = func
        self.events_assinged = True

    def on_update(self, func):
        self.update = lambda: func()

    def on_draw(self, func):
        self.draw = lambda: func()

mesh.py: Mesh class

from .general_imports import *

class Mesh:
    def __init__(self, parnet):
        self.points = []
        self.parent = parnet

    def add_point(self, position):
        position = [position[0] * 100, position[1] * 100, position[2] * 100, 1]
        self.points.append(np.matrix(position))

    def draw(self, window):
        for point in self.points:
            p = (point - self.parent.camera[0])
            p = np.reshape(p, (4, 1))
            projection = np.dot(self.parent.projection_matrix, p)
            projection = projection.tolist()
            x = projection[0][0]
            y = projection[1][0]
            pygame.draw.circle(window, (255, 255, 255), (int(x) + window.get_width() / 2 - 100, int(y) + window.get_width() / 2- 100) , 1)

demo.py: The demo

# Py3D demo

from Py3D.__init__ import *
import random

win = Py3dWindow(title="Py3D")
win.init_window()

mesh_ = Mesh(win)

side = 1

for i in range(-side, side):
    for j in range(-side, side):
        for k in range(-side, side):
            mesh_.add_point((i, j, k))

win.add_mesh(mesh_)

def move(events):
    for i in events:
        if i.type == 771:
            if i.text == 'w':
                win.camera[0][2] -= 1
            if i.text == 's':
                win.camera[0][2] += 1
            if i.text == 'a':
                win.camera[0][0] -= 1
            if i.text == 'd':
                win.camera[0][0] += 1

def rotate():
    win.camera[1][0] = 45
    win.camera[1][1] = 45
    win.camera[1][2] = 45

win.on_events(move)
win.on_update(rotate)
win.run()

Errors

ValueError: shapes (4,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)


问:
Installed Service Pack 3 for SQL Server 2005 but it does not show up when selecting @@version
We installed Service Pack 3 for SQL Server 2005 Standard Edition (64-bit). In the Add or Remove Programs menu we have the following entries under Microsoft SQL Server 2005 (64-bit):

Service Pack 3 for SQL Server Integration Services 64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Notification Services 2005 (64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Database Services 2005 (64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Tools and Workstation Components 2005 (64-bit) ENU (KB955706)

But when I run the following query on the server:

```<code>select @@version
</code>```

I get this result:

Microsoft SQL Server 2005 - 9.00.4035.00 (X64)

Nov 24 2008 16:17:31

Copyright (c) 1988-2005 Microsoft Corporation

Standard Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2)

Why does it not display that it is running Service Pack 3?

答: The version 9.00.4035 uniquely identifies SP3, although it doesn't explicitly state SP3.  That SP2 that you see is referring to the operating system, not the SQL Server.  See Microsoft's KB article on SQL versions.</p>

OwnerDisplayName: Blegger

Body:
We installed Service Pack 3 for SQL Server 2005 Standard Edition (64-bit). In the Add or Remove Programs menu we have the following entries under Microsoft SQL Server 2005 (64-bit):

Service Pack 3 for SQL Server Integration Services 64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Notification Services 2005 (64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Database Services 2005 (64-bit) ENU (KB955706)

Service Pack 3 for SQL Server Tools and Workstation Components 2005 (64-bit) ENU (KB955706)

But when I run the following query on the server:

select @@version

I get this result:

Microsoft SQL Server 2005 - 9.00.4035.00 (X64)

Nov 24 2008 16:17:31

Copyright (c) 1988-2005 Microsoft Corporation

Standard Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2)

Why does it not display that it is running Service Pack 3?

OwnerDisplayName: Scott W


问:
Syntax Error: unexpected $end when using if/else if?
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

```<code>SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end
</code>```

Here is terms_controller.rb:

```<code>class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end
</code>```

My show page currently just consists of:

```<code><h1> <%= @title %> </h1>
</code>```

It's probably something small that I'm just missing - thanks for your help!

答: Instead of else if use elsif.

Body:
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end

Here is terms_controller.rb:

class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end

My show page currently just consists of:

 <%= @title %>

It's probably something small that I'm just missing - thanks for your help!

Body: Instead of else if use elsif.


问:
RecyclerView data not showing
My ReycyclerView is not showing data, but once i removed .setHasFixedSize(true), then only it will display. However, this causes another problem. On the first time entering the fragment, it works fine, my actionBar is displaying, but on the second time, it somehow overlaps or pushes away my ActionBar.

I guess .sethasFixedSize is necessary but if i keep it, it will not display data. What causes this?

First time entering:

Second time entering (before notifyItemInserted()):

After notifyItemInserted():

fragment.xml:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/cartItemRv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
</code>```

fragment.kt:

```<code>onCreateView() {
    binding.cartItemRv.layoutManager = LinearLayoutManager(context)
    binding.cartItemRv.setHasFixedSize(true)
    cartAdapter = CartAdapter(productNameList, productVariationList, cartItemList)
    binding.cartItemRv.adapter = cartAdapter

    //code for retrieving data from Firebase
    cartAdapter.notifyItemInserted(productNameList.size-1)
}
</code>```

Adapter:

```<code>class CartAdapter(...: RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(itemView, mListener)
    }

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        ...
    }

    override fun getItemCount(): Int {
        return productNameList.size
    }

    inner class CartViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
        ...
    }
}
</code>```

答:
add NestedScrollView on the parent of RecyclerView

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/cartItemRv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:nestedScrollingEnabled="false"/>

    </androidx.core.widget.NestedScrollView>

</RelativeLayout>
</code>```

Then set RecyclerView

```<code>cartItemRv.setHasFixedSize(false);
</code>```

Title: RecyclerView data not showing

Body:
My ReycyclerView is not showing data, but once i removed .setHasFixedSize(true), then only it will display. However, this causes another problem. On the first time entering the fragment, it works fine, my actionBar is displaying, but on the second time, it somehow overlaps or pushes away my ActionBar.

I guess .sethasFixedSize is necessary but if i keep it, it will not display data. What causes this?

First time entering:

Second time entering (before notifyItemInserted()):

After notifyItemInserted():

fragment.xml:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/cartItemRv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

fragment.kt:

onCreateView() {
    binding.cartItemRv.layoutManager = LinearLayoutManager(context)
    binding.cartItemRv.setHasFixedSize(true)
    cartAdapter = CartAdapter(productNameList, productVariationList, cartItemList)
    binding.cartItemRv.adapter = cartAdapter

    //code for retrieving data from Firebase
    cartAdapter.notifyItemInserted(productNameList.size-1)
}

Adapter:

class CartAdapter(...: RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(itemView, mListener)
    }

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        ...
    }

    override fun getItemCount(): Int {
        return productNameList.size
    }

    inner class CartViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
        ...
    }
}

Body:
add NestedScrollView on the parent of RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/cartItemRv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:nestedScrollingEnabled="false"/>

    </androidx.core.widget.NestedScrollView>

</RelativeLayout>

Then set RecyclerView

cartItemRv.setHasFixedSize(false);


问:
How can eslint be configured to work with svelte and postcss-nesting?
Using postcss with plugin postcss-nesting in svelte is quite easy -- adding postcss-nesting to the preprocess config in svelte.config.js is the only thing needed:

```<code>import preprocess from "svelte-preprocess";
import postcssNesting from "postcss-nesting";

const config = {
    preprocess: preprocess({
        postcss: {
            plugins: [
                postcssNesting()
            ]
        }
    }),
    // ...
};

export default config;
</code>```

Now I can define nested CSS using the "&" syntax.

For example, when I have this in an example.svelte file:

```<code><div class="example">
    One <span class="nested">two</span> three
</div>

<style lang="postcss">
    .example {
        color: red;
        & .nested {
            text-decoration: underline;
        }
    }
</style>
</code>```

However, I was not able to find a way that eslint does accept it.
It reports that an identifier is expected after the & character.

答:
I had the same problem with postcss-nested when added postcss as npx script npx svelte-add@latest postcss. Adding postcss manually and setting postcss plugins in rollup.config.js like described in svelte-preprocess documentation instead of npx variant however works well.

Install dependencies npm i postcss postcss-nested -D

Replace preprocess: sveltePreprocess({ sourceMap: !production }), line with
```<code>preprocess: sveltePreprocess({
 sourceMap: !production,
 postcss: {
     plugins: [
         require('postcss-nested')()
     ]
 }
}),
</code>```

Body:
Using postcss with plugin postcss-nesting in svelte is quite easy -- adding postcss-nesting to the preprocess config in svelte.config.js is the only thing needed:

import preprocess from "svelte-preprocess";
import postcssNesting from "postcss-nesting";

const config = {
    preprocess: preprocess({
        postcss: {
            plugins: [
                postcssNesting()
            ]
        }
    }),
    // ...
};

export default config;

Now I can define nested CSS using the "&" syntax.

For example, when I have this in an example.svelte file:

    One two three

However, I was not able to find a way that eslint does accept it.
It reports that an identifier is expected after the & character.

Body:
I had the same problem with postcss-nested when added postcss as npx script npx svelte-add@latest postcss. Adding postcss manually and setting postcss plugins in rollup.config.js like described in svelte-preprocess documentation instead of npx variant however works well.

Install dependencies npm i postcss postcss-nested -D

Replace preprocess: sveltePreprocess({ sourceMap: !production }), line with

preprocess: sveltePreprocess({
 sourceMap: !production,
 postcss: {
     plugins: [
         require('postcss-nested')()
     ]
 }
}),


答:
The key to success is to count NaN cases in each row and check whether
it is less than your threshold.
You can get it running:

```<code>df_exercise.isnull().sum(axis=1) < 2
</code>```

And to drop rows exceeding this threshold (keep rows within the threshold),
run:

```<code>df_exercise = df_exercise[df_exercise.isnull().sum(axis=1) < 2]
</code>```

Title: Python code to remove records with two or more empty fields

Body:
I want to remove records which have 2 or more NaNs, but so far all the code I have found online is either for removing one NaN or not relevant to this situation (e.g. Thresh, any and all).

The code I use for at least 1 NaN is df_exercise.isnull().any(axis=1).

I’m not sure how to adapt this specifically to 2 or more NaNs.

Body:
The key to success is to count NaN cases in each row and check whether
it is less than your threshold.
You can get it running:

df_exercise.isnull().sum(axis=1) < 2

And to drop rows exceeding this threshold (keep rows within the threshold),
run:

df_exercise = df_exercise[df_exercise.isnull().sum(axis=1) < 2]


问:
Postgresql unique index: only one date for one foreign key
I have a table "foo":

```<code>ID   PRODUCT_ID  END_DATE
------------------------------
1    1           NULL
2    1           2022-02-02
3    1           2022-01-06 - This date could not be exists
4    2           NULL
5    2           2022-01-23
6    3           NULL
7    3           NULL
</code>```

How can i make unique index for one product whith the same id only one date can exist?

答:
Create a conditional unique index:</p>
```<code>CREATE UNIQUE INDEX u_productid_end_date_not_null
ON foo(product_Id)
WHERE end_date IS NOT NULL; -- this one will do the trick
</code>```

Body:
I have a table "foo":

ID   PRODUCT_ID  END_DATE
------------------------------
1    1           NULL
2    1           2022-02-02
3    1           2022-01-06 - This date could not be exists
4    2           NULL
5    2           2022-01-23
6    3           NULL
7    3           NULL

How can i make unique index for one product whith the same id only one date can exist?

Body:
Create a conditional unique index:

CREATE UNIQUE INDEX u_productid_end_date_not_null
ON foo(product_Id)
WHERE end_date IS NOT NULL; -- this one will do the trick