问:
How to filter array with images and avoid images being re-fetching vue
Hi i want to filter the item but want to avoid re-fetching the images

Question: i want to filter the items without re-fetching the images

Issue: once you filter , you can see image being re-fetched.

here is my code: Codepen

Here is my code:

```<code><div class="display-results" v-for="item in resultQuery" :key="item.name">
        <div>{{item.name}}</div>
        <img :src="item.img" style="width:60px;height:45px;"/>
    </div>
</code>```

Please help me thanks in advance !!!

Body:
Hi i want to filter the item but want to avoid re-fetching the images

Question: i want to filter the items without re-fetching the images

Issue: once you filter , you can see image being re-fetched.

here is my code: Codepen

Here is my code:

{{item.name}}

Please help me thanks in advance !!!


来源: stackexchange

问:
How do I unzip a .gz file in google cloud storage bucket?
I modified the code from this thread to unzip a .gz file, but I'm getting the following error:

How do I unzip a .zip file in google cloud storage?

```<code>AttributeError: 'GzipFile' object has no attribute 'namelist'
</code>```

My code is as follows:

```<code>from google.cloud import storage
from gzip import GzipFile
import io

def gzipextract(bucketname, gzipfilename_with_path):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucketname)

    destination_blob_pathname = gzipfilename_with_path

    blob = bucket.blob(destination_blob_pathname)
    gzipbytes = io.BytesIO(blob.download_as_string())

    with GzipFile(fileobj = gzipbytes, mode = 'r') as mygzip:
        for contentfilename in mygzip.namelist():
            contentfile = mygzip.read(contentfilename)
            blob = bucket.blob(gzipfilename_with_path + "/" + contentfilename)
            blob.upload_from_string(contentfile)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I modified the code from this thread to unzip a .gz file, but I'm getting the following error:

How do I unzip a .zip file in google cloud storage?

AttributeError: 'GzipFile' object has no attribute 'namelist'

My code is as follows:

from google.cloud import storage
from gzip import GzipFile
import io

def gzipextract(bucketname, gzipfilename_with_path):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucketname)

    destination_blob_pathname = gzipfilename_with_path

    blob = bucket.blob(destination_blob_pathname)
    gzipbytes = io.BytesIO(blob.download_as_string())

    with GzipFile(fileobj = gzipbytes, mode = 'r') as mygzip:
        for contentfilename in mygzip.namelist():
            contentfile = mygzip.read(contentfilename)
            blob = bucket.blob(gzipfilename_with_path + "/" + contentfilename)
            blob.upload_from_string(contentfile)


问:
Postman no longer returns the entire body of data in the query
Postman is no longer returning the same information as before.

I include a user using Ruby, when I go to query I can't see the data:

{"status":"success","data": {"name":"Zachariah","salary":8907.639999999999417923390865325927734375,"age":69,"id":580},"message":"Successfully! Record has been added."}

In this case on Postman: https://dummy.restapiexample.com/api/v1/employee/580

{"status":"success","data":null,"message":"Successfully! Record has been fetched."}


问:
How to unit test fasthttp-router handler properly?
I am trying to write unit test for my app. I am using fasthttp lib. I also use fasthttp-routing lib. So the problem is that my handler is not standard type of fasthttp.HandlerFunc but routing.Handler.

In order to test HTTP handlers i've written the function that accepts handler fasthttp.RequestHandler parameter. The lib method fasthttp.Serve() accepts handler with type fasthttp.RequestHandler. I use this method to serve incoming connections from the given listener using the given handler. But my handler is of type routing.Handler

My handler:

func deleteExampleBOById(c *routing.Context) error { // Some logic }

My serve() function that i use to serve connections in order to unit test handlers:

```<code>func serve(handler fasthttp.RequestHandler, req *http.Request) (*http.Response, error) {
    ln := fasthttputil.NewInmemoryListener()
    defer ln.Close()

    go func() {
        err := fasthttp.Serve(ln, handler)
        if err != nil {
            panic(fmt.Errorf("failed to serve: %v", err))
        }
    }()

    client := http.Client{
        Transport: &http.Transport{
            DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
                return ln.Dial()
            },
        },
    }

    return client.Do(req)
}
</code>```

My actual unit test:

```<code>func TestHandler(t *testing.T) {
    r, err := http.NewRequest("GET", "http://localhost:8181/GoService/example/v1/1", nil)
    if err != nil {
        t.Error(err)
    }

    res, err := serve(getExampleBOById, r)
    if err != nil {
        t.Error(err)
    }

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Error(err)
    }

    fmt.Println(string(body))
}
</code>```

I am not able to serve my handler using function fasthttp.serve(), because of signature differences. I would like to ask any ideas how to convert routung.Handler to fasthttp.HandlerFunc or any other ideas how to unit test my handlers.

I don't have ideas how to solve it

Body:
I am trying to write unit test for my app. I am using fasthttp lib. I also use fasthttp-routing lib. So the problem is that my handler is not standard type of fasthttp.HandlerFunc but routing.Handler.

In order to test HTTP handlers i've written the function that accepts handler fasthttp.RequestHandler parameter. The lib method fasthttp.Serve() accepts handler with type fasthttp.RequestHandler. I use this method to serve incoming connections from the given listener using the given handler. But my handler is of type routing.Handler

My handler:

func deleteExampleBOById(c *routing.Context) error { // Some logic }

My serve() function that i use to serve connections in order to unit test handlers:

func serve(handler fasthttp.RequestHandler, req *http.Request) (*http.Response, error) {
    ln := fasthttputil.NewInmemoryListener()
    defer ln.Close()

    go func() {
        err := fasthttp.Serve(ln, handler)
        if err != nil {
            panic(fmt.Errorf("failed to serve: %v", err))
        }
    }()

    client := http.Client{
        Transport: &http.Transport{
            DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
                return ln.Dial()
            },
        },
    }

    return client.Do(req)
}

My actual unit test:

func TestHandler(t *testing.T) {
    r, err := http.NewRequest("GET", "http://localhost:8181/GoService/example/v1/1", nil)
    if err != nil {
        t.Error(err)
    }

    res, err := serve(getExampleBOById, r)
    if err != nil {
        t.Error(err)
    }

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        t.Error(err)
    }

    fmt.Println(string(body))
}

I am not able to serve my handler using function fasthttp.serve(), because of signature differences. I would like to ask any ideas how to convert routung.Handler to fasthttp.HandlerFunc or any other ideas how to unit test my handlers.

I don't have ideas how to solve it


问:
Gradient = nan when using DenseVariational layer
I work with binary data (named mimic) and i want to do a bayesian model to reproduce this data. To do so, i define this model :

```<code>def prior(kernel_size, bias_size, dtype=None):
    n = kernel_size + bias_size
    prior_model = tf.keras.Sequential(
        [
            tfp.layers.DistributionLambda(
                lambda t: tfp.distributions.MultivariateNormalDiag(
                    loc=tf.zeros(n), scale_diag=tf.ones(n)
                )
            )
        ]
    )
    return prior_model

def posterior(kernel_size, bias_size, dtype=None):
    n = kernel_size + bias_size
    posterior_model = tf.keras.Sequential(
        [
            tfp.layers.VariableLayer(
                tfp.layers.MultivariateNormalTriL.params_size(n), dtype=dtype
            ),
            tfp.layers.MultivariateNormalTriL(n),
        ]
    )
    return posterior_model

model = tf.keras.Sequential([
    tfkl.Input(shape=(), name='dummy_input'),
    tfpl.DistributionLambda(lambda t:
        latentNormal,
        convert_to_tensor_fn=lambda x : x.sample(batchSize)

    ),
tfp.layers.DenseVariational(units=inputDim,make_prior_fn=prior,make_posterior_fn=posterior,activation="sigmoid",use_bias=False),
    tfpl.DistributionLambda(lambda t:
        tfd.Bernoulli(probs=t)
    )
])

</code>```

Then i train the model :

```<code>negloglik = lambda data: -model(69).log_prob(data)
optimizer = tf.keras.optimizers.Adam()
loo=[]
kls = []
for epoch in trange(100):
    # print(epoch)
    # model.fit(mimic[:1453*32], mimic[:1453*32], epochs=1, batch_size=batchSize, verbose=0)
    idx = np.random.choice(np.arange(mimic.shape[0]), size=3*batchSize, replace=False)
    shuffled_ds = mimic.numpy()[idx]

    for nBatch in range(3):
        # print(nBatch)
        batch = shuffled_ds[nBatch*batchSize:(1+nBatch)*batchSize]
        with tf.GradientTape() as tape:
            tape.watch(model.trainable_variables)
            loss = negloglik(batch)
            loo.append(loss)
            grads = tape.gradient(loss, model.trainable_variables)

        optimizer.apply_gradients(zip(grads, model.trainable_variables))
    kl = tf.reduce_mean(tfd.kl_divergence(model(0), real_dist))
    kls.append(kl.numpy())

