问:
Compute correlation for each batch with PyTorch DataLoader class
I am trying to modify PyTorch DataLoader class to:

Compute the Pearson's correlation coefficient for each batch

Select only the two features with the highest correlation before

Masking all the remaining features

Pass the resulting batch to an MLP

I tried to write an explanatory Python code for this:

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np

class CorrelationDataset(Dataset):
    def __init__(self, data):
        self.data = data

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

class CorrelationLoader(DataLoader):
    def __init__(self, dataset, batch_size, shuffle=False, num_workers=0):
        super(CorrelationLoader, self).__init__(dataset, batch_size, shuffle, num_workers)

    def __iter__(self):
        for batch in super(CorrelationLoader, self).__iter__():
            # Compute the Pearson correlation coefficient for each batch
            corr = np.corrcoef(batch, rowvar=False)

            # Get the indices of the two features with the highest correlation
            top_corr = np.unravel_index(np.argmax(corr, axis=None), corr.shape)

            # Mask all remaining features
            mask = torch.zeros(batch.shape[1])
            mask[top_corr[0]] = 1
            mask[top_corr[1]] = 1
            mask = mask.byte()

            # Pass the selected features to the NN
            yield batch[:, mask]

data = torch.randn(100, 10)
dataset = CorrelationDataset(data)
dataloader = CorrelationLoader(dataset, batch_size=32)

mlp = nn.Sequential(
    nn.Linear(2, 10),
    nn.ReLU(),
    nn.Linear(10, 1)
)

for batch in dataloader:
    output = mlp(batch)
    print(output)
```

Unfortunately the code does not work properly. Does anyone know how to fix it?

Body:
I am trying to modify PyTorch DataLoader class to:

Compute the Pearson's correlation coefficient for each batch

Select only the two features with the highest correlation before

Masking all the remaining features

Pass the resulting batch to an MLP

I tried to write an explanatory Python code for this:

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np

class CorrelationDataset(Dataset):
    def __init__(self, data):
        self.data = data

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

class CorrelationLoader(DataLoader):
    def __init__(self, dataset, batch_size, shuffle=False, num_workers=0):
        super(CorrelationLoader, self).__init__(dataset, batch_size, shuffle, num_workers)

    def __iter__(self):
        for batch in super(CorrelationLoader, self).__iter__():
            # Compute the Pearson correlation coefficient for each batch
            corr = np.corrcoef(batch, rowvar=False)

            # Get the indices of the two features with the highest correlation
            top_corr = np.unravel_index(np.argmax(corr, axis=None), corr.shape)

            # Mask all remaining features
            mask = torch.zeros(batch.shape[1])
            mask[top_corr[0]] = 1
            mask[top_corr[1]] = 1
            mask = mask.byte()

            # Pass the selected features to the NN
            yield batch[:, mask]

data = torch.randn(100, 10)
dataset = CorrelationDataset(data)
dataloader = CorrelationLoader(dataset, batch_size=32)

mlp = nn.Sequential(
    nn.Linear(2, 10),
    nn.ReLU(),
    nn.Linear(10, 1)
)

for batch in dataloader:
    output = mlp(batch)
    print(output)

Unfortunately the code does not work properly. Does anyone know how to fix it?


来源: stackexchange

问:
Add AdMob in MAUI by Xamarin.GooglePlayServices.Ads.Lite
I am trying to implement AdMob for my application. I need Banners, Full screen, and Native ads.
I was able to create full screen and banner ads by this Nuget https://github.com/marcojak/MauiMTAdmob.
But unfortunately it don't contains native ads.

So I am trying to rewrite the implementations from the tutorial for Xamarin with Xamarin.GooglePlayServices.Ads.Lite Nuget. But there are things here that I don't know how to change.

Code which I trying to rewrite:

```<code>    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        //add test ads and we will remove after upload :::
           RequestConfiguration.Builder builder = new RequestConfiguration.Builder();
        builder = builder.SetTestDeviceIds(new string[] { "your id in output" });
        MobileAds.RequestConfiguration = builder.Build();

        Android.Gms.Ads.MobileAds.Initialize(ApplicationContext);
        //
        LoadApplication(new App());

    }
