问:
My Loop of the Loop is painstakingly slow
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

```<code>Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}
</code>```

答:
you can half the processing time by removing duplicate comparisons.
I.e. once you compared "title1" and "title2", you don't need to compare "title2" and "title1" - you already know the answer.
So, your inner loop should not start from the beginning of the array</p>

Body:
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}


来源: stackexchange

问:
Files writable by PHP even though CHMOD is 555?
I've got a new server and when using my php script, I'm able to write files and detect them as being writable even though CHMOD has them as 555 or 755. Is there an apache module or php.ini that is making this possible? Is this a security problem?</p>

答:
What filesystem is your server/volume using?

Some filesystems use different permission schemes, like Access Control Lists in addition to or instead of Unix permissions.  For example, you might be using AFS or OpenAFS (Andrew File System) which uses ACL's, in which case you'd have to enter a completely different command to change access.  Ask your network administrator; they should be able to answer that.  Or you  can try running

```<code>df -T
</code>```

to see what that gives you.

ContentLicense: CC BY-SA 3.0

Body:
What filesystem is your server/volume using?

Some filesystems use different permission schemes, like Access Control Lists in addition to or instead of Unix permissions.  For example, you might be using AFS or OpenAFS (Andrew File System) which uses ACL's, in which case you'd have to enter a completely different command to change access.  Ask your network administrator; they should be able to answer that.  Or you  can try running

df -T

to see what that gives you.


问:
Cannot execute CTE query via Azure DataBricks
I'm trying to execute CTE query via data bricks getting syntax error for SQL query. Is there any other to use CTE from Data bricks?

Thanks in Advance .

pushdown_query = """(WITH t(x, y) AS (SELECT 1, 2)
SELECT * FROM t WHERE x = 1 AND y = 2) as Test """
df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query, properties=connectionProperties)
display(df)

Error:-
"com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword WITH."

答:
It is impossible using spark.read jdbc. When you use dbtable or query parameters, effect is to insert your SQL code as a subquery inside larger SELECT statement.

Spark docs for dbtable param are poor, IMHO, but you can see where this heading in query doc.

```<code>As an example, spark will issue a query of the following form to the JDBC Source.

SELECT <columns> FROM (<user_specified_query>) spark_gen_alias
</code>```

The thing we specify gets turned into a subquery.

Add that with the fact that a WITH clause must not be included in a subquery. I'm looking for proof of that claim in the Microsoft docs.

Closest I can find is in doc referred to above,
which says WITH must be followed by single SELECT statement. https://github.com/uglide/azure-content/blob/master/articles/sql-data-warehouse/sql-data-warehouse-migrate-code.md

ContentLicense: CC BY-SA 4.0

Body:
It is impossible using spark.read jdbc. When you use dbtable or query parameters, effect is to insert your SQL code as a subquery inside larger SELECT statement.

Spark docs for dbtable param are poor, IMHO, but you can see where this heading in query doc.

As an example, spark will issue a query of the following form to the JDBC Source.

SELECT <columns> FROM (<user_specified_query>) spark_gen_alias

The thing we specify gets turned into a subquery.

Add that with the fact that a WITH clause must not be included in a subquery. I'm looking for proof of that claim in the Microsoft docs.

Closest I can find is in doc referred to above,
which says WITH must be followed by single SELECT statement. https://github.com/uglide/azure-content/blob/master/articles/sql-data-warehouse/sql-data-warehouse-migrate-code.md


问:
Socket programming: How a socket client may discover server IP address inside LAN?
Scope:

OS: MACOS, Windows;

Language: C++Boost library;

Description:

LAN has N computers with MacOS and Windows operating systems, where N ≈ 10. The IP addresses of the computer are not static and assigned by the network. On one of these computers (machine S) a socket server application is running. And on another machine (machine C) a client socket application is running. This is not a static setup, and next time it might be different computers with different IP addresses.

Update:

a server machine -- is a slave. A client machine is a master. A user can install client software in any computer in LAN, and server software in any other computer in LAN. Server take responsibility for the calculations which takes a lot of resources and just send a result to a client. So, the main idea is: a user of a master computer should not provide a server IP address, but the client soft should be able to discover it by itself.

Task:  Client socket application does not know Server application IP address, and should be able to discover it.
Solution should be a cross-platform one (Boost C++)

Please suggest the best practices.

My best guess was: retrieve all the IP addresses of connected devices and socket->send_async_to them. And if I get answer in handle_receive callback -- this is a server app. But I did not find a way how to get all the IP addresses of LAN devices.

Thank you in advance for your suggestions and ideas.

答: use UDP to send request to all the computers in the network.Write a thread in server to respond udp request. then you can get response from the server and get the socket ip.</p>


问:
Unable to connect MongoDB server?
I have tried to connect to MongoDB server using the below-mentioned link but I am getting an error, I have entered the correct password and dbName but it couldn't connect. Can you please help me out?</p>
```<code>const mongoose = require('mongoose');
    mongoose.connect(`mongodb+srv://test:Test@123@cluster0.cvbne.mongodb.net/example?retryWrites=true&w=majority`,{userNewUrlParser : true, useUnifiedTopology: true},
    err => {
        if(!err)
        console.log ("'mongoddb connection successed")
        else
        console.log ('Error white connecting mongodb : ' + JSON.stringify(err, undefined,2))
    })
</code>```

答:
To check if the connection is successful or not, you may use callback functions : on() and once().

```<code>const uri = MONGO_URI;

mongoose.connect(uri, { useNewUrlParser: true });

mongoose.connection.on(
  'error',
  console.error.bind(console, 'connection error: mongodb')
);

mongoose.connection.once('open', () => {
  console.log(`mongodb at : ${uri}`);
});
</code>```

Title: Unable to connect MongoDB server?

Body:
I have tried to connect to MongoDB server using the below-mentioned link but I am getting an error, I have entered the correct password and dbName but it couldn't connect. Can you please help me out?

const mongoose = require('mongoose');
    mongoose.connect(`mongodb+srv://test:Test@123@cluster0.cvbne.mongodb.net/example?retryWrites=true&w=majority`,{userNewUrlParser : true, useUnifiedTopology: true},
    err => {
        if(!err)
        console.log ("'mongoddb connection successed")
        else
        console.log ('Error white connecting mongodb : ' + JSON.stringify(err, undefined,2))
    })

Body:
To check if the connection is successful or not, you may use callback functions : on() and once().

const uri = MONGO_URI;

mongoose.connect(uri, { useNewUrlParser: true });

mongoose.connection.on(
  'error',
  console.error.bind(console, 'connection error: mongodb')
);

mongoose.connection.once('open', () => {
  console.log(`mongodb at : ${uri}`);
});


问:
Java ClassLoader - Adding dynamically loaded jars to the system class loader
Is there any way to update the system class loader at runtime? After I've dynamically loaded a jar file, is there anything I can do to add the classes/packages loaded from this jar into my system class loader?

