问:
Problem with inserting entity object with two unidirectional One to Many relationship
I have two entities, each one pointing to one single table in an postgres. The entities belong to an Spring/graddle/JPA/Hibernate web application.

```<code>@Entity
@Table(name = "STAFF")
@AttributeOverride(name = "id", column = @Column(name = "ID"))
public class StaffEntity extends AbstractEntity {

    @Column(name = "NAME")
    private String name;

    @Column(name = "SHORT_NAME")
    private String shortName;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "STAFF_GROUP_ID", referencedColumnName = "ID")
    private StaffGroupEntity staffGroup;

     /* More attributes, getters and setters */

@Entity
@Table(name = "STAFF_GROUP")
@AttributeOverride(name = "id", column = @Column(name = "ID"))
public class StaffGroupEntity extends AbstractEntity {

    @Column(name = "NAME")
    private String name;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "LEAD_ID", referencedColumnName = "ID")
    private StaffEntity lead;

/* More attributes, getters and setters */
</code>```

When i update with swagger the group with a lead that is already in the group i get a stackOverFlowError

java.lang.StackOverflowError: null

mapping with  mapstruct

Body:
I have two entities, each one pointing to one single table in an postgres. The entities belong to an Spring/graddle/JPA/Hibernate web application.

@Entity
@Table(name = "STAFF")
@AttributeOverride(name = "id", column = @Column(name = "ID"))
public class StaffEntity extends AbstractEntity {

    @Column(name = "NAME")
    private String name;

    @Column(name = "SHORT_NAME")
    private String shortName;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "STAFF_GROUP_ID", referencedColumnName = "ID")
    private StaffGroupEntity staffGroup;

     /* More attributes, getters and setters */

@Entity
@Table(name = "STAFF_GROUP")
@AttributeOverride(name = "id", column = @Column(name = "ID"))
public class StaffGroupEntity extends AbstractEntity {

    @Column(name = "NAME")
    private String name;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "LEAD_ID", referencedColumnName = "ID")
    private StaffEntity lead;

/* More attributes, getters and setters */

When i update with swagger the group with a lead that is already in the group i get a stackOverFlowError

java.lang.StackOverflowError: null

mapping with  mapstruct


来源: stackexchange

问:
GaiException while resolving domain on AOSP platform app
I added an app to AOSP and it has the "platform" certificate. When I just install it on my device it resolves the domain just fine, but as a system app I get an GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname).

This is the entire log of the crash:

```<code>aused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.Linux.android_getaddrinfo(Native Method)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:136)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:221)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:136)
12-22 10:00:32.792  5656  5681 W System.err:    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
</code>```

Do I need to add a permission or tell the build-system somewhere to get the permission to resolve domains?

Thank you!

ContentLicense: CC BY-SA 4.0

Body:
I added an app to AOSP and it has the "platform" certificate. When I just install it on my device it resolves the domain just fine, but as a system app I get an GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname).

This is the entire log of the crash:

aused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.Linux.android_getaddrinfo(Native Method)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:136)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:221)
12-22 10:00:32.792  5656  5681 W System.err:    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:136)
12-22 10:00:32.792  5656  5681 W System.err:    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)

Do I need to add a permission or tell the build-system somewhere to get the permission to resolve domains?

Thank you!


问:
How to replace enter key with space
I am trying to replace enter key in a string with space in VB but unable to replace with it .
With that I have to update that string into grid column value with same datatype declared still giving error datatype mismatch during fied update .

I had tried this line of code to replace  :
Replace(string,vbNewLine,"  ")

And for updating the code is
Gridview.Columns.Items(3).value=string

Title: How to replace enter key with space


问:
different bar text for different groups in plotly
I have the following table:

I know how to create a grouped bar chart, with single text column:

```<code>fig = px.bar(data_frame = df.toPandas(),
x = 'x',
y = ['y1','y2'],
barmode = 'group',
text='y1_labels')
fig.show()
</code>```

which generates:

as you can see, the bars of 'y2' also gets the labels of 'y1_labels' - while I would like them to have their own labels from 'y2_labels'.

how can this be achived?

Body:
I have the following table:

I know how to create a grouped bar chart, with single text column:

fig = px.bar(data_frame = df.toPandas(),
x = 'x',
y = ['y1','y2'],
barmode = 'group',
text='y1_labels')
fig.show()

which generates:

as you can see, the bars of 'y2' also gets the labels of 'y1_labels' - while I would like them to have their own labels from 'y2_labels'.

how can this be achived?


问:
Use validate JWT policy to authenticate dynamics portal in Azure API Management
I have a dynamics 365 portal that I wish to connect to Azure API Management. I get the JWT from the /_services/auth/token endpoint. I want to validate this with the validate-jwt inbound policy in APIM as below.

```<code><policies>
    <inbound>
        <validate-jwt header-name="Authorization" require-scheme="Bearer" output-token-variable-name="jwt">
            <issuer-signing-keys>

            </issuer-signing-keys>
            <audiences>
                <audience>{{ my-app-id }}</audience>
            </audiences>
            <issuers>
                <issuer>{{ my-portal-domain }}</issuer>
            </issuers>
        </validate-jwt>
    </inbound>
    <backend>
        <forward-request />
    </backend>
    <outbound />
    <on-error />
</policies>
</code>```

My problem is I don't know how to include the /_services/auth/publickey endpoint in the issuer-signing-keys to validate the JWT?

Body:
I have a dynamics 365 portal that I wish to connect to Azure API Management. I get the JWT from the /_services/auth/token endpoint. I want to validate this with the validate-jwt inbound policy in APIM as below.

<policies>
    <inbound>
        <validate-jwt header-name="Authorization" require-scheme="Bearer" output-token-variable-name="jwt">
            <issuer-signing-keys>

            </issuer-signing-keys>
            <audiences>
                <audience>{{ my-app-id }}</audience>
            </audiences>
            <issuers>
                <issuer>{{ my-portal-domain }}</issuer>
            </issuers>
        </validate-jwt>
    </inbound>
    <backend>
        <forward-request />
    </backend>
    <outbound />
    <on-error />
</policies>

My problem is I don't know how to include the /_services/auth/publickey endpoint in the issuer-signing-keys to validate the JWT?


问:
Visual Studio Code, How To Change Highlight Color for Code Blocks
I have one dark pro theme installed and I'm trying to find how to manually change the background color of the code block. I am using the snowflake extension in the screenshot below. You can see the dark grey background, line highlight color around select *, and then a brown color that highlights all three lines of the code. What is the name of that brown highlight color so I can adjust it?

I currently have a few specific background colors set but none of them are affecting the code block highlight.

```<code>    "workbench.colorCustomizations": {
        "editor.lineHighlightBackground": "#E06C75",
        "editor.selectionHighlightBorder": "#FFFA",
        "editor.selectionBackground": "#135564",
        "editor.selectionHighlightBackground": "#135564",
        "editor.findMatchBackground": "#00cc44a8",
        "editor.findMatchHighlightBackground": "#ff7b00a1"
    }
</code>```

Body:
I have one dark pro theme installed and I'm trying to find how to manually change the background color of the code block. I am using the snowflake extension in the screenshot below. You can see the dark grey background, line highlight color around select *, and then a brown color that highlights all three lines of the code. What is the name of that brown highlight color so I can adjust it?

I currently have a few specific background colors set but none of them are affecting the code block highlight.

    "workbench.colorCustomizations": {
        "editor.lineHighlightBackground": "#E06C75",
        "editor.selectionHighlightBorder": "#FFFA",
        "editor.selectionBackground": "#135564",
        "editor.selectionHighlightBackground": "#135564",
        "editor.findMatchBackground": "#00cc44a8",
        "editor.findMatchHighlightBackground": "#ff7b00a1"
    }


问:
TypeError: Cannot read properties of null (reading 'map')
I am trying to get my Etherscan Verified Contract Scraper that forwards new Verified Contracts to a specific Discord channel working and have run into issues.

Here is the code--

```<code>const Discord = require("discord.js");
const fetch = require("node-fetch");
const config = require("./config.json");
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Discord.Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
  ]
})

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// Replace CHANNEL_ID with the ID of the channel you want to post in
const channel = client.channels.cache.get('CHANNELID');

// Scrape new verified contracts from Etherscan every minute
setInterval(async () => {
  const response = await fetch('https://etherscan.io/contractsVerified');
  const html = await response.text();

  // Extract the verified contracts from the HTML
  const verifiedContracts = html.match(/href="\/address\/[0-9a-fA-F]+"/g)
    .map((link) => link.slice(8, -1));

  // Send an embedded message to the Discord channel with the verified contracts
  const embed = new Discord.MessageEmbed()
    .setTitle('Verified Contracts')
    .setDescription(verifiedContracts.join('\n'))
    .setColor('#00FF00');
  channel.send(embed);
}, 60000);

client.login(config.BOT_TOKEN);

</code>```

Here is the error I'm getting--

```<code>TypeError: Cannot read properties of null (reading 'map')
    at Timeout._onTimeout (/root/project1/index.js:27:5)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
</code>```