</code>```

When I change global::Xamarin.Forms.Forms.Init(this, savedInstanceState); -> Microsoft.Maui.Controls.Compatibility.Forms.Init() I don't see overwrite which accepts this parameters.

I am not sure what should I put there builder = builder.SetTestDeviceIds(new string[] { "your id in output" }); Should I add Banner, Full screen and Native ads Id?

And LoadApplication(new App()); don't exist in MAUI.

Is anyone able to solve my problem or provide an example implementation for MAUI?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement AdMob for my application. I need Banners, Full screen, and Native ads.
I was able to create full screen and banner ads by this Nuget https://github.com/marcojak/MauiMTAdmob.
But unfortunately it don't contains native ads.

So I am trying to rewrite the implementations from the tutorial for Xamarin with Xamarin.GooglePlayServices.Ads.Lite Nuget. But there are things here that I don't know how to change.

Code which I trying to rewrite:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        //add test ads and we will remove after upload :::
           RequestConfiguration.Builder builder = new RequestConfiguration.Builder();
        builder = builder.SetTestDeviceIds(new string[] { "your id in output" });
        MobileAds.RequestConfiguration = builder.Build();

        Android.Gms.Ads.MobileAds.Initialize(ApplicationContext);
        //
        LoadApplication(new App());

    }

When I change global::Xamarin.Forms.Forms.Init(this, savedInstanceState); -> Microsoft.Maui.Controls.Compatibility.Forms.Init() I don't see overwrite which accepts this parameters.

I am not sure what should I put there builder = builder.SetTestDeviceIds(new string[] { "your id in output" }); Should I add Banner, Full screen and Native ads Id?

And LoadApplication(new App()); don't exist in MAUI.

Is anyone able to solve my problem or provide an example implementation for MAUI?


问:
tsfresh efficient feature set extraction is stuck at 0%
I am using the tsfresh library to extract features from my time-series dataset.
My problem is that I can only use the setting for the minimal feature set (MinimalFCParameters) because even the efficient one (EfficientFCParameters) is always stuck at 0% and never calculates any features.

The data is pretty large (over 40. Mio. rows, 100k windows) but this is even the smallest data set I am going to use. I am using a compute cluster, so computing resources should not be the issue. I also tried to use the n_jobs parameter for the extract_features-method (n_jobs=32). Finally, as suggested by the tsfresh website, I used dask instead of pandas for the input data frame - but no success too.

My questions are: Is there anything else I can try? Or are there any other libraries I could use?


问:
Using TLS 1.2 on .net 6
Is there any way to force my .net 6.0 application to use TLS 1.2? Im sadly forced to use TLS 1.2 by an API that is yet to be updated and i would prefer to not make a lot of loopholes to run 4.7/4.8 just to get TLS 1.2.</p>

Title: Using TLS 1.2 on .net 6


问:
Sveletkit import issue with Vite
I have a vite.config.js file that defines and exports a config object that looks like this:

....
const config = {
    plugins: [sveltekit(),
        (ViteRestart).default({
            restart: [
              'restart',
              // 'src/**/*.[jt]s'
            ],
          })],
    //server: { https: true },
    server: {
        https: {
            //key: fs.readFileSync('key.pem'),
            //cert: fs.readFileSync('cert.pem')
            key: tlsconfig.key,
            cert: tlsconfig.cert
        },
        port: 3031,
        proxy: {},

    },

    }
export default config;
```
<p>I also have a <code>server.js</code> file that sits in my <code>routes</code> folder which tries to import the config like this:</p>
<pre class="lang-js prettyprint-override"><code>import config from "../../../../vite.config";
</code>```

However, this throws an SSR error:

```<code>__vite_ssr_import_2__.default.default is not a function
TypeError: __vite_ssr_import_2__.default.default is not a function
    at /vite.config.js:73:24
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async instantiateModule (file:///Users/cbourne/Development/my-sveltekit-app/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:52224:9)
</code>```

Title: Sveletkit import issue with Vite

Body:
I have a vite.config.js file that defines and exports a config object that looks like this:

....
const config = {
    plugins: [sveltekit(),
        (ViteRestart).default({
            restart: [
              'restart',
              // 'src/**/*.[jt]s'
            ],
          })],
    //server: { https: true },
    server: {
        https: {
            //key: fs.readFileSync('key.pem'),
            //cert: fs.readFileSync('cert.pem')
            key: tlsconfig.key,
            cert: tlsconfig.cert
        },
        port: 3031,
        proxy: {},

    },

    }
export default config;

I also have a server.js file that sits in my routes folder which tries to import the config like this:

import config from "../../../../vite.config";

However, this throws an SSR error:

__vite_ssr_import_2__.default.default is not a function
TypeError: __vite_ssr_import_2__.default.default is not a function
    at /vite.config.js:73:24
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async instantiateModule (file:///Users/cbourne/Development/my-sveltekit-app/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:52224:9)


问:
Jump from emacs .tex file to .pdf without pressing enter every time
I am on OSX 12.2 and am using Aquamacs 3.6  GNU Emacs 25.3.50.1, and I edit a .tex file manuscript.tex with Aquamacs Emacs. I press Cmd + shift + left mouse button to jump from the .tex file to the pdf, and I get asked in the lower bar

```<code>View command: (lambda () (aquamacs-call-viewer 156 "manuscript.tex"))
</code>```

Then I press enter and I get correctly prompted to the PDF, which is opened with Skim (156 is the line number).

How may I avoid being asked to press enter every time, in order to jump to the pdf directly?

Body:
I am on OSX 12.2 and am using Aquamacs 3.6  GNU Emacs 25.3.50.1, and I edit a .tex file manuscript.tex with Aquamacs Emacs. I press Cmd + shift + left mouse button to jump from the .tex file to the pdf, and I get asked in the lower bar

View command: (lambda () (aquamacs-call-viewer 156 "manuscript.tex"))

Then I press enter and I get correctly prompted to the PDF, which is opened with Skim (156 is the line number).

How may I avoid being asked to press enter every time, in order to jump to the pdf directly?


问:
iTerm2: What is the best way to compare / diff two panes (like vimdiff)?
I would like to compare two panes in iTerm2, like I can do it in vimdiff.
(Or is it the best way to do it in vimdiff, not using iTerm2 panes??)

– I couldn't find anything in the documentation.

– And how can I search the iTerm documentation – – only with help of Google?


问:
Can I use two local strategies to login User and Admin using passport.js?
I could create a strategy for user and successfully logged in. But after creating second local strategy for admin ,I am getting the error  "missing credentials" in both admin and user login pages  . The below code will be required in my userController module. Same way I am not able to do admin's Local strategy and adminController.</p>
```<code>`const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt');

function initialize(passport , getUserByEmail, getUserById){
    const  authenticateUser = async (email, password, done)=>{
        const user =  await getUserByEmail(email)
        if(user==null){
            return done(null, false ,{message:'No user with that email'})
        }
        try {
            const isMatch = (password===user.password);
            if(isMatch){
                return done(null, user)
            }else{
                return done(null, false ,{message:'Password incorrect'})
            }
        } catch (e){
            return done(e)
        }
    }
    passport.use(new LocalStrategy({usernameField: 'email' },authenticateUser))
    passport.serializeUser((user,done)=>done(null,user.id))
    passport.deserializeUser((id,done)=>{
        return done(null,getUserById(id))
    })

}

module.exports = {initialize};
`
---

</code>```

Body:
I could create a strategy for user and successfully logged in. But after creating second local strategy for admin ,I am getting the error  "missing credentials" in both admin and user login pages  . The below code will be required in my userController module. Same way I am not able to do admin's Local strategy and adminController.

`const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt');

function initialize(passport , getUserByEmail, getUserById){
    const  authenticateUser = async (email, password, done)=>{
        const user =  await getUserByEmail(email)
        if(user==null){
            return done(null, false ,{message:'No user with that email'})
        }
        try {
            const isMatch = (password===user.password);
            if(isMatch){
                return done(null, user)
            }else{
                return done(null, false ,{message:'Password incorrect'})
            }
        } catch (e){
            return done(e)
        }
    }
    passport.use(new LocalStrategy({usernameField: 'email' },authenticateUser))
    passport.serializeUser((user,done)=>done(null,user.id))
    passport.deserializeUser((id,done)=>{
        return done(null,getUserById(id))
    })

}

module.exports = {initialize};
`
---


问:
How to assign value from enum to object in TreeMap?
I need to create a book library that will be a singleton. It contains a map of books. Each book has its own index number and genre (taken from enum). How can I add a method that returns a list of all books by genre (genre is transmitted as a string in different registers and I need to use a switch in the method). P.S. I am self-taught so I will be very happy if you can explain me, how can I do it.

My main question is, how can I assign a value from enum(genre) to multiple class objects(books) that I put in. a collection and output them using switch?

Here is my code:

public class Result {

```<code>public static void main(String[] args) {
    Singleton singleton = Singleton.getInstance();
    singleton.books.put(1,new Books("The Great Gatsby.", "Alex Lomi"));
    singleton.books.put(2,new Books("Don Quixote","Samuel Puga"));
    singleton.books.put(3,new Books("Beloved", "Antony Gradsby"));
    singleton.books.put(4,new Books("To Kill a Mockingbird","Sofia Beluci" ));
    singleton.books.put(5,new Books("One Hundred Years of Solitude", "Laura Petera"));
    singleton.books.put(6,new Books("One Hundred Years of Solitude", "Kristian Roberts"));

}
</code>```

}

public class Singleton {
private static Singleton LIBRARY;

```<code>public Singleton() {
}

public static Singleton getInstance(){
    if(LIBRARY == null){
        LIBRARY = new Singleton();
    }
    return LIBRARY;
}

Map<Integer, Books> books = new TreeMap<>();
</code>```

}

public class Books {

```<code>private String nameOfBook;
private String author;

public Books(String nameOfBook, String author) {
    this.nameOfBook = nameOfBook;
    this.author = author;
}
</code>```

}

public enum Genre {

```<code>ACTION,
COMEDY,
DRAMA,
FANTASY;
</code>```

//I've started trying, but if there will be 100 books of the same genre, it will be hard to write every book using switch method.

public static Genre getGenre(String genre){
switch (genre.toUpperCase()){
case "COMDEY":
return
}
}
}

Body:
I need to create a book library that will be a singleton. It contains a map of books. Each book has its own index number and genre (taken from enum). How can I add a method that returns a list of all books by genre (genre is transmitted as a string in different registers and I need to use a switch in the method). P.S. I am self-taught so I will be very happy if you can explain me, how can I do it.

My main question is, how can I assign a value from enum(genre) to multiple class objects(books) that I put in. a collection and output them using switch?

Here is my code:

public class Result {

public static void main(String[] args) {
    Singleton singleton = Singleton.getInstance();
    singleton.books.put(1,new Books("The Great Gatsby.", "Alex Lomi"));
    singleton.books.put(2,new Books("Don Quixote","Samuel Puga"));
    singleton.books.put(3,new Books("Beloved", "Antony Gradsby"));
    singleton.books.put(4,new Books("To Kill a Mockingbird","Sofia Beluci" ));
    singleton.books.put(5,new Books("One Hundred Years of Solitude", "Laura Petera"));
    singleton.books.put(6,new Books("One Hundred Years of Solitude", "Kristian Roberts"));

}

}

public class Singleton {
private static Singleton LIBRARY;

public Singleton() {
}

public static Singleton getInstance(){
    if(LIBRARY == null){
        LIBRARY = new Singleton();
    }
    return LIBRARY;
}

Map<Integer, Books> books = new TreeMap<>();

}

public class Books {

private String nameOfBook;
private String author;

public Books(String nameOfBook, String author) {
    this.nameOfBook = nameOfBook;
    this.author = author;
}

}

public enum Genre {

ACTION,
COMEDY,
DRAMA,
FANTASY;

//I've started trying, but if there will be 100 books of the same genre, it will be hard to write every book using switch method.

public static Genre getGenre(String genre){
switch (genre.toUpperCase()){
case "COMDEY":
return
}
}
}


问:
Flutter with Firestore Performance
The problem I'm dealing with is performance issues when needing to perform multiple Firestore queries in order to reach a result similar to to joins in SQL.

In my Flutter app, which uses Firebase and Firestore, I use Cloud Functions for serving my REST API. My API is the only thing that actually interacts with the Firestore database, not the Flutter app itself. I was always taught to design apps like this (not allowing the client to interact directly with the database) and so continued with that approach.

A potential solution I've seen are the official Firestore plugins for Flutter and have seen people designing their clients to interact directly with Firebase, however I haven't found any official documentation explicitly saying this design is preferred or even ok, and since it goes against when have been taught I haven't tried it yet. Can anyone confirm this or point me to documentation confirming this?

Edit
Perhaps it's worth noting that the reasons I've been told not to have the client connect directly to the database are 1. Security and 2. It would require business logic for managing data to be in the client and that should be handled server-side.

Title: Flutter with Firestore Performance


问:
How to circumvent Here Maps JS API screentogeo bug with mousewheel zooming?
If one zooms out and in on a map with mousewheel, Here Maps breaks or at least its coordinate system goes asunder.

I added map.screenToGeo(ev.currentPointer.viewportX, ev.currentPointer.viewportY) to my map.addEventListener('tap') function, and the lat,lon results varied after mousewheel zooming even though I didn't change the physical X,Y coords (viewportX and viewportY stayed constant).

Some debug:

```<code>Screencoord: 660, 660
mg {lat: 61.48160495921855, lng: 23.7620574375982}
mousewheel
mousewheel
Screencoord: 660, 660
mg {lat: 61.47521004787344, lng: 23.76205743759826}
</code>```

Any suggestions how to circumvent this? Implement my own screentogeo?

Body:
If one zooms out and in on a map with mousewheel, Here Maps breaks or at least its coordinate system goes asunder.

I added map.screenToGeo(ev.currentPointer.viewportX, ev.currentPointer.viewportY) to my map.addEventListener('tap') function, and the lat,lon results varied after mousewheel zooming even though I didn't change the physical X,Y coords (viewportX and viewportY stayed constant).

Some debug:

Screencoord: 660, 660
mg {lat: 61.48160495921855, lng: 23.7620574375982}
mousewheel
mousewheel
Screencoord: 660, 660
mg {lat: 61.47521004787344, lng: 23.76205743759826}

Any suggestions how to circumvent this? Implement my own screentogeo?


问:
Invoke-SqlCmd generates an exception in foreach loop?
I am running 2 different sql query one after the other to get the details from database using Invoke-Sqlcmd but getting an exception.

The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread. Validate that the cmdlet makes these calls correctly

Script:

```<code>$ok = "true"
$serverName = $env:COMPUTERNAME
$query1 = "SELECT * FROM sys.server_audits WHERE name = 'Login'"
$query2 = "SELECT * FROM sys.dm_server_audit_status WHERE name = 'Login' AND status_desc = 'STARTED'"

try
{
    Write-Host "Getting running Sql Server Instance (online)"
    $sqlInstances = (Get-Service -Name MSSQL$* | Where-Object { $_.status -eq "Running" }).Name

    $sqlInstancesCount = $sqlInstances.Count
    Write-Host $eventID "$sqlInstancesCount Sql Server Instance found"

    if($sqlInstancesCount)
    {
        foreach($item in $sqlInstances)
        {
            $count = 0
            $instanceName = $item -replace "MSSQL\$", ""
            $sqlInstanceFullname = Join-Path -Path $serverName -ChildPath "\" | Join-Path -ChildPath $instanceName
            Write-Host "Sql Server instance fullname - $sqlInstanceFullname"

            while($count -lt 3)
            {
                Write-Host "Clear existing connection."
                [System.Data.SqlClient.SqlConnection]::ClearAllPools()

                Write-Host "Executing query - $query1"
                $result1 = (Invoke-Sqlcmd -Query $query1 -ServerInstance $sqlInstanceFullname)

                Start-Sleep -Seconds 30

                Write-Host "Clear existing connection."
                [System.Data.SqlClient.SqlConnection]::ClearAllPools()

                Write-Host "Executing query - $query2"
                $result2 = (Invoke-Sqlcmd -Query $query2 -ServerInstance $sqlInstanceFullname)

                if($null -eq $result1)
                {
                    $message = "$serverName - The SQL Server [Login] does not exist."
                    $ok = "false"
                    $count = $count + 1
                }
                elseif($null -eq $result2)
                {
                    $message = "$serverName - The SQL Server [Login] is disabled."
                    $ok = "false"
                    $count = $count + 1
                }
                else
                {
                    $message = "SQL Login is enabled and running."
                    $count = 3
                    $ok = "true"
                }
            }
        }
    }
    else
    {
        $ok = "false"
        throw "$serverName - SQL Server Instances might be offline or not exist!"
    }
}
catch
{
    throw $_
}
</code>```

I have tried enclosing Invoke-Sqlcmd in brackets but still getting same exception so is there a way to remove existing thread or close the connection before executing another query.

Body:
I am running 2 different sql query one after the other to get the details from database using Invoke-Sqlcmd but getting an exception.

The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread. Validate that the cmdlet makes these calls correctly

Script:

$ok = "true"
$serverName = $env:COMPUTERNAME
$query1 = "SELECT * FROM sys.server_audits WHERE name = 'Login'"
$query2 = "SELECT * FROM sys.dm_server_audit_status WHERE name = 'Login' AND status_desc = 'STARTED'"

try
{
    Write-Host "Getting running Sql Server Instance (online)"
    $sqlInstances = (Get-Service -Name MSSQL$* | Where-Object { $_.status -eq "Running" }).Name

    $sqlInstancesCount = $sqlInstances.Count
    Write-Host $eventID "$sqlInstancesCount Sql Server Instance found"

    if($sqlInstancesCount)
    {
        foreach($item in $sqlInstances)
        {
            $count = 0
            $instanceName = $item -replace "MSSQL\$", ""
            $sqlInstanceFullname = Join-Path -Path $serverName -ChildPath "\" | Join-Path -ChildPath $instanceName
            Write-Host "Sql Server instance fullname - $sqlInstanceFullname"

            while($count -lt 3)
            {
                Write-Host "Clear existing connection."
                [System.Data.SqlClient.SqlConnection]::ClearAllPools()

                Write-Host "Executing query - $query1"
                $result1 = (Invoke-Sqlcmd -Query $query1 -ServerInstance $sqlInstanceFullname)

                Start-Sleep -Seconds 30

                Write-Host "Clear existing connection."
                [System.Data.SqlClient.SqlConnection]::ClearAllPools()

                Write-Host "Executing query - $query2"
                $result2 = (Invoke-Sqlcmd -Query $query2 -ServerInstance $sqlInstanceFullname)

                if($null -eq $result1)
                {
                    $message = "$serverName - The SQL Server [Login] does not exist."
                    $ok = "false"
                    $count = $count + 1
                }
                elseif($null -eq $result2)
                {
                    $message = "$serverName - The SQL Server [Login] is disabled."
                    $ok = "false"
                    $count = $count + 1
                }
                else
                {
                    $message = "SQL Login is enabled and running."
                    $count = 3
                    $ok = "true"
                }
            }
        }
    }
    else
    {
        $ok = "false"
        throw "$serverName - SQL Server Instances might be offline or not exist!"
    }
}
catch
{
    throw $_
}

I have tried enclosing Invoke-Sqlcmd in brackets but still getting same exception so is there a way to remove existing thread or close the connection before executing another query.


问:
an issue with tone.js sampler
so here is the example of working sampler from tone.js site:

    const synth = new Tone.Sampler({
        urls: {
            A1: "A1.mp3",
            A2: "A2.mp3",
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
    }).connect(FXreverb).toDestination();
```
<p>the problem is, when i try to use my own url with .mp3 file:</p>
<pre class="lang-js prettyprint-override"><code>        urls: {
            E1: "musicBox.mp3",
        },
        baseUrl: "https://od.lk/s/NDFfNDcxMjg0MjFf/",
</code>```

I'm getting this message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.

how can i do Access-Control-Allow-Origin for this request?

for hosting .mp3 file i tried github as well, but it did not work

Title: an issue with tone.js sampler

Body:
so here is the example of working sampler from tone.js site:

    const synth = new Tone.Sampler({
        urls: {
            A1: "A1.mp3",
            A2: "A2.mp3",
        },
        baseUrl: "https://tonejs.github.io/audio/casio/",
    }).connect(FXreverb).toDestination();

the problem is, when i try to use my own url with .mp3 file:

        urls: {
            E1: "musicBox.mp3",
        },
        baseUrl: "https://od.lk/s/NDFfNDcxMjg0MjFf/",

I'm getting this message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.

how can i do Access-Control-Allow-Origin for this request?

for hosting .mp3 file i tried github as well, but it did not work


问:
Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization when importing redux store
I cannot import redux store from store.js to customAxios.js file.
I need to send token to backend which resides in redux store. So I need to extract that token, then add into axios Header.

Steps I followed

Created a store.js file which exports redux store.

Imported redux store from store.js in customAxios.js.

This is giving error: Cannot access 'WEBPACK_DEFAULT_EXPORT' before initialization.

github_repo

error image

index.js

```<code>import { createRoot } from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import store from "./redux/store";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
</code>```

customAxios.js

```<code>import axios from "axios";
import { BASE_URL } from "./apiUrls";
import store from "../redux/store";

// console.log(store, "iiiiiiiiiiiiiiiiiii");

export const customAxios = axios.create({ baseURL: BASE_URL });
</code>```

store.js

```<code>import logger from "redux-logger";
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";

const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
devTools: true,
});