</code>```

More precisely, when i run for 1 epoch and one batch, my model is full of nan. enter image description here and the gradient is also nan enter image description here

Do you have any idea how can i solve that please ?

I tried to replace the VariationalDense by a Denser layer and everything works well. I don't get why DenseVariational is a problem here.

Body:
I work with binary data (named mimic) and i want to do a bayesian model to reproduce this data. To do so, i define this model :

def prior(kernel_size, bias_size, dtype=None):
    n = kernel_size + bias_size
    prior_model = tf.keras.Sequential(
        [
            tfp.layers.DistributionLambda(
                lambda t: tfp.distributions.MultivariateNormalDiag(
                    loc=tf.zeros(n), scale_diag=tf.ones(n)
                )
            )
        ]
    )
    return prior_model

def posterior(kernel_size, bias_size, dtype=None):
    n = kernel_size + bias_size
    posterior_model = tf.keras.Sequential(
        [
            tfp.layers.VariableLayer(
                tfp.layers.MultivariateNormalTriL.params_size(n), dtype=dtype
            ),
            tfp.layers.MultivariateNormalTriL(n),
        ]
    )
    return posterior_model

model = tf.keras.Sequential([
    tfkl.Input(shape=(), name='dummy_input'),
    tfpl.DistributionLambda(lambda t:
        latentNormal,
        convert_to_tensor_fn=lambda x : x.sample(batchSize)

    ),
tfp.layers.DenseVariational(units=inputDim,make_prior_fn=prior,make_posterior_fn=posterior,activation="sigmoid",use_bias=False),
    tfpl.DistributionLambda(lambda t:
        tfd.Bernoulli(probs=t)
    )
])

Then i train the model :

negloglik = lambda data: -model(69).log_prob(data)
optimizer = tf.keras.optimizers.Adam()
loo=[]
kls = []
for epoch in trange(100):
    # print(epoch)
    # model.fit(mimic[:1453*32], mimic[:1453*32], epochs=1, batch_size=batchSize, verbose=0)
    idx = np.random.choice(np.arange(mimic.shape[0]), size=3*batchSize, replace=False)
    shuffled_ds = mimic.numpy()[idx]

    for nBatch in range(3):
        # print(nBatch)
        batch = shuffled_ds[nBatch*batchSize:(1+nBatch)*batchSize]
        with tf.GradientTape() as tape:
            tape.watch(model.trainable_variables)
            loss = negloglik(batch)
            loo.append(loss)
            grads = tape.gradient(loss, model.trainable_variables)

        optimizer.apply_gradients(zip(grads, model.trainable_variables))
    kl = tf.reduce_mean(tfd.kl_divergence(model(0), real_dist))
    kls.append(kl.numpy())

More precisely, when i run for 1 epoch and one batch, my model is full of nan. enter image description here and the gradient is also nan enter image description here

Do you have any idea how can i solve that please ?

I tried to replace the VariationalDense by a Denser layer and everything works well. I don't get why DenseVariational is a problem here.


问:
Import svg as an object in Rmarkdown file
In my Rmarkdown script, I create an svg file that I want to display like this:

```<code>![alt text](file.svg)
</code>```

The problem is that the svg file is a temporary file (because my Rmarkdown is embedded in a pipeline, so the user doesn't always have the same path to the svg file).

So I want to store this svg file temporarily and create an object that will always be displayed in the html file generated by my Rmarkdown script.

Is there a way to do this?

Thank you very much

Body:
In my Rmarkdown script, I create an svg file that I want to display like this:

![alt text](file.svg)

The problem is that the svg file is a temporary file (because my Rmarkdown is embedded in a pipeline, so the user doesn't always have the same path to the svg file).

So I want to store this svg file temporarily and create an object that will always be displayed in the html file generated by my Rmarkdown script.

Is there a way to do this?

Thank you very much


问:
Twitter StreamingClient 2 rules
I'm running this file with 1 rule:

value1 = ('from:{user} -is:retweet').format(user)
value2 = ('to:{user} is:reply').format(user)

class CustomStream(StreamingClient):
    def on_connect(self):
        print("Connected!")
    def on_tweet(self, tweet):
        try:
            print(f"{tweet.id} {tweet.created_at} ({tweet.author_id}): {tweet.text}")
            print("-" * 50)
            time.sleep(0.2)
            return True
        except BaseException as e:
            sys.stderr.write('Error on_data: {}\n'.format(e))
            time.sleep(5)
        return True

stream = CustomStream(bearer_token=bearer_token, wait_on_rate_limit=True)
previousRules = stream.get_rules().data
if previousRules:
    stream.delete_rules(previousRules)
rule1 = StreamRule(value=value1)
# rule2 = StreamRule(value=value2)
stream.add_rules(rule1)
stream.filter(tweet_fields=["created_at", "author_id"],expansions=["author_id"])
```

Is it possible to run a stream by two rules at the same time? maybe possible to do multiprocessing, but i dont know how.Thanks

Title: Twitter StreamingClient 2 rules

Body:
I'm running this file with 1 rule:

value1 = ('from:{user} -is:retweet').format(user)
value2 = ('to:{user} is:reply').format(user)

class CustomStream(StreamingClient):
    def on_connect(self):
        print("Connected!")
    def on_tweet(self, tweet):
        try:
            print(f"{tweet.id} {tweet.created_at} ({tweet.author_id}): {tweet.text}")
            print("-" * 50)
            time.sleep(0.2)
            return True
        except BaseException as e:
            sys.stderr.write('Error on_data: {}\n'.format(e))
            time.sleep(5)
        return True

stream = CustomStream(bearer_token=bearer_token, wait_on_rate_limit=True)
previousRules = stream.get_rules().data
if previousRules:
    stream.delete_rules(previousRules)
rule1 = StreamRule(value=value1)
# rule2 = StreamRule(value=value2)
stream.add_rules(rule1)
stream.filter(tweet_fields=["created_at", "author_id"],expansions=["author_id"])

Is it possible to run a stream by two rules at the same time? maybe possible to do multiprocessing, but i dont know how.Thanks


问:
How to call function from one controller to another controller?
I'm using MVC3.
I have a ActionLink in my home page, which will redirect to another dueItem page:

```<code>@Html.ActionLink("Due Items", "Reports", "Reports", null, new { @class = "btn btn-sm btn-outline-secondary", @style = "color:black; font-size: 15px;" })
</code>```

The controller & model of dueItem page are below:

Model:

```<code> public class ViewModel
{
    public IEnumerable<InvHardwareModel>Report_HardwareListByExpiration { get; set; }

}
</code>```

Controller:

```<code>public class ReportsController : Controller
{
    // GET: Report
    public ActionResult Reports()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        ViewModel myViewModel = new ViewModel
        {
            User = GetSessionInfoFromSessions(),
            Params = new ParametersModel
            {
                Start_Date = new DateTime(2015, 12, 31),
                End_Date   = DateTime.Now.AddDays(60)
            }
        };

        myViewModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);

        return View(myViewModel);
    }
</code>```

Now I want to remove this ActionLink and copy the code to my home page directly, but after I run the project it has a error:
Error page

My home page are using different controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        var myViewAgModel = new ViewModel();
        //Populate ViewModel that goes into Dashboards and Reports.
        myViewAgModel.User = GetSessionInfoFromSessions();

        var InvHardwareModel =new InvHardwareModel();
        ViewBag.InvHardwareTotalPrice = InvHardwareModel.InvHardwareBalance(GetSessionInfoFromSessions(), true);
        ViewBag.InvHardwareTotal = InvHardwareModel.InvHardwareCount(GetSessionInfoFromSessions(), true);

        //myViewAgModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewAgModel);

        return View(myViewAgModel);

    }
</code>```

Thanks!

Body:
I'm using MVC3.
I have a ActionLink in my home page, which will redirect to another dueItem page:

@Html.ActionLink("Due Items", "Reports", "Reports", null, new { @class = "btn btn-sm btn-outline-secondary", @style = "color:black; font-size: 15px;" })

The controller & model of dueItem page are below:

Model:

 public class ViewModel
{
    public IEnumerable<InvHardwareModel>Report_HardwareListByExpiration { get; set; }

}

Controller:

public class ReportsController : Controller
{
    // GET: Report
    public ActionResult Reports()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        ViewModel myViewModel = new ViewModel
        {
            User = GetSessionInfoFromSessions(),
            Params = new ParametersModel
            {
                Start_Date = new DateTime(2015, 12, 31),
                End_Date   = DateTime.Now.AddDays(60)
            }
        };

        myViewModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);

        return View(myViewModel);
    }

Now I want to remove this ActionLink and copy the code to my home page directly, but after I run the project it has a error:
Error page

My home page are using different controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
        {
            return RedirectToAction("Login", "Account");
        }
        var myViewAgModel = new ViewModel();
        //Populate ViewModel that goes into Dashboards and Reports.
        myViewAgModel.User = GetSessionInfoFromSessions();

        var InvHardwareModel =new InvHardwareModel();
        ViewBag.InvHardwareTotalPrice = InvHardwareModel.InvHardwareBalance(GetSessionInfoFromSessions(), true);
        ViewBag.InvHardwareTotal = InvHardwareModel.InvHardwareCount(GetSessionInfoFromSessions(), true);

        //myViewAgModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewAgModel);

        return View(myViewAgModel);

    }

Thanks!


问:
iOS Universal Link only redirecting to the App under specific circumstances

The Problem:

I am building an app that uses PayPal for payments, and I set up universal links so that the user gets redirected into the app after the user has confirmed the payment at PayPal's site.

Universal links are working in general. But here is what I have discovered:

The following scenario works:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User has to log in and presses the login button.

User presses the confirmation button on the PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser closes, and the user gets redirected into the app.

Now when the user has just recently logged into PayPal then PayPal does not show the login page, instead the user has to only press one button. This scenario fails:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User does not have to log in and presses the confirmation button on PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser opens the website behind the universal link instead of redirecting to the app.

This scenario also works:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User does not have to log in, but actively logs out.

User has to log in and presses the login button.

User presses the confirmation button on the PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser closes, and the user gets redirected into the app.

This happens consistently and reproducible.

Some additional details:

I am developing the App using Flutter

I set up the Runner.entitlements as follows:

...
<key>com.apple.developer.associated-domains</key>
<array>
    <string>applinks:sub.example.com</string>
</array>
...
```
<ol start="3">
<li>I set up the Info.plist as follows for deep links with different schema:</li>
</ol>
<pre class="lang-xml prettyprint-override"><code>...
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>sub.example.com</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>web+example</string>
        </array>
    </dict>