Any help would be greatly appreciated. Thank you!

Body:
I am trying to get my Etherscan Verified Contract Scraper that forwards new Verified Contracts to a specific Discord channel working and have run into issues.

Here is the code--

const Discord = require("discord.js");
const fetch = require("node-fetch");
const config = require("./config.json");
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Discord.Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
  ]
})

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// Replace CHANNEL_ID with the ID of the channel you want to post in
const channel = client.channels.cache.get('CHANNELID');

// Scrape new verified contracts from Etherscan every minute
setInterval(async () => {
  const response = await fetch('https://etherscan.io/contractsVerified');
  const html = await response.text();

  // Extract the verified contracts from the HTML
  const verifiedContracts = html.match(/href="\/address\/[0-9a-fA-F]+"/g)
    .map((link) => link.slice(8, -1));

  // Send an embedded message to the Discord channel with the verified contracts
  const embed = new Discord.MessageEmbed()
    .setTitle('Verified Contracts')
    .setDescription(verifiedContracts.join('\n'))
    .setColor('#00FF00');
  channel.send(embed);
}, 60000);

client.login(config.BOT_TOKEN);

Here is the error I'm getting--

TypeError: Cannot read properties of null (reading 'map')
    at Timeout._onTimeout (/root/project1/index.js:27:5)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Any help would be greatly appreciated. Thank you!


问:
Skip row in google sheets script search
I want to specify the search range for following piece of code to prevent the first 'campaignID' to show up as test result. How can I specify the search range for createTextFinder()?</p>
```<code>  function FindRow() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var campaignID = sheet.getRange('D12').getValue();
    var linkValue = sheet.getRange('D16').getValue(); // get the value of link
    var a = sheet.createTextFinder(campaignID).matchEntireCell(true).findNext().getRow();
    //sheet.getRange(a,7).setValue(linkValue); // set the value of link to campain
    var ui = SpreadsheetApp.getUi();
     ui.alert("search row: " + a)
</code>```

Title: Skip row in google sheets script search

Body:
I want to specify the search range for following piece of code to prevent the first 'campaignID' to show up as test result. How can I specify the search range for createTextFinder()?

  function FindRow() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var campaignID = sheet.getRange('D12').getValue();
    var linkValue = sheet.getRange('D16').getValue(); // get the value of link
    var a = sheet.createTextFinder(campaignID).matchEntireCell(true).findNext().getRow();
    //sheet.getRange(a,7).setValue(linkValue); // set the value of link to campain
    var ui = SpreadsheetApp.getUi();
     ui.alert("search row: " + a)


问:
Is it possible to convert Core ML output to a string
I have managed to change input requirements of my model but I couldn't manage to change the output. my aim is having a string output rather then a multiArrayType. I don't even know is it possible or not but these are the things that I've tried until now.

```<code>mlmodel = ct.convert(tf_model, inputs=[ct.ImageType()],outputs=[ct.StringType()])
</code>```
```<code>mlmodel = ct.converters.mil.output_types.ClassifierConfig(class_labels, predicted_feature_name='Identity', predicted_probabilities_output=str)
</code>```
```<code>spec = ct.utils.load_spec('10MobileNetV2.mlmodel')

output = spec.description.output[0]
output.type = ft.StringFeatureType

ct.utils.save_spec(spec, "10MobileNetV2.mlmodel")
print(spec.description)
</code>```

As a summary when I use print(spec.description) this prints out

```<code>output {
  name: "Identity"
  type {
    multiArrayType {
      dataType: FLOAT32
    }
  }
}

</code>```

and I want this

```<code>output {
  name: "Identity"
  type {
    dictionaryType {
      stringKeyType {
      }
    }
  }
}
</code>```

Body:
I have managed to change input requirements of my model but I couldn't manage to change the output. my aim is having a string output rather then a multiArrayType. I don't even know is it possible or not but these are the things that I've tried until now.

mlmodel = ct.convert(tf_model, inputs=[ct.ImageType()],outputs=[ct.StringType()])

mlmodel = ct.converters.mil.output_types.ClassifierConfig(class_labels, predicted_feature_name='Identity', predicted_probabilities_output=str)

spec = ct.utils.load_spec('10MobileNetV2.mlmodel')

output = spec.description.output[0]
output.type = ft.StringFeatureType

ct.utils.save_spec(spec, "10MobileNetV2.mlmodel")
print(spec.description)

As a summary when I use print(spec.description) this prints out

output {
  name: "Identity"
  type {
    multiArrayType {
      dataType: FLOAT32
    }
  }
}

and I want this

output {
  name: "Identity"
  type {
    dictionaryType {
      stringKeyType {
      }
    }
  }
}


问:
Error trying to push an app from streamlit to heroku
I'm attempting to push an app from streamlit to heroku. In streamlit, the app works fine and the build is pushed successfully to heroku. However, when I deploy the app on heroku I keep getting this error message

Please assist me with this. I'm not sure how to approach


问:
Loading recaptcha asynchronously (grecaptcha.enterprise)
I'm using grecaptcha.enterprise v3 but it is common for some requests to have connection failures.

I want to load the async script but in enterprise mode.

```<code><script src="https://www.google.com/recaptcha/enterprise.js?badge=<?php echo $badge; ?>&size=invisible&render=<?php echo RECAPTCHA_SITE_KEY; ?>"></script>

<script>
  function recaptchaRenew() {
    grecaptcha.enterprise.execute('<?php echo RECAPTCHA_SITE_KEY; ?>', {action:'validate_captcha'})
      .then(function(token) {
        console.log('reCaptcha');

        // Apply token
        document.querySelector('.js-g-recaptcha-token').value = token;
      });
  }

  function recaptchaSubmit(token) {
    var $form = document.querySelector('.js-recaptcha');

    if ($form) {
      $form.submit();
    }
  }

  grecaptcha.enterprise.ready(function(){
    recaptchaRenew();
  });
</script>
</code>```


问:
How to get the set-cookie from http response that is set by server using express.js?
For the cookie that is attached to http request we use "req.headers.cookie". Just like that I want to be able to console log the set-cookie value.

Currently I'm using "res._headers" which logs

```<code>[Object: null prototype] {
  'x-powered-by': 'Express',
  location: 'secrets',
  vary: 'Accept',
  'content-type': 'text/html; charset=utf-8',
  'content-length': '58',
  'set-cookie': [
    'connect.sid=s%3A0nacHXK6fTKoQwBsVNvjW659OltdoVMR.L38W5Exjqg7wHnx70MF8OQu05uOFzWrrxJCgZ41RX7o; Path=/; HttpOnly'
  ]
</code>```

But how can I just log the connect.sid(set-cookie) value?

Tried: res._headers"

Body:
For the cookie that is attached to http request we use "req.headers.cookie". Just like that I want to be able to console log the set-cookie value.

Currently I'm using "res._headers" which logs

[Object: null prototype] {
  'x-powered-by': 'Express',
  location: 'secrets',
  vary: 'Accept',
  'content-type': 'text/html; charset=utf-8',
  'content-length': '58',
  'set-cookie': [
    'connect.sid=s%3A0nacHXK6fTKoQwBsVNvjW659OltdoVMR.L38W5Exjqg7wHnx70MF8OQu05uOFzWrrxJCgZ41RX7o; Path=/; HttpOnly'
  ]

But how can I just log the connect.sid(set-cookie) value?

Tried: res._headers"


问:
How to apply function to each time series in a tsibble?
DISCLAIMER: this question is related to this other question of mine, but it is more generic.

I have a tsibble called population with this structure:

```<code>> population
# A tsibble: 1,296 x 7 [1Y]
# Key:       sex, geo [54]
   citizen age   unit  sex   geo    time  values
   <chr>   <chr> <chr> <chr> <chr> <dbl>   <dbl>
 1 TOTAL   TOTAL NR    F     AT     1998 4122811
 2 TOTAL   TOTAL NR    F     AT     1999 4126432
 3 TOTAL   TOTAL NR    F     AT     2000 4133855
 4 TOTAL   TOTAL NR    F     AT     2001 4143737
 5 TOTAL   TOTAL NR    F     AT     2002 4156906
 6 TOTAL   TOTAL NR    F     AT     2003 4170674
 7 TOTAL   TOTAL NR    F     AT     2004 4189973
 8 TOTAL   TOTAL NR    F     AT     2005 4216493
 9 TOTAL   TOTAL NR    F     AT     2006 4239954
10 TOTAL   TOTAL NR    F     AT     2007 4252922
# … with 1,286 more rows
</code>```

I'd like to know how I can apply a function to each of the 54 time series in the data.

This is how to reproduce the dataset:

```<code>library(countrycode)
library(eurostat)
library(fpp3)

# defines
eu27 <- setdiff(eu_countries$code, "UK")

# Population on 1 January by age group, sex and citizenship
population <-
  get_eurostat(id = "migr_pop1ctz",
               time_format = "num")

# filter what's needed
population <- population %>%
  filter(citizen == "TOTAL",
         sex %in% c("F", "M"),
         age == "TOTAL",
         geo %in% eu27)

# convert to time series
population_ts <- population %>%
  as_tsibble(key = c("sex", "geo"), index = time) %>%
  fill_gaps(.full = TRUE) # fill missing index
</code>```

If I run this code against the population_ts tsibble, it will still retain the time index while grouping, whereas if I do this with the original population tibble, I get 54 rows as result. Is it normal?

```<code>res1 <- population %>%
   group_by(sex, geo) %>%
   summarise(sum(values))

res2 <- population_ts %>%
   group_by(sex, geo) %>%
   summarise(sum(values))
</code>```

My concern to use a tibble instead of a tsibble is that 1) I need to use fill_gaps() in my code, and 2) I would then need to run functions specific for time series, such as time disaggregation (td).