export default store;
</code>```

Body:
I cannot import redux store from store.js to customAxios.js file.
I need to send token to backend which resides in redux store. So I need to extract that token, then add into axios Header.

Steps I followed

Created a store.js file which exports redux store.

Imported redux store from store.js in customAxios.js.

This is giving error: Cannot access 'WEBPACK_DEFAULT_EXPORT' before initialization.

github_repo

error image

index.js

import { createRoot } from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import store from "./redux/store";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);

customAxios.js

import axios from "axios";
import { BASE_URL } from "./apiUrls";
import store from "../redux/store";

// console.log(store, "iiiiiiiiiiiiiiiiiii");

export const customAxios = axios.create({ baseURL: BASE_URL });

store.js

import logger from "redux-logger";
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";

const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
devTools: true,
});

export default store;


问:
ImportError: /lib/x86_64-linux-gnu/libexpat.so.1: invalid ELF header
I am getting error while executing line  RUN pip install poetry==1.1.13  in following DockerFile (doing dev up in python (FastApi project)):

DockerFile

```<code>FROM python:3.10

WORKDIR /src
EXPOSE 8080

RUN apt-get update && apt-get install -y curl make && rm -rf /var/lib/apt/lists/*

RUN pip install poetry==1.1.13
RUN poetry config virtualenvs.create false
COPY poetry.lock /src/
COPY pyproject.toml /src/
RUN poetry export -f requirements.txt --without-hashes --output requirements.txt
RUN pip install -r requirements.txt

COPY . /src
RUN cd /src && python setup.py develop

RUN chmod +x /src/bin/run.sh

CMD ["/src/bin/run.sh"]
</code>```

Error

ImportError: /lib/x86_64-linux-gnu/libexpat.so.1: invalid ELF header

Error Logs

```<code># ERROR
#8 1.550 Traceback (most recent call last):
#8 1.550   File "/usr/local/bin/pip", line 8, in <module>
#8 1.550     sys.exit(main())
#8 1.550   File "/usr/local/lib/python3.10/site-packages/pip/_internal/cli/main.py", line 68, in main
#8 1.550     command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
#8 1.550   File "/usr/local/lib/python3.10/site-packages/pip/_internal/commands/__init__.py", line 114, in create_command
#8 1.550     module = importlib.import_module(module_path)
#8 1.550   File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
#8 1.550     return _bootstrap._gcd_import(name[level:], package, level)
#8 1.550   File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
#8 1.550   File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
#8 1.551   File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
#8 1.551   File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
#8 1.551   File "<frozen importlib._bootstrap_external>", line 883, in exec_module
#8 1.551   File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/commands/install.py", line 16, in <module>
#8 1.551     from pip._internal.cli.req_command import (
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/cli/req_command.py", line 21, in <module>
#8 1.551     from pip._internal.index.package_finder import PackageFinder
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/index/package_finder.py", line 33, in <module>
#8 1.551     from pip._internal.req import InstallRequirement
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/req/__init__.py", line 8, in <module>
#8 1.551     from .req_install import InstallRequirement
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/req/req_install.py", line 44, in <module>
#8 1.551     from pip._internal.operations.install.wheel import install_wheel
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/operations/install/wheel.py", line 39, in <module>
#8 1.551     from pip._vendor.distlib.scripts import ScriptMaker
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_vendor/distlib/scripts.py", line 16, in <module>
#8 1.552     from .compat import sysconfig, detect_encoding, ZipFile
#8 1.552   File "/usr/local/lib/python3.10/site-packages/pip/_vendor/distlib/compat.py", line 83, in <module>
#8 1.552     import xmlrpc.client as xmlrpclib
#8 1.552   File "/usr/local/lib/python3.10/xmlrpc/client.py", line 138, in <module>
#8 1.552     from xml.parsers import expat
#8 1.552   File "/usr/local/lib/python3.10/xml/parsers/expat.py", line 4, in <module>
#8 1.552     from pyexpat import *
#8 1.552 ImportError: /lib/x86_64-linux-gnu/libexpat.so.1: invalid ELF header
#8 ERROR: executor failed running [/bin/sh -c pip install poetry==1.1.13]: exit code: 1
------
 > [ 4/12] RUN pip install poetry==1.1.13:
------
executor failed running [/bin/sh -c pip install poetry==1.1.13]: exit code: 1
Cleaning up...
 - No resources found
build failed: exit status 1. Docker build ran into internal error. Please retry
</code>```

Body:
I am getting error while executing line  RUN pip install poetry==1.1.13  in following DockerFile (doing dev up in python (FastApi project)):

DockerFile

FROM python:3.10

WORKDIR /src
EXPOSE 8080

RUN apt-get update && apt-get install -y curl make && rm -rf /var/lib/apt/lists/*

RUN pip install poetry==1.1.13
RUN poetry config virtualenvs.create false
COPY poetry.lock /src/
COPY pyproject.toml /src/
RUN poetry export -f requirements.txt --without-hashes --output requirements.txt
RUN pip install -r requirements.txt

COPY . /src
RUN cd /src && python setup.py develop

RUN chmod +x /src/bin/run.sh

CMD ["/src/bin/run.sh"]

Error

ImportError: /lib/x86_64-linux-gnu/libexpat.so.1: invalid ELF header

Error Logs

# ERROR
#8 1.550 Traceback (most recent call last):
#8 1.550   File "/usr/local/bin/pip", line 8, in <module>
#8 1.550     sys.exit(main())
#8 1.550   File "/usr/local/lib/python3.10/site-packages/pip/_internal/cli/main.py", line 68, in main
#8 1.550     command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
#8 1.550   File "/usr/local/lib/python3.10/site-packages/pip/_internal/commands/__init__.py", line 114, in create_command
#8 1.550     module = importlib.import_module(module_path)
#8 1.550   File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
#8 1.550     return _bootstrap._gcd_import(name[level:], package, level)
#8 1.550   File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
#8 1.550   File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
#8 1.551   File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
#8 1.551   File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
#8 1.551   File "<frozen importlib._bootstrap_external>", line 883, in exec_module
#8 1.551   File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/commands/install.py", line 16, in <module>
#8 1.551     from pip._internal.cli.req_command import (
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/cli/req_command.py", line 21, in <module>
#8 1.551     from pip._internal.index.package_finder import PackageFinder
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/index/package_finder.py", line 33, in <module>
#8 1.551     from pip._internal.req import InstallRequirement
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/req/__init__.py", line 8, in <module>
#8 1.551     from .req_install import InstallRequirement
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/req/req_install.py", line 44, in <module>
#8 1.551     from pip._internal.operations.install.wheel import install_wheel
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_internal/operations/install/wheel.py", line 39, in <module>
#8 1.551     from pip._vendor.distlib.scripts import ScriptMaker
#8 1.551   File "/usr/local/lib/python3.10/site-packages/pip/_vendor/distlib/scripts.py", line 16, in <module>
#8 1.552     from .compat import sysconfig, detect_encoding, ZipFile
#8 1.552   File "/usr/local/lib/python3.10/site-packages/pip/_vendor/distlib/compat.py", line 83, in <module>
#8 1.552     import xmlrpc.client as xmlrpclib
#8 1.552   File "/usr/local/lib/python3.10/xmlrpc/client.py", line 138, in <module>
#8 1.552     from xml.parsers import expat
#8 1.552   File "/usr/local/lib/python3.10/xml/parsers/expat.py", line 4, in <module>
#8 1.552     from pyexpat import *
#8 1.552 ImportError: /lib/x86_64-linux-gnu/libexpat.so.1: invalid ELF header
#8 ERROR: executor failed running [/bin/sh -c pip install poetry==1.1.13]: exit code: 1
------
 > [ 4/12] RUN pip install poetry==1.1.13:
------
executor failed running [/bin/sh -c pip install poetry==1.1.13]: exit code: 1
Cleaning up...
 - No resources found
build failed: exit status 1. Docker build ran into internal error. Please retry


问:
Chrome Extension : generate screenshot - Permission error
I'm trying to develop a chrome extension that will capture screenshots without user intervention and push them to a server. I do not intend to publish this extension, I just want to develop it for me. I would feed the extension with a list of urls to visit on a daily base and then capture screenshots and send them to a server.

I'm already stuck by a permission problem at the very beginning. Here is the code in background.js:

```<code>chrome.tabs.create({ url: 'https://www.example.com', active: true }, tab =>
{
    if (chrome.runtime.lastError)
        {
            console.error(chrome.runtime.lastError);
        }
    else
        {
            console.log(tab);

            chrome.tabs.captureVisibleTab(null, {format: 'png'}, function(dataURI)
              {
                // do something
              });
       }
 });
</code>```

When running this code, I get the following error: Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host.

In my manifest, I have:

```<code>"host_permissions":
[
    "tabs",
    "*://*/",
    "http://*/",
    "https://*/",
    "<all_urls>",
    "notifications",
    "webRequest",
    "webNavigation",
    "management",
    "storage",
    "webRequestBlocking",
    "http://*/*",
    "background",
    "alarms",
    "desktopCapture",
    "activeTab",
    "https://*/*"

],