The reason I'm trying to do this is that while I've had some success through just passing around my newly created ClassLoader in my own code, I'm having trouble with a third party library (apache-WSIF) that doesn't seem to be working with the passed in ClassLoader.

答:
I've been able to achieve what I was attempting to do using the following:

Thread.currentThread().setContextClassLoader(myClassLoader);

As discussed in the top answer here: How do you change the CLASSPATH within Java?

Basically, before calling into the WSIF library all I need to do is make sure I've set my custom classLoader as the contextClassLoader on the current thread.


问:
Spring boot integration - ref not recognizing bean for adapter
I am trying to build a spring boot project with spring integration to handle incoming as2 messages using a custom inbound-channel-adapter. for some reason the ref argument of the adapter is not finding a bean definition for my class.

I have the followed spring reference files and online resources and have the following understanding:

Adding the @ImportResource("/integration/integration.xml") annotation pointing to my spring integration xml file adds it to the application context

```<code>
@SpringBootApplication
@ImportResource("/integration/integration.xml")
public class MyApplication implements ServletContextListener {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);
    }
</code>```

adding the @Component annotation above my class should make it autodetectable as a bean by my spring boot application

```<code>@Component
public class MyHandlerModule extends AbstractProcessorModule implements IProcessorStorageModule {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyHandlerModule.class);

    @Override
    public boolean canHandle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info(" Handle Info:" + s);
        LOGGER.info(map.toString());
        return s.equals(DO_STORE);
    }

    @SneakyThrows
    @Override
    public void handle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info("----- AS2 MESSAGE RECEIVED !!! ------");
}
}
</code>```

and yet I am getting an error when running the application in my integration.xml file with the following message:

```<code>A component required a bean named 'com.example.MyHandlerModule' that could not be found.
</code>```

For reference, here is my integration.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <int:channel id="as2MessageChannel"/>

    <int:inbound-channel-adapter id="as2" ref="com.example.MyHandlerModule" method="handle" channel="as2MessageChannel"/>

</beans>
</code>```

Is there something I am missing?

答: The error is correct : without any custom name the framework makes it like myHandlerModule - the camel case based on a simple class name . The package is not involved in bean naming . Not sure what made you to point fully qualified class name in that ref…

Body:
I am trying to build a spring boot project with spring integration to handle incoming as2 messages using a custom inbound-channel-adapter. for some reason the ref argument of the adapter is not finding a bean definition for my class.

I have the followed spring reference files and online resources and have the following understanding:

Adding the @ImportResource("/integration/integration.xml") annotation pointing to my spring integration xml file adds it to the application context

@SpringBootApplication
@ImportResource("/integration/integration.xml")
public class MyApplication implements ServletContextListener {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);
    }

adding the @Component annotation above my class should make it autodetectable as a bean by my spring boot application

@Component
public class MyHandlerModule extends AbstractProcessorModule implements IProcessorStorageModule {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyHandlerModule.class);

    @Override
    public boolean canHandle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info(" Handle Info:" + s);
        LOGGER.info(map.toString());
        return s.equals(DO_STORE);
    }

    @SneakyThrows
    @Override
    public void handle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info("----- AS2 MESSAGE RECEIVED !!! ------");
}
}

and yet I am getting an error when running the application in my integration.xml file with the following message:

A component required a bean named 'com.example.MyHandlerModule' that could not be found.

For reference, here is my integration.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <int:channel id="as2MessageChannel"/>

    <int:inbound-channel-adapter id="as2" ref="com.example.MyHandlerModule" method="handle" channel="as2MessageChannel"/>

</beans>

Is there something I am missing?


问:
How to write this function to have as output a vector when the input is a vector?(UPDATE)

h = max{dk(l), hmin}, where dk(l) is the distance from l to the 70th nearest li and hmin=1000.
Hello, I want to have in output a vector when the entry is vector for this function.
I want l,li and yi in entries, so I can calcultef1(L,li=position,yi=y) with differents vectors for li and yi. Let's consider only this vectors for yi and li for example:

```<code>y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
L <- seq(11190000, 11460000, by=10)

</code>```

With help of @jblood94 I got this

```<code>library(parallel)

f1 <- function(l) {
  dkAll <- abs(outer(position, l, "-"))
  Knorm <- dnorm(outer(position, l, "-")/pmax(dkAll[order(col(dkAll), dkAll)[seq(70, by = length(position), length.out = length(l))]], 1000))
  colSums(Knorm*y)/colSums(Knorm)
}

y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
l <- seq(11190000, 11460000, by=10)
# ysmoothed <- f1(l) # memory allocation error
cl <- makeCluster(detectCores())
clusterExport(cl, list("y", "position", "l", 'f1'))
system.time(ysmoothed <- parLapply(cl, l, f1))
#>    user  system elapsed
#>    0.02    0.00   20.13
</code>```

This function works correctly. The purpose is to rewrite with three entries and avoid error Error in get(name, envir = envir) : object 'y' not found by using the command clusterExport(cl, list("y", "position", "l", 'f1')) .
I hope @jblood94 will see my message!

答:
Is this what you're looking for?

I've modified the function and added a second set of data so you could see how you can change values in the input vectors.

```<code># modified function
fl = function(l, li, yi){
  dkAll <- abs(outer(li, l, "-"))
  Knorm <- dnorm(outer(li,
                       l,
                       "-")/pmax(
                         dkAll[order(col(dkAll), dkAll)[
                           seq(70, by = length(li),
                               length.out = length(l))]], 1000))
  colSums(Knorm * yi)/colSums(Knorm)
}
</code>```

First run (with data from the question)

```<code># original values
y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
l <- seq(11190000, 11460000, by=10)

# call function
cl <- makeCluster(detectCores())
system.time(ysmoothed <- parLapply(cl, l, fl, position, y))
#    user  system elapsed
#   0.032   0.034   7.487
stopCluster(cl)
ysmoothed[1:8] %>% unlist()
#  [1] 41.08598 41.08646 41.08694 41.08741 41.08789 41.08837 41.08885 41.08933
</code>```

Second run (changed input vectors)

```<code># new values (appended numbers to original values in position and L)
yx <- seq(1, 100, length.out = 23710)
positionX <- seq(103516730, 124220820, length.out=23710)
LX <- seq(1119000, 1146000, by=10)

# call function
cl <- makeCluster(detectCores())
system.time(ysmoothed <- parLapply(cl, LX, fl, positionX, yx))
# user  system elapsed
# 0.017   0.006   0.621