Body:
DISCLAIMER: this question is related to this other question of mine, but it is more generic.

I have a tsibble called population with this structure:

> population
# A tsibble: 1,296 x 7 [1Y]
# Key:       sex, geo [54]
   citizen age   unit  sex   geo    time  values
   <chr>   <chr> <chr> <chr> <chr> <dbl>   <dbl>
 1 TOTAL   TOTAL NR    F     AT     1998 4122811
 2 TOTAL   TOTAL NR    F     AT     1999 4126432
 3 TOTAL   TOTAL NR    F     AT     2000 4133855
 4 TOTAL   TOTAL NR    F     AT     2001 4143737
 5 TOTAL   TOTAL NR    F     AT     2002 4156906
 6 TOTAL   TOTAL NR    F     AT     2003 4170674
 7 TOTAL   TOTAL NR    F     AT     2004 4189973
 8 TOTAL   TOTAL NR    F     AT     2005 4216493
 9 TOTAL   TOTAL NR    F     AT     2006 4239954
10 TOTAL   TOTAL NR    F     AT     2007 4252922
# … with 1,286 more rows

I'd like to know how I can apply a function to each of the 54 time series in the data.

This is how to reproduce the dataset:

library(countrycode)
library(eurostat)
library(fpp3)

# defines
eu27 <- setdiff(eu_countries$code, "UK")

# Population on 1 January by age group, sex and citizenship
population <-
  get_eurostat(id = "migr_pop1ctz",
               time_format = "num")

# filter what's needed
population <- population %>%
  filter(citizen == "TOTAL",
         sex %in% c("F", "M"),
         age == "TOTAL",
         geo %in% eu27)

# convert to time series
population_ts <- population %>%
  as_tsibble(key = c("sex", "geo"), index = time) %>%
  fill_gaps(.full = TRUE) # fill missing index

If I run this code against the population_ts tsibble, it will still retain the time index while grouping, whereas if I do this with the original population tibble, I get 54 rows as result. Is it normal?

res1 <- population %>%
   group_by(sex, geo) %>%
   summarise(sum(values))

res2 <- population_ts %>%
   group_by(sex, geo) %>%
   summarise(sum(values))

My concern to use a tibble instead of a tsibble is that 1) I need to use fill_gaps() in my code, and 2) I would then need to run functions specific for time series, such as time disaggregation (td).


问:
Java service looses a connection to Rabbitmq and throws a NullPointerException
I have a java service that works with Rabbitmq server, it gets tasks and send answers to the queue. However, after 334 handling to the Rabbitmq queue connection looses and throw nullPointerException. I can not understand why after long time working service looses connection to Rabbitmq.

How error looks

```<code> [1;31mERROR[0;39m - Consumer com.rabbitmq.client.impl.ChannelN$4@59ef17e4 (amq.ctag-_itVmRHd4yWS6gG-Gh4XqQ) method handleDelivery for channel AMQChannel(amqp://guest@0.0.0.0:5672/,1) threw an exception for channel AMQChannel(amqp://guest@0.0.0.0:5672/,1)
java.lang.NullPointerException: null
    at com.peterservice.artifactory.deployPlugins.RabbitWorker.getSenderChannel(RabbitWorker.java:1364)
    at com.peterservice.artifactory.deployPlugins.RabbitWorker.lambda$runWorker$0(RabbitWorker.java:269)
    at com.rabbitmq.client.impl.ChannelN$4.handleDelivery(ChannelN.java:1404)
    at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:149)
    at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:104)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)
</code>```

Where error happens

```<code>private static Channel getSenderChannel(Connection connection) throws IOException {
    Channel channel = connection.createChannel();
    channel.queueDeclare(settings.deployDoneQueue(), durable, false, false, null);
    return channel;
}
</code>```

I made a load testing and understood that this error happens every time after 334 counts that service connects to Rabbitmq.

Body:
I have a java service that works with Rabbitmq server, it gets tasks and send answers to the queue. However, after 334 handling to the Rabbitmq queue connection looses and throw nullPointerException. I can not understand why after long time working service looses connection to Rabbitmq.

How error looks

 [1;31mERROR[0;39m - Consumer com.rabbitmq.client.impl.ChannelN$4@59ef17e4 (amq.ctag-_itVmRHd4yWS6gG-Gh4XqQ) method handleDelivery for channel AMQChannel(amqp://guest@0.0.0.0:5672/,1) threw an exception for channel AMQChannel(amqp://guest@0.0.0.0:5672/,1)
java.lang.NullPointerException: null
    at com.peterservice.artifactory.deployPlugins.RabbitWorker.getSenderChannel(RabbitWorker.java:1364)
    at com.peterservice.artifactory.deployPlugins.RabbitWorker.lambda$runWorker$0(RabbitWorker.java:269)
    at com.rabbitmq.client.impl.ChannelN$4.handleDelivery(ChannelN.java:1404)
    at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:149)
    at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:104)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)

Where error happens

private static Channel getSenderChannel(Connection connection) throws IOException {
    Channel channel = connection.createChannel();
    channel.queueDeclare(settings.deployDoneQueue(), durable, false, false, null);
    return channel;
}

I made a load testing and understood that this error happens every time after 334 counts that service connects to Rabbitmq.


问:
I am tryin to protect my admin link, ButI am catching below error
Argument of type '(user: any) => AngularFireObject | Observable' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.ts(2345)
Argument of type '(user: any) => AngularFireObject | Observable' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
Type 'AngularFireObject | Observable' is not assignable to type 'ObservableInput'.
Type 'AngularFireObject' is not assignable to type 'ObservableInput'.ts(2345)
Below us my code

```<code>import { Injectable } from "@angular/core";
import { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Observable } from "rxjs/internal/Observable";
import firebase from 'firebase/compat/app';
import { ActivatedRoute, Router, RouterLink, RouterStateSnapshot } from "@angular/router";
import { switchMap, of } from "rxjs";
import { UserService } from "./user.service";
import { AppUser } from "./Models/app-user";

@Injectable({ providedIn: 'root' })

export class AuthService {
  [x: string]: any;
  user$: Observable<firebase.User|any> ;

  constructor(private afAuth:AngularFireAuth, private router:Router,private  route: ActivatedRoute,
    private userService: UserService) {
    this.user$ = afAuth.authState;
   }
  login() {
    let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
    localStorage.setItem('returnUrl',returnUrl);
    this.afAuth.signInWithRedirect(new GoogleAuthProvider());
  }
  logout(){
    this.afAuth.signOut();
  }
  isLoggedin(state:RouterStateSnapshot,route:RouterStateSnapshot){
    this.user$?.subscribe(user =>{
      if(user) return true;

      this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}});
      return false;
    })
  }
  getAppUser(): Observable<AppUser> {
    return this.user$.pipe(
      switchMap((user) =>{
        if (user) {
          return this.userService.get(user.uid);
        }
        return of(null);
      })
    );
  }

}
</code>```

and the eror is coming from

```<code>getAppUser(): Observable<AppUser> {
    return this.user$.pipe(
      switchMap((user) =>{
        if (user) {
          return this.userService.get(user.uid);
        }
        return of(null);
      })
    );
  }
</code>```

This is my user.servie.ts

```<code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/compat/database';
import firebase from 'firebase/compat/app';
import { AppUser } from './Models/app-user';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private db : AngularFireDatabase) { }
  save(user: firebase.User){
    this.db.object('/user/'+user.uid).update({
      name: user.displayName,
      email:user.email
    });
  }
  get(uid:String):AngularFireObject <AppUser>{
    return this.db.object('/user/'+uid);
  }
}
</code>```

Please help me for this

Body:
Argument of type '(user: any) => AngularFireObject | Observable' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.ts(2345)
Argument of type '(user: any) => AngularFireObject | Observable' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
Type 'AngularFireObject | Observable' is not assignable to type 'ObservableInput'.
Type 'AngularFireObject' is not assignable to type 'ObservableInput'.ts(2345)
Below us my code

import { Injectable } from "@angular/core";
import { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Observable } from "rxjs/internal/Observable";
import firebase from 'firebase/compat/app';
import { ActivatedRoute, Router, RouterLink, RouterStateSnapshot } from "@angular/router";
import { switchMap, of } from "rxjs";
import { UserService } from "./user.service";
import { AppUser } from "./Models/app-user";