"permissions": [
    "tabs",
    "http://*/",
    "https://*/",
    "<all_urls>",
    "notifications",
    "webRequest",
    "webNavigation",
    "management",
    "storage",
    "webRequestBlocking",
    "http://*/*",
    "background",
    "alarms",
    "desktopCapture",
    "activeTab",
    "https://*/*"

],

 "background": {
"scripts": ["background.js"],
"persistent": true
  },

"content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]

    }],

"browser_action": {
    "default_icon": "logo.png",
    "default_popup": "popup.html"
    }
</code>```

There are multiple discussions about this topic on stackexchange, I have applied recommendations about permissions but it still doesn't work.

Where am I missing something?

Thanks

Laurent

Body:
I'm trying to develop a chrome extension that will capture screenshots without user intervention and push them to a server. I do not intend to publish this extension, I just want to develop it for me. I would feed the extension with a list of urls to visit on a daily base and then capture screenshots and send them to a server.

I'm already stuck by a permission problem at the very beginning. Here is the code in background.js:

chrome.tabs.create({ url: 'https://www.example.com', active: true }, tab =>
{
    if (chrome.runtime.lastError)
        {
            console.error(chrome.runtime.lastError);
        }
    else
        {
            console.log(tab);

            chrome.tabs.captureVisibleTab(null, {format: 'png'}, function(dataURI)
              {
                // do something
              });
       }
 });

When running this code, I get the following error: Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host.

In my manifest, I have:

"host_permissions":
[
    "tabs",
    "*://*/",
    "http://*/",
    "https://*/",
    "<all_urls>",
    "notifications",
    "webRequest",
    "webNavigation",
    "management",
    "storage",
    "webRequestBlocking",
    "http://*/*",
    "background",
    "alarms",
    "desktopCapture",
    "activeTab",
    "https://*/*"

],

"permissions": [
    "tabs",
    "http://*/",
    "https://*/",
    "<all_urls>",
    "notifications",
    "webRequest",
    "webNavigation",
    "management",
    "storage",
    "webRequestBlocking",
    "http://*/*",
    "background",
    "alarms",
    "desktopCapture",
    "activeTab",
    "https://*/*"

],

 "background": {
"scripts": ["background.js"],
"persistent": true
  },

"content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]

    }],

"browser_action": {
    "default_icon": "logo.png",
    "default_popup": "popup.html"
    }

There are multiple discussions about this topic on stackexchange, I have applied recommendations about permissions but it still doesn't work.

Where am I missing something?

Thanks

Laurent


问:
How do you hook and call a member function that returns an object?
I want to develop a wrapper class that wraps a DLL class that I do not have the source to. Originally, my plan was to just do a bunch of inline assembly to call the real functions.. but I've spent several hours now researching and tinkering how to call member functions by their addresses.

I managed to successfully call the constructor method, and then I moved on to trying to call an operator method (specifically the + operator). This is where things started to go wrong, and I'm unsure if I'm defining/calling the method properly now...

MyStringWrapper.h

```<code>#pragma once

#include <string>

class MyStringWrapper
{
public:
   static void InitializeAddresses();

   static MyStringWrapper* CastFrom(
      const uintptr_t address);

   MyStringWrapper(
      const std::wstring& original);

   MyStringWrapper operator+(
      const MyStringWrapper& other);

private:
   uintptr_t m_string_address;
   int m_u1;
   int m_u2;
   // Still need to figure out how to determine the correct size of a class, but hopefully this is big enough.
   char mData[2900];

   static struct FunctionDefinitions
   {
      typedef void(__thiscall* Create_FromArray)(void* pThis, wchar_t const* original);
      Create_FromArray CreateFromArray;

      // I think my issue is here, should I be returning/providing MyStringWrapper objects or the original MyString objects (that I do not have the source for).
      // and... if I should be using MyString objects, how can I do this without the compiler being upset about incomplete types?
      // Original symbol "public: class MyString __thiscall MyString::operator+(class MyString const &)"
      typedef MyStringWrapper(__thiscall* Combine_MyString)(void* pThis, const MyStringWrapper& other);
      Combine_MyString CombineMyString;
   } CustomFunctions;
};
</code>```

MyStringWrapper.cpp

```<code>#include "MyStringWrapper.h"
#include "GlobalDLLBases.h"

MyStringWrapper::FunctionDefinitions MyStringWrapper::CustomFunctions;

void MyStringWrapper::InitializeAddresses()
{
   CustomFunctions.CreateFromArray = FunctionDefinitions::Create_FromArray((DWORD_PTR)DLLBase + 0x2c40);

   CustomFunctions.CombineMyString = FunctionDefinitions::Combine_MyString((DWORD_PTR)DLLBase + 0x3740);
}

MyStringWrapper* MyStringWrapper::CastFrom(
   const uintptr_t address)
{
   return reinterpret_cast<MyStringWrapper*>(address);
}

MyStringWrapper::MyStringWrapper(
   const std::wstring& original) :
   m_string_address(0),
   m_u1(0),
   m_u2(0)
{
   CustomFunctions.Create_FromArray(this, original.data());
}