</array>
...
</code>```

I set up the apple-app-site-association file on the website at https://sub.example.com/.well-known/apple-app-site-association as follows:

{
  "activitycontinuation": {},
  "webcredentials": {},
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "XXXXXXXXXX.com.example.example",
        "paths": [ "/*" ]
      }
    ]
  }
}
```

To open the urls from Flutter I am using the package url_launcher and simply call await launchUrl(nextActionUrl)

What I've tried and what I've learned:

I tried many things, before I discovered this consistent behavior. For example:

I connected my device to the mac and opened the console for it in xcode to see how the logs look like when it works and how it looks like when it does not work. I found out that when it works there is a log entry that requests the switch to my App from the SpringBoard-process: [Received trusted open application request for <applicationId> from <FBProcess: ...], but in the cases where it does not work there isn't a rejected request or anything. The SafariViewController does not even seem to try to go the universal link route and instead opens the link as a website directly.

For even more logs, I pressed and hold the volume buttons and clicked the lock screen button until a haptic feedback occurred. After that, I extracted the syslogs that were generated from the settings/privacy section via AirDrop on to the mac. I took a look at the swcutil_show.txt file and the universal link is definitely set up correctly there. I also skimmed around in the other logs, but I couldn't find anything helpful.

I have inspected the url_launcher package to see how it works for iOS and if there may be something wrong, but I didn't really find a problem. I only discovered that the package is using the SFSafariViewController and after some googling I've read the WKWebView would be more suitable, but it didn't seem to be the problem.

I googled a lot and found many problems related with setting up universal links correctly, but no topics about universal links sometimes working and sometimes not. The only thing close I found was that a universal link won't redirect you to your app if you type it into safari directly but if you click it for example from an email.

The workaround that works...

After I confirmed that it consistently works after logging in first, my theory was that it needs at least one navigation between opening the PayPal site in the browser and PayPal redirecting to the universal link.

To confirm my theory I created an intermediate page that redirects the user immediately after the load event to the PayPal site and I was disappointed. It didn't change anything.

Then I thought: Maybe it's the User-Interaction that is needed, and I change the intermediate page to only redirect if the user presses a button. And from there on, redirecting to the App using a universal link always worked.

But this isn't a nice solution - at max, this is an ugly workaround that may help someone.

My question(s)

Now I am not sure if this is a bug on Apple's side since I didn't find anything on the web or maybe even something strange on PayPal's side?

Am I doing something wrong?

Did someone experience the same thing and has a solution?

Thank you for your time and hopefully for your input on this!

Body:
The Problem:

I am building an app that uses PayPal for payments, and I set up universal links so that the user gets redirected into the app after the user has confirmed the payment at PayPal's site.

Universal links are working in general. But here is what I have discovered:

The following scenario works:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User has to log in and presses the login button.

User presses the confirmation button on the PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser closes, and the user gets redirected into the app.

Now when the user has just recently logged into PayPal then PayPal does not show the login page, instead the user has to only press one button. This scenario fails:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User does not have to log in and presses the confirmation button on PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser opens the website behind the universal link instead of redirecting to the app.

This scenario also works:

App opens the nextActionUrl from PayPal using SFSafariViewController.

User does not have to log in, but actively logs out.

User has to log in and presses the login button.

User presses the confirmation button on the PayPal site.

PayPal redirects to the return_url that was provided when creating the payment intent.

The browser closes, and the user gets redirected into the app.

This happens consistently and reproducible.

Some additional details:

I am developing the App using Flutter

I set up the Runner.entitlements as follows:

...
<key>com.apple.developer.associated-domains</key>
<array>
    <string>applinks:sub.example.com</string>
</array>
...

I set up the Info.plist as follows for deep links with different schema:

...
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>sub.example.com</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>web+example</string>
        </array>
    </dict>
</array>
...

I set up the apple-app-site-association file on the website at https://sub.example.com/.well-known/apple-app-site-association as follows:

{
  "activitycontinuation": {},
  "webcredentials": {},
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "XXXXXXXXXX.com.example.example",
        "paths": [ "/*" ]
      }
    ]
  }
}

To open the urls from Flutter I am using the package url_launcher and simply call await launchUrl(nextActionUrl)

What I've tried and what I've learned:

I tried many things, before I discovered this consistent behavior. For example:

I connected my device to the mac and opened the console for it in xcode to see how the logs look like when it works and how it looks like when it does not work. I found out that when it works there is a log entry that requests the switch to my App from the SpringBoard-process: [Received trusted open application request for <applicationId> from <FBProcess: ...], but in the cases where it does not work there isn't a rejected request or anything. The SafariViewController does not even seem to try to go the universal link route and instead opens the link as a website directly.

For even more logs, I pressed and hold the volume buttons and clicked the lock screen button until a haptic feedback occurred. After that, I extracted the syslogs that were generated from the settings/privacy section via AirDrop on to the mac. I took a look at the swcutil_show.txt file and the universal link is definitely set up correctly there. I also skimmed around in the other logs, but I couldn't find anything helpful.

I have inspected the url_launcher package to see how it works for iOS and if there may be something wrong, but I didn't really find a problem. I only discovered that the package is using the SFSafariViewController and after some googling I've read the WKWebView would be more suitable, but it didn't seem to be the problem.

I googled a lot and found many problems related with setting up universal links correctly, but no topics about universal links sometimes working and sometimes not. The only thing close I found was that a universal link won't redirect you to your app if you type it into safari directly but if you click it for example from an email.

The workaround that works...

After I confirmed that it consistently works after logging in first, my theory was that it needs at least one navigation between opening the PayPal site in the browser and PayPal redirecting to the universal link.

To confirm my theory I created an intermediate page that redirects the user immediately after the load event to the PayPal site and I was disappointed. It didn't change anything.

Then I thought: Maybe it's the User-Interaction that is needed, and I change the intermediate page to only redirect if the user presses a button. And from there on, redirecting to the App using a universal link always worked.

But this isn't a nice solution - at max, this is an ugly workaround that may help someone.

My question(s)

Now I am not sure if this is a bug on Apple's side since I didn't find anything on the web or maybe even something strange on PayPal's side?

Am I doing something wrong?

Did someone experience the same thing and has a solution?

Thank you for your time and hopefully for your input on this!


问:
Import OSM data to MongoDB
since last few days I am trying to import data from OpenStreetMap to MongoDB. After importing geojson to database cant create any index, beacuse of various errors described below.

Hello, since last few days I am trying to import data from OpenStreetMap to MongoDB. After importing geojson to database cant create any index, beacuse of various errors described below.
Steps to download and load files to databse, maybe you can find what I am doing wrong.

Download data with overpass api and save as JSON file using python

```<code>import requests
import json

overpass_url = "http://overpass-api.de/api/interpreter"
overpass_query = """
[out:json][timeout:600];
area["ISO3166-1"="PL"][admin_level=2];
(way["natural"="water"]["water"="lake"](area);
 relation["natural"="water"]["water"="lake"](area);
);
out geom;
"""
response = requests.get(overpass_url,
                        params={'data': overpass_query})
data = response.json()

</code>```

Format data with osmtojson and jq:

```<code>node --max_old_space_size=10000 `which osmtogeojson` input.json | ./jq-linux64 --compact-output ".features" > ../data_geojson/output.geojson
</code>```

I was following instructions from here.

Insert data with mongoimport:

```<code>mongoimport -d <db> -c <col> --file output.geojson --jsonArray -j 4 --batchSize=1000
</code>```

Inserting is successful but when trying to create 2dsphere index I am getting errors about Unclosed Loop for polygons or duplicates in nodes.

Do you know any package or script to help clear my data before inserting to db? Or maybe I am missing something in my steps?

Thanks :)

Title: Import OSM data to MongoDB

Body:
since last few days I am trying to import data from OpenStreetMap to MongoDB. After importing geojson to database cant create any index, beacuse of various errors described below.

Hello, since last few days I am trying to import data from OpenStreetMap to MongoDB. After importing geojson to database cant create any index, beacuse of various errors described below.
Steps to download and load files to databse, maybe you can find what I am doing wrong.

Download data with overpass api and save as JSON file using python

import requests
import json