@Injectable({ providedIn: 'root' })

export class AuthService {
  [x: string]: any;
  user$: Observable<firebase.User|any> ;

  constructor(private afAuth:AngularFireAuth, private router:Router,private  route: ActivatedRoute,
    private userService: UserService) {
    this.user$ = afAuth.authState;
   }
  login() {
    let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
    localStorage.setItem('returnUrl',returnUrl);
    this.afAuth.signInWithRedirect(new GoogleAuthProvider());
  }
  logout(){
    this.afAuth.signOut();
  }
  isLoggedin(state:RouterStateSnapshot,route:RouterStateSnapshot){
    this.user$?.subscribe(user =>{
      if(user) return true;

      this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}});
      return false;
    })
  }
  getAppUser(): Observable<AppUser> {
    return this.user$.pipe(
      switchMap((user) =>{
        if (user) {
          return this.userService.get(user.uid);
        }
        return of(null);
      })
    );
  }

}

and the eror is coming from

getAppUser(): Observable<AppUser> {
    return this.user$.pipe(
      switchMap((user) =>{
        if (user) {
          return this.userService.get(user.uid);
        }
        return of(null);
      })
    );
  }

This is my user.servie.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/compat/database';
import firebase from 'firebase/compat/app';
import { AppUser } from './Models/app-user';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private db : AngularFireDatabase) { }
  save(user: firebase.User){
    this.db.object('/user/'+user.uid).update({
      name: user.displayName,
      email:user.email
    });
  }
  get(uid:String):AngularFireObject <AppUser>{
    return this.db.object('/user/'+uid);
  }
}

Please help me for this


问:
Only run a function once in JavaScript?
The title is weird, let me explain:

I am creating a website with animations. I have created a sort of "intro" to the website which lasts about 3 seconds using anime.js and setTimeOut functions. After the intro has "played" I am using more animations to 'build' the website where the user can browse between different links to other pages on the website. When a user presses on a link, they are being directed to the page, but then when they return to the main website clicking on a return-symbol, the animation plays again of course because I have made the intro animation functions run on "DOMContentLoaded". But I don't want the animation to run everytime a user just goes back to the main page because that is annoying. But I don't know how to fix the problem considering I have anchor tags to navigate between pages which reloads the page everytime and triggers the functions to execute.

Any ideas of solutions?

Title: Only run a function once in JavaScript?


问:
I edit an excel file and the following error appears UserWarning: Unknown extension is not supported and will be removed warn(msg)
the excel document is ready, I just need to make some changes and save the pdf document

```<code>from win32com import client
import openpyxl
import datetime
from openpyxl.formatting.rule import Rule
from openpyxl.formatting.rule import DataBar, FormatObject

Previous_Date = datetime.datetime.today() - datetime.timedelta(days=2)
Previous_Date_f = Previous_Date.strftime("%m/%d/%Y")

def date():
    wb = openpyxl.load_workbook("09.xlsx", read_only=False, data_only=False, keep_links=True)
    ws = wb.active
    ws["B1"] = Previous_Date_f
    ws["B2"] = Previous_Date_f
    first = FormatObject(type='min')
    second = FormatObject(type='max')
    data_bar = DataBar(cfvo=[first, second], color="32CD32", showValue=None, minLength=None, maxLength=None)
    rule = Rule(type='dataBar', dataBar=data_bar)
    ws.conditional_formatting.add("F5:F52", rule)
    wb.save(filename='n09.xlsx')

def pdf():
    excel = client.Dispatch("Excel.Application")
    sheets = excel.Workbooks.Open("../Desktop/new/n09.xlsx")
    work_sheets = sheets.Worksheets[0]
    work_sheets.PageSetup.Orientation = 2
    work_sheets.ExportAsFixedFormat(0, "../Desktop/new/n09.pdf")

if __name__ == "__main__":
    date()
    pdf()
</code>```

gives the following errors

```<code>UserWarning: Unknown extension is not supported and will be removed
  warn(msg)
</code>```
```<code>UserWarning: Conditional Formatting extension is not supported and will be removed
  warn(msg)
</code>```

The code does not work perfectly.
It just has to convert the edited excel file to pdf.
Who knows how to fix the errors, please tell me.

Body:
the excel document is ready, I just need to make some changes and save the pdf document

from win32com import client
import openpyxl
import datetime
from openpyxl.formatting.rule import Rule
from openpyxl.formatting.rule import DataBar, FormatObject

Previous_Date = datetime.datetime.today() - datetime.timedelta(days=2)
Previous_Date_f = Previous_Date.strftime("%m/%d/%Y")

def date():
    wb = openpyxl.load_workbook("09.xlsx", read_only=False, data_only=False, keep_links=True)
    ws = wb.active
    ws["B1"] = Previous_Date_f
    ws["B2"] = Previous_Date_f
    first = FormatObject(type='min')
    second = FormatObject(type='max')
    data_bar = DataBar(cfvo=[first, second], color="32CD32", showValue=None, minLength=None, maxLength=None)
    rule = Rule(type='dataBar', dataBar=data_bar)
    ws.conditional_formatting.add("F5:F52", rule)
    wb.save(filename='n09.xlsx')

def pdf():
    excel = client.Dispatch("Excel.Application")
    sheets = excel.Workbooks.Open("../Desktop/new/n09.xlsx")
    work_sheets = sheets.Worksheets[0]
    work_sheets.PageSetup.Orientation = 2
    work_sheets.ExportAsFixedFormat(0, "../Desktop/new/n09.pdf")

if __name__ == "__main__":
    date()
    pdf()

gives the following errors

UserWarning: Unknown extension is not supported and will be removed
  warn(msg)

UserWarning: Conditional Formatting extension is not supported and will be removed
  warn(msg)

The code does not work perfectly.
It just has to convert the edited excel file to pdf.
Who knows how to fix the errors, please tell me.


问:
MarkLogic Java Client JSONDocumentManager word search returns incorrect total number of results
```<code>jsonDocumentManager.setPageLength(pagination.getItemsPerPage());
var offset = ((pagination.getPage() - 1) * pagination.getItemsPerPage()) + 1;
</code>```
```<code>try (var documentPage = jsonDocumentManager.search(queryDefinition, offset)) {
            var results = new ArrayList<TransportOrder>();
            for (var documentRecord : documentPage) {
                try {
                    var jsonParser = documentRecord.getContent(new JacksonParserHandle()).get();
                    ...
                } catch (IOException e) {
                    System.out.println("Something went wrong");
                }
            }

            var totalNumberOfResults = documentPage.getTotalSize();
            System.out.println("totalNumberOfResults : " + totalNumberOfResults);
        }
    }
</code>```

where the queryDefinition contains multiple word queries:

```<code>qb.word(qb.jsonProperty(searchField), StructuredQueryBuilder.FragmentScope.DOCUMENTS,
                new String[] {"wildcarded"}, 1.0, wildcardString);
</code>```

The problem is the totalNumberOfResults is the total items from the database not only the items that match the search criteria. It is mentioned in the documentation for getTotalSize that: "The total count (most likely an estimate) of all possible items in the set."
I need to get somehow the actual number of items found by the search. Any idea how I can achieve this?

https://docs.marklogic.com/javadoc/client/com/marklogic/client/Page.html#getTotalSize--

Body:
jsonDocumentManager.setPageLength(pagination.getItemsPerPage());
var offset = ((pagination.getPage() - 1) * pagination.getItemsPerPage()) + 1;

try (var documentPage = jsonDocumentManager.search(queryDefinition, offset)) {
            var results = new ArrayList<TransportOrder>();
            for (var documentRecord : documentPage) {
                try {
                    var jsonParser = documentRecord.getContent(new JacksonParserHandle()).get();
                    ...
                } catch (IOException e) {
                    System.out.println("Something went wrong");
                }
            }

            var totalNumberOfResults = documentPage.getTotalSize();
            System.out.println("totalNumberOfResults : " + totalNumberOfResults);
        }
    }

where the queryDefinition contains multiple word queries:

qb.word(qb.jsonProperty(searchField), StructuredQueryBuilder.FragmentScope.DOCUMENTS,
                new String[] {"wildcarded"}, 1.0, wildcardString);

The problem is the totalNumberOfResults is the total items from the database not only the items that match the search criteria. It is mentioned in the documentation for getTotalSize that: "The total count (most likely an estimate) of all possible items in the set."
I need to get somehow the actual number of items found by the search. Any idea how I can achieve this?

https://docs.marklogic.com/javadoc/client/com/marklogic/client/Page.html#getTotalSize--


问:
xsl-fo: configure gap between two pages
I am using xsl-fo to generate PDFs.

How do we configure gap between two subsequent pages, like in image below?

Title: xsl-fo: configure gap between two pages


问:
Decrypt function not working in Windows form C#
I am trying to decrypt from an encrypted word using c# in windows form. When I tried to use the function, I am getting an "ofield_encryptionkey" message in the message box.