MyStringWrapper MyStringWrapper::operator+(
   const MyStringWrapper& other)
{
   return CustomFunctions.CombineMyString(this, other);
}
</code>```

Main.cpp

```<code>MyStringWrapper* obj1 = MyStringWrapper::CastFrom(address_to_existing_mystring);
MyStringWrapper* obj2 = MyStringWrapper::CastFrom(address_to_another_existing_mystring);
if(obj1 && obj2)
{
    // It crashes calling this, I expected ECX to hold the address of obj1, but the compiler seems to push both obj1 and obj2 addresses on to the stack and moves some other address into ecx.
    // It should only be pushing obj2's address, and moving obj1's address into ecx.
    MyStringWrapper final_product = *obj1 + *obj2;
}
</code>```

Body:
I want to develop a wrapper class that wraps a DLL class that I do not have the source to. Originally, my plan was to just do a bunch of inline assembly to call the real functions.. but I've spent several hours now researching and tinkering how to call member functions by their addresses.

I managed to successfully call the constructor method, and then I moved on to trying to call an operator method (specifically the + operator). This is where things started to go wrong, and I'm unsure if I'm defining/calling the method properly now...

MyStringWrapper.h

#pragma once

#include <string>

class MyStringWrapper
{
public:
   static void InitializeAddresses();

   static MyStringWrapper* CastFrom(
      const uintptr_t address);

   MyStringWrapper(
      const std::wstring& original);

   MyStringWrapper operator+(
      const MyStringWrapper& other);

private:
   uintptr_t m_string_address;
   int m_u1;
   int m_u2;
   // Still need to figure out how to determine the correct size of a class, but hopefully this is big enough.
   char mData[2900];

   static struct FunctionDefinitions
   {
      typedef void(__thiscall* Create_FromArray)(void* pThis, wchar_t const* original);
      Create_FromArray CreateFromArray;

      // I think my issue is here, should I be returning/providing MyStringWrapper objects or the original MyString objects (that I do not have the source for).
      // and... if I should be using MyString objects, how can I do this without the compiler being upset about incomplete types?
      // Original symbol "public: class MyString __thiscall MyString::operator+(class MyString const &)"
      typedef MyStringWrapper(__thiscall* Combine_MyString)(void* pThis, const MyStringWrapper& other);
      Combine_MyString CombineMyString;
   } CustomFunctions;
};

MyStringWrapper.cpp

#include "MyStringWrapper.h"
#include "GlobalDLLBases.h"

MyStringWrapper::FunctionDefinitions MyStringWrapper::CustomFunctions;

void MyStringWrapper::InitializeAddresses()
{
   CustomFunctions.CreateFromArray = FunctionDefinitions::Create_FromArray((DWORD_PTR)DLLBase + 0x2c40);

   CustomFunctions.CombineMyString = FunctionDefinitions::Combine_MyString((DWORD_PTR)DLLBase + 0x3740);
}

MyStringWrapper* MyStringWrapper::CastFrom(
   const uintptr_t address)
{
   return reinterpret_cast<MyStringWrapper*>(address);
}

MyStringWrapper::MyStringWrapper(
   const std::wstring& original) :
   m_string_address(0),
   m_u1(0),
   m_u2(0)
{
   CustomFunctions.Create_FromArray(this, original.data());
}

MyStringWrapper MyStringWrapper::operator+(
   const MyStringWrapper& other)
{
   return CustomFunctions.CombineMyString(this, other);
}

Main.cpp

MyStringWrapper* obj1 = MyStringWrapper::CastFrom(address_to_existing_mystring);
MyStringWrapper* obj2 = MyStringWrapper::CastFrom(address_to_another_existing_mystring);
if(obj1 && obj2)
{
    // It crashes calling this, I expected ECX to hold the address of obj1, but the compiler seems to push both obj1 and obj2 addresses on to the stack and moves some other address into ecx.
    // It should only be pushing obj2's address, and moving obj1's address into ecx.
    MyStringWrapper final_product = *obj1 + *obj2;
}


问:
The specific steps to use Twilio to enable a landline for texting (TTL)?
I am seeing porting options but I know that is no longer needed. I know based on what eztexting and others are offering.

I am looking for documentation or someone to speak with who has made this happen.  I appreciate any help.


问:
compare log files and change text in one file while comparing with other logs
I am looking for a script in Linux where I can change the text in log files while comparing it with other files.

basically, I am exporting some Netflow logs from two different devices and from each log file there is something common. I want to compare that common string and replace it with some extra string.

e.g
There are files named as logA1.txt, logA2.txt logA3.txt... and so on.

data inside the files is as follows.

10.1.0.14|60647|YYYY|YYYY|

10.1.0.15|60647|YYYY|YYYY|

10.1.0.15|60647|YYYY|YYYY|

10.1.0.16|60647|YYYY|YYYY|

10.1.0.14|60611|YYYY|YYYY|

10.1.0.17|61117|YYYY|YYYY|

10.1.0.17|60111|YYYY|YYYY|

and in the second folder where I have different logs named as LogB1.txt, logB2.txt, .... so on.
data inside the files is as follows.

aaaaaa|10.1.0.14|

bbbbbb|10.1.0.15|

dddddd|10.1.0.16|

ccccccc|10.1.0.17|

i want to take "aaaaaa|10.1.0.14|" from second folder files and put in first folder files as.

aaaaaa|10.1.0.14|60647|YYYY|YYYY|

bbbbbb|10.1.0.15|60647|YYYY|YYYY|

bbbbbb|10.1.0.15|60647|YYYY|YYYY|

dddddd|10.1.0.16|60647|YYYY|YYYY|

aaaaaa|10.1.0.14|60611|YYYY|YYYY|

cccccc|10.1.0.17|61117|YYYY|YYYY|

cccccc|10.1.0.17|60111|YYYY|YYYY|

thanks in advance.

i'm looking for solution where i run the cron job nightly and it does the job for all files


问:
PHPMyAdmin not showing foreign-key related data in search or insert
Sometimes it happens so, that PHPMYadmin isn't displaying names (or at least some data) from foreign keys in Insert/Search pages. It seems to be just empty.

Our used version is 5.1.3

Can you please recommend on how to fix this?


问:
Stream live video over the network(udp,rtp-rtsp) with Python
I want to broadcast a video file or a live broadcast over the network in Python. Normally I do this using ffmpeg but due to some problems I don't want to use it. As an example in my research, they designed a stream as a sender and a receiver. While doing this, socket and cv2 are generally used. I can use the same. What I want to do is to broadcast the video file to (rtp/udp/rtsp or http) protocols and watch it instantly. To give an example, the broadcast of the video file can be watched at udp://224.1.100.1:5000. I think I can open and capture the file I want using CV2, but how should I go about broadcasting on the network. Do you have a sample socket code or framework that you would recommend?

`Import cv2, imutils, socket

filename =  'demo.mp4'

vid = cv2.VideoCapture(filename)

FPS = vid.get(cv2.CAP_PROP_FPS)

global TS

TS = (0.5/FPS)

BREAK=False

print('FPS:',FPS,TS)

totalNoFrames = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))

durationInSeconds = float(totalNoFrames) / float(FPS)

d=vid.Get (cv2.CAP_PROP_POS_MSEC)  print (durationInSeconds, d)`


问:
How to show a button on selecting the value in DropDown List
As a beginner in PHP.
I have a dropdownlist of event names and a button, And I tried to display it only when I selecting any value > 0 only. Please help me out.

Thanks in advance

```<code><?Php

    @$event=$_GET['event'];
    if(strlen($event) < 0 ){
    echo "Data Error";
    exit;
    }

    $sql="SELECT id,event_name FROM wp_evr_event order by id";

    if(isset($event) and strlen($event) > 0){
    $quer="SELECT id,fname,status,email,event_id  FROM  wp_evr_attendee where event_id=$event order by fname";}
    else{$quer="SELECT id,fname,status,email,event_id  FROM  wp_evr_attendee order by event_id";}

    echo "<form method=post name=Reload action=''>";

    echo "<select name='event' onchange=\"reload(this.form)\"><option value=''>please select..</option>";
    foreach ($con->query($sql) as $row){
    if($row['id']==@$event){echo "<option selected value='$row[id]'>$row[event_name]</option>"."<BR>";}
    else{echo  "<option value='$row[id]'>$row[event_name]</option>";
        }
    }
    echo "</select>";

    ?>

</div>
<div class="container">
<table>
    <tr>
    <td class='c_td'>id</td>
    <td class='c_td'>name</td>
    <td class='c_td'>status</td>
    <td class='c_td'>email</td>
    <td class='c_td'>event_id</td>
    <td class='c_td'>edit</td> <td>delete</td>
    </tr>
    <?php
    $i=1;
    foreach ($con->query($quer) as $row2) {
    $i=$i+1;
    ?>
    <tr>
    <td class='i_td'><?php  echo $row2['id']    ?> </td>
    <td class='i_td'><?php  echo $row2['fname']    ?> </td>
    <td class='i_td'><?php  echo $row2['status']    ?> </td>
    <td class='i_td'><?php  echo $row2['email']    ?> </td>
    <td class='i_td'><?php  echo $row2['event_id']    ?> </td>
    </tr>

    <?php
    }
    ?>
</code>```

Because only the names of attendees will be exported for the selected event

```<code><?php
 echo '<td><a class="btn" href="test3.php?event=' . $row2['event_id'] . '">Export To Excel</a>     </td>';
?>
</code>```

I tried this

```<code> select:invalid + button {
  display: none;
}
</code>```

Body:
As a beginner in PHP.
I have a dropdownlist of event names and a button, And I tried to display it only when I selecting any value > 0 only. Please help me out.

Thanks in advance

<?Php

    @$event=$_GET['event'];
    if(strlen($event) < 0 ){
    echo "Data Error";
    exit;
    }

    $sql="SELECT id,event_name FROM wp_evr_event order by id";

    if(isset($event) and strlen($event) > 0){
    $quer="SELECT id,fname,status,email,event_id  FROM  wp_evr_attendee where event_id=$event order by fname";}
    else{$quer="SELECT id,fname,status,email,event_id  FROM  wp_evr_attendee order by event_id";}

    echo "<form method=post name=Reload action=''>";

    echo "<select name='event' onchange=\"reload(this.form)\"><option value=''>please select..</option>";
    foreach ($con->query($sql) as $row){
    if($row['id']==@$event){echo "<option selected value='$row[id]'>$row[event_name]</option>"."
";}
    else{echo  "<option value='$row[id]'>$row[event_name]</option>";
        }
    }
    echo "</select>";

    ?>

    id
    name
    status
    email
    event_id
    edit	 delete

    <?php
    $i=1;
    foreach ($con->query($quer) as $row2) {
    $i=$i+1;
    ?>

    <?php  echo $row2['id']    ?>
    <?php  echo $row2['fname']    ?>
    <?php  echo $row2['status']    ?>
    <?php  echo $row2['email']    ?>
    <?php  echo $row2['event_id']    ?>

    <?php
    }
    ?>

Because only the names of attendees will be exported for the selected event

<?php
 echo 'Export To Excel     	';
?>

I tried this

 select:invalid + button {
  display: none;
}


问:
Create Kotlin multiplatform mobile project from cli
How to create a Kotlin multiplatform mobile project via command line in linux?

I installed Kotlin command-line compiler (kotlinc).

And Gradle build tool.

I add gradle and kotlin bin directory to my PATH.

Now, I would like to create an example multiplatform project. Is there any template I can use to set up the project structure?

For Gradle, I found good tutorial, such as to build CLI applications, but not mobile. On the Kotlin side, I found a nice tutorial by using the GUI.


问:
gitlab docker registery equivalent in github
I am new to docker and I wanted to create a prod container.

For this, I decided to take reference from the company I work at.

They have something like this in dockerfile.prod

```<code>
# ---- Base ----
FROM registry.gitlab.com/somepath/api-base:latest AS base
COPY package.json .

# ---- Build ----
FROM base AS build

COPY . .
RUN ls -al
RUN yarn install --frozen-lockfile --prod
RUN yarn build:ci
</code>```

In github, what would be the equivalent for this?

```<code>FROM registry.gitlab.com/somepath/api-base:latest AS base
</code>```

Body:
I am new to docker and I wanted to create a prod container.

For this, I decided to take reference from the company I work at.

They have something like this in dockerfile.prod

# ---- Base ----
FROM registry.gitlab.com/somepath/api-base:latest AS base
COPY package.json .

# ---- Build ----
FROM base AS build

COPY . .
RUN ls -al
RUN yarn install --frozen-lockfile --prod
RUN yarn build:ci

In github, what would be the equivalent for this?

FROM registry.gitlab.com/somepath/api-base:latest AS base


问:
Convert 3D CBCT dicom to 2D Panaromic View
I want to generate 2D panarmoic view from the series of 3D cbct dental images by python.

I am converting the series of 3D Cbct images to 2D panaromic view by python. The code is working fine but the output is not complete.

```<code>import sys
import vtkmodules.all as vtk
from PyQt5 import QtCore, QtWidgets
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor

def create_reader(dir):

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dir)
    reader.Update()

    return reader

def create_center(reader):

    (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()

    center = [x0 + xSpacing * 0.5 * (xMin + xMax),
            y0 + ySpacing * 0.5 * (yMin + yMax),
            z0 + zSpacing * 0.5 * (zMin + zMax)]

    return center

def create_sagittal_slice_matrix(center):

    #Create Sagittal Slice Matrix
    sagittal = vtk.vtkMatrix4x4()
    sagittal.DeepCopy((0, 0, -1, center[0],
                        1, 0, 0, center[1],
                        0, -1, 0, center[2],
                        0, 0, 0, 1))

    return sagittal

def create_resliced_image(reader, sagittal, frame):

    # Reslice image
    widget = QVTKRenderWindowInteractor(frame)
    slice = vtk.vtkImageReslice()
    slice.SetInputConnection(reader.GetOutputPort())
    slice.SetOutputDimensionality(2)
    slice.SetResliceAxes(sagittal)
    slice.SetInterpolationModeToLinear()

    return widget, slice

def create_display_image_actor(slice):

    # Display the image
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(slice.GetOutputPort())
    # renderer = vtk.vtkRenderer()

    return actor

def adjust_renderer_settings(renderer, widget, actor):

    # Remove Renderer And Reset
    renderer.RemoveAllViewProps()
    renderer.ResetCamera()
    widget.GetRenderWindow().Render()
    renderer.AddActor(actor)

    widget.GetRenderWindow().AddRenderer(renderer)

    return widget

def setup_interaction(widget):
    # Set up the interaction
    slice_interactorStyle = vtk.vtkInteractorStyleImage()
    slice_interactor = widget.GetRenderWindow().GetInteractor()
    slice_interactor.SetInteractorStyle(slice_interactorStyle)
    widget.GetRenderWindow().SetInteractor(slice_interactor)
    widget.GetRenderWindow().Render()

    return slice_interactor
    # Start interaction
    # slice_interactor.Start()

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()

        reader = create_reader(r"C:\work.ateeb\2.16.840.114421.10241.9572018034.9603554034\DECOMPRESSED\One")
        center = create_center(reader)
        sagittal = create_sagittal_slice_matrix(center)

        self.vtkWidget, slice = create_resliced_image(reader, sagittal, self.frame)
        self.vl.addWidget(self.vtkWidget)

        # create renderer
        renderer = vtk.vtkRenderer()

        # create actor
        actor = create_display_image_actor(slice)

        self.vtkWidget = adjust_renderer_settings(renderer, self.vtkWidget, actor)

        slice_interactor = setup_interaction(self.vtkWidget)
        self.show()

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        slice_interactor.Initialize()
        slice_interactor.Start()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    window = MainWindow()

    sys.exit(app.exec_())
</code>```

I was expecting the output like this
enter image description here

But the output the code is generating is:
enter image description here

Body:
I want to generate 2D panarmoic view from the series of 3D cbct dental images by python.

I am converting the series of 3D Cbct images to 2D panaromic view by python. The code is working fine but the output is not complete.

import sys
import vtkmodules.all as vtk
from PyQt5 import QtCore, QtWidgets
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor

def create_reader(dir):

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dir)
    reader.Update()

    return reader

def create_center(reader):

    (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()

    center = [x0 + xSpacing * 0.5 * (xMin + xMax),
            y0 + ySpacing * 0.5 * (yMin + yMax),
            z0 + zSpacing * 0.5 * (zMin + zMax)]

    return center

def create_sagittal_slice_matrix(center):

    #Create Sagittal Slice Matrix
    sagittal = vtk.vtkMatrix4x4()
    sagittal.DeepCopy((0, 0, -1, center[0],
                        1, 0, 0, center[1],
                        0, -1, 0, center[2],
                        0, 0, 0, 1))

    return sagittal

def create_resliced_image(reader, sagittal, frame):

    # Reslice image
    widget = QVTKRenderWindowInteractor(frame)
    slice = vtk.vtkImageReslice()
    slice.SetInputConnection(reader.GetOutputPort())
    slice.SetOutputDimensionality(2)
    slice.SetResliceAxes(sagittal)
    slice.SetInterpolationModeToLinear()

    return widget, slice

def create_display_image_actor(slice):

    # Display the image
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(slice.GetOutputPort())
    # renderer = vtk.vtkRenderer()

    return actor

def adjust_renderer_settings(renderer, widget, actor):

    # Remove Renderer And Reset
    renderer.RemoveAllViewProps()
    renderer.ResetCamera()
    widget.GetRenderWindow().Render()
    renderer.AddActor(actor)

    widget.GetRenderWindow().AddRenderer(renderer)

    return widget

def setup_interaction(widget):
    # Set up the interaction
    slice_interactorStyle = vtk.vtkInteractorStyleImage()
    slice_interactor = widget.GetRenderWindow().GetInteractor()
    slice_interactor.SetInteractorStyle(slice_interactorStyle)
    widget.GetRenderWindow().SetInteractor(slice_interactor)
    widget.GetRenderWindow().Render()

    return slice_interactor
    # Start interaction
    # slice_interactor.Start()

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()

        reader = create_reader(r"C:\work.ateeb\2.16.840.114421.10241.9572018034.9603554034\DECOMPRESSED\One")
        center = create_center(reader)
        sagittal = create_sagittal_slice_matrix(center)

        self.vtkWidget, slice = create_resliced_image(reader, sagittal, self.frame)
        self.vl.addWidget(self.vtkWidget)

        # create renderer
        renderer = vtk.vtkRenderer()

        # create actor
        actor = create_display_image_actor(slice)

        self.vtkWidget = adjust_renderer_settings(renderer, self.vtkWidget, actor)

        slice_interactor = setup_interaction(self.vtkWidget)
        self.show()

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        slice_interactor.Initialize()
        slice_interactor.Start()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    window = MainWindow()

    sys.exit(app.exec_())

I was expecting the output like this
enter image description here

But the output the code is generating is:
enter image description here


问:
Javascript smart and good way to make array of size N where each object in the array has a certain probability?
So basically I have an array and I want to randomly put 100 objects inside it, each object also have a chance property like 5 for 5% or 10 for 10%. My question is, does anyone have any idea for a smart way to do this?

I tried something like picking a random number from 1-100 inside a for loop and with multiple if statements just add an object so for example if the number is between five and zero then I'll put the 5% probability object in the array and repeat. This solution is obviously not very elegant and efficient though does anyone have any ideas for how I can accomplish this?


问:
Two different keys decrypting same content in javascript
Is it possible (for example, using some library) to encrypt a secret using two keys in such a way that each of these keys (separately) is able to decrypt this secret.</p>


问:
Send file to WhatsApp API's '/media' endpoint present in S3 bucket without storing it locally
TL;DR:
I  want to send a file that is in an S3 bucket to WhatsApp API's /media endpoint without saving it locally first.

Long Version:
I'm trying to store file in WhatsApp server by sending request to /media endpoint in WhatsApp cloud API. I'm getting a success response when file is present locally by using fs.createReadStream('file-path'), but failing when I get file from S3 and create a read stream.

In terms of code:

```<code>const stream = s3.getObject({ Bucket: this.bucketName, Key: fileNameWithFullPath }).createReadStream()
</code>```

Then I add header, and other required parameters and send the request.

```<code>const formdata = new FormData();
formdata.append("file", stream, { contentType: "application/pdf" });
formdata.append("messaging_product", "whatsapp");
try {
  const {
  data: { id: mediaId },
  } = await axios.post(`https://graph.facebook.com/${this.graphAPIVersion}/${this.senderPhoneNumberId}/media`, formdata, {
  headers: {
  Authorization: `Bearer ${this.accessToken}`,
  ...formdata.getHeaders(),
  }
});
  console.log("Success: ", mediaId);
}
catch (error) {
  console.error("Error: ", error)
}
</code>```

The error has status code 500 with no specific cause.

```<code>error: {
  statusCode: 500,
  statusMessage: 'Internal Server Error',
  message: 'An unknown error has occurred.',
  type: 'OAuthException',
  code: 1,
  fbtrace_id: 'AxiCaSoItKscIF1qVgy3bej'
}
</code>```

I'm pretty sure that nothing else is wrong with this request because when I replace S3's createReadStream() with fs.createReadStream('file-path'), it is working fine.

Please keep in mind that there is no local file storage available in the server from where this function will be called. That's why I won't be able to store the file locally first before sending request to WhatsApp API's /media endpoint.

Body:
TL;DR:
I  want to send a file that is in an S3 bucket to WhatsApp API's /media endpoint without saving it locally first.

Long Version:
I'm trying to store file in WhatsApp server by sending request to /media endpoint in WhatsApp cloud API. I'm getting a success response when file is present locally by using fs.createReadStream('file-path'), but failing when I get file from S3 and create a read stream.

In terms of code:

const stream = s3.getObject({ Bucket: this.bucketName, Key: fileNameWithFullPath }).createReadStream()

Then I add header, and other required parameters and send the request.

const formdata = new FormData();
formdata.append("file", stream, { contentType: "application/pdf" });
formdata.append("messaging_product", "whatsapp");
try {
  const {
  data: { id: mediaId },
  } = await axios.post(`https://graph.facebook.com/${this.graphAPIVersion}/${this.senderPhoneNumberId}/media`, formdata, {
  headers: {
  Authorization: `Bearer ${this.accessToken}`,
  ...formdata.getHeaders(),
  }
});
  console.log("Success: ", mediaId);
}
catch (error) {
  console.error("Error: ", error)
}

The error has status code 500 with no specific cause.

error: {
  statusCode: 500,
  statusMessage: 'Internal Server Error',
  message: 'An unknown error has occurred.',
  type: 'OAuthException',
  code: 1,
  fbtrace_id: 'AxiCaSoItKscIF1qVgy3bej'
}

I'm pretty sure that nothing else is wrong with this request because when I replace S3's createReadStream() with fs.createReadStream('file-path'), it is working fine.

Please keep in mind that there is no local file storage available in the server from where this function will be called. That's why I won't be able to store the file locally first before sending request to WhatsApp API's /media endpoint.


问:
Carrierwave multiple images: operator does not exist: json = unknown
In my product model, I have an images json type column, for storing
multiple product images through Carrierwave in an array. I'm using Postgresql.

```<code>t.json "images"
</code>```