stopCluster(cl)
ysmoothed[1:8] %>% unlist()
#  [1] 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928
</code>```

If this isn't what you were looking for let me know.

Body:
h = max{dk(l), hmin}, where dk(l) is the distance from l to the 70th nearest li and hmin=1000.
Hello, I want to have in output a vector when the entry is vector for this function.
I want l,li and yi in entries, so I can calcultef1(L,li=position,yi=y) with differents vectors for li and yi. Let's consider only this vectors for yi and li for example:

y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
L <- seq(11190000, 11460000, by=10)

With help of @jblood94 I got this

library(parallel)

f1 <- function(l) {
  dkAll <- abs(outer(position, l, "-"))
  Knorm <- dnorm(outer(position, l, "-")/pmax(dkAll[order(col(dkAll), dkAll)[seq(70, by = length(position), length.out = length(l))]], 1000))
  colSums(Knorm*y)/colSums(Knorm)
}

y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
l <- seq(11190000, 11460000, by=10)
# ysmoothed <- f1(l) # memory allocation error
cl <- makeCluster(detectCores())
clusterExport(cl, list("y", "position", "l", 'f1'))
system.time(ysmoothed <- parLapply(cl, l, f1))
#>    user  system elapsed
#>    0.02    0.00   20.13

This function works correctly. The purpose is to rewrite with three entries and avoid error Error in get(name, envir = envir) : object 'y' not found by using the command clusterExport(cl, list("y", "position", "l", 'f1')) .
I hope @jblood94 will see my message!

Body:
Is this what you're looking for?

I've modified the function and added a second set of data so you could see how you can change values in the input vectors.

# modified function
fl = function(l, li, yi){
  dkAll <- abs(outer(li, l, "-"))
  Knorm <- dnorm(outer(li,
                       l,
                       "-")/pmax(
                         dkAll[order(col(dkAll), dkAll)[
                           seq(70, by = length(li),
                               length.out = length(l))]], 1000))
  colSums(Knorm * yi)/colSums(Knorm)
}

First run (with data from the question)

# original values
y <- seq(1, 100, length.out = 23710)
position <- seq(10351673, 12422082, length.out=23710)
l <- seq(11190000, 11460000, by=10)

# call function
cl <- makeCluster(detectCores())
system.time(ysmoothed <- parLapply(cl, l, fl, position, y))
#    user  system elapsed
#   0.032   0.034   7.487
stopCluster(cl)
ysmoothed[1:8] %>% unlist()
#  [1] 41.08598 41.08646 41.08694 41.08741 41.08789 41.08837 41.08885 41.08933

Second run (changed input vectors)

# new values (appended numbers to original values in position and L)
yx <- seq(1, 100, length.out = 23710)
positionX <- seq(103516730, 124220820, length.out=23710)
LX <- seq(1119000, 1146000, by=10)

# call function
cl <- makeCluster(detectCores())
system.time(ysmoothed <- parLapply(cl, LX, fl, positionX, yx))
# user  system elapsed
# 0.017   0.006   0.621

stopCluster(cl)
ysmoothed[1:8] %>% unlist()
#  [1] 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928 48.66928

If this isn't what you were looking for let me know.


问:
dynamodb putItem callback function not working
```<code>const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    dynamodb.putItem(obj, function(err,result){
        console.log('function called!!');
        console.log(err);

        return response;
    });

};
</code>```

My putItem is not working, the callback function is not being called. I have given full access to role of this user, but still function is not getting called.

答:
Another possible reason for this error is because of one using  AWS.DynamoDB.DocumentClient() instead of AWS.DynamoDB();
In that case, DocumentClient uses the put method instead of putItem

I kept checking the async and promise code when this was the cause

Body:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    dynamodb.putItem(obj, function(err,result){
        console.log('function called!!');
        console.log(err);

        return response;
    });

};

My putItem is not working, the callback function is not being called. I have given full access to role of this user, but still function is not getting called.


问:
Android Studio Bumblebee Navigation can't access FragmentDirections for action
I create such action before Android Studio bumblebee update and it was working fine.

```<code>fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}
</code>```

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

```<code>buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My build.gradle App

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}
</code>```

答:
I solved my problem by cleaning my project and rebuilding and adding.

Thank you very much for your support

Build.gradle

```<code>id ("androidx.navigation.safeargs")
</code>```

build

```<code>
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'

        def nav_version = "2.3.0"
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")

    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

Body:
I create such action before Android Studio bumblebee update and it was working fine.

fragment_button.setOnClickListener{
val action = FeedFragmentDirections.actionFeedFragmentToCountryFragment()
Navigation.findNavController(it).navigate(action)
}

But currently FragmentDirections are not accessible.I don't know where the problem comes from, I guess I can't manage to add navigation.

My build.gradle:

buildscript {
    dependencies {
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.0")
    }
}
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'androidx.navigation.safeargs.kotlin' version '2.4.0' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My build.gradle App

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
    id 'kotlin-android-extensions'
}