Here is the Main. The encryption is working but when I tried to decrypt on the other end is not working.

```<code>

static void Main(string[] args)
{
    string TokenID = Decrypt("fU2vE9Pc9Wb2HQn3qTHWN66lnxWxgOkpLfbGmiOOlVq32r8q40Iqq8ql8mPCkgLx");
    MessageBox.Show(TokenID);
}

//Here's the function
public static string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    cipherText = cipherText.Replace(" ", "+");
    var cipherBytes = Convert.FromBase64String(cipherText);
    using (var encryptor = Aes.Create())
    {
        var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}
</code>```

Body:
I am trying to decrypt from an encrypted word using c# in windows form. When I tried to use the function, I am getting an "ofield_encryptionkey" message in the message box.

Here is the Main. The encryption is working but when I tried to decrypt on the other end is not working.

static void Main(string[] args)
{
    string TokenID = Decrypt("fU2vE9Pc9Wb2HQn3qTHWN66lnxWxgOkpLfbGmiOOlVq32r8q40Iqq8ql8mPCkgLx");
    MessageBox.Show(TokenID);
}

//Here's the function
public static string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    cipherText = cipherText.Replace(" ", "+");
    var cipherBytes = Convert.FromBase64String(cipherText);
    using (var encryptor = Aes.Create())
    {
        var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20, 0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}


问:
Bad routes for admin in Laravel
I am a newbie in Laravel and wanna create Admin Login and Registration. I have user registration and it works properly.

My web.php

```<code><?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::view('/', 'index');

Route::name('user.')->group(function () {
   Route::view('/private', 'private')->middleware('auth')->name('private');

   Route::get('/login', function() {
       if (Auth::check()) {
           return redirect(route('user.private'));
       }
       return view('login');
   })->name('login');

   Route::post('/login', [\App\Http\Controllers\LoginController::class, 'login']);

    Route::get('/logout', function () {
        Auth::logout();
        return redirect('/');
    })->name('logout');

    Route::get('/registration', function() {
        if (Auth::check()) {
            return redirect(route('user.private'));
        }
        return view('registration');
    })->name('registration');

    Route::post('/registration', [\App\Http\Controllers\RegisterController::class, 'save']);
});

Route::name('admin.')->group(function () {
    Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('adminPrivate');
//    dd(Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('private'));

    Route::get('/adminLogin', function() {
        if (Auth::guard('admin')->check()) {

            return redirect(route('admin.adminPrivate'));
        }
        return view('adminLogin');
    })->name('login');

    Route::post('/adminLogin', [\App\Http\Controllers\LoginAdminController::class, 'login']);

    Route::get('/adminLogout', function () {
        Auth::guard('admin')->logout();
        return redirect('/');
    })->name('logout');

    Route::get('/adminRegistration', function() {
        if (Auth::guard('admin')->check()) {
            return redirect(route('admin.adminPrivate'));
        }
        return view('adminRegistration');
    })->name('registration');

    Route::post('/adminRegistration', [\App\Http\Controllers\RegisterAdminController::class, 'save']);
});

</code>```

My RegisterAdminController.php

```<code><?php

namespace App\Http\Controllers;

use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RegisterAdminController extends Controller
{
    public function save(Request $request) {
        if (Auth::guard('admin')->check()) {
            return redirect(route('admin.adminPrivate'));
        }

        $validateFields = $request->validate([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (Admin::where('username', $validateFields['username'])->exists()) {
            return redirect(route('admin.registration'))->withErrors([
                'username' => 'Username already registered!'
            ]);
        }

        $admin = Admin::create($validateFields);
        if ($admin) {
            Auth::guard('admin')->login($admin);
            return redirect(route('admin.adminPrivate'));
        }
        return redirect(route('admin.login'))->withErrors([
            'formError' => 'Cannot save admin!'
        ]);
    }
}

</code>```

My LoginAdminController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginAdminController extends Controller
{
    public function login(Request $request) {
        if (Auth::guard('admin')->check()) {
            return Redirect::to(route('admin.adminPrivate'));
        }

        $formFields = $request->only(['username', 'password']);

        if (Auth::guard('admin')->attempt($formFields)) {
            return Redirect::to(route('admin.adminPrivate'));
        }

        return redirect(route('admin.login'))->withErrors([
            'username' => 'Can not authorize'
        ]);
    }
}

</code>```

I don't understand how I can solve this problem. Need a help. I tried modify all names of my Routes, but this didn't help.

Title: Bad routes for admin in Laravel

Body:
I am a newbie in Laravel and wanna create Admin Login and Registration. I have user registration and it works properly.

My web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::view('/', 'index');

Route::name('user.')->group(function () {
   Route::view('/private', 'private')->middleware('auth')->name('private');

   Route::get('/login', function() {
       if (Auth::check()) {
           return redirect(route('user.private'));
       }
       return view('login');
   })->name('login');

   Route::post('/login', [\App\Http\Controllers\LoginController::class, 'login']);

    Route::get('/logout', function () {
        Auth::logout();
        return redirect('/');
    })->name('logout');

    Route::get('/registration', function() {
        if (Auth::check()) {
            return redirect(route('user.private'));
        }
        return view('registration');
    })->name('registration');

    Route::post('/registration', [\App\Http\Controllers\RegisterController::class, 'save']);
});

Route::name('admin.')->group(function () {
    Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('adminPrivate');
//    dd(Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('private'));

    Route::get('/adminLogin', function() {
        if (Auth::guard('admin')->check()) {

            return redirect(route('admin.adminPrivate'));
        }
        return view('adminLogin');
    })->name('login');

    Route::post('/adminLogin', [\App\Http\Controllers\LoginAdminController::class, 'login']);

    Route::get('/adminLogout', function () {
        Auth::guard('admin')->logout();
        return redirect('/');
    })->name('logout');

    Route::get('/adminRegistration', function() {
        if (Auth::guard('admin')->check()) {
            return redirect(route('admin.adminPrivate'));
        }
        return view('adminRegistration');
    })->name('registration');

    Route::post('/adminRegistration', [\App\Http\Controllers\RegisterAdminController::class, 'save']);
});

My RegisterAdminController.php

<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RegisterAdminController extends Controller
{
    public function save(Request $request) {
        if (Auth::guard('admin')->check()) {
            return redirect(route('admin.adminPrivate'));
        }

        $validateFields = $request->validate([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (Admin::where('username', $validateFields['username'])->exists()) {
            return redirect(route('admin.registration'))->withErrors([
                'username' => 'Username already registered!'
            ]);
        }

        $admin = Admin::create($validateFields);
        if ($admin) {
            Auth::guard('admin')->login($admin);
            return redirect(route('admin.adminPrivate'));
        }
        return redirect(route('admin.login'))->withErrors([
            'formError' => 'Cannot save admin!'
        ]);
    }
}

My LoginAdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginAdminController extends Controller
{
    public function login(Request $request) {
        if (Auth::guard('admin')->check()) {
            return Redirect::to(route('admin.adminPrivate'));
        }

        $formFields = $request->only(['username', 'password']);

        if (Auth::guard('admin')->attempt($formFields)) {
            return Redirect::to(route('admin.adminPrivate'));
        }

        return redirect(route('admin.login'))->withErrors([
            'username' => 'Can not authorize'
        ]);
    }
}

I don't understand how I can solve this problem. Need a help. I tried modify all names of my Routes, but this didn't help.


问:
react native + firestore - how to get last document id?
As in Title.
How to get the last ID of a document? Should you use limit(1) in your query? Is there any other faster way?

I have not found an answer to this question anywhere.


问:
Custom loss function error in Tensorflow when passing model inputs as an argument (with y_true and y_pred)
Using Tensorflow 2.10, I am trying to implement a custom loss function that takes the model inputs as well as y_true and y_pred arguments.

```<code>inputs  = tf.keras.layers.Input(shape=X.shape[-1:], batch_size=16)
dense1  = tf.keras.layers.Dense(8, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(1, activation='sigmoid')(dense1)
model   = tf.keras.Model(inputs=inputs, outputs=outputs)

def custom_loss(i):
    def loss(y_true, y_pred):
        mask = tf.equal(y_true, tf.cast(tf.round(y_pred), 'float32'))
        selec = tf.where(mask, 1., 0.)
        x1 = (1 - tf.reduce_mean(selec))
        mask = tf.reshape(selec, (-1,))
        m = tf.boolean_mask(i, mask)
        x2 = tf.reduce_mean(m[:, -1])
        return x1 * x2
    return loss

model.compile(loss=custom_loss(inputs),
              optimizer='adam',
              metrics=['accuracy',
                       tf.keras.metrics.Precision(name='precision')])

h = model.fit(X_train,
              y_train,
              validation_data=(X_test, y_test),
              epochs=5,
              batch_size=16,
              verbose=2)
</code>```

When trying to fit the model I got the following error:

```<code>TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(), dtype=tf.float32, name=None), name='Placeholder:0', description="created by layer 'tf.cast_17'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as `tf.cond`, `tf.function`, gradient tapes, or `tf.map_fn`. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as `tf.math.add` or `tf.reshape`. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer `call` and calling that layer on this symbolic input/output.
</code>```

Similar posts proposed to disable eager execution:

```<code>from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()
</code>```

But this leads to another error in the loss function:

```<code>ValueError: Variable <tf.Variable 'dense_14/kernel:0' shape=(13, 8) dtype=float32> has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
</code>```

Body:
Using Tensorflow 2.10, I am trying to implement a custom loss function that takes the model inputs as well as y_true and y_pred arguments.

inputs  = tf.keras.layers.Input(shape=X.shape[-1:], batch_size=16)
dense1  = tf.keras.layers.Dense(8, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(1, activation='sigmoid')(dense1)
model   = tf.keras.Model(inputs=inputs, outputs=outputs)

def custom_loss(i):
    def loss(y_true, y_pred):
        mask = tf.equal(y_true, tf.cast(tf.round(y_pred), 'float32'))
        selec = tf.where(mask, 1., 0.)
        x1 = (1 - tf.reduce_mean(selec))
        mask = tf.reshape(selec, (-1,))
        m = tf.boolean_mask(i, mask)
        x2 = tf.reduce_mean(m[:, -1])
        return x1 * x2
    return loss

model.compile(loss=custom_loss(inputs),
              optimizer='adam',
              metrics=['accuracy',
                       tf.keras.metrics.Precision(name='precision')])

h = model.fit(X_train,
              y_train,
              validation_data=(X_test, y_test),
              epochs=5,
              batch_size=16,
              verbose=2)

When trying to fit the model I got the following error:

TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(), dtype=tf.float32, name=None), name='Placeholder:0', description="created by layer 'tf.cast_17'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as `tf.cond`, `tf.function`, gradient tapes, or `tf.map_fn`. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as `tf.math.add` or `tf.reshape`. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer `call` and calling that layer on this symbolic input/output.

Similar posts proposed to disable eager execution:

from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

But this leads to another error in the loss function:

ValueError: Variable <tf.Variable 'dense_14/kernel:0' shape=(13, 8) dtype=float32> has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.


问:
numpy.loadtxt() Unicode Character type (<U) numpy is non-dimensional when the file has only one element. Cannot access the single characters
I encountered this situation while programming in python:

I have a file containing only 1 sequence of  64 bits. The goal of the program is to perform some sort of manipulation on this string of bits. To let you understand this is its content:

bias.txt

```<code>0000000000000000000000000000001010000101001110011110011000101010
</code>```

The extract of the code is the following:

```<code>import numpy as np