overpass_url = "http://overpass-api.de/api/interpreter"
overpass_query = """
[out:json][timeout:600];
area["ISO3166-1"="PL"][admin_level=2];
(way["natural"="water"]["water"="lake"](area);
 relation["natural"="water"]["water"="lake"](area);
);
out geom;
"""
response = requests.get(overpass_url,
                        params={'data': overpass_query})
data = response.json()

Format data with osmtojson and jq:

node --max_old_space_size=10000 `which osmtogeojson` input.json | ./jq-linux64 --compact-output ".features" > ../data_geojson/output.geojson

I was following instructions from here.

Insert data with mongoimport:

mongoimport -d <db> -c <col> --file output.geojson --jsonArray -j 4 --batchSize=1000

Inserting is successful but when trying to create 2dsphere index I am getting errors about Unclosed Loop for polygons or duplicates in nodes.

Do you know any package or script to help clear my data before inserting to db? Or maybe I am missing something in my steps?

Thanks :)


问:
Ajax post not sending data to c# API Controller
I am trying to use $.Ajax() function to post data after a triggered event to my controller, but the data is not being sent. If I change the same function to "GET" method instead of "POST", it sends the data correctly, so I guess it has something to do with the VS2019 ASP.NET web project configuration, but I cannot find what it is.

The front code I am using is as follows:

marker.on('click', function (ev) {
                let id = ev.target.features.properties.id

                $.ajax({
                    url: "/public/pushDocuments",
                    method: "POST",
                    data: {
                        id: id,
                        objectname: "Prueba2",
                        bucketkey: "Prueba2"
                    },
                    contentType: "JSON",
                    success: function (data) {
                        launchViewer(data.urn);
                    }
                });

            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

and in the server side:

```<code>[HttpPost]
    [Route("public/pushDocuments")]
    public async Task<IActionResult> postDocument(string id, string objectname, string bucketkey)
    {
        //Code here

    }
</code>```

but, as I said, the server is not getting the information. Nevertheless, if I change the method to GET in the server and front, I do get the data I am sending, but it is not the correct way to do it, as the work I want to do inside the server function is to save some data to a database. I have done it multiple times in other project and works, but I cannot figure out why it is not working on this one.

Body:
I am trying to use $.Ajax() function to post data after a triggered event to my controller, but the data is not being sent. If I change the same function to "GET" method instead of "POST", it sends the data correctly, so I guess it has something to do with the VS2019 ASP.NET web project configuration, but I cannot find what it is.

The front code I am using is as follows:

marker.on('click', function (ev) {
                let id = ev.target.features.properties.id

                $.ajax({
                    url: "/public/pushDocuments",
                    method: "POST",
                    data: {
                        id: id,
                        objectname: "Prueba2",
                        bucketkey: "Prueba2"
                    },
                    contentType: "JSON",
                    success: function (data) {
                        launchViewer(data.urn);
                    }
                });

            });

and in the server side:

[HttpPost]
    [Route("public/pushDocuments")]
    public async Task<IActionResult> postDocument(string id, string objectname, string bucketkey)
    {
        //Code here

    }

but, as I said, the server is not getting the information. Nevertheless, if I change the method to GET in the server and front, I do get the data I am sending, but it is not the correct way to do it, as the work I want to do inside the server function is to save some data to a database. I have done it multiple times in other project and works, but I cannot figure out why it is not working on this one.


问:
How to retrieve multiple objects from PostgreSQL using a single JsonPath
Given the following JSON example:

```<code>{
    "root": {
        "child-1": {
            "grandchild-1": "value1",
            "grandchild-2": "value2",
            "grandchild-3": "value3"
        },
        "child-2": {
            "grandchild-4": "value4",
            "grandchild-5": {
                "grandgrandchild-1": "value5"
            }
        }
    }
}
</code>```

How to build a PostgreSQL query, using (one single) json-path that would return multiple object values?

E.g., [value3, value5]

The closest I came to is the following query:

```<code>select jsonb_path_query(resp_json, '$.*.child-1.grandchild-3'),
       jsonb_path_query(resp_json, '$.*.child-2.grandchild-5.grandgrandchild-1')
from req_resp_body;
</code>```

The obvious issue with this approach is that it requires one jsonb_path_query function call for each object. Given that the incoming nr. of objects is indefinite, this is unusable.

Notes:

The '*' instead of 'root' is on purpose, since the user of the query might not know the actual root name

Body:
Given the following JSON example:

{
    "root": {
        "child-1": {
            "grandchild-1": "value1",
            "grandchild-2": "value2",
            "grandchild-3": "value3"
        },
        "child-2": {
            "grandchild-4": "value4",
            "grandchild-5": {
                "grandgrandchild-1": "value5"
            }
        }
    }
}

How to build a PostgreSQL query, using (one single) json-path that would return multiple object values?

E.g., [value3, value5]

The closest I came to is the following query:

select jsonb_path_query(resp_json, '$.*.child-1.grandchild-3'),
       jsonb_path_query(resp_json, '$.*.child-2.grandchild-5.grandgrandchild-1')
from req_resp_body;

The obvious issue with this approach is that it requires one jsonb_path_query function call for each object. Given that the incoming nr. of objects is indefinite, this is unusable.

Notes:

The '*' instead of 'root' is on purpose, since the user of the query might not know the actual root name


问:
Multiple Instances of Random Hovering Events
I have a div that shows random positions of thumbnails within a grey div, when you over over the word 'Text'.

Now, I am trying to make multiples of these grey divs, that also appear in random positions when a page is refreshed.
Ideally it would be scalable (i.e.. I will have max 10 grey divs).

Here's what I have so far:

{ // scope isolating block

    const
        origins = [
            { x : 0, y : 0 },
            { x : 0, y : 1 },
            { x : 1, y : 1 },
            { x : 1, y : 0 },
        ],
        buttonImgEvent = (e) => {
            let img = e.currentTarget.nextElementSibling;
            if (img) {
                let
                    originIndex = Math.floor(origins.length * Math.random());
                const
                    wrapper = e.currentTarget.closest(".buttonThumbs"),
                    halfWidth = wrapper.clientWidth / 2,
                    halfHeight = wrapper.clientHeight / 2;
                do {
                    img.style.left = (
                        Math.random() * (halfWidth - img.clientWidth) +
                        origins[originIndex].x * halfWidth
                    ) + "px";
                    img.style.top = (
                        Math.random() * (halfHeight - img.clientHeight) +
                        origins[originIndex].y * halfHeight
                    ) + "px";
                    originIndex = (originIndex + 1) % origins.length;
                } while (img = img.nextElementSibling);
            }
        };

    for (const button of document.querySelectorAll(".buttonThumbs button")) {
        button.addEventListener("mouseover", buttonImgEvent);
        button.addEventListener("focus", buttonImgEvent);
    }

} // end scope isolation```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height:100%;
}

body {
  display:flex;
  align-items:center;
  justify-content:center;
}

.buttonThumbs {
  position:relative;
  width:30em;
  height:20em;
  max-width:100%;
  max-height:100%;
  margin:auto; /* force scrollbars if too small */
  background:#EEE;
}

.buttonThumbs > * {
  position:absolute;
}

.buttonThumbs button {
  top:50%;
  left:50%;
  border:0;
  background:transparent;
  transform:translate(-50%, -50%);
}

.buttonThumbs img {
  width:100px;
  height:100px;
  opacity:0;
  transition:opacity 1s;
}

.buttonThumbs button:focus ~ img,
.buttonThumbs button:hover ~ img {
  opacity:1;
}

.buttonThumbs img:nth-of-type(1) {
  top:25%;
  left:25%;
}

.buttonThumbs img:nth-of-type(2) {
  top:25%;
  left:75%;
}

.buttonThumbs img:nth-of-type(3) {
  top:75%;
  left:25%;
}

.buttonThumbs img:nth-of-type(4) {
  top:75%;
  left:75%;
}</code>```

  <button type="button">text</button>

```

Body:
I have a div that shows random positions of thumbnails within a grey div, when you over over the word 'Text'.

Now, I am trying to make multiples of these grey divs, that also appear in random positions when a page is refreshed.
Ideally it would be scalable (i.e.. I will have max 10 grey divs).

Here's what I have so far:

{ // scope isolating block

    const
        origins = [
            { x : 0, y : 0 },
            { x : 0, y : 1 },
            { x : 1, y : 1 },
            { x : 1, y : 0 },
        ],
        buttonImgEvent = (e) => {
            let img = e.currentTarget.nextElementSibling;
            if (img) {
                let
                    originIndex = Math.floor(origins.length * Math.random());
                const
                    wrapper = e.currentTarget.closest(".buttonThumbs"),
                    halfWidth = wrapper.clientWidth / 2,
                    halfHeight = wrapper.clientHeight / 2;
                do {
                    img.style.left = (
                        Math.random() * (halfWidth - img.clientWidth) +
                        origins[originIndex].x * halfWidth
                    ) + "px";
                    img.style.top = (
                        Math.random() * (halfHeight - img.clientHeight) +
                        origins[originIndex].y * halfHeight
                    ) + "px";
                    originIndex = (originIndex + 1) % origins.length;
                } while (img = img.nextElementSibling);
            }
        };

    for (const button of document.querySelectorAll(".buttonThumbs button")) {
        button.addEventListener("mouseover", buttonImgEvent);
        button.addEventListener("focus", buttonImgEvent);
    }

} // end scope isolation

html, body {
  height:100%;
}

body {
  display:flex;
  align-items:center;
  justify-content:center;
}

.buttonThumbs {
  position:relative;
  width:30em;
  height:20em;
  max-width:100%;
  max-height:100%;
  margin:auto; /* force scrollbars if too small */
  background:#EEE;
}

.buttonThumbs > * {
  position:absolute;
}

.buttonThumbs button {
  top:50%;
  left:50%;
  border:0;
  background:transparent;
  transform:translate(-50%, -50%);
}

.buttonThumbs img {
  width:100px;
  height:100px;
  opacity:0;
  transition:opacity 1s;
}

.buttonThumbs button:focus ~ img,
.buttonThumbs button:hover ~ img {
  opacity:1;
}

.buttonThumbs img:nth-of-type(1) {
  top:25%;
  left:25%;
}

.buttonThumbs img:nth-of-type(2) {
  top:25%;
  left:75%;
}

.buttonThumbs img:nth-of-type(3) {
  top:75%;
  left:25%;
}

.buttonThumbs img:nth-of-type(4) {
  top:75%;
  left:75%;
}

  <button type="button">text</button>


问:
What types of compilers can I use in Eclipse Theia?
I am new to Eclipse Theia . How can I link the compiler in Eclipse Theia?</p>


问:
How to decode the "categories" and "trigger" parameters of an iCalendar?
I want to extract information from an .ics file and I am having problems with certain parameters. When extracting "categories" the encoded information appears, and with the "trigger" parameter I can't directly extract anything. I have tried many alternatives and none have worked.

```<code>import icalendar
from icalendar import Calendar, Event, vCalAddress, vText
from datetime import datetime
from pathlib import Path
import os

datos = {"CATEGORIES": [],
         "DTSTART": [],
         "SUMMARY": [],
         "DESCRIPTION": [],
         "TRIGGER": [],
         }

e = open('C:/Users/XXX/PycharmProjects/XXX/Calendario ALEMANIA.ics', 'r', encoding='utf-8')
ecal = icalendar.Calendar.from_ical(e.read())
for component in ecal.walk():
    if component.name == "VEVENT":
        categories = component.get("categories")
        datos["CATEGORIES"].append(categories)
        dtstart = component.decoded("dtstart")
        datos["DTSTART"].append(dtstart)
        summary = component.get("summary")
        datos["SUMMARY"].append(summary)
        description = component.decoded("description")
        datos["DESCRIPTION"].append(description)
        trigger = component.get("trigger")
        datos["TRIGGER"].append(trigger)

e.close()
print(datos)
</code>```

I get this result in the two mentioned categories:

```<code>{'TRIGGER': [None], 'CATEGORIES': [<icalendar.prop.vCategory object at 0x0000011240C056C0>]}
</code>```

When actually (info from the .ics) should give me:

```<code>{'TRIGGER': [-PT15M], 'CATEGORIES': [Categoría Roja]}
</code>```

I have tried many functions and I GET NOTHING... Some of them:

```<code>.decode('utf-8') , component.decode("categories") , .from_ical() , .ical()...
</code>```

Anyone who can help me? Regards!

Body:
I want to extract information from an .ics file and I am having problems with certain parameters. When extracting "categories" the encoded information appears, and with the "trigger" parameter I can't directly extract anything. I have tried many alternatives and none have worked.

import icalendar
from icalendar import Calendar, Event, vCalAddress, vText
from datetime import datetime
from pathlib import Path
import os

datos = {"CATEGORIES": [],
         "DTSTART": [],
         "SUMMARY": [],
         "DESCRIPTION": [],
         "TRIGGER": [],
         }

e = open('C:/Users/XXX/PycharmProjects/XXX/Calendario ALEMANIA.ics', 'r', encoding='utf-8')
ecal = icalendar.Calendar.from_ical(e.read())
for component in ecal.walk():
    if component.name == "VEVENT":
        categories = component.get("categories")
        datos["CATEGORIES"].append(categories)
        dtstart = component.decoded("dtstart")
        datos["DTSTART"].append(dtstart)
        summary = component.get("summary")
        datos["SUMMARY"].append(summary)
        description = component.decoded("description")
        datos["DESCRIPTION"].append(description)
        trigger = component.get("trigger")
        datos["TRIGGER"].append(trigger)

e.close()
print(datos)

I get this result in the two mentioned categories:

{'TRIGGER': [None], 'CATEGORIES': [<icalendar.prop.vCategory object at 0x0000011240C056C0>]}

When actually (info from the .ics) should give me:

{'TRIGGER': [-PT15M], 'CATEGORIES': [Categoría Roja]}

I have tried many functions and I GET NOTHING... Some of them:

.decode('utf-8') , component.decode("categories") , .from_ical() , .ical()...

Anyone who can help me? Regards!


问:
Can we calculate the Surface tones at runtime in android
First things first Surface color is not static. Here is the documentation from Material 3 that says when a surface is elevated the color of the Surface changes via an overlay of the primary color. Since I am displaying my app via edge to edge by making the system bars transparent I would like to determine the color of my surface on a particular elevation.</p>


问:
AWS RDS automated backup not deleted
I have a RDS instance with automated backup configured for 2 days. Now I can notice I have 4 backups while I except only two. If I change the configuration to zero-days, all backups are deleted. I don't undestand why is not deleting the backups older than 2 days.

Title: AWS RDS automated backup not deleted


问:
Firebase Firestore Stock Count updating?
I am using firebase purely to integrate a simple ticket buying system.
I would think this is a very common scenario people have and wondering what the solutions are.
I have an issue with the write limit time, it means I can't keep the stock count updated.
Due to Firebase's 1 second write limit and the way transactions work, they keep timing out when there is a large buy of tickets at one point in time.
For example:
Let's say we have a simple ticket document like this

```<code> {
name: "Taylor Bieber Concert"
stock: 100
price: 1000
 }
</code>```

I use a firebase transaction server side that does (pseudo)

```<code>transaction{
ticket = t.get(ticketRef).data() //get the data of ticketRef doc
guard (ticket .stock > 0) else return //check the stock is more than 0
t.update(ticketRef, {stock : increment(-1) }) //update the document and remove 1 stock value
}
</code>```

The transaction and functionality all works however if I get 20-100 people trying to buy a ticket as it releases, it goes into contention it seems and times out a bunch of the requests...
Is there a way to avoid these timeouts? Some sort of queue or something?

I have tried using Transactions server-side in firebase functions to update the stock value, when many people try to purchase the product simultaneously it leads to majority of the transactions being locked out / Aborted Code 10

Body:
I am using firebase purely to integrate a simple ticket buying system.
I would think this is a very common scenario people have and wondering what the solutions are.
I have an issue with the write limit time, it means I can't keep the stock count updated.
Due to Firebase's 1 second write limit and the way transactions work, they keep timing out when there is a large buy of tickets at one point in time.
For example:
Let's say we have a simple ticket document like this

 {
name: "Taylor Bieber Concert"
stock: 100
price: 1000
 }

I use a firebase transaction server side that does (pseudo)

transaction{
ticket = t.get(ticketRef).data() //get the data of ticketRef doc
guard (ticket .stock > 0) else return //check the stock is more than 0
t.update(ticketRef, {stock : increment(-1) }) //update the document and remove 1 stock value
}

The transaction and functionality all works however if I get 20-100 people trying to buy a ticket as it releases, it goes into contention it seems and times out a bunch of the requests...
Is there a way to avoid these timeouts? Some sort of queue or something?

I have tried using Transactions server-side in firebase functions to update the stock value, when many people try to purchase the product simultaneously it leads to majority of the transactions being locked out / Aborted Code 10


问:
Synchronizing a usermode application to a kernel driver
We have a driver that schedules work using a timer (using add_timer). Whenever the work results in a change, an application should be notified of this change.
Currently this is done by providing a sysfs entry from the driver, that blocks a read operation until there is a change in the data.
(Please see the relevant code from the driver and the application in the code block below.)

I have inspected the source of most functions related to this in the linux kernel (4.14.98), and I did not notice any obvious problems in dev_attr_show, sysfs_kf_seq_show,__vfs_read and vfs_read.

However in seq_read the mutex file->private_data->lock is held for the duration of the read:
https://elixir.bootlin.com/linux/v4.14.98/source/fs/seq_file.c#L165

Will this pose a problem?

Are there any other (potential?) problems that I should be aware of?

Please note that:

The data will change at least once per second, usually way faster

The application should respond as soon as possible to a change in the data

This runs in a controlled (embedded) environment

```<code>// driver.c
static DECLARE_WAIT_QUEUE_HEAD(wq);
static int xxx_block_c = 0;

// driver calls this to notify the application that something changed (from a timer, `timer_list`)
void xxx_Persist(void)
{
  xxx_block_c = 1;
  wake_up_interruptible(&wq);
}

// Sysfs entry that blocks until there is a change in the data.
static ssize_t xxx_show(struct device *dev,
                 struct device_attribute *attr,
                 char *buf)
{
    wait_event_interruptible(wq, xxx_block_c != 0);
    xxx_block_c = 0;

    /* Remainder of the implementation */
}
</code>```
```<code>//application.cpp
std::ifstream xxx;
xxx.open("xxx", std::ios::binary | std::ios::in);
while (true)
{
    xxx.clear();
    xxx.seekg(0, std::ios_base::beg);
    xxx.read(data, size);
    /* Do something with data */
}
</code>```

Body:
We have a driver that schedules work using a timer (using add_timer). Whenever the work results in a change, an application should be notified of this change.
Currently this is done by providing a sysfs entry from the driver, that blocks a read operation until there is a change in the data.
(Please see the relevant code from the driver and the application in the code block below.)

I have inspected the source of most functions related to this in the linux kernel (4.14.98), and I did not notice any obvious problems in dev_attr_show, sysfs_kf_seq_show,__vfs_read and vfs_read.

However in seq_read the mutex file->private_data->lock is held for the duration of the read:
https://elixir.bootlin.com/linux/v4.14.98/source/fs/seq_file.c#L165

Will this pose a problem?

Are there any other (potential?) problems that I should be aware of?

Please note that:

The data will change at least once per second, usually way faster

The application should respond as soon as possible to a change in the data

This runs in a controlled (embedded) environment

// driver.c
static DECLARE_WAIT_QUEUE_HEAD(wq);
static int xxx_block_c = 0;

// driver calls this to notify the application that something changed (from a timer, `timer_list`)
void xxx_Persist(void)
{
  xxx_block_c = 1;
  wake_up_interruptible(&wq);
}

// Sysfs entry that blocks until there is a change in the data.
static ssize_t xxx_show(struct device *dev,
                 struct device_attribute *attr,
                 char *buf)
{
    wait_event_interruptible(wq, xxx_block_c != 0);
    xxx_block_c = 0;

    /* Remainder of the implementation */
}

//application.cpp
std::ifstream xxx;
xxx.open("xxx", std::ios::binary | std::ios::in);
while (true)
{
    xxx.clear();
    xxx.seekg(0, std::ios_base::beg);
    xxx.read(data, size);
    /* Do something with data */
}


问:
How to fix "Could not load file or assembly 'Oracle.DataAccess,' or one of its dependencies" in VS 2022
I am getting below error in VS2022:

Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified.        C:\Users<project_folder>\Web.Config    206

The line 206 in web.config is:

```<code><add assembly="Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89B483F429C47342"/>
</code>```

The target framework is 4.0 and I do have Oracle client installed.
I do have oracle data access DLL at Oracle_Folder\odp.net\bin\4

I checked the project properties and found that the Oracle DLL is being referred from GAC.

GacUTIL command output:

```<code>gacutil /l | findstr Oracle.Data
  Policy.4.112.Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
  Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=de, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=es, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=fr, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=it, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=ja, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=ko, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=pt-BR, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=zh-CHS, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=zh-CHT, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Policy.4.112.Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
</code>```

Note that I can run the application directly from IIS. However, when I try to run from VS2022 or VS2017 I am getting above error.

Body:
I am getting below error in VS2022:

Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified.        C:\Users<project_folder>\Web.Config    206

The line 206 in web.config is:

<add assembly="Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89B483F429C47342"/>

The target framework is 4.0 and I do have Oracle client installed.
I do have oracle data access DLL at Oracle_Folder\odp.net\bin\4

I checked the project properties and found that the Oracle DLL is being referred from GAC.

GacUTIL command output:

gacutil /l | findstr Oracle.Data
  Policy.4.112.Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
  Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=de, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=es, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=fr, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=it, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=ja, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=ko, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=pt-BR, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=zh-CHS, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Oracle.DataAccess.resources, Version=4.112.4.0, Culture=zh-CHT, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
  Policy.4.112.Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86

Note that I can run the application directly from IIS. However, when I try to run from VS2022 or VS2017 I am getting above error.


问:
How to extract digits and string from a combined string and put them seperately into different list
List list = ['25 Fly','50 Back','75 free','100 Med'];

List ListA = [];
List ListB = [];

I want to know that how i extract numbers and string and put them into different lists seperatly.


问:
Predictions from a Cox model with splines and confidence interval
I have to make a prediction tool from a Cox model.
Normally I could have used predictCox from the riskRegression package to get the predicted survival and confidence interval.
But for that I would have to upload my data with the tool. But I don't have the right to do that.

The alternative is to estimate the basis risk at a given instant, obtain the estimated coefficients to build a simple regression model which can be put online.
However, I'm not sure about the procedure and the packages I can use to get it.
I have read that some packages center linear predictors etc.
Also, I don't know how to get the confidence interval.

Can someone confirm me in a few words what would be the right procedure and the packages to use in this case?

```<code>library(survival)
library(riskRegression)
mfit <- coxph(Surv(futime, death) ~ sex +ns(age,2), data=mgus, x=T, y=T)
prediction_surv2 <- predictCox(mfit, newdata=newdata, times=365.25*5 , type = "survival",
                       se = TRUE, iid = TRUE, band = TRUE)

prediction_surv2
</code>```

Thanks a lot !

Body:
I have to make a prediction tool from a Cox model.
Normally I could have used predictCox from the riskRegression package to get the predicted survival and confidence interval.
But for that I would have to upload my data with the tool. But I don't have the right to do that.

The alternative is to estimate the basis risk at a given instant, obtain the estimated coefficients to build a simple regression model which can be put online.
However, I'm not sure about the procedure and the packages I can use to get it.
I have read that some packages center linear predictors etc.
Also, I don't know how to get the confidence interval.

Can someone confirm me in a few words what would be the right procedure and the packages to use in this case?

library(survival)
library(riskRegression)
mfit <- coxph(Surv(futime, death) ~ sex +ns(age,2), data=mgus, x=T, y=T)
prediction_surv2 <- predictCox(mfit, newdata=newdata, times=365.25*5 , type = "survival",
                       se = TRUE, iid = TRUE, band = TRUE)

prediction_surv2

Thanks a lot !


问:
SSL offloading Application Load Balancer gives "Host not found"
I have an amazon application load balancer with ssl certificate listening to 443 and forwarding to 80 on private ec2 instances. All worked fine until I integrated the saml authentification. The saml identity provider forwards back to http://mydomain instead of the https://mydomain and I get a "Host not found". I have tried a number of proxy_ssl_engine settings in the Apache config but they don't work, or resulted in a 463 error. Does anyone know what Apache config will solve the "Host not found" Error? somehow I need to get back to ssl..</p>


问:
I setInterval to refresh my page when I get new infomation, but it's not work (react / chart.js)
hi gus this is my first react work

I want to make a chart to get the value of stock every 2min, then refresh the chart

this is my work:

First, I setInterval to push the data into chart.js data array:

const putValueIntoOntime = () => {
    for (let n = 0; n < stockValue.length; n++) {
        stockValueOntime[n].value.push(stockValue[n].value[0]);
        stockValue[n].value.shift();
    }
};

useEffect(() => {
    const setIntervalDate = setInterval(() => {
        putValueIntoOntime();
        const now = new Date();
        let timestamp = now.getMinutes();
        setDate(timestamp);
        return () => clearInterval(setIntervalDate);
    }, 60000);
}, []);
```
<p>Then set the datetime to refresh the page:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
    setShowData(dataMap);
    console.log("refresh");
}, [item, date]);
</code>```

I'm sure that chart had got the data, because when I click to change the stock item, I can see the update chart, but why dosen't it work when I setDate?

sorry for my poor English, and thanks everyone

Body:
hi gus this is my first react work

I want to make a chart to get the value of stock every 2min, then refresh the chart

this is my work:

First, I setInterval to push the data into chart.js data array:

const putValueIntoOntime = () => {
    for (let n = 0; n < stockValue.length; n++) {
        stockValueOntime[n].value.push(stockValue[n].value[0]);
        stockValue[n].value.shift();
    }
};

useEffect(() => {
    const setIntervalDate = setInterval(() => {
        putValueIntoOntime();
        const now = new Date();
        let timestamp = now.getMinutes();
        setDate(timestamp);
        return () => clearInterval(setIntervalDate);
    }, 60000);
}, []);

Then set the datetime to refresh the page:

useEffect(() => {
    setShowData(dataMap);
    console.log("refresh");
}, [item, date]);

I'm sure that chart had got the data, because when I click to change the stock item, I can see the update chart, but why dosen't it work when I setDate?

sorry for my poor English, and thanks everyone


问:
Layout of flexdashboard - having multiple tabsets
I currently have my dashboard which looks like:

What I am trying to do is under the Data tab have additional tabs. For example I want to combine the Table Population tab with the Graphic iris tab so that the table and graphic are on the same page. Then in a new tab have the Another tab-pag (as it currently is).

How can I merge the two tabs to have them on the same page?

I would like this joined tab to look like the Analysis tab:

Dashboard:

```<code>---
title: "Analysis"
output:
  flexdashboard::flex_dashboard:
    #css: "custom_style.css"
    theme:
      base_font:
        google: Prompt
      code_font:
        google: JetBrains Mono
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(shinyWidgets)
library(shinyjs)
library(gt)
library(gtExtras)
library(plotly)
```

MySidebar {.sidebar}
==============================

```{r}
useShinyjs(rmd = TRUE)

shinyWidgets::pickerInput(
  inputId = "select_species",
  label = h4("Species"),
  choices = unique(iris$Species),
  selected = unique(iris$Species[1]),
  multiple = TRUE,
  options = list(
    `actions-box`= TRUE,
    size = 10,
    `selected-text-format` = "count > 1"
  )
)

```

Introduction {data-vertical_layout=scroll}
==============================

Column {data-width=650 .main .tabset}
-----------------------------------------------------------------------

Here is some introduction text

Data {data-vertical_layout=scroll}
==============================

IRIS Species {.tabset .tabset-fade}
-------------------------------------

### Table Population

```{r}

output$irisTable = render_gt({
  iris %>%
    gt() %>%
    gt_add_divider(columns = "Provincias", weight = px(3), color = "lightgrey", include_labels = FALSE)
})

div(style='height:800px; overflow-y: scroll',
    gt_output("populationTable")
)
```

### Graphic iris

```{r}
renderPlotly({
  ggplotly(
    iris %>%
      ggplot(aes(x = Species, y = Petal.Length)) +
      geom_bar() +
      theme_bw()
  )
})
```

### Another tab-page

Analysis {data-vertical_layout=scroll}
==============================

Column
-------------------------------------

### Tab 1

some text

### Tab 2

some more text
</code>```

Body:
I currently have my dashboard which looks like:

What I am trying to do is under the Data tab have additional tabs. For example I want to combine the Table Population tab with the Graphic iris tab so that the table and graphic are on the same page. Then in a new tab have the Another tab-pag (as it currently is).

How can I merge the two tabs to have them on the same page?

I would like this joined tab to look like the Analysis tab:

Dashboard:

---
title: "Analysis"
output:
  flexdashboard::flex_dashboard:
    #css: "custom_style.css"
    theme:
      base_font:
        google: Prompt
      code_font:
        google: JetBrains Mono
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(shinyWidgets)
library(shinyjs)
library(gt)
library(gtExtras)
library(plotly)
```

MySidebar {.sidebar}
==============================

```{r}
useShinyjs(rmd = TRUE)

shinyWidgets::pickerInput(
  inputId = "select_species",
  label = h4("Species"),
  choices = unique(iris$Species),
  selected = unique(iris$Species[1]),
  multiple = TRUE,
  options = list(
    `actions-box`= TRUE,
    size = 10,
    `selected-text-format` = "count > 1"
  )
)

```

Introduction {data-vertical_layout=scroll}
==============================

Column {data-width=650 .main .tabset}
-----------------------------------------------------------------------

Here is some introduction text

Data {data-vertical_layout=scroll}
==============================

IRIS Species {.tabset .tabset-fade}
-------------------------------------

### Table Population

```{r}

output$irisTable = render_gt({
  iris %>%
    gt() %>%
    gt_add_divider(columns = "Provincias", weight = px(3), color = "lightgrey", include_labels = FALSE)
})

div(style='height:800px; overflow-y: scroll',
    gt_output("populationTable")
)
```

### Graphic iris

```{r}
renderPlotly({
  ggplotly(
    iris %>%
      ggplot(aes(x = Species, y = Petal.Length)) +
      geom_bar() +
      theme_bw()
  )
})
```

### Another tab-page

Analysis {data-vertical_layout=scroll}
==============================

Column
-------------------------------------

### Tab 1

some text

### Tab 2

some more text


问:
useNavigateMock don't receive url
I'm trying to test a redirect from my Login page using Vitest + Testing library. All seems ok until I try to test the useNavigate hook. Here is my component:

Login.tsx

const userData: User = {
  id: '1',
  name: 'angel',
  permissions: ['management'],
  roles: ['admin'],
}

const fakeAuth = (): Promise<User> =>
  new Promise((resolve) => {
    setTimeout(() => resolve(userData), 250)
  })

function Login() {
  const { t } = useTranslation()
  const location = useLocation()
  const navigate = useNavigate()
  const { login } = useAuth()
  const handleLogin = (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault()
    fakeAuth().then((user) => {
      login(user)
      const origin = location.state?.from?.pathname || '/translation'
      navigate(origin)
    })

  }
return (

      <Card
        title={t('login.title')}
        body={
          <form onSubmit={handleLogin}>
            <button
              data-testid="login-btn"
              type="submit"
            >
              Login to your account
            </button>
          </form>
        }
      />

  )
}

export default Login
```
<p>And the test file, I use a mock to do it:</p>
<p><code>Login.test.tsx</code></p>
<pre class="lang-js prettyprint-override"><code>import { describe, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import * as router from 'react-router-dom'
import Login from './Login'

const mockedUsedNavigate = vi.fn()

vi.mock('react-router-dom', async () => {
  return {
    ...((await vi.importActual('react-router-dom')) as any),
    useNavigate: () => mockedUsedNavigate,
  }
})

describe('Login Page', () => {
  const user = userEvent.setup()

  it('Call the useNavigate when user click', async () => {
    const navigate = vi.spyOn(router, 'useNavigate')

    render(
      <MemoryRouter initialEntries={['/login']}>
        <Login />
      </MemoryRouter>
    )

    const loginBtn = screen.getByTestId('login-btn')

    user.click(loginBtn)

    expect(navigate).toHaveBeenCalledTimes(1)
    expect(navigate).toBeCalledWith('/translation')
  })
})
</code>```

The first expect work fine. But the second one throws this error:

AssertionError: expected "useNavigate" to be called with arguments: [ '/translation' ]expected "useNavigate" to be called with arguments: [ '/translation' ]

My dependencies and vite config

    "react": "^18.2.0",
    "react-dom": "^18.2.0",,
    "react-router-dom": "^6.6.2",
    "@testing-library/dom": "^8.19.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.4.3",
    "jsdom": "^21.0.0",
    "vite": "^4.0.4",
    "vitest": "^0.27.0"
```
<pre class="lang-js prettyprint-override"><code>export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/setupTest.ts'],
    coverage: {
      reporter: ['text', 'json', 'html'],
    },
  },
})
</code>```

Honestly I don't know what more to do. All the examples i saw works perfectly doing this. Any help would be appreciated. Thanks in advance

Title: useNavigateMock don't receive url

Body:
I'm trying to test a redirect from my Login page using Vitest + Testing library. All seems ok until I try to test the useNavigate hook. Here is my component:

Login.tsx

const userData: User = {
  id: '1',
  name: 'angel',
  permissions: ['management'],
  roles: ['admin'],
}

const fakeAuth = (): Promise<User> =>
  new Promise((resolve) => {
    setTimeout(() => resolve(userData), 250)
  })

function Login() {
  const { t } = useTranslation()
  const location = useLocation()
  const navigate = useNavigate()
  const { login } = useAuth()
  const handleLogin = (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault()
    fakeAuth().then((user) => {
      login(user)
      const origin = location.state?.from?.pathname || '/translation'
      navigate(origin)
    })

  }
return (

      <Card
        title={t('login.title')}
        body={
          <form onSubmit={handleLogin}>
            <button
              data-testid="login-btn"
              type="submit"
            >
              Login to your account
            </button>
          </form>
        }
      />

  )
}

export default Login

And the test file, I use a mock to do it:

Login.test.tsx

import { describe, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import * as router from 'react-router-dom'
import Login from './Login'

const mockedUsedNavigate = vi.fn()

vi.mock('react-router-dom', async () => {
  return {
    ...((await vi.importActual('react-router-dom')) as any),
    useNavigate: () => mockedUsedNavigate,
  }
})

describe('Login Page', () => {
  const user = userEvent.setup()

  it('Call the useNavigate when user click', async () => {
    const navigate = vi.spyOn(router, 'useNavigate')

    render(
      <MemoryRouter initialEntries={['/login']}>
        <Login />
      </MemoryRouter>
    )

    const loginBtn = screen.getByTestId('login-btn')

    user.click(loginBtn)

    expect(navigate).toHaveBeenCalledTimes(1)
    expect(navigate).toBeCalledWith('/translation')
  })
})

The first expect work fine. But the second one throws this error:

AssertionError: expected "useNavigate" to be called with arguments: [ '/translation' ]expected "useNavigate" to be called with arguments: [ '/translation' ]

My dependencies and vite config

    "react": "^18.2.0",
    "react-dom": "^18.2.0",,
    "react-router-dom": "^6.6.2",
    "@testing-library/dom": "^8.19.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.4.3",
    "jsdom": "^21.0.0",
    "vite": "^4.0.4",
    "vitest": "^0.27.0"

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/setupTest.ts'],
    coverage: {
      reporter: ['text', 'json', 'html'],
    },
  },
})