I made a rake task to import products, that imports the images from a JSON file that contains images like this:

In my rake task:

```<code>record = Product.find_or_create_by(
   images: item['AllImages'].to_json
}
</code>```

I'm getting the error:

```<code>No operator matches the given name and argument types. You might need to add explicit type casts.
</code>```

¿Am I missing something?

Body:
In my product model, I have an images json type column, for storing
multiple product images through Carrierwave in an array. I'm using Postgresql.

t.json "images"

I made a rake task to import products, that imports the images from a JSON file that contains images like this:

In my rake task:

record = Product.find_or_create_by(
   images: item['AllImages'].to_json
}

I'm getting the error:

No operator matches the given name and argument types. You might need to add explicit type casts.

¿Am I missing something?


问:
how to launch a certain fragment through the lower navigation view, if the role can be a user (client, specialist)
It is necessary that if a specialist's account is authorized, then when clicking profile in bottomNavView, SpecProfileFragment is launched, just the opposite when the client is authorized


问:
Use string variable (or some other way) as command with args?
Is it possible to pass command (with args) as variable in ansible?

For example, I have this playbook:

- name: My playbook
  hosts: myhosts
  tasks:
    - name: Run Service Command
      ansible.builtin.command: "docker compose run --rm service {{ cmd }}"
      args:
        chdir: "{{ PATH_COMPOSE_DIR }}"
```

And then I try to run it as:

ansible-playbook my-book.yml -e cmd="my-cmd --arg1 --arg2"

But then it just stucks on running it and nothing happens. Don't see any errors, anything.

If I fully define command on ansible task or just use variables on arg values, it works. But would be nice to be able to pass whole command, so playbook could be more versatile.

Body:
Is it possible to pass command (with args) as variable in ansible?

For example, I have this playbook:

- name: My playbook
  hosts: myhosts
  tasks:
    - name: Run Service Command
      ansible.builtin.command: "docker compose run --rm service {{ cmd }}"
      args:
        chdir: "{{ PATH_COMPOSE_DIR }}"

And then I try to run it as:

ansible-playbook my-book.yml -e cmd="my-cmd --arg1 --arg2"

But then it just stucks on running it and nothing happens. Don't see any errors, anything.

If I fully define command on ansible task or just use variables on arg values, it works. But would be nice to be able to pass whole command, so playbook could be more versatile.


问:
Getting this error Unpermitted parameter: :line_items_attributes when editing and downloading invoice
I a editing invoice and trying to download it but getting an error that Unpermitted parameter: :line_items_attributes whereas i have permitted it in controller and it is working on new form but not on edit form

I've tried tp permit them in controller and its not working yet applied debugger and tried finding them value is not not saving in parameters


问:
Hide bottomNavigation when bottomSheet is open in Compose
I have a Scaffold which contains BottomNavigation with 4 menus/items and each item has it's specific screen which displays when we click on the bottom navigation item. On the third screen/menu I have to show a BottomSheet that covers the bottomNavigation also. Right now I am using ModalBottomSheetLayout but with it bottom navigation doesn't get hidden.</p>


问:
Program takes a lot of time to end because of this warning Executor: Issue communicating with driver in heartbeater
I have the standalone spark cluster with one master and four workers which must read the large oracle table and process it. Each node has 30G Ram. In average program time is about 1.7 Hours, but sometimes it takes a lot of time because of this warning:

```<code>WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.rpc.RpcTimeoutException: Futures timed out after [10000 milliseconds]. This timeout is controlled by spark.executor.heartbeatInterval
at org.apache.spark.rpc.RpcTimeout.org$apache$spark$rpc$RpcTimeout$$createRpcTimeoutException(RpcTimeout.scala:47)
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:62)
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:58)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:76)
at org.apache.spark.rpc.RpcEndpointRef.askSync(RpcEndpointRef.scala:103)
at org.apache.spark.executor.Executor.reportHeartBeat(Executor.scala:996)
at org.apache.spark.executor.Executor.$anonfun$heartbeater$1(Executor.scala:212)
at org.apache.spark.executor.Executor$$Lambda$356/321695195.apply$mcV$sp(Unknown Source)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1996)
at org.apache.spark.Heartbeater$$anon$1.run(Heartbeater.scala:46)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.TimeoutException: Futures timed out after [10000 milliseconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:259)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:263)
at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:293)
at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
... 14 more
</code>```

I search and added these options to the spark_submit command.But, still receive the same warning.

```<code> --conf spark.sql.broadcastTimeout=3600 --conf spark.rpc.message.maxSize=1024  --conf spark.rpc.askTimeout=600s
</code>```

Also, I set 28G for driver memory and 24G for executor memory. Moreover, I read this post:

```<code>https://stackoverflow.com/a/54038675/6640504
</code>```

As this comment said, it is not right to increase spark.network.timeout and spark.executor.heartbeatInterval to 10000000 with the same value. I am sure the program takes more time to run with this setting.

Would you please guide me how to solve this problem and improve speed of the program?

Any help is really appreciated.

Body:
I have the standalone spark cluster with one master and four workers which must read the large oracle table and process it. Each node has 30G Ram. In average program time is about 1.7 Hours, but sometimes it takes a lot of time because of this warning:

WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.rpc.RpcTimeoutException: Futures timed out after [10000 milliseconds]. This timeout is controlled by spark.executor.heartbeatInterval
at org.apache.spark.rpc.RpcTimeout.org$apache$spark$rpc$RpcTimeout$$createRpcTimeoutException(RpcTimeout.scala:47)
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:62)
at org.apache.spark.rpc.RpcTimeout$$anonfun$addMessageIfTimeout$1.applyOrElse(RpcTimeout.scala:58)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:76)
at org.apache.spark.rpc.RpcEndpointRef.askSync(RpcEndpointRef.scala:103)
at org.apache.spark.executor.Executor.reportHeartBeat(Executor.scala:996)
at org.apache.spark.executor.Executor.$anonfun$heartbeater$1(Executor.scala:212)
at org.apache.spark.executor.Executor$$Lambda$356/321695195.apply$mcV$sp(Unknown Source)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1996)
at org.apache.spark.Heartbeater$$anon$1.run(Heartbeater.scala:46)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.TimeoutException: Futures timed out after [10000 milliseconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:259)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:263)
at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:293)
at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
... 14 more

I search and added these options to the spark_submit command.But, still receive the same warning.

 --conf spark.sql.broadcastTimeout=3600 --conf spark.rpc.message.maxSize=1024  --conf spark.rpc.askTimeout=600s

Also, I set 28G for driver memory and 24G for executor memory. Moreover, I read this post:

https://stackoverflow.com/a/54038675/6640504

As this comment said, it is not right to increase spark.network.timeout and spark.executor.heartbeatInterval to 10000000 with the same value. I am sure the program takes more time to run with this setting.

Would you please guide me how to solve this problem and improve speed of the program?

Any help is really appreciated.


问:
Nunit: Custom Test Execution
I have a custom TestMethodAttribute in MSTest and want to build something similar in NUnit.

The Custom TestMethodAttribute in MSTest:

```<code>public class CustomTestMethod : TestMethodAttribute
{
   public override TestResult[] Execute(ITestMethod testMethod)
   {

      if(SomeConditon){
            var results = new[]
            {
                new TestResult
                {
                    Outcome = UnitTestOutcome.Inconclusive,
                    TestContextMessages = "Test Skipped"
                }
            };
            return results;
      }
      return base.Execute(testMethod);
   }
}
</code>```

I this possible in Nunit and yes how can I do this?

Title: Nunit: Custom Test Execution

Body:
I have a custom TestMethodAttribute in MSTest and want to build something similar in NUnit.

The Custom TestMethodAttribute in MSTest:

public class CustomTestMethod : TestMethodAttribute
{
   public override TestResult[] Execute(ITestMethod testMethod)
   {

      if(SomeConditon){
            var results = new[]
            {
                new TestResult
                {
                    Outcome = UnitTestOutcome.Inconclusive,
                    TestContextMessages = "Test Skipped"
                }
            };
            return results;
      }
      return base.Execute(testMethod);
   }
}

I this possible in Nunit and yes how can I do this?


问:
Python dict-how to send both default and add user input value
I have requirement to set the default value if the tag is None ,else need to keep the default value and add user input tag for AWS Secret Manager Create secrets.

Here is the current code-

```<code>def create_secret(self, secret_name, secret_value, tags_dict=None):
    default_tag = [{"Key": "applicationid", "Value": "AP149393"}]
    if tags_dict is None:
        tags_dict = default_tag
    create_response = {}
    for region, client in self.client.items():
        try:
            create_secret = {"Name": secret_name}
            if isinstance(secret_value, str):
                create_secret["SecretString"] = secret_value
            elif isinstance(secret_value, bytes):
                create_secret["SecretBinary"] = secret_value
            logging.info(f'Creating secret {secret_name} in the {region} region')
            create_response = client.create_secret(**create_secret, Tags=tags_dict)
        except Exception as e:
            logging.info(f'Could not create a secret {secret_name} in the {region} region. Error: {e}')
    return create_response
</code>```

I have tried to parse with else condition and add tags_dict = {default_tag, tags_dict} . this has issue with the datatype being sent.

  if tags_dict is not None:
      tags_dict = tags_dict, default_tag
  else:
      tags_dict = default_tag
  #tags_dict = tags_dict if tags_dict is not None else default_tag
```

Body:
I have requirement to set the default value if the tag is None ,else need to keep the default value and add user input tag for AWS Secret Manager Create secrets.

Here is the current code-

def create_secret(self, secret_name, secret_value, tags_dict=None):
    default_tag = [{"Key": "applicationid", "Value": "AP149393"}]
    if tags_dict is None:
        tags_dict = default_tag
    create_response = {}
    for region, client in self.client.items():
        try:
            create_secret = {"Name": secret_name}
            if isinstance(secret_value, str):
                create_secret["SecretString"] = secret_value
            elif isinstance(secret_value, bytes):
                create_secret["SecretBinary"] = secret_value
            logging.info(f'Creating secret {secret_name} in the {region} region')
            create_response = client.create_secret(**create_secret, Tags=tags_dict)
        except Exception as e:
            logging.info(f'Could not create a secret {secret_name} in the {region} region. Error: {e}')
    return create_response

I have tried to parse with else condition and add tags_dict = {default_tag, tags_dict} . this has issue with the datatype being sent.

  if tags_dict is not None:
      tags_dict = tags_dict, default_tag
  else:
      tags_dict = default_tag
  #tags_dict = tags_dict if tags_dict is not None else default_tag