bias_str = np.loadtxt(fname=bias_filename, dtype=dt_string, delimiter="\n")

</code>```

which leads to:

```<code>array('0000000000000000000000000000001010000101001110011110011000101010',
      dtype='<U64')
</code>```

which is 0-dimensional, infact bias_str.shape returns ().
This does not really bother me but when I try to access one character of the string things get fishy.
Since I know this is string, which is supposedly a python strings which can be accessed specifing the character index of the string I want to access to, I try:

```<code>bias_str[0]
</code>```

but now I get the error:

```<code>too many indices for array: array is 0-dimensional, but 1 were indexed
</code>```

The problem is solved if passing the paramter ndmin = 1, which forces an array of dimension 1 to be created. In that case the loadtxt function returns

```<code>array(['0000000000000000000000000000001010000101001110011110011000101010'],
      dtype='<U64')
</code>```

And I am able to access the first character by double indexing:

```<code>bias_str[0][0]
</code>```

Why such situation arises? What use would it make to have a string I cannot access to? And is there a way to access the only element of a 0-dimensional numpy array with one element inside?

Body:
I encountered this situation while programming in python:

I have a file containing only 1 sequence of  64 bits. The goal of the program is to perform some sort of manipulation on this string of bits. To let you understand this is its content:

bias.txt

0000000000000000000000000000001010000101001110011110011000101010

The extract of the code is the following:

import numpy as np

bias_str = np.loadtxt(fname=bias_filename, dtype=dt_string, delimiter="\n")

which leads to:

array('0000000000000000000000000000001010000101001110011110011000101010',
      dtype='<U64')

which is 0-dimensional, infact bias_str.shape returns ().
This does not really bother me but when I try to access one character of the string things get fishy.
Since I know this is string, which is supposedly a python strings which can be accessed specifing the character index of the string I want to access to, I try:

bias_str[0]

but now I get the error:

too many indices for array: array is 0-dimensional, but 1 were indexed

The problem is solved if passing the paramter ndmin = 1, which forces an array of dimension 1 to be created. In that case the loadtxt function returns

array(['0000000000000000000000000000001010000101001110011110011000101010'],
      dtype='<U64')

And I am able to access the first character by double indexing:

bias_str[0][0]

Why such situation arises? What use would it make to have a string I cannot access to? And is there a way to access the only element of a 0-dimensional numpy array with one element inside?


问:
ArangoSearch View Shard Key
Hello ArangoDb community,

I could not find documents related to shard key for ArangoSearch view. Without shardKey for ArangoSearch view, the request would hit all nodes and search performance would be very bad because it would hit all nodes in the cluster. Imagine 300 servers got hit every time someone search?
I've read this shard key document for collections, but could not find for ArangoSearch view.
https://www.arangodb.com/docs/stable/architecture-deployment-modes-cluster-sharding.html

Title: ArangoSearch View Shard Key


问:
Using negative values as index in Arrays in JavaScript
why an error is not shown, when I try to add new elements in the array, using negative indexing.

```<code>var myArray = new Array(3);
myArray[0] = 0;
myArray[1] = 1;
myArray[2] = 2;

myArray[-1] = -1;

console.log(myArray);
</code>```

I was expecting an Error,But instead I get a output like this.

enter image description here

Body:
why an error is not shown, when I try to add new elements in the array, using negative indexing.

var myArray = new Array(3);
myArray[0] = 0;
myArray[1] = 1;
myArray[2] = 2;

myArray[-1] = -1;

console.log(myArray);

I was expecting an Error,But instead I get a output like this.

enter image description here


问:
Getting InterruptedException when deploying JMS app in JBoss
My war file is deployed in a JBoss server and it connects to the queue in another machine. While deploying the war file I'm getting this exception:

```<code>2022-12-21 11:28:02,749 ERROR [org.apache.activemq.artemis.ra] (Thread-254 (ActiveMQ-client-global-threads)) AMQ154004: Failed to deliver message: java.lang.NullPointerException
    at org.apache.activemq.artemis.ra.inflow.ActiveMQMessageHandler.onMessage(ActiveMQMessageHandler.java:330)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:1031)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:50)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1154)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:42)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:31)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.executePendingTasks(ProcessorBase.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)

2022-12-21 11:28:02,778 ERROR [org.apache.activemq.artemis.core.client] (Thread-254 (ActiveMQ-client-global-threads)) AMQ214000: Failed to call onMessage: org.apache.activemq.artemis.api.core.ActiveMQInterruptedException: java.lang.InterruptedException
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:430)
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:358)
    at org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext.sessionStop(ActiveMQSessionContext.java:473)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.stop(ClientSessionImpl.java:1096)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.stop(ClientSessionImpl.java:1085)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.rollback(ClientSessionImpl.java:989)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.rollback(ClientSessionImpl.java:972)
    at org.apache.activemq.artemis.ra.inflow.ActiveMQMessageHandler.onMessage(ActiveMQMessageHandler.java:385)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:1031)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:50)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1154)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:42)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:31)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.executePendingTasks(ProcessorBase.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)
Caused by: java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2151)
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:428)
    ... 16 more