Honestly I don't know what more to do. All the examples i saw works perfectly doing this. Any help would be appreciated. Thanks in advance


Title: Python-Pandas| How to convert date which is in object data type to customized format

Body:
I am trying to convert a date column which is object data type which is in YYYY/MMDD & YYYY/MM/DD Timeestamp format  to customized format i.e. MM/DD/YYYY

Dataset CreditDetail_bkp: has these below columns with below data types.

Code:

Printed the unique  types available for each column for the conversion

print('SO Start Date',CreditDetail['SO Start Date'].unique())
print('##########################################')
print('SO End Date',CreditDetail['SO End Date'].unique())
print('##########################################')
print('Cancellation Date (UTC)',CreditDetail['Cancellation Date (UTC)'].unique())
print('##########################################')
print('Registration Date (UTC)',CreditDetail['Registration Date (UTC)'].unique())
print('##########################################')
print('Country Hire Date',CreditDetail['Country Hire Date'].unique())

O/P :

SO Start Date [nan '2022/08/23 17:30:00' '2022/08/25 15:02:00' ... '2022/09/13 08:43:00'
 '2022/09/14 19:00:00' '2022/08/17 18:00:00']
##########################################
SO End Date [nan '2022/08/23 18:30:00' '2022/08/25 16:46:00' ... '2022/09/14 20:00:00'
 '2022/09/30 15:00:00' '2022/08/17 19:30:00']