android {
    dataBinding {
        enabled = true
}
dependencies {
    def navVersion = '2.4.0'

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
}

Body:
I solved my problem by cleaning my project and rebuilding and adding.

Thank you very much for your support

Build.gradle

id ("androidx.navigation.safeargs")

build

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'

        def nav_version = "2.3.0"
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")

    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'com.google.gms.google-services' version '4.3.0' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
ExcelJS not importing xlsx data

I'm NOT using the node load option

External js files ARE being called and loaded

The xlsx file to be imported IS local to the published files

This is the script so far - all I want to do is check to see if the source is being imported and populating the created workbook

var workbook = new ExcelJS.Workbook();

var importBook = "./story_content/external_files/sample.xlsx";

console.dir( importBook );

workbook.xlsx.readFile( importBook );

console.dir ( workbook );

var ws = workbook.getWorksheet("Sheet1");

console.dir( ws );

line 112 is the result of console.dir ( workbook ); which says to me that NOTHING is either loaded OR imported, and I can't understand why not....wasted too much time trying possible solutions so i'm reaching out to the community.

Thanks in advance for any insight

答:
You can try this.

    const filePath: string = `assets/1962.xlsx`;

    const buffer = await fetch(filePath).then(res => res.arrayBuffer());
    const workbook = new Workbook();
    await workbook.xlsx.load(buffer);

    const worksheet = workbook.getWorksheet(1);
    console.dir(worksheet);
```

Title: ExcelJS not importing xlsx data


问:
How to use linux command "cat" from a script?
Input:A.fasta

```<code>>A
sldkfjslkdcskd
</code>```

Input:B.fasta

```<code>>B
pofnvkweu
</code>```

Expected output:A_B.fasta

```<code>>A
sldkfjslkdcskd
>B
pofnvkweu
</code>```

Code:

```<code>my_model_dir_path='../my_model'
word='.fasta'

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{f}"])
</code>```

Error message:

```<code>No such file or directory
</code>```

I used subprocess to call linux command cat to concatenate fasta files in a fasta format like expected output. However, I got a message like No such file or directory even though the files and the directory exist in right path.

答:
Seems likes file path was missing the working directory part.
Also using tail makes things a bit less difficult

```<code>#!/usr/bin/env python3
import os
import subprocess

CWD = os.getcwd()
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
subprocess.run(["tail", "-n", "+1", *files])
</code>```

cat is probably not the best tool to use in this case.
But if you really want to use cat, then I would suggest to do it like this:

```<code>for f in files:
    file_path = CWD+"/"+f
    subprocess.run(["echo", f])
    subprocess.run(["cat", file_path])
</code>```

I might be wrong, but it doesn't really makes a lot of sense to call bash from python, when it can be done within python as well.

```<code>seq = ""
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
for f in files:
    seq += ">" + f + "\n"
    fasta = open(f'{CWD}/{f}', "r")
    seq += fasta.read()
    fasta.close()
out = open("A_B.fasta", "w")
out.write(seq)
out.close()
</code>```

Body:
Input:A.fasta

>A
sldkfjslkdcskd

Input:B.fasta

>B
pofnvkweu

Expected output:A_B.fasta

>A
sldkfjslkdcskd
>B
pofnvkweu

Code:

my_model_dir_path='../my_model'
word='.fasta'

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{f}"])

Error message:

No such file or directory

I used subprocess to call linux command cat to concatenate fasta files in a fasta format like expected output. However, I got a message like No such file or directory even though the files and the directory exist in right path.

Body:
Seems likes file path was missing the working directory part.
Also using tail makes things a bit less difficult

#!/usr/bin/env python3
import os
import subprocess

CWD = os.getcwd()
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
subprocess.run(["tail", "-n", "+1", *files])

cat is probably not the best tool to use in this case.
But if you really want to use cat, then I would suggest to do it like this:

for f in files:
    file_path = CWD+"/"+f
    subprocess.run(["echo", f])
    subprocess.run(["cat", file_path])

I might be wrong, but it doesn't really makes a lot of sense to call bash from python, when it can be done within python as well.

seq = ""
files = [f for f in os.listdir(CWD) if str(f).endswith(".fasta")]
for f in files:
    seq += ">" + f + "\n"
    fasta = open(f'{CWD}/{f}', "r")
    seq += fasta.read()
    fasta.close()
out = open("A_B.fasta", "w")
out.write(seq)
out.close()


问:
how to search inside the array of objects in mongodb?
I have this kind of structure in mongoDB
my schema

```<code>{
 user: String,
 skills: Array
}
</code>```

for every user How to search all users by a particular skill

答:
You can use the $in operator

```<code>db.collection.find({ skills: { $in: ['programming', 'cooking'] }})
</code>```

or Mongoose models.

```<code>Model.find({ skills: { $in: ['programming', 'cooking'] }})
</code>```

https://docs.mongodb.com/manual/reference/operator/query/in/

Body:
I have this kind of structure in mongoDB
my schema

{
 user: String,
 skills: Array
}

for every user How to search all users by a particular skill

Body:
You can use the $in operator

db.collection.find({ skills: { $in: ['programming', 'cooking'] }})

or Mongoose models.

Model.find({ skills: { $in: ['programming', 'cooking'] }})

https://docs.mongodb.com/manual/reference/operator/query/in/


问:
How can I change this to have it stop printing the else statement on top and bottom?
```<code>public double getPrice() {
    if(size.equals("S")) {
        price = 19.99;
    }
    else if(size.equals("M")) {
        price = 29.99;
    }
    else if(size.equals("L")) {
        price = 39.99;
    }
    return price;
}
</code>```

}

```<code>public double getPrice() {

    if(this.Citrus) {
        return super.getPrice() + 5.99;
    }
    else {
        System.out.println("That is not a citrus fruit your price is: " + super.getPrice());
        return super.getPrice();
</code>```

Was wondering why my getPrice() was printing in two spaces, but I managed to figure it out.

答:
Remove your getPrice() and Display() methods and include this code in your FruitSnack Class

small edit you don't need the setter. Instead update the price in getPrice() method.

```<code>private double price
//public void setPrice(double price){
    //this.price = super.getPrice() + 5.99;
//}

public double getPrice() {
    return super.getPrice() + 5.99;
}

public void display() {
    if (! this.Citrus)
        System.out.println("That is not a citrus fruit your price
        is:\n" + super.getPrice());
    else
        System.out.println(getPrice());
}
</code>```

Body:
public double getPrice() {
    if(size.equals("S")) {
        price = 19.99;
    }
    else if(size.equals("M")) {
        price = 29.99;
    }
    else if(size.equals("L")) {
        price = 39.99;
    }
    return price;
}

}

public double getPrice() {

    if(this.Citrus) {
        return super.getPrice() + 5.99;
    }
    else {
        System.out.println("That is not a citrus fruit your price is: " + super.getPrice());
        return super.getPrice();

Was wondering why my getPrice() was printing in two spaces, but I managed to figure it out.

Body:
Remove your getPrice() and Display() methods and include this code in your FruitSnack Class

small edit you don't need the setter. Instead update the price in getPrice() method.

private double price
//public void setPrice(double price){
    //this.price = super.getPrice() + 5.99;
//}

public double getPrice() {
    return super.getPrice() + 5.99;
}

public void display() {
    if (! this.Citrus)
        System.out.println("That is not a citrus fruit your price
        is:\n" + super.getPrice());
    else
        System.out.println(getPrice());
}


问:
Remove subslists that contains a set of words in Nested List on R
I have a nested list videos inside the sublist there is element "title" I want to filter and remove all the sublists in which x$title has the words like {trailer, highlights, match}. Can some good soul help me in solving this ?

Here is the Nested List in R

Here is the Sublist

(Sorry for my language) Thanks in advance

答:
Find all the sublists x for which x$title contains any of the forbidden words and remove them.

```<code>forbidden <- c("trailer", "highlights", "match")
bad <- sapply(videos, function(x) any(stringr::str_detect(x$title, regex(forbidden, ignore_case = T))))
videos <- videos[-which(bad)]
</code>```

Body:
Find all the sublists x for which x$title contains any of the forbidden words and remove them.

forbidden <- c("trailer", "highlights", "match")
bad <- sapply(videos, function(x) any(stringr::str_detect(x$title, regex(forbidden, ignore_case = T))))
videos <- videos[-which(bad)]


问:
Converting a pointer to int into a pointer to an array of int
I'm reading a book about the C language and it says

The assignment of an array name to a pointer to an array of ints, such as a, is implicitly converted into a pointer to the array’s first element, not a pointer to the whole array and it requires an explicit type conversion.

So the following code would give "Error: mismatched pointer types".

```<code>int(*arrPtr)[4] = NULL;
int a[4] = {7, 8, 9, 5};
arrPtr = a;
</code>```

We should change it to

```<code>arrPtr = (int(*)[4])a;
</code>```

My question is why it's required to do type casting when we can simply get the address of the whole array a using & operator.

```<code>arrPtr = &a;
</code>```

Is there any advantage in doing the cast? aren't they both the same?

答:
An explicit cast is needed here:

```<code>arrPtr = (int(*)[4])a;
</code>```

Because the pointer types are not compatible.  However, that doesn't mean that such a conversion is valid.  Taking the address as you stated:

```<code>arrPtr = &a;
</code>```

Would be the correct thing to do, and elements of a can then be access via arrPtr with notation such as (*arrPtr)[n].

Body:
I'm reading a book about the C language and it says

The assignment of an array name to a pointer to an array of ints, such as a, is implicitly converted into a pointer to the array’s first element, not a pointer to the whole array and it requires an explicit type conversion.

So the following code would give "Error: mismatched pointer types".

int(*arrPtr)[4] = NULL;
int a[4] = {7, 8, 9, 5};
arrPtr = a;

We should change it to

arrPtr = (int(*)[4])a;

My question is why it's required to do type casting when we can simply get the address of the whole array a using & operator.

arrPtr = &a;

Is there any advantage in doing the cast? aren't they both the same?

Body:
An explicit cast is needed here:

arrPtr = (int(*)[4])a;

Because the pointer types are not compatible.  However, that doesn't mean that such a conversion is valid.  Taking the address as you stated:

arrPtr = &a;

Would be the correct thing to do, and elements of a can then be access via arrPtr with notation such as (*arrPtr)[n].


问:
dayjs - not a function
I'm passing two dayjs date to Vars.date global variables.

```<code>var dayjs = require("dayjs") for import

Vars.date1 = dayjs(whateverdate1("add", 2)).format('MMM D, YYYY')
Vars.date2 = dayjs(whateverdate2("add", 2)).format('MMM D, YYYY')

const date1 = Vars.date1
const date2 = Vars.date2
let diff = date1.diff(date2, 'month')
console.log('diff' + diff)
</code>```

error: TypeError: date1.diff is not a function

I am unable to use diff and get methods, always 'not a function'

What did I miss?

答:
Make sure that Day.js supports the require() function. If it is import-based, you need to maybe change the import to that.

So, just try doing the following.

import dayjs from "dayjs";
```

Links

npm Package

Official Day.js website

Title: dayjs - not a function

Body:
I'm passing two dayjs date to Vars.date global variables.

var dayjs = require("dayjs") for import

Vars.date1 = dayjs(whateverdate1("add", 2)).format('MMM D, YYYY')
Vars.date2 = dayjs(whateverdate2("add", 2)).format('MMM D, YYYY')

const date1 = Vars.date1
const date2 = Vars.date2
let diff = date1.diff(date2, 'month')
console.log('diff' + diff)

error: TypeError: date1.diff is not a function

I am unable to use diff and get methods, always 'not a function'

What did I miss?

Body:
Make sure that Day.js supports the require() function. If it is import-based, you need to maybe change the import to that.

So, just try doing the following.

import dayjs from "dayjs";

Links

npm Package

Official Day.js website


问:
cakephp and imagick - raw files won't upload
When I upload a JPEG everything works just fine. However, when upload a RAW it does work.  I have the php.ini upload limits set to 25M.  I was able to upload a 7MB JPEG file but not a 7MB RAW file.  Below is the error I am recieving:

```<code>[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: PHP Fatal error:  Uncaught exception 'ImagickException' with message 'Can not process empty wand' in /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php:264, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: Stack trace:, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #0 /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php(264): Imagick->getimagewidth(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #1 /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php(124): PhotoBankImage->computeImageFieldsForSave(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #2 /usr/share/php/cake/cakephp/cake/libs/model/model.php(1282): PhotoBankImage->beforeSave(Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #3 /home/photobound/public_html/plugins/photo_bank/controllers/photo_bank_images_controller.php(131): Model->save(Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #4 [internal function]: PhotoBankImagesController->upload('-1'), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #5 /usr/share/php/cake/cakephp/cake/dispatcher.php(204): call_user_func_array(Array, Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #6 /usr/share/php/cake/cakephp/cake/dispatcher.php(171): Dispatcher->_invoke(Object(PhotoBankImagesController), Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #7 /home/photobound/public_html/webroot/index.php(84): Dispatcher->dispatch(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #8 {main}, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr:   thrown in /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php on line 264, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
</code>```

Here is the code on line 264:

```<code>$this->data['PhotoBankImage']['width'] = $this->image->getImageWidth();
</code>```

Here are my php.ini settings that I thought were relevent:

```<code>post_max_size = 25M
post_max_size = 25M
memory_limit = 512M
max_execution_time = 120
max_input_time = 120
</code>```

I'd appreciate any help, let me know if you need anything else from me in order understand the problem.

答: RAW files are not standard images. Standard graphics libraries are not going to be able to work with them. The format varies depending on camera make/model, etc. </p>

Body:
When I upload a JPEG everything works just fine. However, when upload a RAW it does work.  I have the php.ini upload limits set to 25M.  I was able to upload a 7MB JPEG file but not a 7MB RAW file.  Below is the error I am recieving:

[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: PHP Fatal error:  Uncaught exception 'ImagickException' with message 'Can not process empty wand' in /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php:264, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: Stack trace:, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #0 /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php(264): Imagick->getimagewidth(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #1 /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php(124): PhotoBankImage->computeImageFieldsForSave(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #2 /usr/share/php/cake/cakephp/cake/libs/model/model.php(1282): PhotoBankImage->beforeSave(Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #3 /home/photobound/public_html/plugins/photo_bank/controllers/photo_bank_images_controller.php(131): Model->save(Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #4 [internal function]: PhotoBankImagesController->upload('-1'), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #5 /usr/share/php/cake/cakephp/cake/dispatcher.php(204): call_user_func_array(Array, Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #6 /usr/share/php/cake/cakephp/cake/dispatcher.php(171): Dispatcher->_invoke(Object(PhotoBankImagesController), Array), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #7 /home/photobound/public_html/webroot/index.php(84): Dispatcher->dispatch(), referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr: #8 {main}, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf
[Wed Aug 17 17:23:55 2011] [warn] [client 192.168.1.6] mod_fcgid: stderr:   thrown in /home/photobound/public_html/plugins/photo_bank/models/photo_bank_image.php on line 264, referer: http://photobound.local/photo_bank/js/plupload/plupload.flash.swf

Here is the code on line 264:

$this->data['PhotoBankImage']['width'] = $this->image->getImageWidth();

Here are my php.ini settings that I thought were relevent:

post_max_size = 25M
post_max_size = 25M
memory_limit = 512M
max_execution_time = 120
max_input_time = 120

I'd appreciate any help, let me know if you need anything else from me in order understand the problem.


问:
ERROR: can't get the inverse laplace transform expression with sympy
I've been trying to calculate the inverse laplace transform with sympy for the follow transfer function wlt:

```<code>                             -2⋅s
         (1.0e-8⋅s + 0.02)⋅ℯ
────────────────────────────────────────
  ⎛         2                           ⎞
s⋅⎝1.0e-11⋅s  + 2.0000003e-5⋅s + 0.00177⎠
</code>```

with the next expression:

```<code>wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)
</code>```

where

```<code>s = sp.symbols('s')
t = sp.symbols('t', positive=True)
</code>```

but when I run the code, this errors appears:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 211, in _parallel_dict_from_expr_if_gens
    monom[indices[base]] = exp
KeyError: RisingFactorial(_t + 1, 1.0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 81, in apart
    (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4340, in parallel_poly_from_expr
    return _parallel_poly_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4393, in _parallel_poly_from_expr
    reps, opt = _parallel_dict_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 332, in _parallel_dict_from_expr
    reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 216, in _parallel_dict_from_expr_if_gens
    raise PolynomialError("%s contains an element of "
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/mnt/hgfs/FACULTAD/3er año/SDC/S&C_withPython/SDC_ex/GTP2_ex3.py", line 62, in <module>
    wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1341, in inverse_laplace_transform
    return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1287, in _compute_transform
    return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1213, in _inverse_laplace_transform
    f, cond = inverse_mellin_transform(F, s, exp(-t), (None, oo),
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 908, in inverse_mellin_transform
    return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 846, in _compute_transform
    return _inverse_mellin_transform(F, s, x, strip, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 773, in _inverse_mellin_transform
    h = hyperexpand(G)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2513, in hyperexpand
    return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1497, in replace
    rv = walk(self, rec_replace)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1481, in walk
    rv = F(rv)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1490, in rec_replace
    v = _value(expr, result)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1419, in <lambda>
    _value = lambda expr, result: value(*expr.args)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2509, in do_meijer
    r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2394, in _meijergexpand
    slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2320, in do_slater
    hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2061, in _hyperexpand
    formula = try_lerchphi(func)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 1799, in try_lerchphi
    part = apart(numer/denom, t)
  File "/usr/local/lib/python3.9/dist-packages/sympy/utilities/decorator.py", line 34, in threaded_func
    return func(expr, *args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 84, in apart
    raise PolynomialError(msg)
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.
</code>```

I also tried with partial fractions and factorize the TF, but nothing happened.

答: I had a similar error with sp.inverse_laplace_transform(...) and downgrading Sympy from 1.9 to 1.7.1 helped.</p>

Body:
I've been trying to calculate the inverse laplace transform with sympy for the follow transfer function wlt:

                             -2⋅s
         (1.0e-8⋅s + 0.02)⋅ℯ
────────────────────────────────────────
  ⎛         2                           ⎞
s⋅⎝1.0e-11⋅s  + 2.0000003e-5⋅s + 0.00177⎠

with the next expression:

wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)

where

s = sp.symbols('s')
t = sp.symbols('t', positive=True)

but when I run the code, this errors appears:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 211, in _parallel_dict_from_expr_if_gens
    monom[indices[base]] = exp
KeyError: RisingFactorial(_t + 1, 1.0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 81, in apart
    (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4340, in parallel_poly_from_expr
    return _parallel_poly_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4393, in _parallel_poly_from_expr
    reps, opt = _parallel_dict_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 332, in _parallel_dict_from_expr
    reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 216, in _parallel_dict_from_expr_if_gens
    raise PolynomialError("%s contains an element of "
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/mnt/hgfs/FACULTAD/3er año/SDC/S&C_withPython/SDC_ex/GTP2_ex3.py", line 62, in <module>
    wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1341, in inverse_laplace_transform
    return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1287, in _compute_transform
    return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1213, in _inverse_laplace_transform
    f, cond = inverse_mellin_transform(F, s, exp(-t), (None, oo),
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 908, in inverse_mellin_transform
    return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 846, in _compute_transform
    return _inverse_mellin_transform(F, s, x, strip, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 773, in _inverse_mellin_transform
    h = hyperexpand(G)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2513, in hyperexpand
    return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1497, in replace
    rv = walk(self, rec_replace)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1481, in walk
    rv = F(rv)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1490, in rec_replace
    v = _value(expr, result)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1419, in <lambda>
    _value = lambda expr, result: value(*expr.args)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2509, in do_meijer
    r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2394, in _meijergexpand
    slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2320, in do_slater
    hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2061, in _hyperexpand
    formula = try_lerchphi(func)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 1799, in try_lerchphi
    part = apart(numer/denom, t)
  File "/usr/local/lib/python3.9/dist-packages/sympy/utilities/decorator.py", line 34, in threaded_func
    return func(expr, *args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 84, in apart
    raise PolynomialError(msg)
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

I also tried with partial fractions and factorize the TF, but nothing happened.


问:
Using Firebase v9, how can I add the user to the user collection upon logging in with gmail?
How can I add a user to the users collection logging in with Gmail?

I tried the addUser but it does not work. I'm quite new to Firebase v9

```<code>//firebase
    import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
    import { auth, signInWithGoogle, db } from "../../Firebase/utils";
    import { doc, setDoc, collection } from "firebase/firestore";

const Login = (props) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const addUser = async () => {
    const userRef = doc(db, "users", auth.currentUser);
    setDoc(userRef);
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        addUser();
        console.log(auth.currentUser, "login page");
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

  return (
    <>
        <form>
           <Button onClick={googleHandler}>Login with Gmail</Button>
        </form>
    </>
  );
};

export default Login;
</code>```

These are my package.json just to be sure:

This is what the console.log(auth.currentUser) shows:

UPDATE:

```<code>const addUser = async (userId) => {
    const userRef = doc(db, "users", userId);
    return await setDoc(userRef, { ...data });
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then(async (result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        // addUser();

        const { isNewUser } = getAdditionalUserInfo(result);
        if (isNewUser) {
          await addUser(user.uid);
        } else {
          console.log("User already exists");
        }
      })

      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };
</code>```

答:
The doc() function takes Firestore instance as first argument and the rest are path segments (strings) so you cannot pass currentUser object there. Also there might be a chance that auth.currentUser. You can use isNewUser property to check if the user has just signed up or is logging in again and then add the document. Try refactoring the code as shown below:

```<code>signInWithPopup(auth, signInWithGoogle)
  .then(async (result) => {
    const user = result.user;

    const { isNewUser } = getAdditionalUserInfo(result)
    if (isNewUser) {
      await addUser(user.uid);
    } else {
      console.log("User already exists")
    }
})

const addUser = async (userId) => {
  const userRef = doc(db, "users", userId);
  return await setDoc(userRef, {...data});
};
</code>```

Body:
How can I add a user to the users collection logging in with Gmail?

I tried the addUser but it does not work. I'm quite new to Firebase v9

//firebase
    import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
    import { auth, signInWithGoogle, db } from "../../Firebase/utils";
    import { doc, setDoc, collection } from "firebase/firestore";

const Login = (props) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const addUser = async () => {
    const userRef = doc(db, "users", auth.currentUser);
    setDoc(userRef);
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        addUser();
        console.log(auth.currentUser, "login page");
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

  return (
    <>
        <form>
           <Button onClick={googleHandler}>Login with Gmail</Button>
        </form>
    </>
  );
};

export default Login;

These are my package.json just to be sure:

This is what the console.log(auth.currentUser) shows:

UPDATE:

const addUser = async (userId) => {
    const userRef = doc(db, "users", userId);
    return await setDoc(userRef, { ...data });
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then(async (result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        // addUser();

        const { isNewUser } = getAdditionalUserInfo(result);
        if (isNewUser) {
          await addUser(user.uid);
        } else {
          console.log("User already exists");
        }
      })

      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

Body:
The doc() function takes Firestore instance as first argument and the rest are path segments (strings) so you cannot pass currentUser object there. Also there might be a chance that auth.currentUser. You can use isNewUser property to check if the user has just signed up or is logging in again and then add the document. Try refactoring the code as shown below:

signInWithPopup(auth, signInWithGoogle)
  .then(async (result) => {
    const user = result.user;

    const { isNewUser } = getAdditionalUserInfo(result)
    if (isNewUser) {
      await addUser(user.uid);
    } else {
      console.log("User already exists")
    }
})

const addUser = async (userId) => {
  const userRef = doc(db, "users", userId);
  return await setDoc(userRef, {...data});
};


问:
How to use IDEA to auto complete YAML configurations
I am currently working on spring boot and exploring the spring configurations for spring cloud using YAML. I always copy and paste the whole configuration from some source to my project, is there a way that IDEA auto-completes or shows suggestions while writing the spring cloud configurations. please help.</p>

答: You can use spring assistant plugin</p>

Body: You can use spring assistant plugin


问:
How to get rid of spacing on edge of screen
Everytime I start a new react project and I specify width: 100% for any item (let's just say a navbar) it stretches horizontally and then leaves like 5 px or so worth of "margin" or spacing between it and the edge. I'll attach a picture below.

It's kind of hard to see, but if you look closely right above the top border, you can see the bottom of the bookmark bar - that amount of spacing is on the left and right sides of the nav bar as well. Any ideas? (I've tried setting margin to 0, but didn't work)

答:
By default, body adds a 8px margin.. use body { margin: 0px; } in your main CSS to fix this.
This is not a bug, just a default behaviour


问:
how do I delete/gc an object in Actionscript 3?
I want to delete/force garbage collection on a class instance from inside itself. Obviously, this = null and delete this don't work. Is it any way I can do that, or am I barking up the wrong tree? I'm basically looking for a destructor of some sort..

I have a class instance that attempts to load an XML file, and if the file is not found, I want to destroy the instance, preferably from inside itself. The point is then to do some things in the parent class depending on whether the child instance is null or not.

I've thought of throwing an event to the parent and delete the child from there, but I'd prefer to do that only if there's no other way.

答:
Here is an unsupported way to force garbage collection from GSkinner.</p>

```<code>try {
   new LocalConnection().connect('foo');
   new LocalConnection().connect('foo');
} catch (e:*) {}
// the GC will perform a full mark/sweep on the second call.
</code>```

OwnerDisplayName: evilpenguin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: evilpenguin

Body:
Here is an unsupported way to force garbage collection from GSkinner.

try {
   new LocalConnection().connect('foo');
   new LocalConnection().connect('foo');
} catch (e:*) {}
// the GC will perform a full mark/sweep on the second call.

OwnerDisplayName: jedierikb


问:
NodeJs: read from file with type definitions and write to file as class definition
I have a typescript file with types definitions. I need to find for specific type name and write it to another file but as a class. For example:

```<code>type exampleOne = {
    atrA: string
    atrB: number
}
type exampleTwo = {
    atrA: number
    atrB: string
    atrC: string
}
</code>```

and write exampleTwo to another file as:

```<code>class exampleTwo {
    atrA: number
    atrB: string
    atrC: string
}
</code>```

I have this idea but I don't know how to implement it:

read the file

find the type name I want

select from the beginning of the line where what I am looking for is, until the next closing bracket

replace the word 'type' by 'class' and suppress the equal sign

write to another file

答:
you maybe are looking for this: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

in this case maybe you are trying typing something like this?

```<code>class exampleTwo {
  atrA: number;
  atrB: string;
  atrC: string;

constructor(atrA: number, atrB: string, atrC: string)
  this.atrA = atrA;
  this.atrB = atrB;
  this.atrC = atrC;
}

const newExample = new exampleTwo(2, 'hello', 'world');
</code>```

Body:
I have a typescript file with types definitions. I need to find for specific type name and write it to another file but as a class. For example:

type exampleOne = {
    atrA: string
    atrB: number
}
type exampleTwo = {
    atrA: number
    atrB: string
    atrC: string
}

and write exampleTwo to another file as:

class exampleTwo {
    atrA: number
    atrB: string
    atrC: string
}

I have this idea but I don't know how to implement it:

read the file

find the type name I want

select from the beginning of the line where what I am looking for is, until the next closing bracket

replace the word 'type' by 'class' and suppress the equal sign

write to another file

Body:
you maybe are looking for this: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

in this case maybe you are trying typing something like this?

class exampleTwo {
  atrA: number;
  atrB: string;
  atrC: string;

constructor(atrA: number, atrB: string, atrC: string)
  this.atrA = atrA;
  this.atrB = atrB;
  this.atrC = atrC;
}

const newExample = new exampleTwo(2, 'hello', 'world');


问:
ImportError: cannot import name 'det_curve' from 'sklearn.metrics'
I don't know why I am getting this error, the official document reference

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.det_curve.html#sklearn.metrics.det_curve

Code:

```<code>import numpy as np
from sklearn.metrics import det_curve

fpr, fnr, thresholds = det_curve(y_test, y_pred)
print(fpr, fnr, thresholds)
</code>```

Error:

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-46-d8d6f0b546ca> in <module>()
     10
     11 import numpy as np
---> 12 from sklearn.metrics import det_curve
     13
     14 fpr, fnr, thresholds = det_curve(y_test['cEXT'], y_pred)

ImportError: cannot import name 'det_curve' from 'sklearn.metrics' (/usr/local/lib/python3.7/dist-packages/sklearn/metrics/__init__.py)

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------
</code>```

答: Same kind of problem happened to me in my Jupyter notebook. I uninstall and re-install both scikit-learn and imblearn. It didn't work. Then restarting the kernel and running again solved the problem.

Body:
I don't know why I am getting this error, the official document reference

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.det_curve.html#sklearn.metrics.det_curve

Code:

import numpy as np
from sklearn.metrics import det_curve

fpr, fnr, thresholds = det_curve(y_test, y_pred)
print(fpr, fnr, thresholds)

Error:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-46-d8d6f0b546ca> in <module>()
     10
     11 import numpy as np
---> 12 from sklearn.metrics import det_curve
     13
     14 fpr, fnr, thresholds = det_curve(y_test['cEXT'], y_pred)

ImportError: cannot import name 'det_curve' from 'sklearn.metrics' (/usr/local/lib/python3.7/dist-packages/sklearn/metrics/__init__.py)

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------


问:
Groovy: Maps deep nesting
I got a map matrix that looks like this:

```<code>def matrix = [
    field1:[role1:[state1:["f1r1s1",true],
                   state2:["f1r1s2",false]],
            role2:[state1:["f1r2s1",true],
                   state2:["f1r2s2",false]]
           ],
    field2:[role1:[state1:["f2r1s1",true],
                   state2:["f2r1s2",false]],
            role2:[state1:["f2r2s1",true],
                   state2:["f1r2s2",false]]
           ]
]
</code>```

I am trying to get all fields where role is "role1" and state is "state1". Easy? Help pls.

答:
```<code>matrix.values().role1.state1
</code>```

works for this case, as you've only got a single level of unknown to search through.

Title: Groovy: Maps deep nesting

Body:
I got a map matrix that looks like this:

def matrix = [
    field1:[role1:[state1:["f1r1s1",true],
                   state2:["f1r1s2",false]],
            role2:[state1:["f1r2s1",true],
                   state2:["f1r2s2",false]]
           ],
    field2:[role1:[state1:["f2r1s1",true],
                   state2:["f2r1s2",false]],
            role2:[state1:["f2r2s1",true],
                   state2:["f1r2s2",false]]
           ]
]

I am trying to get all fields where role is "role1" and state is "state1". Easy? Help pls.

Body:
matrix.values().role1.state1

works for this case, as you've only got a single level of unknown to search through.


问:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component wehn trying to change data
I am learning React, in an app I'm trying to change description and amount and add a note, but every time I try I get an error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
```
<p>My code:</p>
```import React from "react";
import { useParams } from "react-router-dom";
import { connect } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

const navigate = useNavigate();

  return (

    <ExpenseForm
      expense ={props.expense}
       onSubmit={(expense) => {
        props.dispatch(editExpense(props.expense.id, expense))
          navigate('/')
         }}
       />

  )
}

const mapStateToProps = (state) => {
  const params = useParams()
  return {
     expense: state.expenses.find((expense) => expense.id === params.id)
  }
}

export default connect(mapStateToProps)(EditExpensePage)
```

答:
Why do you want to connect when the component is already a function component?

```<code>import React from "react";
import { useParams } from "react-router-dom";
import { useSelector, useDispatch } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const params = useParams()
  const expenses = useSelector(state => state.expenses);

  const expense = expenses.find((expense) => expense.id === params.id)

  return (
   <div>
    <ExpenseForm
      expense={expense}
      onSubmit={(exp) => {
        dispatch(editExpense(expense.id, exp))
        navigate('/')
      }}
     />
   </div>
  )
}

export default EditExpensePage
</code>```

Body:
I am learning React, in an app I'm trying to change description and amount and add a note, but every time I try I get an error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

My code:

import React from "react";
import { useParams } from "react-router-dom";
import { connect } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

const navigate = useNavigate();

  return (

    <ExpenseForm
      expense ={props.expense}
       onSubmit={(expense) => {
        props.dispatch(editExpense(props.expense.id, expense))
          navigate('/')
         }}
       />

  )
}

const mapStateToProps = (state) => {
  const params = useParams()
  return {
     expense: state.expenses.find((expense) => expense.id === params.id)
  }
}

export default connect(mapStateToProps)(EditExpensePage)

Body:
Why do you want to connect when the component is already a function component?

import React from "react";
import { useParams } from "react-router-dom";
import { useSelector, useDispatch } from 'react-redux'
import ExpenseForm from "./ExpenseForm";
import { editExpense } from "../actions/expenses";
import { useNavigate } from "react-router-dom";

const EditExpensePage = (props) => {

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const params = useParams()
  const expenses = useSelector(state => state.expenses);

  const expense = expenses.find((expense) => expense.id === params.id)

  return (
   <div>
    <ExpenseForm
      expense={expense}
      onSubmit={(exp) => {
        dispatch(editExpense(expense.id, exp))
        navigate('/')
      }}
     />
   </div>
  )
}

export default EditExpensePage


问:
Read data from own api url and use a interface
I try to get the json-data from a api-server. I can't add this to the variable.
I got the error

Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, pop, push, concat" und 27 weitere.ts(2740)

Where I is my mistake?

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[] = this.getJSON();
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {
      this.getJSON().subscribe(data => {
          console.log(data);
      });
  }

  ngOnInit(): void {
  }

  public getJSON(): Observable<any> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}
</code>```

答:
If you still get any error with the above code then try to change one line change
games: GAMELIST[];

to

games: GAMELIST[]=[];

Body:
I try to get the json-data from a api-server. I can't add this to the variable.
I got the error

Type is missing the following properties from Type "Observable" missing the properties from type "GAMELIST[]": "length, pop, push, concat" und 27 weitere.ts(2740)

Where I is my mistake?

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import gamelistjson from '../../assets/data/gamelist.json';

interface GAMELIST {
    id: number,
    title: string,
    releasedate: number,
    shortdescription: string,
    adddate: string,
    changedate: string,
    tags: any
}

@Component({
  selector: 'app-gamelist',
  templateUrl: './gamelist.component.html',
  styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {

  private data:any = [];
  games: GAMELIST[] = this.getJSON();
  idspiel: number = 0;

  constructor(private router: Router, private http: HttpClient) {
      this.getJSON().subscribe(data => {
          console.log(data);
      });
  }

  ngOnInit(): void {
  }

  public getJSON(): Observable<any> {
    return this.http.get("https://example.org/api/gamelist");
  }

  onSelect(game: any){
    this.router.navigate(['/spiel', game.id, game.title]);
  }
}


问:
int() function not working when accepting an input
I need to write a python program to accept an integer and display its binary and octal equivalent. I have tried different formats, but keep getting errors on my int() function.

This is what I have

dec = int(input())

print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
```
<p>This is the error:</p>
```5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-154-9d3dcb9e828e> in <module>()
----> 1 dec = int(input())
      2
      3 print("The decimal value of", dec, "is:")
      4 print(bin(dec), "in binary.")
      5 print(oct(dec), "in octal.")

TypeError: 'str' object is not callable
```

答:
I see your problem
You want to print the number but it gives you an error right? That's because you are trying to print an integer with a string. That is not possible. So you want to convert the integer to a string to print it.

Your final code should look like this

```<code>dec = int(input("Your input: "))

str(dec)

print("The decimal value of", dec, "is:")
bin(int(dec))
str(dec) # Turning to string for binary printing
print(bin(dec), "in binary.")
oct(int(dec))
str(dec) # Turning to string for octal printing
print(oct(dec), "in octal.")
</code>```

Body:
I need to write a python program to accept an integer and display its binary and octal equivalent. I have tried different formats, but keep getting errors on my int() function.

This is what I have

dec = int(input())

print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")

This is the error:

5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-154-9d3dcb9e828e> in <module>()
----> 1 dec = int(input())
      2
      3 print("The decimal value of", dec, "is:")
      4 print(bin(dec), "in binary.")
      5 print(oct(dec), "in octal.")

TypeError: 'str' object is not callable

Body:
I see your problem
You want to print the number but it gives you an error right? That's because you are trying to print an integer with a string. That is not possible. So you want to convert the integer to a string to print it.

Your final code should look like this

dec = int(input("Your input: "))

str(dec)

print("The decimal value of", dec, "is:")
bin(int(dec))
str(dec) # Turning to string for binary printing
print(bin(dec), "in binary.")
oct(int(dec))
str(dec) # Turning to string for octal printing
print(oct(dec), "in octal.")