</code>```

What could be the issue?

Body:
My war file is deployed in a JBoss server and it connects to the queue in another machine. While deploying the war file I'm getting this exception:

2022-12-21 11:28:02,749 ERROR [org.apache.activemq.artemis.ra] (Thread-254 (ActiveMQ-client-global-threads)) AMQ154004: Failed to deliver message: java.lang.NullPointerException
    at org.apache.activemq.artemis.ra.inflow.ActiveMQMessageHandler.onMessage(ActiveMQMessageHandler.java:330)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:1031)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:50)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1154)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:42)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:31)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.executePendingTasks(ProcessorBase.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)

2022-12-21 11:28:02,778 ERROR [org.apache.activemq.artemis.core.client] (Thread-254 (ActiveMQ-client-global-threads)) AMQ214000: Failed to call onMessage: org.apache.activemq.artemis.api.core.ActiveMQInterruptedException: java.lang.InterruptedException
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:430)
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:358)
    at org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQSessionContext.sessionStop(ActiveMQSessionContext.java:473)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.stop(ClientSessionImpl.java:1096)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.stop(ClientSessionImpl.java:1085)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.rollback(ClientSessionImpl.java:989)
    at org.apache.activemq.artemis.core.client.impl.ClientSessionImpl.rollback(ClientSessionImpl.java:972)
    at org.apache.activemq.artemis.ra.inflow.ActiveMQMessageHandler.onMessage(ActiveMQMessageHandler.java:385)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.callOnMessage(ClientConsumerImpl.java:1031)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl.access$400(ClientConsumerImpl.java:50)
    at org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl$Runner.run(ClientConsumerImpl.java:1154)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:42)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.doTask(OrderedExecutor.java:31)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.executePendingTasks(ProcessorBase.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)
Caused by: java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2151)
    at org.apache.activemq.artemis.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:428)
    ... 16 more

What could be the issue?


问:
Navigation bar with drop-down menu is not sticky-ing
The navigation menu is not 'freezing' to the top of the page while I scroll sticky this navigation menu at the top of the page.

let nav_toggle = document.querySelector('.nav_toggle');
let nav_toggle_icon = document.querySelector('.nav_toggle ion-icon');
let nav_menu = document.querySelector('.nav_menu');

nav_toggle.addEventListener('click', () => {
  nav_menu.classList.toggle('active');
  nav_toggle_icon.setAttribute('name',
    nav_menu.classList.contains('active') ? 'close-outline' : 'menu-outline'
  );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap');
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
  list-style-type: none;
}

:root {
  --primary: #7F56D9;
  --secondary: #F4EBFF;
  --text-primary: #101828;
  --text-secondary: #667085;
  --badge-bg: #ECFDF3;
  --badge-text: #027A48;
  --white: #fff;
  --dropdown-bg: rgb(252, 253, 251);
  --shadow: rgba(32, 7, 65, 0.14);
  --container: 124rem;
  --nav-height: 7rem;
}

html {
  font-family: 'Inter', sans-serif;
  font-size: 62.5%;
  font-style: normal;
}

body {
  font-size: 1.6rem;
}

ion-icon {
  font-size: 20px;
}

h4 {
  font-size: 110%;
  font-weight: 300;
}

h3 {
  font-size: 130%;
  font-weight: 500;
}

a.logo {
  color: rgb(9, 2, 114);
  font-size: 20px;
  font-weight: 500;
}

h4:hover {
  color: #eba714;
}

h3:hover {
  color: #3d3d3d;
}

.container {
  max-width: var(--container);
  margin: 0 auto;
  padding: 0 1rem;
  opacity: 0.98;
  position: sticky;
  top: 0;
}

.navigation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: var(--nav-height);
  position: relative;
  background: var(--white);
}

.nav_list {
  display: inline-flex;
  gap: 2rem;
  align-items: center;
  margin: 0 1.5rem;
}

.nav_action {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.nav_link,
.btn {
  display: flex;
  justify-content: center;
  gap: 1rem;
  font-weight: 500;
  color: var(--text-primary);
}

.btn-primary {
  display: inline-flex;
  color: var(--white);
  background: var(--primary);
  font-weight: 500;
  padding: 0.6rem 1.5rem;
  border-radius: 1.5rem;
}

.nav_toggle {
  cursor: pointer;
  display: none;
}

.nav_toggle ion-icon {
  font-size: 3.5rem;
  color: var(--text-primary);
}

.dropdown {
  position: absolute;
  top: var(--nav-height);
  left: 0;
  width: 100%;
  background: var(--dropdown-bg);
  box-shadow: 0rem 0.2rem 0.5rem var(--shadow);
  clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);
  transition: all 0.5s ease-in;
}

.dropdown-inner {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
  gap: 1rem;
  padding: 2rem;
}

.nav_list_menu:hover ion-icon {
  transition: all 0.5s ease-in;
  transform: rotate(180deg);
}

.nav_list_menu:hover .dropdown {
  clip-path: polygon(0 0, 100% 0, 100% 102%, 0 102%);
}

.item-list {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin: 3rem 0;
}

.item-list-info {
  position: relative;
  width: 100%;
}

.info-badge {
  position: absolute;
  right: 1rem;
  top: 0;
  background: var(--badge-bg);
  padding: 0.1rem 0.5rem;
  border-radius: 1rem;
  color: var(--badge-text);
}

@media (max-width:730px) {
  .nav_toggle {
    display: block;
  }
  .nav_menu {
    position: absolute;
    top: var(--nav-height);
    left: 0;
    width: 100%;
    background: var(--dropdown-bg);
    display: none;
  }
  .nav_menu.active {
    display: block;
  }
  .nav_list {
    display: block;
    margin: 2rem 0;
    text-align: center;
  }
  .nav_link {
    padding: 0 2rem;
    display: flex;
    justify-content: space-between;
  }
  .dropdown {
    top: 0;
    position: relative;
    clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);
    box-shadow: none;
    height: 0;
    text-align: start;
    transition: all 0.5s ease-in;
  }
  .nav_list_menu:hover .dropdown {
    height: 100%;
    transition: all 0.5s ease-in;
  }
}

@media (max-width:365px) {
  .logo-img {
    width: 10rem;
  }
  .btn,
  .btn-primary {
    padding: 0.4rem 1rem;
  }
}</code>```

       RA

          <ion-icon name="menu"></ion-icon>

Menu

Home

About

Blog

Get in touch

Projects

Carbon Calculator

Price my car

Coffee Finder

Quran Whiteboard

```

I have tried to attach the 'position: sticky;' and the 'top: 0;' to the container, navigation, etc., and to no effect. I am fairly new to JS and just getting back into HTML and CSS, your help would be appreciated, thank you!

Body:
The navigation menu is not 'freezing' to the top of the page while I scroll sticky this navigation menu at the top of the page.

let nav_toggle = document.querySelector('.nav_toggle');
let nav_toggle_icon = document.querySelector('.nav_toggle ion-icon');
let nav_menu = document.querySelector('.nav_menu');

nav_toggle.addEventListener('click', () => {
  nav_menu.classList.toggle('active');
  nav_toggle_icon.setAttribute('name',
    nav_menu.classList.contains('active') ? 'close-outline' : 'menu-outline'
  );
});

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap');
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
  list-style-type: none;
}

:root {
  --primary: #7F56D9;
  --secondary: #F4EBFF;
  --text-primary: #101828;
  --text-secondary: #667085;
  --badge-bg: #ECFDF3;
  --badge-text: #027A48;
  --white: #fff;
  --dropdown-bg: rgb(252, 253, 251);
  --shadow: rgba(32, 7, 65, 0.14);
  --container: 124rem;
  --nav-height: 7rem;
}

html {
  font-family: 'Inter', sans-serif;
  font-size: 62.5%;
  font-style: normal;
}

body {
  font-size: 1.6rem;
}

ion-icon {
  font-size: 20px;
}

h4 {
  font-size: 110%;
  font-weight: 300;
}

h3 {
  font-size: 130%;
  font-weight: 500;
}

a.logo {
  color: rgb(9, 2, 114);
  font-size: 20px;
  font-weight: 500;
}

h4:hover {
  color: #eba714;
}

h3:hover {
  color: #3d3d3d;
}

.container {
  max-width: var(--container);
  margin: 0 auto;
  padding: 0 1rem;
  opacity: 0.98;
  position: sticky;
  top: 0;
}

.navigation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: var(--nav-height);
  position: relative;
  background: var(--white);
}

.nav_list {
  display: inline-flex;
  gap: 2rem;
  align-items: center;
  margin: 0 1.5rem;
}

.nav_action {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.nav_link,
.btn {
  display: flex;
  justify-content: center;
  gap: 1rem;
  font-weight: 500;
  color: var(--text-primary);
}

.btn-primary {
  display: inline-flex;
  color: var(--white);
  background: var(--primary);
  font-weight: 500;
  padding: 0.6rem 1.5rem;
  border-radius: 1.5rem;
}

.nav_toggle {
  cursor: pointer;
  display: none;
}

.nav_toggle ion-icon {
  font-size: 3.5rem;
  color: var(--text-primary);
}

.dropdown {
  position: absolute;
  top: var(--nav-height);
  left: 0;
  width: 100%;
  background: var(--dropdown-bg);
  box-shadow: 0rem 0.2rem 0.5rem var(--shadow);
  clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);
  transition: all 0.5s ease-in;
}

.dropdown-inner {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
  gap: 1rem;
  padding: 2rem;
}

.nav_list_menu:hover ion-icon {
  transition: all 0.5s ease-in;
  transform: rotate(180deg);
}

.nav_list_menu:hover .dropdown {
  clip-path: polygon(0 0, 100% 0, 100% 102%, 0 102%);
}

.item-list {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin: 3rem 0;
}

.item-list-info {
  position: relative;
  width: 100%;
}

.info-badge {
  position: absolute;
  right: 1rem;
  top: 0;
  background: var(--badge-bg);
  padding: 0.1rem 0.5rem;
  border-radius: 1rem;
  color: var(--badge-text);
}

@media (max-width:730px) {
  .nav_toggle {
    display: block;
  }
  .nav_menu {
    position: absolute;
    top: var(--nav-height);
    left: 0;
    width: 100%;
    background: var(--dropdown-bg);
    display: none;
  }
  .nav_menu.active {
    display: block;
  }
  .nav_list {
    display: block;
    margin: 2rem 0;
    text-align: center;
  }
  .nav_link {
    padding: 0 2rem;
    display: flex;
    justify-content: space-between;
  }
  .dropdown {
    top: 0;
    position: relative;
    clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);
    box-shadow: none;
    height: 0;
    text-align: start;
    transition: all 0.5s ease-in;
  }
  .nav_list_menu:hover .dropdown {
    height: 100%;
    transition: all 0.5s ease-in;
  }
}

@media (max-width:365px) {
  .logo-img {
    width: 10rem;
  }
  .btn,
  .btn-primary {
    padding: 0.4rem 1rem;
  }
}

       RA

          <ion-icon name="menu"></ion-icon>

Menu

Home

About

Blog

Get in touch

Projects

Carbon Calculator

Price my car

Coffee Finder

Quran Whiteboard

I have tried to attach the 'position: sticky;' and the 'top: 0;' to the container, navigation, etc., and to no effect. I am fairly new to JS and just getting back into HTML and CSS, your help would be appreciated, thank you!


问:
Files deleted from Application
I have a dotnet application which i have accidently deleted files from the application itself but in my sql mdf file the size of my database is still the same and also from the sql database path the size is almost 9GB. Is there a way to recover those deleted data from the application by using mdf file which is showing the data's in the tables? Please advise

I have just taken the current backup from the sql management studio just in case

Title: Files deleted from Application


问:
React Native Flatlist shows a blank space in tvOS
I'm trying to show a flatList in tvOS and when the flatlist is rendered it shows unwanted space at the top of the rendered items inside the flatlist. This issue is not happening in Android TV or Fire TV.

My code :

```<code><SafeAreaView
      style={{
        flex: 1,
        backgroundColor: Colors.APP_BACKGROUND,
        flexDirection: 'row',
      }}>
      <View style={{width: '27%'}}>
        <View
          style={[{flex: 1, marginLeft: Platform.OS === 'android' ? '10%' : '5%', marginRight: '10%', marginTop: '10%'}]}>
          <Text
            style={[
              {
                fontSize: FontSize.large,
                color: Colors.WHITE,
                fontFamily: FontFamily.bold,
                marginBottom: '5%',
                paddingHorizontal: ms(10),
                marginLeft: Platform.OS === 'android' ? ms(5) : ms(2),
              },
            ]}>
            Settings
          </Text>
          <FlatList
            data={pages}
            renderItem={({item, index}) => renderSettingItem(item, index)}
            removeClippedSubviews={false}
          />
        </View>
      </View>

      <View
        style={{
          backgroundColor: Colors.SEPARATOR_SETTING_PAGE,
          width: 3,
          marginTop: '2%',
          height: '60%',
        }}
      />

      <View style={{width: '73%'}}>
        <SettingPageComponent page={page} />
      </View>
    </SafeAreaView>