问:
Meta Tags React Not Working Properly In React + Codeignitor
because meta tags does not work in react so I used an approach, which is when an api call hit the controller, I reads the index.html file of build and write the meta tags dynamically from backend and then send response. it is working like index.html is being updating but when I test that on meta preview app (https://metapreview.app/, https://metatags.io/) etc, it does not picking the tags of the link that I have entered. For Example I have two links

https://ukvisa.herosolutions.com.pk/

https://ukvisa.herosolutions.com.pk/faq

when I open first link in website and go to meta preview apps it shows mw the tags of link 1 and when I open second link in meta preview app without opening second link on my website it does not shows the second link tags it still show the tags of link 1.

How meta tags bots of social media works exactly? When a link is shared the hit that link and get the latest html or get the html without triggering that link that have been shared?

Can anyone help me with this. I am so confused.


问:
Python Dask: Unable to convert Date column from PST,PDT to UTC using Dask
I am trying to convert date column timezone from PST,PDT to UTC using Dask but its giving me warning is there any way i can do it using dask without dateutils
df is dataframe i get by reading file with daskdf
I am trying this df[dfColumn] = daskdf.to_datetime(df[dfColumn], utc=True) its just adding +00:00 and giving a warning UnknownTimezoneWarning: tzname PST identified but not understood.  Passtzinfosargument in order to correctly return a timezone-aware datetime.  In a future version, this will raise an exception. category=UnknownTimezoneWarning)


问:
Create a model to identify the next available day based on waiting times
I am trying to create a operating theatre management tool. There is a list of patients waiting for operations and the time each operation takes. I also have a list of the time capacity of each theatre per day. I want to get the sheet to tell me what day the next availability is based on the total time of booked operations. For example if I have 16 hours of operating to do, I know the next available day is Thursday (because the capacity on Tuesday (today) is 8 hours, Wednesday has 4 hours, and Thursday has 8 hours)

I have tried various ways around this problem


问:
Why SpringBootTest with DEFINED_PORT can not be used along with TestRestTemplate for integration test?
I try to write an integration test using TestRestTemplate, but it can not be injected when using DEFINED_PORT inside @SpringBootTest (only using RANDOM_PORT), is it possible to use it with TestRestTemplate ?

```<code>@ActiveProfiles("integration-test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SampleApiControllerIntegrationTest {

    @LocalServerPort
    private Integer port;

    private final static Integer TEST_DEFINED_PORT = 8060;

    @Autowired
    private TestRestTemplate testRestTemplate;
}
</code>```

Body:
I try to write an integration test using TestRestTemplate, but it can not be injected when using DEFINED_PORT inside @SpringBootTest (only using RANDOM_PORT), is it possible to use it with TestRestTemplate ?

@ActiveProfiles("integration-test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SampleApiControllerIntegrationTest {

    @LocalServerPort
    private Integer port;

    private final static Integer TEST_DEFINED_PORT = 8060;

    @Autowired
    private TestRestTemplate testRestTemplate;
}


问:
Using SpaCy's EntityRecognizer to augment EntityRuler
I'm working in a domain-specific language, and I have a substantial but not exhaustive gazetteer that allows me to label maybe three-quarters of tokens. What I've got at the moment is:

Use EntityRuler/Phrasematcher to label known tokens

Take all the sentences where all their tokens have been labelled

Train an NER system on these sentences

Use this to label all the tokens in the other sentences.

What I'd like to do is: pass sentences first through the EntityRuler, and then use the NER only to label the tokens that are still unlabelled.

How do I construct a pipeline to do this? I'm doing all this through Python scripts rather than through .cfg files and command line interface.


问:
Migration - Comport 3.2 (delphi 7) to Comport 4.11 (delphi seattle)
I have an application with the old version for Delphi 7 and when I try to migrate to Delphi 10 Seattle several problems occur, how can I solve it? Could you help me, please?

The errors shown on the screen are attached

Example error code with comport 4.11:

```<code>Comport1.FlowControl.DTR := TDTRControl(GetEnumValue(TypeInfo(TDTRControl), Balanca.DTR.Valor));
Comport1.FlowControl.RTS := TRTSControl(GetEnumValue(TypeInfo(TRTSControl), Balanca.RTS.Valor));
Comport1.FlowControl.XOnXOff := TXOnXOffControl(GetEnumValue(TypeInfo(TXOnXOffControl), Balanca.XOnXOff.Valor));
Comport1.Options := PegaOpcoesBalanca(Balanca.OPTIONS.Valor);
</code>```

I'm trying to migrate the comport 3.2 component (delphi 7) to comport 4.11 (delphi 10 seattle). There are many different properties and I'm not able to adjust.

Body:
I have an application with the old version for Delphi 7 and when I try to migrate to Delphi 10 Seattle several problems occur, how can I solve it? Could you help me, please?

The errors shown on the screen are attached

Example error code with comport 4.11:

Comport1.FlowControl.DTR := TDTRControl(GetEnumValue(TypeInfo(TDTRControl), Balanca.DTR.Valor));
Comport1.FlowControl.RTS := TRTSControl(GetEnumValue(TypeInfo(TRTSControl), Balanca.RTS.Valor));
Comport1.FlowControl.XOnXOff := TXOnXOffControl(GetEnumValue(TypeInfo(TXOnXOffControl), Balanca.XOnXOff.Valor));
Comport1.Options := PegaOpcoesBalanca(Balanca.OPTIONS.Valor);

I'm trying to migrate the comport 3.2 component (delphi 7) to comport 4.11 (delphi 10 seattle). There are many different properties and I'm not able to adjust.


问:
mysql source command using variable name for script
I have two script for mysql:

crt_db_small.sql

crt_db_large.sql

I would like to be able to use a varible to set which script gets run with mysql.

I have tried the following:

```<code>set @sname := 'crt_db_large.sql';

source @sname ;
</code>```

But this errors with:

ERROR: Failed to open file '@sname', error: 2

Similarly, I'd also like to use a variable with use dbname command:

```<code>set @db := 'devdb';

use @db;

</code>```

This also errors with:

Unknown database '@db'

The bigger aim here is to have scripts that can be deployed to any environment without having to change them.

So we would have a  'settingsXXX.sql' file, where XXX is the environment name, and when running 'deplopyXXX.sql' would reference this,m and all scripts that get called by deployXXXX.sql simply refer to the variables for things like database name in the use command.

Is there a way to do this in mysql.

Body:
I have two script for mysql:

crt_db_small.sql

crt_db_large.sql

I would like to be able to use a varible to set which script gets run with mysql.

I have tried the following:

set @sname := 'crt_db_large.sql';

source @sname ;

But this errors with:

ERROR: Failed to open file '@sname', error: 2

Similarly, I'd also like to use a variable with use dbname command:

set @db := 'devdb';

use @db;

This also errors with:

Unknown database '@db'

The bigger aim here is to have scripts that can be deployed to any environment without having to change them.

So we would have a  'settingsXXX.sql' file, where XXX is the environment name, and when running 'deplopyXXX.sql' would reference this,m and all scripts that get called by deployXXXX.sql simply refer to the variables for things like database name in the use command.

Is there a way to do this in mysql.


问:
Convert rows from a SQL Query or Table to JSON format
I need a query result to be assigned to a column in the query response. I'm using 'For JSON' but I'm getting a strange error

This is the sub query I'm using and I want to convert the response to JSON

```<code>   {Account}.[Name],
        {Country}.[ISOCode], --Country ISO CODE
        {Account}.[BusinessTypeId], --AccountTypeID

        -- BusinessUnits
        (SELECT {BusinessUnit}.[Id] AS BusinessUnitId,
                {BusinessUnit}.[Name] AS BusinessUnitName
        FROM {BusinessUnit}
        INNER JOIN {BusinessUnit_Account} ON {BusinessUnit_Account}.[BusinessUnitId] = {BusinessUnit}.[Id]
        WHERE {BusinessUnit_Account}.[AccountId] = {Account}.[Id]
        FOR JSON PATH
        ) AS BusinessUnitUnits,

        {FarmDetail}.[FarmType_Id], --FarmTypeID
        {Account}.[Website],
</code>```

I don't know why but the answer keeps fields that are not interesting or bring too much information.

Response:

```<code>500197  10SXo-G6226jywTlZlXf1   460115      Mariana Teste   FJ  65088   {"Business":[{"BusinessUnitId":2,"BusinessUnitName":"Swine"},{"BusinessUnitId":1,"BusinessUnitName":"Poultry"}]}    0   ssgsgsg sgsgsg  sgsgsg  sgsgsg  sgfsgsg 0   0   14
</code>```

NOTE: I notice that the other fields are from another attributes of the table. But I only want to bring the attributes of the subquery

What am I doing wrong to not see the information that is underlined in red?

I've tried other options without success.

Thanks

Body:
I need a query result to be assigned to a column in the query response. I'm using 'For JSON' but I'm getting a strange error

This is the sub query I'm using and I want to convert the response to JSON

   {Account}.[Name],
        {Country}.[ISOCode], --Country ISO CODE
        {Account}.[BusinessTypeId], --AccountTypeID

        -- BusinessUnits
        (SELECT {BusinessUnit}.[Id] AS BusinessUnitId,
                {BusinessUnit}.[Name] AS BusinessUnitName
        FROM {BusinessUnit}
        INNER JOIN {BusinessUnit_Account} ON {BusinessUnit_Account}.[BusinessUnitId] = {BusinessUnit}.[Id]
        WHERE {BusinessUnit_Account}.[AccountId] = {Account}.[Id]
        FOR JSON PATH
        ) AS BusinessUnitUnits,

        {FarmDetail}.[FarmType_Id], --FarmTypeID
        {Account}.[Website],

I don't know why but the answer keeps fields that are not interesting or bring too much information.

Response:

500197  10SXo-G6226jywTlZlXf1   460115      Mariana Teste   FJ  65088   {"Business":[{"BusinessUnitId":2,"BusinessUnitName":"Swine"},{"BusinessUnitId":1,"BusinessUnitName":"Poultry"}]}    0   ssgsgsg sgsgsg  sgsgsg  sgsgsg  sgfsgsg 0   0   14

NOTE: I notice that the other fields are from another attributes of the table. But I only want to bring the attributes of the subquery

What am I doing wrong to not see the information that is underlined in red?

I've tried other options without success.

Thanks


问:
How to make a path follow the serie step in highcharts?
I am working with highcharts and I have a serie that uses userOptions step :'right'. This serie builds a path (serie.userOptions.pathList), which I would like to follow the parent. I am unable to find an attribute to change it.

I have tried finding an answer in the highcharts documentation but with no luck so far