##########################################
Cancellation Date (UTC) [nan '2022/10/20' '2022/08/02']
##########################################
Registration Date (UTC) [nan '2023/01/03' '2022/08/31' '2022/11/04' '2022/11/23' '2022/11/21'
 '2022/09/18' '2022/08/04' '2022/09/16' '2022/08/16' '2022/12/07'
##########################################
Country Hire Date ['2022/08/17' '2022/09/05' '2022/08/22' ... '1993/09/13' '2018/06/30'
 '2022/05/21']

Code:

Tried multiple approaches , but getting different errors due to object data type and format:

Approach1:

    CreditDetail_bkp['Cancellation Date (UTC)_1'] = CreditDetail_bkp['Cancellation Date
    (UTC)'].strftime("%m/%d/%Y")

    Approach2:
    CreditDetail_bkp['Cancellation Date (UTC)'].apply(lambda x: x.strftime('%m%d%Y'))

    Approach3:
    CreditDetail_bkp['SO Start Date1'] = CreditDetail_bkp['SO Start Date'].dt.strftime('%m%d%Y')

    Approach4:
    pd.to_datetime(CreditDetail_bkp['Cancellation Date (UTC)_1']).strftime('%m/%d%Y')

    All the above approaches  are throwing errors and not giving the expected format which is
    MM/DD/YYYY


问:
How to upload external pdf document to server NEXTJS
I've used hours to find out how to upload external pdf (or any other files) from url to server (for example to public folder like /public/uploads). I found tons of examples how to upload it from form, but not from the external url.

Lets say that I have this url https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
and I like to upload it to /public/uploads

Is there any directions or examples available?


问:
How import modules in haskell
I'm trying to use this module in my haskell code: (http://hackage.haskell.org/package/MissingH-1.0.0/docs/Data-String-Utils.html) to use the function "replace" - However, when I try this code:
import Data.String.Utils
Haskell tells me there is no such module.

I've installed cabal and stack to do stack build and cabal build

Title: How import modules in haskell


问:
How to take metro in graphql out of the solve?
I'm having the following problem, I need to dynamically create an object type from the data I get from the database.

However I need the args parameter of the grapqh solving function.

```<code>import listResolvers from "../resolvers/listResolvers"
import listType from "../types/listType"

const listSchema = {
    list: {
        type: listType.listType(),
        args: {
            schema: {
                type: new GraphQLNonNull(GraphQLString)
            },
        },
        resolve: async (_, args) => {

            return await listResolvers.get(args.schema)
        },

    }
}
</code>```

my listType() function already creates the type dynamically, but as I said, I need the parameter that is passed in the graphql query

if it were an APIREST it was only the req.params within the function that worked

how to do something like that here in grapqhQl ???

Body:
I'm having the following problem, I need to dynamically create an object type from the data I get from the database.

However I need the args parameter of the grapqh solving function.

import listResolvers from "../resolvers/listResolvers"
import listType from "../types/listType"

const listSchema = {
    list: {
        type: listType.listType(),
        args: {
            schema: {
                type: new GraphQLNonNull(GraphQLString)
            },
        },
        resolve: async (_, args) => {

            return await listResolvers.get(args.schema)
        },

    }
}

my listType() function already creates the type dynamically, but as I said, I need the parameter that is passed in the graphql query

if it were an APIREST it was only the req.params within the function that worked

how to do something like that here in grapqhQl ???


问:
python pandas help from html reports
i have a bunch of html reports titled "ReportHistory-****" where **** refers to account numbers .. which are bascially reports that MT5 (Trading app) sends periodically to an FTP server

```<code>from bs4 import BeautifulSoup

my_html = open("Reports/ReportHistory-117339.html", "rb")

soup = BeautifulSoup(my_html, 'lxml')
table_tags = soup.find_all('table')

for table in table_tags:
        print(table.text)
</code>```

when i run this ... i get the following info printed.
Along with every single trade that occurred.. which is irrelevant for my purpose

Name:
Little John Norris

Account:
117339 (USD, M4Markets-MT5, demo, Hedge)

Company:
Trinota Markets Ltd

Date:
2023.01.12 03:53

Balance:
100 751.00

Free Margin:
100 751.00

Equity:
100 751.00

Total Net Profit:
751.00

Gross Profit:
39 704.50

Gross Loss:
-38 953.50

Balance Drawdown Absolute:
4 253.00

i want this info to be added to a dataframe so i can store it and pull it into another table

if i add the below code... it errors

```<code>data = []
df=pd.DataFrame(table.text),columns=['col1','col2'])

print(df)
</code>```

it prints the same this traceback error

```<code>Traceback (most recent call last):
  File "/Users/PycharmProjects/readhtml/reports.py", line 13, in <module>
    df=pd.DataFrame(table.text)
  File "/Users/PycharmProjects/readhtml/venv/lib/python3.9/site-packages/pandas/core/frame.py", line 780, in __init__
    raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
</code>```

followed by the regular table.text data and then

Process finished with exit code 1

my end goal is to be able to run the python code over each of the html reports and get the same relevant info from each of them associated with the account number

Is this possible?

Title: python pandas help from html reports

Body:
i have a bunch of html reports titled "ReportHistory-****" where **** refers to account numbers .. which are bascially reports that MT5 (Trading app) sends periodically to an FTP server

from bs4 import BeautifulSoup

my_html = open("Reports/ReportHistory-117339.html", "rb")

soup = BeautifulSoup(my_html, 'lxml')
table_tags = soup.find_all('table')

for table in table_tags:
        print(table.text)

when i run this ... i get the following info printed.
Along with every single trade that occurred.. which is irrelevant for my purpose

Name:
Little John Norris

Account:
117339 (USD, M4Markets-MT5, demo, Hedge)

Company:
Trinota Markets Ltd

Date:
2023.01.12 03:53

Balance:
100 751.00

Free Margin:
100 751.00

Equity:
100 751.00

Total Net Profit:
751.00

Gross Profit:
39 704.50

Gross Loss:
-38 953.50

Balance Drawdown Absolute:
4 253.00

i want this info to be added to a dataframe so i can store it and pull it into another table

if i add the below code... it errors

data = []
df=pd.DataFrame(table.text),columns=['col1','col2'])

print(df)

it prints the same this traceback error

Traceback (most recent call last):
  File "/Users/PycharmProjects/readhtml/reports.py", line 13, in <module>
    df=pd.DataFrame(table.text)
  File "/Users/PycharmProjects/readhtml/venv/lib/python3.9/site-packages/pandas/core/frame.py", line 780, in __init__
    raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!

followed by the regular table.text data and then

Process finished with exit code 1

my end goal is to be able to run the python code over each of the html reports and get the same relevant info from each of them associated with the account number

Is this possible?


问:
Apache - placeholder image for missing files no displaying
I am migrating from a server running Centos 8 where the following code works to replace requests for images that don't exist with a placeholder image:

```<code><Directory /home/site/public_html>
 Options -Indexes
 AllowOverride All

 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^.*(\.gif|\.jpe?g|\.png)$ placeholderimage.gif [L]
</Directory>
</code>```

On the new server that is running AlmaLinux 8 this no longer works and a 404 error is logged. This server is running php-fpm so I have tried adding the ProxyErrorOverride On directive but the problem remains.

EDIT: These rules are working on the new server in a .htaccess file, it would be preferable to keep them in the virtual host config.

Body:
I am migrating from a server running Centos 8 where the following code works to replace requests for images that don't exist with a placeholder image:

<Directory /home/site/public_html>
 Options -Indexes
 AllowOverride All

 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^.*(\.gif|\.jpe?g|\.png)$ placeholderimage.gif [L]
</Directory>

On the new server that is running AlmaLinux 8 this no longer works and a 404 error is logged. This server is running php-fpm so I have tried adding the ProxyErrorOverride On directive but the problem remains.

EDIT: These rules are working on the new server in a .htaccess file, it would be preferable to keep them in the virtual host config.


问:
"set_xlabel" or "set_ylabel " is not supported in GeoAxesSubplot of cartopy v0.21.1
I used cartopy v0.21.1 to plot subplots, but "set_xlabel" or "set_ylabel " is not supported in GeoAxesSubplot.
Any recommendations for how to solve this or investigate further?
Thanks!
fig, axs = plt.subplots(nrows=3,ncols=3,subplot_kw={'projection': background.crs},figsize=(11,8))
axs=axs.flatten()
axs.set_ylabel('Isoprene')

How to set_xlabel or set_ylabel in GeoAxesSubplot