</code>```

I don't know what I did wrong. I'd really appreciate some help. Thanks !

Body:
I'm trying to show a flatList in tvOS and when the flatlist is rendered it shows unwanted space at the top of the rendered items inside the flatlist. This issue is not happening in Android TV or Fire TV.

My code :

<SafeAreaView
      style={{
        flex: 1,
        backgroundColor: Colors.APP_BACKGROUND,
        flexDirection: 'row',
      }}>
      <View style={{width: '27%'}}>
        <View
          style={[{flex: 1, marginLeft: Platform.OS === 'android' ? '10%' : '5%', marginRight: '10%', marginTop: '10%'}]}>
          <Text
            style={[
              {
                fontSize: FontSize.large,
                color: Colors.WHITE,
                fontFamily: FontFamily.bold,
                marginBottom: '5%',
                paddingHorizontal: ms(10),
                marginLeft: Platform.OS === 'android' ? ms(5) : ms(2),
              },
            ]}>
            Settings
          </Text>
          <FlatList
            data={pages}
            renderItem={({item, index}) => renderSettingItem(item, index)}
            removeClippedSubviews={false}
          />
        </View>
      </View>

      <View
        style={{
          backgroundColor: Colors.SEPARATOR_SETTING_PAGE,
          width: 3,
          marginTop: '2%',
          height: '60%',
        }}
      />

      <View style={{width: '73%'}}>
        <SettingPageComponent page={page} />
      </View>
    </SafeAreaView>

I don't know what I did wrong. I'd really appreciate some help. Thanks !


问:
Countdown game in Python using stacks
Recently, our teacher told us to do an illustration.

I figured that Brute-forcing would be the fastest and easiest way to solve the problem. Furthermore, I wanted to find a solution by using **stacks **in Python. It's basically just a simple brute-force algorithm with exponential complexity. Here's my progress so far:

```<code>import random

add = lambda a,b: a+b
sub = lambda a,b: a-b
mul = lambda a,b: a*b
div = lambda a,b: a/b if a % b == 0 else 0/0

operations = [ (add, '+'),
               (sub, '-'),
               (mul, '*'),
               (div, '/')]

def OneFromTheTop():
    return [25, 50, 75][random.randint(0,2)]

def OneOfTheOthers():
    return random.randint(1,10)

def sumOfStack(stack):
    try:
        total = 0
        lastOper = add
        for item in stack:
            if type(item) is int:
                total = lastOper(total, item)
            else:
                lastOper = item[0]

        return total
    except:
        return 0

def ReprStack(stack):
    reps = [ str(item) if type(item) is int else item[1] for item in stack ]
    return ''.join(reps)

def Solve(target, numbers):

    def Recurse(stack, nums):
        for n in range(len(nums)):
            stack.append( nums[n] )

            remaining = nums[:n] + nums[n+1:]

            if sumOfStack(stack) == target:
                print(ReprStack(stack))

            if len(remaining) > 0:
                for op in operations:
                    stack.append(op)
                    stack = Recurse(stack, remaining)
                    stack = stack[:-1]

            stack = stack[:-1]

        return stack

    Recurse([], numbers)

target = 13

numbers = [4, 4, 3]

print("Target: {0} using {1}".format(target, numbers))

Solve(target, numbers)
</code>```

Now I was wondering, how to write an algorithm that follows the multiplication / division before addition / subtraction rule.

Example:
Let's say my target number is 941 and I would like to use the following numbers to get to 941:
[50, 100, 7, 6, 1, 10]
A possible solution which does not follow the addressed rule would be 50 + 100 + 7 * 6 - 1 = 941

I would really appreciate any ideas regarding my issue:)

Title: Countdown game in Python using stacks

Body:
Recently, our teacher told us to do an illustration.

I figured that Brute-forcing would be the fastest and easiest way to solve the problem. Furthermore, I wanted to find a solution by using **stacks **in Python. It's basically just a simple brute-force algorithm with exponential complexity. Here's my progress so far:

import random

add = lambda a,b: a+b
sub = lambda a,b: a-b
mul = lambda a,b: a*b
div = lambda a,b: a/b if a % b == 0 else 0/0

operations = [ (add, '+'),
               (sub, '-'),
               (mul, '*'),
               (div, '/')]

def OneFromTheTop():
    return [25, 50, 75][random.randint(0,2)]

def OneOfTheOthers():
    return random.randint(1,10)

def sumOfStack(stack):
    try:
        total = 0
        lastOper = add
        for item in stack:
            if type(item) is int:
                total = lastOper(total, item)
            else:
                lastOper = item[0]

        return total
    except:
        return 0

def ReprStack(stack):
    reps = [ str(item) if type(item) is int else item[1] for item in stack ]
    return ''.join(reps)

def Solve(target, numbers):

    def Recurse(stack, nums):
        for n in range(len(nums)):
            stack.append( nums[n] )

            remaining = nums[:n] + nums[n+1:]

            if sumOfStack(stack) == target:
                print(ReprStack(stack))

            if len(remaining) > 0:
                for op in operations:
                    stack.append(op)
                    stack = Recurse(stack, remaining)
                    stack = stack[:-1]

            stack = stack[:-1]

        return stack

    Recurse([], numbers)

target = 13

numbers = [4, 4, 3]

print("Target: {0} using {1}".format(target, numbers))

Solve(target, numbers)

Now I was wondering, how to write an algorithm that follows the multiplication / division before addition / subtraction rule.

Example:
Let's say my target number is 941 and I would like to use the following numbers to get to 941:
[50, 100, 7, 6, 1, 10]
A possible solution which does not follow the addressed rule would be 50 + 100 + 7 * 6 - 1 = 941

I would really appreciate any ideas regarding my issue:)


问:
Conditionally fire trigger to invoke lambda in AWS?
I have a S3 bucket that when it receives a json file it fires a trigger to invoke a lambda that processes the file.  I don't not want to invoke the lambda however for every file.  Only certain files where an key - value within the json is of a certain value.  For example, if the json contains "process":True then invoke the lambda but if "process": False then do not invoke the lambda.  There are millions of files sent daily so I do not want to add this logic to the lambda itself or it will be invoked unnecessarily many times.</p>