问:
D3 Sankey diagram links do not cover the entire node height
I am using D3.js to produce Sankey diagrams, and I'm not satisfied with the resulting connection between nodes, particularly when the total input of a node is different from its total output.

As an example:

// set the dimensions and margins of the data
var margin = { top: 10, right: 10, bottom: 10, left: 10 },
    width = 300 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// Set the sankey diagram properties
var sankey = d3.sankey()
    .nodeWidth(10)
    .nodePadding(10)
    .size([width, height]);

data = {
    "nodes": [
        { "node": 0, "name": "A" },
        { "node": 1, "name": "B" },
        { "node": 2, "name": "C" }
    ],
    "links": [
        { "source": 0, "target": 1, "value": 2 },
        { "source": 1, "target": 2, "value": 1 }
    ]
}

// Constructs a new Sankey generator with the default settings.
sankey
    .nodes(data.nodes)
    .links(data.links)
    .layout(1);

// add in the links
svg.append("g")
    .selectAll(".link")
    .data(data.links)
    .enter()
    .append("path")
    .attr("class", "link")
    .attr("d", sankey.link())
    .style("stroke-width", function (d) { return Math.max(1, d.dy); })

// add in the nodes
var node = svg.append("g")
    .selectAll(".node")
    .data(data.nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })

// add the rectangles for the nodes
node.append("rect")
    .attr("height", function (d) { return d.dy; })
    .attr("width", sankey.nodeWidth())

// add in the title for the nodes
node.append("text")
    .attr("x", -6)
    .attr("y", function (d) { return d.dy / 2; })
    .attr("dy", ".35em")
    .attr("text-anchor", "end")
    .attr("transform", null)
    .text(function (d) { return d.name; })
    .filter(function (d) { return d.x < width / 2; })
    .attr("x", 6 + sankey.nodeWidth())
    .attr("text-anchor", "start")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <style>
        .link {
            fill: none;
            stroke: #000;
            stroke-opacity: .2;
        }
    </style>

    <div id="graph"></div>

    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/sankey.js"></script>
    <script src="test.js"></script>
</body></code>```

This produces:

But without chaning the input data I would like:

Meaning the node size is determined by the link value, but the link size matches both the input and the output nodes.

Body:
I am using D3.js to produce Sankey diagrams, and I'm not satisfied with the resulting connection between nodes, particularly when the total input of a node is different from its total output.

As an example:

// set the dimensions and margins of the data
var margin = { top: 10, right: 10, bottom: 10, left: 10 },
    width = 300 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// Set the sankey diagram properties
var sankey = d3.sankey()
    .nodeWidth(10)
    .nodePadding(10)
    .size([width, height]);

data = {
    "nodes": [
        { "node": 0, "name": "A" },
        { "node": 1, "name": "B" },
        { "node": 2, "name": "C" }
    ],
    "links": [
        { "source": 0, "target": 1, "value": 2 },
        { "source": 1, "target": 2, "value": 1 }
    ]
}

// Constructs a new Sankey generator with the default settings.
sankey
    .nodes(data.nodes)
    .links(data.links)
    .layout(1);

// add in the links
svg.append("g")
    .selectAll(".link")
    .data(data.links)
    .enter()
    .append("path")
    .attr("class", "link")
    .attr("d", sankey.link())
    .style("stroke-width", function (d) { return Math.max(1, d.dy); })

// add in the nodes
var node = svg.append("g")
    .selectAll(".node")
    .data(data.nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })

// add the rectangles for the nodes
node.append("rect")
    .attr("height", function (d) { return d.dy; })
    .attr("width", sankey.nodeWidth())

// add in the title for the nodes
node.append("text")
    .attr("x", -6)
    .attr("y", function (d) { return d.dy / 2; })
    .attr("dy", ".35em")
    .attr("text-anchor", "end")
    .attr("transform", null)
    .text(function (d) { return d.name; })
    .filter(function (d) { return d.x < width / 2; })
    .attr("x", 6 + sankey.nodeWidth())
    .attr("text-anchor", "start")

This produces:

But without chaning the input data I would like:

Meaning the node size is determined by the link value, but the link size matches both the input and the output nodes.


来源: stackexchange

问:
How to add a state and a list of links displayed in react js and storybook?
I need to have the accordion component that will change over a state when user clicks on the icon.
When user clicks on the icon, the icon and color of the title should get changed and list of links should display.
So far I managed to add onClick option to the component but what will be the best approach to achieve the result of a list displaying over a click?
How to make the icon change over click and display a list with storybook?
Could you please kindly give some advise?
Any help would be appreciated.

I already added two options for the icon, so I think I can add somehow a state to it and make it display on storybook, but not really sure how :(

Here is the component:

```<code>import { string, oneOf, func, bool } from "prop-types"

import Icon, { icons } from "design-system/components/icon"

import * as Styled from "./Button.styled"

const Button = ({
  href,
  text,
  iconStart,
  iconEnd,
  variant,
  color,
  size,
  active,
  onClick,
}) => (
  <Styled.Component
    as={href ? `a` : `button`}
    variant={variant}
    color={color}
    size={size}
    href={href}
    onClick={onClick}
  >
    {iconStart && (
      <Styled.Icon>
        <Icon name={iconStart} size={size} />
      </Styled.Icon>
    )}
    <Styled.Text variant={variant} color={color} active={active}>
      {text}
    </Styled.Text>

    {iconEnd && (
      <Styled.Icon>
        <Icon name={iconEnd} size={size} />
      </Styled.Icon>
    )}
  </Styled.Component>
)

Button.propTypes = {
  text: string.isRequired,
  href: string,
  iconStart: oneOf(Object.keys(icons)),
  iconEnd: oneOf(Object.keys(icons)),
  variant: oneOf(["fill", "border", "text", "textLine"]),
  color: oneOf(["primary", "black", "white"]),
  size: oneOf(["small", "medium", "large"]),
  active: bool,
  onClick: func,
}

Button.defaultProps = {
  href: null,
  iconStart: null,
  iconEnd: null,
  variant: "fill",
  color: "primary",
  size: "medium",
  active: null,
  onClick: null,
}

export default Button
</code>```

Here are the styles:

```<code>import styled from "@emotion/styled"
import { css } from "@emotion/react"
import theme from "design-system/theme"

const sizes = {
  small: {
    typography: theme.typography.desktop.bodySmall,
    padding: "8px 32px",
  },
  medium: {
    typography: theme.typography.desktop.h5,
    padding: "10px 40px",
  },
  large: {
    typography: theme.typography.desktop.h4,
    padding: "12px 48px",
  },
}

const colors = {
  primary: {
    mainColor: theme.colors.primary[500],
    filledText: theme.colors.neutrals[100],
  },
  black: {
    mainColor: theme.colors.grey[600],
    filledText: theme.colors.neutrals[100],
  },
  white: {
    mainColor: theme.colors.neutrals[100],
    filledText: theme.colors.primary[300],
  },
}
export const Component = styled.a`
text-align: center;
  border-radius: 10px;
  padding: 19px;
  position: relative;
  color: ${({ theme }) => theme.colors.grey[600]};
  background-color: ${({ theme }) => theme.colors.complementary[100]};
`

export const Text = styled.span`
  ${({ variant }) =>
    variant === "textLine" &&
    css`
      text-decoration: underline;
    `}

  ${({ active, variant, color }) =>
    active &&
    variant === "text" &&
    css`
      border-bottom: 2px solid ${colors[color].mainColor};
    `}
`

export const Icon = styled.span`
  display: inline-flex;
  align-items: center;
  justify-content: center;
`
</code>```

and storybook:

```<code>import { Meta, Canvas, Story, ArgsTable } from "@storybook/addon-docs"

import Button from "design-system/components/button"
import Icon from "design-system/components/icon"

<Meta title="Components/Button" component={Button} />

# Button

<Canvas>

  <Story
    name="Overview - button icon end"
    args={{
      text: "O nas",
      iconEnd: "arrowDown",
      variant: "fill",
      size: "medium",
    }}
  >
    {Template.bind()}
  </Story>

</Canvas>

<ArgsTable />

export const Template = (args) => <Button {...args} />

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to have the accordion component that will change over a state when user clicks on the icon.
When user clicks on the icon, the icon and color of the title should get changed and list of links should display.
So far I managed to add onClick option to the component but what will be the best approach to achieve the result of a list displaying over a click?
How to make the icon change over click and display a list with storybook?
Could you please kindly give some advise?
Any help would be appreciated.

I already added two options for the icon, so I think I can add somehow a state to it and make it display on storybook, but not really sure how :(

Here is the component:

import { string, oneOf, func, bool } from "prop-types"

import Icon, { icons } from "design-system/components/icon"

import * as Styled from "./Button.styled"

const Button = ({
  href,
  text,
  iconStart,
  iconEnd,
  variant,
  color,
  size,
  active,
  onClick,
}) => (

    )}

    {iconEnd && (

    )}
  </Styled.Component>
)

Button.propTypes = {
  text: string.isRequired,
  href: string,
  iconStart: oneOf(Object.keys(icons)),
  iconEnd: oneOf(Object.keys(icons)),
  variant: oneOf(["fill", "border", "text", "textLine"]),
  color: oneOf(["primary", "black", "white"]),
  size: oneOf(["small", "medium", "large"]),
  active: bool,
  onClick: func,
}

Button.defaultProps = {
  href: null,
  iconStart: null,
  iconEnd: null,
  variant: "fill",
  color: "primary",
  size: "medium",
  active: null,
  onClick: null,
}

export default Button

Here are the styles:

import styled from "@emotion/styled"
import { css } from "@emotion/react"
import theme from "design-system/theme"

const sizes = {
  small: {
    typography: theme.typography.desktop.bodySmall,
    padding: "8px 32px",
  },
  medium: {
    typography: theme.typography.desktop.h5,
    padding: "10px 40px",
  },
  large: {
    typography: theme.typography.desktop.h4,
    padding: "12px 48px",
  },
}

const colors = {
  primary: {
    mainColor: theme.colors.primary[500],
    filledText: theme.colors.neutrals[100],
  },
  black: {
    mainColor: theme.colors.grey[600],
    filledText: theme.colors.neutrals[100],
  },
  white: {
    mainColor: theme.colors.neutrals[100],
    filledText: theme.colors.primary[300],
  },
}
export const Component = styled.a`
text-align: center;
  border-radius: 10px;
  padding: 19px;
  position: relative;
  color: ${({ theme }) => theme.colors.grey[600]};
  background-color: ${({ theme }) => theme.colors.complementary[100]};
`

export const Text = styled.span`
  ${({ variant }) =>
    variant === "textLine" &&
    css`
      text-decoration: underline;
    `}

  ${({ active, variant, color }) =>
    active &&
    variant === "text" &&
    css`
      border-bottom: 2px solid ${colors[color].mainColor};
    `}
`

export const Icon = styled.span`
  display: inline-flex;
  align-items: center;
  justify-content: center;
`

and storybook:

import { Meta, Canvas, Story, ArgsTable } from "@storybook/addon-docs"

import Button from "design-system/components/button"
import Icon from "design-system/components/icon"

<Meta title="Components/Button" component={Button} />

# Button

<Canvas>

  <Story
    name="Overview - button icon end"
    args={{
      text: "O nas",
      iconEnd: "arrowDown",
      variant: "fill",
      size: "medium",
    }}
  >
    {Template.bind()}
  </Story>

</Canvas>

<ArgsTable />

export const Template = (args) => <Button {...args} />


问:
Improving ExpansionPanelList performance for big item count in flutter?
ExpansionPanelList seems not to have a on demand builder method for flutter to call when new items need to be created. This leads to the creation of all items in the ExpansionPanelList everytime it needs to be rebuilt.

In my particular scenario, I can have around 10k items and it turns pretty slow.

This is how I am building and filling the ExpansionPanelList:

```<code>List<ExpansionPanel> widgets = state.games.map<ExpansionPanel>((VMUserGame game) {
  var gameAddedStatus = VMGameTools.getGameStatus(game);

  return ExpansionPanel(
    canTapOnHeader: true,
    headerBuilder: (BuildContext context, bool isExpanded) {
      return ListTile(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: Text(game.userGame.name, style: Theme.of(context).textTheme.headline5, textAlign: TextAlign.left)),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 24, 0),
                  child: game.userGame.isExternal ? null : Text(StringTools.bytesToStorageUnity(game.userGame.gameSize)),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 24, 0),
                  child: _getExeCurrentStateIcon(gameAddedStatus),
                ),
                IconButton(
                  onPressed: () {
                    _nsgpBloc.renameGame(context, game);
                  },
                  icon: Icon(Icons.edit),
                  tooltip: tr("rename_game"),
                ),
                IconButton(
                  onPressed: () {
                    _nsgpBloc.deleteGame(context, game);
                  },
                  icon: Icon(Icons.delete),
                  tooltip: tr("delete"),
                ),
              ],
            ),
            if(game.foldingState) Text("${game.userGame.path}",textAlign: TextAlign.left, style: TextStyle(color:themeExtension.gameCardHeaderPath, fontSize: 13),)
          ],
        ),
      );
    },
    body: _buildGameTile(context, themeExtension,  game.userGame, state.availableProntonNames),
    isExpanded: game.foldingState,
  );
}).toList();

return Form(
  key: _formKey,
  child: ExpansionPanelList(
      expansionCallback: (int index, bool isExpanded) {
        _nsgpBloc.swapExpansionStateForItem(index);
      },
      children: widgets,),
);
</code>```

Body:
ExpansionPanelList seems not to have a on demand builder method for flutter to call when new items need to be created. This leads to the creation of all items in the ExpansionPanelList everytime it needs to be rebuilt.

In my particular scenario, I can have around 10k items and it turns pretty slow.

This is how I am building and filling the ExpansionPanelList:

List<ExpansionPanel> widgets = state.games.map<ExpansionPanel>((VMUserGame game) {
  var gameAddedStatus = VMGameTools.getGameStatus(game);

  return ExpansionPanel(
    canTapOnHeader: true,
    headerBuilder: (BuildContext context, bool isExpanded) {
      return ListTile(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: Text(game.userGame.name, style: Theme.of(context).textTheme.headline5, textAlign: TextAlign.left)),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 24, 0),
                  child: game.userGame.isExternal ? null : Text(StringTools.bytesToStorageUnity(game.userGame.gameSize)),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 24, 0),
                  child: _getExeCurrentStateIcon(gameAddedStatus),
                ),
                IconButton(
                  onPressed: () {
                    _nsgpBloc.renameGame(context, game);
                  },
                  icon: Icon(Icons.edit),
                  tooltip: tr("rename_game"),
                ),
                IconButton(
                  onPressed: () {
                    _nsgpBloc.deleteGame(context, game);
                  },
                  icon: Icon(Icons.delete),
                  tooltip: tr("delete"),
                ),
              ],
            ),
            if(game.foldingState) Text("${game.userGame.path}",textAlign: TextAlign.left, style: TextStyle(color:themeExtension.gameCardHeaderPath, fontSize: 13),)
          ],
        ),
      );
    },
    body: _buildGameTile(context, themeExtension,  game.userGame, state.availableProntonNames),
    isExpanded: game.foldingState,
  );
}).toList();

return Form(
  key: _formKey,
  child: ExpansionPanelList(
      expansionCallback: (int index, bool isExpanded) {
        _nsgpBloc.swapExpansionStateForItem(index);
      },
      children: widgets,),
);


问:
How many days files in a github comment last?
How long do files hosted on GitHub's servers remain available after they are uploaded through the drag-and-drop feature in a comment?

Is there an expiration date for these files,

or are they stored indefinitely?


问:
Facebook-scraper not giving exact count of likes and comments for video posted
I wanted to scrape likes and comments of the posts from the Facebook. I used facebook_scraper package for retrieving the information. For the post which contains images, i am able to retrieve the exact number of likes and comments. But for the videos, the numbers are very much different. Even though the likes are around 130 in actual post, it is stored as 851105005506560112120226810.

The code i used for the scrape the post is given below:

```<code>from facebook_scraper import get_posts

p=0
for post in get_posts("ISKCONBangaloreTemple",pages=2):
    print(p)
    try:
        posttext.append(post['text'][:100])
        postid.append(post['post_id'])
        likes.append(post['likes'])
        time.append(post['time'])
        comments.append(post['comments'])
        shares.append(post['shares'])
        post_url.append(post['post_url'])
        imagelink.append(post['image'])
        videolink.append(post['video'])
        live.append(post['is_live'])
        reactions.append(post['reactions'])
        print(post['reactions'])
    except:
        pass

   p=p+1
</code>```

The sample of actual numbers on the post and what is retrieved is shown below:

Likes Actual
Likes Obtained

572
572

105
851105005506560112120226810

83
6560112120226810

6810
6810

Body:
I wanted to scrape likes and comments of the posts from the Facebook. I used facebook_scraper package for retrieving the information. For the post which contains images, i am able to retrieve the exact number of likes and comments. But for the videos, the numbers are very much different. Even though the likes are around 130 in actual post, it is stored as 851105005506560112120226810.

The code i used for the scrape the post is given below:

from facebook_scraper import get_posts

p=0
for post in get_posts("ISKCONBangaloreTemple",pages=2):
    print(p)
    try:
        posttext.append(post['text'][:100])
        postid.append(post['post_id'])
        likes.append(post['likes'])
        time.append(post['time'])
        comments.append(post['comments'])
        shares.append(post['shares'])
        post_url.append(post['post_url'])
        imagelink.append(post['image'])
        videolink.append(post['video'])
        live.append(post['is_live'])
        reactions.append(post['reactions'])
        print(post['reactions'])
    except:
        pass

   p=p+1

The sample of actual numbers on the post and what is retrieved is shown below:

Likes Actual
Likes Obtained

572
572

105
851105005506560112120226810

83
6560112120226810

6810
6810


问:
POI Excel chart - set property to - 'Don't move or size with cells'
I have an excel template which has the table and charts already setup, just need to add data. There is a collapsible table (using group row) which has a variable number of rows. Beneath this table are two bar charts at the same vertical level.

After filling the table data the two charts are shifted down so when the table is expanded there is no overlapping between the table and charts.

To enable this the chart properties are set to 'Move but dont size with cells'. This works but when any columns or rows are resized the two charts start to move. This can be fixed by using the 'Dont move or size with cells' option.

I have tried the below code but am getting NPE with the following code. The getGraphicFrame() returns null.

dbSheet.getDrawingPatriarch().getCharts().get(0).getGraphicFrame().getAnchor().setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);

Can someone advise how this can be done? Thanks.


问:
Setup Google Tag Manager in Angular application
When we are trying to implement GTM (Google Tag Manager) code in our Angular Universal application, we are facing following challenges:

The  tag changes include some JQuery parameters/fields which are not working in Angular and giving us errors and those errors are running in infinite loop. The error is related to $ not defined. As per the requirements we are not allowed to use JQuery library.
In the  tag changes  throwing us error related not supporting items in .
please help me out

Getting errors like this ->
(494)Uncaught ReferenceError: $ is not defined
VM725:1 Uncaught ReferenceError: jQuery is not defined

We tried

window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'MEASUREMENT-ID');

but not working as expected.


问:
How can I interact with shell responses with .NET Core console app?
I am writing a CLI app to hide some of the details of running commands in the shell/terminal.

With the code below I can execute a single command ssh, for example:

var result = RunCommand("ssh", "100.100.109.86");

static string RunCommand(string command, string args)
{
    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();

    var output = process.StandardOutput.ReadToEnd();
    var error = process.StandardError.ReadToEnd();

    return string.IsNullOrEmpty(error) ? output : error;
}
```

My question is how can implement a loop so that I can output the result of the command to the user and enable them to execute another command (or more)?

For example, the response to the above ssh command might as the to ask them if they are sure they want to connect inviting them to respond with (yes/no/[fingerprint])

Body:
I am writing a CLI app to hide some of the details of running commands in the shell/terminal.

With the code below I can execute a single command ssh, for example:

var result = RunCommand("ssh", "100.100.109.86");

static string RunCommand(string command, string args)
{
    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();

    var output = process.StandardOutput.ReadToEnd();
    var error = process.StandardError.ReadToEnd();

    return string.IsNullOrEmpty(error) ? output : error;
}

My question is how can implement a loop so that I can output the result of the command to the user and enable them to execute another command (or more)?

For example, the response to the above ssh command might as the to ask them if they are sure they want to connect inviting them to respond with (yes/no/[fingerprint])


问:
CKEditor: How to set max-width for image upload?

I want to set a maximum width value that a user can define while using CKEditor.

I can't find any specific config in CKEditor that allows me to implement this functionality.


问:
TensorFlow unable to set large precision of tensors for 12 decimals with float 64
Hello i am using TensorFlow i have i try to load float 64 tensor value but when i load to i loose decimals any help?

```<code> tenosr = tf.constant([57.695030261422, 11.911734826863], dtype=tf.float64)
</code>```

Body:
Hello i am using TensorFlow i have i try to load float 64 tensor value but when i load to i loose decimals any help?

 tenosr = tf.constant([57.695030261422, 11.911734826863], dtype=tf.float64)


问:
Creating an array from formula results in google script
I am using Alphavantage add-on on GoogleSheet to retrieve stocks' information.
The API has a 5 calls/minute and 500 calls/day limit.

I am testing it out on a list of 6.000 stocks just to begin with.
And I want to build a script that once a month retrieves a series of data (EBITDA, PE, ...) from the AVGetCompanyOverview formula.

When you insert this formula in a cell, the formula returns a 2 columns table with strings on the left and corresponding values on the right (i.e.: PE | 19,5; EBITDA | 3000000; ...).

This is the code I wrote:

```<code>function MarketDataMonthly() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
const lastrow = sheet.getLastRow();
var symbol = sheet.getRange(2,2,lastrow).getValues();
var formularange = sheet.getRange(2,7,lastrow);

var ebitda = sheet.getRange(2,9,lastrow);
var pe = sheet.getRange(2,10,lastrow);
var book = sheet.getRange(2,11,lastrow);
var dps = sheet.getRange(2,12,lastrow);
var divyield = sheet.getRange(2,13,lastrow);
var eps = sheet.getRange(2,14,lastrow);
var profit = sheet.getRange(2,15,lastrow);
var roa = sheet.getRange(2,16,lastrow);
var roe = sheet.getRange(2,17,lastrow);
var p2b = sheet.getRange(2,18,lastrow);
var ev2r = sheet.getRange(2,19,lastrow);
var ev2ebitda = sheet.getRange(2,20,lastrow);
var beta = sheet.getRange(2,21,lastrow);

for (var i=1;i<=500;i++){
var formula = formularange.getCell(i, 1)
formula.setValue('=AVGetCompanyOverview('+'"'+symbol[i-1]+'"'+')') // Question 1 and 4
formula.getValue() // Question 2

Utilities.sleep(20000)

var ebitdavalue = sheet.getRange(i+14,8).getValue()
ebitda.getCell(i, 1).setValue(ebitdavalue)
var pevalue = sheet.getRange(i+15,8).getValue()
pe.getCell(i, 1).setValue(pevalue)
var bookvalue = sheet.getRange(i+17,8).getValue()
book.getCell(i, 1).setValue(bookvalue)
var dpsvalue = sheet.getRange(i+18,8).getValue()
dps.getCell(i, 1).setValue(dpsvalue)
var divyieldvalue = sheet.getRange(i+19,8).getValue()
divyield.getCell(i, 1).setValue(divyieldvalue)
var epsvalue = sheet.getRange(i+20,8).getValue()
eps.getCell(i, 1).setValue(epsvalue)
var profitvalue = sheet.getRange(i+22,8).getValue()
profit.getCell(i, 1).setValue(profitvalue)
var roavalue = sheet.getRange(i+24,8).getValue()
roa.getCell(i, 1).setValue(roavalue)
var roevalue = sheet.getRange(i+25,8).getValue()
roe.getCell(i, 1).setValue(roevalue)
var p2bvalue = sheet.getRange(i+35,8).getValue()
p2b.getCell(i, 1).setValue(p2bvalue)
var ev2rvalue = sheet.getRange(i+36,8).getValue()
ev2r.getCell(i, 1).setValue(ev2rvalue)
var ev2ebitdavalue = sheet.getRange(i+37,8).getValue()
ev2ebitda.getCell(i, 1).setValue(ev2ebitdavalue)
var betavalue = sheet.getRange(i+38,8).getValue()
beta.getCell(i, 1).setValue(beta)

formula.getCell(i,1).setValue("")
}
}
</code>```

This script works, but I can't figure out this: instead of writing the formula in an actual cell, is it possible to transform it into an Array? So I can reference it instead of browsing through cells.

Thanks!

Body:
I am using Alphavantage add-on on GoogleSheet to retrieve stocks' information.
The API has a 5 calls/minute and 500 calls/day limit.

I am testing it out on a list of 6.000 stocks just to begin with.
And I want to build a script that once a month retrieves a series of data (EBITDA, PE, ...) from the AVGetCompanyOverview formula.

When you insert this formula in a cell, the formula returns a 2 columns table with strings on the left and corresponding values on the right (i.e.: PE | 19,5; EBITDA | 3000000; ...).

This is the code I wrote:

function MarketDataMonthly() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
const lastrow = sheet.getLastRow();
var symbol = sheet.getRange(2,2,lastrow).getValues();
var formularange = sheet.getRange(2,7,lastrow);

var ebitda = sheet.getRange(2,9,lastrow);
var pe = sheet.getRange(2,10,lastrow);
var book = sheet.getRange(2,11,lastrow);
var dps = sheet.getRange(2,12,lastrow);
var divyield = sheet.getRange(2,13,lastrow);
var eps = sheet.getRange(2,14,lastrow);
var profit = sheet.getRange(2,15,lastrow);
var roa = sheet.getRange(2,16,lastrow);
var roe = sheet.getRange(2,17,lastrow);
var p2b = sheet.getRange(2,18,lastrow);
var ev2r = sheet.getRange(2,19,lastrow);
var ev2ebitda = sheet.getRange(2,20,lastrow);
var beta = sheet.getRange(2,21,lastrow);

for (var i=1;i<=500;i++){
var formula = formularange.getCell(i, 1)
formula.setValue('=AVGetCompanyOverview('+'"'+symbol[i-1]+'"'+')') // Question 1 and 4
formula.getValue() // Question 2

Utilities.sleep(20000)

var ebitdavalue = sheet.getRange(i+14,8).getValue()
ebitda.getCell(i, 1).setValue(ebitdavalue)
var pevalue = sheet.getRange(i+15,8).getValue()
pe.getCell(i, 1).setValue(pevalue)
var bookvalue = sheet.getRange(i+17,8).getValue()
book.getCell(i, 1).setValue(bookvalue)
var dpsvalue = sheet.getRange(i+18,8).getValue()
dps.getCell(i, 1).setValue(dpsvalue)
var divyieldvalue = sheet.getRange(i+19,8).getValue()
divyield.getCell(i, 1).setValue(divyieldvalue)
var epsvalue = sheet.getRange(i+20,8).getValue()
eps.getCell(i, 1).setValue(epsvalue)
var profitvalue = sheet.getRange(i+22,8).getValue()
profit.getCell(i, 1).setValue(profitvalue)
var roavalue = sheet.getRange(i+24,8).getValue()
roa.getCell(i, 1).setValue(roavalue)
var roevalue = sheet.getRange(i+25,8).getValue()
roe.getCell(i, 1).setValue(roevalue)
var p2bvalue = sheet.getRange(i+35,8).getValue()
p2b.getCell(i, 1).setValue(p2bvalue)
var ev2rvalue = sheet.getRange(i+36,8).getValue()
ev2r.getCell(i, 1).setValue(ev2rvalue)
var ev2ebitdavalue = sheet.getRange(i+37,8).getValue()
ev2ebitda.getCell(i, 1).setValue(ev2ebitdavalue)
var betavalue = sheet.getRange(i+38,8).getValue()
beta.getCell(i, 1).setValue(beta)

formula.getCell(i,1).setValue("")
}
}

This script works, but I can't figure out this: instead of writing the formula in an actual cell, is it possible to transform it into an Array? So I can reference it instead of browsing through cells.

Thanks!


问:
How to get all the zeroes for the derivative of a function using DualNumbers
The original problem I had was, given an interval, [a, b] and a function f(x) and its derivative continuous over that interval, find the minimum and maximum of the derivative over that integral, (and since it's continuous, every single value of the derivative will be within that interval), and I'd have to do this using DualNumber.

So I implemented DualNumbers in python and I was able to operator overload in order to achieve the functioning of the class, and I also implemented the function which merely calculated the derivative of the function at a specific point.

I wasn't sure how would I find the minimum and maximum of the derivative since it would include real numbers as well, and hence I set out to find the zero's of the derivative (do note there might be multiple 0's in the interval).

I wasn't sure how I would go about that, and hence I'm here asking this question.

Here is my DualNumbers class implementation:

class DualNumbers:
    def __init__(self, coef = 0, epsilon = 0) -> None:
        self.coef = coef
        self.epsilon = epsilon

    def __add__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef + __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef + __o.coef, self.epsilon + __o.epsilon)

    def __radd__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef + __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef + __o.coef, self.epsilon + __o.epsilon)

    def __sub__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef - __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef - __o.coef, self.epsilon - __o.epsilon)

    def __rsub__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(__o - self.coef, -1 * self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(__o - self.coef, -1 * self.epsilon)

    def __eq__(self, __o: object) -> bool:
        if type(__o) != DualNumbers:
            return False

        return self.coef == __o.coef and self.epsilon == __o.epsilon

    def __ne__(self, __o: object) -> bool:
        return not self.__eq__(__o)

    def __mul__(self, __o) -> float:
        if type(__o) != DualNumbers:
            if type(__o) == int or type(__o) == float:
                return DualNumbers(self.coef * __o, self.epsilon * __o)
            else:
                raise TypeError

        return DualNumbers(self.coef * __o.coef, (self.epsilon * __o.coef) + (self.coef * __o.epsilon))

    def __rmul__(self, __o) -> float:
        if type(__o) != DualNumbers:
            if type(__o) == int or type(__o) == float:
                return DualNumbers(self.coef * __o, self.epsilon * __o)
            else:
                raise TypeError

        return DualNumbers(self.coef * __o.coef, (self.epsilon * __o.coef) + (self.coef * __o.epsilon))

    def __div__(self, __o: object) -> float:
        if type(__o) != DualNumbers:
            return False

        try:
            return DualNumbers(self.coef / __o.coef, ((self.epsilon * __o.coef) - (__o.epsilon * self.coef)) / (__o.coef ** 2))
        except:
            raise "c is 0, division with 0"

    def __str__(self) -> str:
        return (f"{self.coef} + {self.epsilon}ε")

    def __repr__(self) -> str:
        return (f"{self.coef} + {self.epsilon}ε")

    def __pow__(self, other):
        x = DualNumbers(self.coef, self.epsilon)
        a = x
        for _ in range(other - 1):
            x = x * a
        return x
```
<p>and my derivative computing function is:</p>
<pre class="lang-py prettyprint-override"><code>def compute_derivative(f, x):
    x_dn = DualNumbers(x, 1)

    y_dn = f(x_dn)

    derivative = y_dn.epsilon

    return derivative
</code>```

Is there a better way to do this, or worst case could I use the second derivative (not sure how I'd go about calculating that) to get the 0's in some way (Newton's method or something)?

Body:
The original problem I had was, given an interval, [a, b] and a function f(x) and its derivative continuous over that interval, find the minimum and maximum of the derivative over that integral, (and since it's continuous, every single value of the derivative will be within that interval), and I'd have to do this using DualNumber.

So I implemented DualNumbers in python and I was able to operator overload in order to achieve the functioning of the class, and I also implemented the function which merely calculated the derivative of the function at a specific point.

I wasn't sure how would I find the minimum and maximum of the derivative since it would include real numbers as well, and hence I set out to find the zero's of the derivative (do note there might be multiple 0's in the interval).

I wasn't sure how I would go about that, and hence I'm here asking this question.

Here is my DualNumbers class implementation:

class DualNumbers:
    def __init__(self, coef = 0, epsilon = 0) -> None:
        self.coef = coef
        self.epsilon = epsilon

    def __add__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef + __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef + __o.coef, self.epsilon + __o.epsilon)

    def __radd__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef + __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef + __o.coef, self.epsilon + __o.epsilon)

    def __sub__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(self.coef - __o, self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(self.coef - __o.coef, self.epsilon - __o.epsilon)

    def __rsub__(self, __o):
        if type(__o) != DualNumbers:
            if type(__o) == float or type(__o) == int:
                return DualNumbers(__o - self.coef, -1 * self.epsilon)
            else:
                raise "Incorrect variable type called in add"

        return DualNumbers(__o - self.coef, -1 * self.epsilon)

    def __eq__(self, __o: object) -> bool:
        if type(__o) != DualNumbers:
            return False

        return self.coef == __o.coef and self.epsilon == __o.epsilon

    def __ne__(self, __o: object) -> bool:
        return not self.__eq__(__o)

    def __mul__(self, __o) -> float:
        if type(__o) != DualNumbers:
            if type(__o) == int or type(__o) == float:
                return DualNumbers(self.coef * __o, self.epsilon * __o)
            else:
                raise TypeError

        return DualNumbers(self.coef * __o.coef, (self.epsilon * __o.coef) + (self.coef * __o.epsilon))

    def __rmul__(self, __o) -> float:
        if type(__o) != DualNumbers:
            if type(__o) == int or type(__o) == float:
                return DualNumbers(self.coef * __o, self.epsilon * __o)
            else:
                raise TypeError

        return DualNumbers(self.coef * __o.coef, (self.epsilon * __o.coef) + (self.coef * __o.epsilon))

    def __div__(self, __o: object) -> float:
        if type(__o) != DualNumbers:
            return False

        try:
            return DualNumbers(self.coef / __o.coef, ((self.epsilon * __o.coef) - (__o.epsilon * self.coef)) / (__o.coef ** 2))
        except:
            raise "c is 0, division with 0"

    def __str__(self) -> str:
        return (f"{self.coef} + {self.epsilon}ε")

    def __repr__(self) -> str:
        return (f"{self.coef} + {self.epsilon}ε")

    def __pow__(self, other):
        x = DualNumbers(self.coef, self.epsilon)
        a = x
        for _ in range(other - 1):
            x = x * a
        return x

and my derivative computing function is:

def compute_derivative(f, x):
    x_dn = DualNumbers(x, 1)

    y_dn = f(x_dn)

    derivative = y_dn.epsilon

    return derivative

Is there a better way to do this, or worst case could I use the second derivative (not sure how I'd go about calculating that) to get the 0's in some way (Newton's method or something)?


问:
XML editor with Bootstrap nested collapse
My task is to create a editor of predefined XML where all the parent and child tags are known. I am trying to solve this with the help of bootstrap nested collapse functionality.

In the attached code I can have the value only on last child element in the hierarchy because all the parent item is pointing to the child. Please help me to handle the scenario where parent also have its own value as well . So now both thing should work when I click on parent item I can capture its own value as well as it will open the child structure like XML did.

```<code>                                <a href="#item-1" class="list-group-item" data-toggle="collapse">
                                    <i class="glyphicon glyphicon-chevron-right"></i>Item 1
                                </a>
                                <div class="list-group collapse" id="item-1">

                                    <a href="#item-1-1" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 1.1
                                    </a>
                                    <div class="list-group collapse" id="item-1-1">
                                        <a href="#" class="list-group-item">Item 1.1.1</a>
                                        <a href="#" class="list-group-item">Item 1.1.2</a>
                                        <a href="#" class="list-group-item">Item 1.1.3</a>
                                    </div>

                                    <a href="#item-1-2" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 1.2
                                    </a>
                                    <div class="list-group collapse" id="item-1-2">
                                        <a href="#" class="list-group-item">Item 1.2.1</a>
                                        <a href="#" class="list-group-item">Item 1.2.2</a>
                                        <a href="#" class="list-group-item">Item 1.2.3</a>
                                    </div>

                                    <a href="#item-1-3" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 1.3
                                    </a>
                                    <div class="list-group collapse" id="item-1-3">
                                        <a href="#" class="list-group-item">Item 1.3.1</a>
                                        <a href="#" class="list-group-item">Item 1.3.2</a>
                                        <a href="#" class="list-group-item">Item 1.3.3</a>
                                    </div>

                                </div>

                                <a href="#item-2" class="list-group-item" data-toggle="collapse">
                                    <i class="glyphicon glyphicon-chevron-right"></i>Item 2
                                </a>
                                <div class="list-group collapse" id="item-2">

                                    <a href="#item-2-1" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 2.1
                                    </a>
                                    <div class="list-group collapse" id="item-2-1">
                                        <a href="#" class="list-group-item">Item 2.1.1</a>
                                        <a href="#" class="list-group-item">Item 2.1.2</a>
                                        <a href="#" class="list-group-item">Item 2.1.3</a>
                                    </div>

                                    <a href="#item-2-2" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 2.2
                                    </a>
                                    <div class="list-group collapse" id="item-2-2">
                                        <a href="#" class="list-group-item">Item 2.2.1</a>
                                        <a href="#" class="list-group-item">Item 2.2.2</a>
                                        <a href="#" class="list-group-item">Item 2.2.3</a>
                                    </div>

                                    <a href="#item-2-3" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 2.3
                                    </a>
                                    <div class="list-group collapse" id="item-2-3">
                                        <a href="#" class="list-group-item">Item 2.3.1</a>
                                        <a href="#" class="list-group-item">Item 2.3.2</a>
                                        <a href="#" class="list-group-item">Item 2.3.3</a>
                                    </div>

                                </div>

                                <a href="#item-3" class="list-group-item" data-toggle="collapse">
                                    <i class="glyphicon glyphicon-chevron-right"></i>Item 3
                                </a>
                                <div class="list-group collapse" id="item-3">

                                    <a href="#item-3-1" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 3.1
                                    </a>
                                    <div class="list-group collapse" id="item-3-1">
                                        <a href="#" class="list-group-item">Item 3.1.1</a>
                                        <a href="#" class="list-group-item">Item 3.1.2</a>
                                        <a href="#" class="list-group-item">Item 3.1.3</a>
                                    </div>

                                    <a href="#item-3-2" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 3.2
                                    </a>
                                    <div class="list-group collapse" id="item-3-2">
                                        <a href="#" class="list-group-item">Item 3.2.1</a>
                                        <a href="#" class="list-group-item">Item 3.2.2</a>
                                        <a href="#" class="list-group-item">Item 3.2.3</a>
                                    </div>

                                    <a href="#item-3-3" class="list-group-item" data-toggle="collapse">
                                        <i class="glyphicon glyphicon-chevron-right"></i>Item 3.3
                                    </a>
                                    <div class="list-group collapse" id="item-3-3">
                                        <a href="#detailsDiv1" class="list-group-item">Item 3.3.1</a>
                                        <a href="#detailsDiv2" class="list-group-item">Item 3.3.2</a>
                                        <a href="#detailsDiv3" class="list-group-item">Item 3.3.3</a>
                                    </div>

                                </div>

                            </div>
                        </div>
</code>```

Body:
My task is to create a editor of predefined XML where all the parent and child tags are known. I am trying to solve this with the help of bootstrap nested collapse functionality.

In the attached code I can have the value only on last child element in the hierarchy because all the parent item is pointing to the child. Please help me to handle the scenario where parent also have its own value as well . So now both thing should work when I click on parent item I can capture its own value as well as it will open the child structure like XML did.

                                    Item 1

                                        Item 1.1

                                        Item 1.1.1
                                        Item 1.1.2
                                        Item 1.1.3

                                        Item 1.2

                                        Item 1.2.1
                                        Item 1.2.2
                                        Item 1.2.3

                                        Item 1.3

                                        Item 1.3.1
                                        Item 1.3.2
                                        Item 1.3.3

                                    Item 2

                                        Item 2.1

                                        Item 2.1.1
                                        Item 2.1.2
                                        Item 2.1.3

                                        Item 2.2

                                        Item 2.2.1
                                        Item 2.2.2
                                        Item 2.2.3

                                        Item 2.3

                                        Item 2.3.1
                                        Item 2.3.2
                                        Item 2.3.3

                                    Item 3

                                        Item 3.1

                                        Item 3.1.1
                                        Item 3.1.2
                                        Item 3.1.3

                                        Item 3.2

                                        Item 3.2.1
                                        Item 3.2.2
                                        Item 3.2.3

                                        Item 3.3

                                        Item 3.3.1
                                        Item 3.3.2
                                        Item 3.3.3


问:
How do I make a model generate a migration with PK and FK?
I'm trying to generate two items as primary key and foreign key within sql server, but when I do the migration it doesn't come out as expected. Below are the codes.

```<code>namespace ContratosMVC.Models
{
    public class AtaRegistroPrecoModel
    {
        public int Id { get; set; }
        public DateTime Data { get; set; }
        public short Numero { get; set; }
        public short Ano { get; set; }
        public string? Objeto { get; set; }
        public string? Observacao { get; set; }
        public DateTime DataInicio { get; set; }
        public DateTime DataFim { get; set; }
        public string? Arquivo { get; set; }
        public DateTime DataCriacao { get; set; }
        public ContratoModel? Contrato_ { get; set; }
        public ProcessoModel? Processo_ { get; set; }
        public CorrespondenciaModel? Correspondencia_ { get; set; }
    }
}
</code>```
```<code>namespace ContratosMVC.Models
{
    public class AtaRegistroPrecoFornecedorModel
    {
        [Required, Key, ForeignKey("AtaRegistraPrecoFornecedor_Fornecedor_Id")]
        public AtaRegistroPrecoModel AtaRegistraPrecoFornecedor_Fornecedor_ { get; set; }

        [Required, Key]
        public FornecedorModel Fornecedores_ { get; set; }
    }

    public class AtaRegistroPrecoFornecedorMap : IEntityTypeConfiguration<AtaRegistroPrecoFornecedorModel>
    {
        public void Configure(EntityTypeBuilder<AtaRegistroPrecoFornecedorModel> builder)
        {
            builder.HasNoKey();
        }
    }
}
</code>```

What the current code generates:

What I need:

I hope you understand why an item is defined with a primary key and a foreign key.

I also hope to solve this problem that I've been holding on to for a long time.

Body:
I'm trying to generate two items as primary key and foreign key within sql server, but when I do the migration it doesn't come out as expected. Below are the codes.

namespace ContratosMVC.Models
{
    public class AtaRegistroPrecoModel
    {
        public int Id { get; set; }
        public DateTime Data { get; set; }
        public short Numero { get; set; }
        public short Ano { get; set; }
        public string? Objeto { get; set; }
        public string? Observacao { get; set; }
        public DateTime DataInicio { get; set; }
        public DateTime DataFim { get; set; }
        public string? Arquivo { get; set; }
        public DateTime DataCriacao { get; set; }
        public ContratoModel? Contrato_ { get; set; }
        public ProcessoModel? Processo_ { get; set; }
        public CorrespondenciaModel? Correspondencia_ { get; set; }
    }
}

namespace ContratosMVC.Models
{
    public class AtaRegistroPrecoFornecedorModel
    {
        [Required, Key, ForeignKey("AtaRegistraPrecoFornecedor_Fornecedor_Id")]
        public AtaRegistroPrecoModel AtaRegistraPrecoFornecedor_Fornecedor_ { get; set; }

        [Required, Key]
        public FornecedorModel Fornecedores_ { get; set; }
    }

    public class AtaRegistroPrecoFornecedorMap : IEntityTypeConfiguration<AtaRegistroPrecoFornecedorModel>
    {
        public void Configure(EntityTypeBuilder<AtaRegistroPrecoFornecedorModel> builder)
        {
            builder.HasNoKey();
        }
    }
}

What the current code generates:

What I need:

I hope you understand why an item is defined with a primary key and a foreign key.

I also hope to solve this problem that I've been holding on to for a long time.


问:
Electron webpack template - images in the main process
I have an electron app based on electron forge 6 and their webpack template.

It seems to work fine and when built assets, etc. are migrated to .webpack correctly for the render process.

My app has a tray component defined in the main process and needs to load a tray icon from there, however on build, the icon doesn't seem to be being moved into the .webpack dir and therefore nativeImage can't load it.

When I inspect the path being passed to native image it has been updated by webpack to a point i.e. it is .webpack/main/images/logo.png vs. src/images/logo.png (the icon's original location) but the filename isn't being hashed and the file isn't being copied into .webpack/main/

What might I be doing wrong/missing?

I have added this to my main process webpack config which was all I needed to do to make things work for the renderer, but it doesn't seem to have changed anything for main:

```<code> {
      test: /\.(png|jpe?g|gif|ico|svg)$/,
      type: 'asset/resource'
    },
</code>```

I'm relatively new to the ins and outs of webpack but I can see how it more or less works though I'm starting to run out of ideas as to why this specifically might not be working for me.

Body:
I have an electron app based on electron forge 6 and their webpack template.

It seems to work fine and when built assets, etc. are migrated to .webpack correctly for the render process.

My app has a tray component defined in the main process and needs to load a tray icon from there, however on build, the icon doesn't seem to be being moved into the .webpack dir and therefore nativeImage can't load it.

When I inspect the path being passed to native image it has been updated by webpack to a point i.e. it is .webpack/main/images/logo.png vs. src/images/logo.png (the icon's original location) but the filename isn't being hashed and the file isn't being copied into .webpack/main/

What might I be doing wrong/missing?

I have added this to my main process webpack config which was all I needed to do to make things work for the renderer, but it doesn't seem to have changed anything for main:

 {
      test: /\.(png|jpe?g|gif|ico|svg)$/,
      type: 'asset/resource'
    },

I'm relatively new to the ins and outs of webpack but I can see how it more or less works though I'm starting to run out of ideas as to why this specifically might not be working for me.


问:
react-admin calls executes previous api request along with the new api request
I am using React admin for our panel with grapqhl ,I noticed that there are lot duplicate or unwanted api calls to the backend with react-admin default pagination ,not sure whats wrong with my implementation .Look for some help here .Whenever i click on a page number the backend is called twice once with the previous page selection and another request with the current page selection

My List component

```<code> <List {...props} filters={TitleFilter} actions={false} bulkActionButtons={false} pagination={<Pagination />}>
      <Datagrid bulkActionButtons={false}>
        <NumberField source='order' label='Position' />
        <TextField source='title' label='Titel' />
      </Datagrid>
    </List>
</code>```

and the network requests when i clicked on page 2, it is just overloading the backend with too many requests

Looks like this is not related to pagiantion, happening if i navigate to a different resource too , guessing the issue might be with caching

Body:
I am using React admin for our panel with grapqhl ,I noticed that there are lot duplicate or unwanted api calls to the backend with react-admin default pagination ,not sure whats wrong with my implementation .Look for some help here .Whenever i click on a page number the backend is called twice once with the previous page selection and another request with the current page selection

My List component

 <List {...props} filters={TitleFilter} actions={false} bulkActionButtons={false} pagination={<Pagination />}>
      <Datagrid bulkActionButtons={false}>
        <NumberField source='order' label='Position' />
        <TextField source='title' label='Titel' />
      </Datagrid>
    </List>

and the network requests when i clicked on page 2, it is just overloading the backend with too many requests

Looks like this is not related to pagiantion, happening if i navigate to a different resource too , guessing the issue might be with caching


问:
How to filnd Path to Sharepoint in NodeJs
I have a code that is supposed to connect to a server, but I am getting a 'Microsoft SharePoint Foundation Error' when I try to run it. What could be causing this error and how can I fix it?
Status 200
OK

`

Microsoft SharePoint Foundation Error.

User: please report details to this Web site's Webmaster.

Webmaster: please see the server's application event log for more details.

`

```<code>const adal = require('adal-node');
const clientId = '<myclientID>';
const clientSecret = '<myclientSecret>';
const resource = 'https://<domain>.sharepoint.com/';
const folderName = '';
const context = new adal.AuthenticationContext('https://login.windows.net/common');
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
  if (err) {
    //  console.log('Błąd podczas pobierania tokenu dostępu: ' + err);
  } else {
    upload(tokenResponse.accessToken)
  }
});
function upload(accessToken){
const fs = require('fs');
const axios = require('axios');

const filePath = './test.txt';
const sharepointSiteUrl = resource+'teams/<name_my_Sharepoint/';
const fileName = 'test.txt';
const folderName = '';
//add(url='${fileName}',overwrite=true)
const options = {
  method: 'POST',
  url: sharepointSiteUrl+ "/_api://<myclientID>",
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Accept': 'application/json;odata=verbose',
    'Content-Type': 'application/json;odata=verbose'
  },
  data: fs.createReadStream(filePath)
};

axios(options)
  .then((response) => {
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.data)
  })
  .catch((error) => {
    console.log("test")
    console.error(error);
  });}
</code>```

Body:
I have a code that is supposed to connect to a server, but I am getting a 'Microsoft SharePoint Foundation Error' when I try to run it. What could be causing this error and how can I fix it?
Status 200
OK

`

Microsoft SharePoint Foundation Error.

User: please report details to this Web site's Webmaster.

Webmaster: please see the server's application event log for more details.

`

const adal = require('adal-node');
const clientId = '<myclientID>';
const clientSecret = '<myclientSecret>';
const resource = 'https://<domain>.sharepoint.com/';
const folderName = '';
const context = new adal.AuthenticationContext('https://login.windows.net/common');
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
  if (err) {
    //  console.log('Błąd podczas pobierania tokenu dostępu: ' + err);
  } else {
    upload(tokenResponse.accessToken)
  }
});
function upload(accessToken){
const fs = require('fs');
const axios = require('axios');

const filePath = './test.txt';
const sharepointSiteUrl = resource+'teams/<name_my_Sharepoint/';
const fileName = 'test.txt';
const folderName = '';
//add(url='${fileName}',overwrite=true)
const options = {
  method: 'POST',
  url: sharepointSiteUrl+ "/_api://<myclientID>",
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Accept': 'application/json;odata=verbose',
    'Content-Type': 'application/json;odata=verbose'
  },
  data: fs.createReadStream(filePath)
};

axios(options)
  .then((response) => {
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.data)
  })
  .catch((error) => {
    console.log("test")
    console.error(error);
  });}


问:
How to obtain the "seek to" time in MPMoviePlayerController?
I am using an MPMoviePlayerController instance to play live-streaming videos. When the user seeks forward or backward, I want to obtain the time to which the play-head should seek to.

MPMoviePlayerPlaybackStateDidChangeNotification notifies me of a seek event just fine, and currentPlaybackTime returns the current time i.e. before seeking. How do I obtain the "seek-to" time without waiting for the next MPMoviePlaybackStatePlaying notification?

ContentLicense: CC BY-SA 3.0


问:
how i do scrap fisrt is  and  in BeautifulSoup "lxml"
Every time I download it, and open the file.html the result is a black blank. Image does not appear.
enter image description here

This my python code:

```<code>try:
      url = f"link.com"
      response = requests.get(url)
      response_html = response.text
      soup = BeautifulSoup(response_html, 'lxml')
      page_count = soup.find("span", class_="num-pages")
      img_link = soup.findAll("img")
      img_links = img_link["src"].split("/")
      list_of_pages = []
      for i in range(int(page_count)):
        temp = img_links[-1]
        temp = temp.split(".")
        temp[0] = str(i + 1)
        pagenum = ".".join(temp)
        img_links[-1] = pagenum
        list_of_pages.append("/".join(img_links))
      return list_of_pages
    except requests.exceptions.ConnectionError:
      return "Check the host's network Connection"
</code>```

This my tag html:

I want when I open the scrap file.html the image appears. How to?

Title: how i do scrap fisrt is <a href> and <img src> in BeautifulSoup "lxml"

Body:
Every time I download it, and open the file.html the result is a black blank. Image does not appear.
enter image description here

This my python code:

try:
      url = f"link.com"
      response = requests.get(url)
      response_html = response.text
      soup = BeautifulSoup(response_html, 'lxml')
      page_count = soup.find("span", class_="num-pages")
      img_link = soup.findAll("img")
      img_links = img_link["src"].split("/")
      list_of_pages = []
      for i in range(int(page_count)):
        temp = img_links[-1]
        temp = temp.split(".")
        temp[0] = str(i + 1)
        pagenum = ".".join(temp)
        img_links[-1] = pagenum
        list_of_pages.append("/".join(img_links))
      return list_of_pages
    except requests.exceptions.ConnectionError:
      return "Check the host's network Connection"

This my tag html:

I want when I open the scrap file.html the image appears. How to?


问:
Translate an entire page with Google Translate API
I'm using the google Translate API to translate content that's inside an IFRAME. When using the API, I notice that it returns a array(string) with the translated texts, but when inserting it in the DOM, the entire structure disappears, leaving only the text.

The original Page

The result page after the response of the Google API (translate in Portuguese)

This is the code that I'm using:

```<code>function translate(lang) {
  var iframe = document.getElementById('mainIframe');
  var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
  var iframeBody = iframeDoc.body;
  var iframeHTML = iframeDoc.documentElement;
  var iframeText = iframeBody.innerText || iframeHTML.innerText;
  var url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=pt&dt=t&q=' + encodeURI(iframeText);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var response = JSON.parse(xhr.responseText);
      var translatedText = ''

    for (var i = 0; i < response[0].length; i++) {
        translatedText += response[0][i][0];
    }

      iframeDoc.body.innerHTML = translatedText;
    }
  };
  xhr.send();
}
</code>```

How can I not affect the structure within the Iframe (Not to be like the second image I sent above)? Just replace the original text with what comes in the response and leave the original look.

I've already tried using functions to find the original text in the DOM to replace it with the translated text but without success. In this case, the idea was just to replace the text correspondence literally.

Thanks for your help and thanks in advance

Body:
I'm using the google Translate API to translate content that's inside an IFRAME. When using the API, I notice that it returns a array(string) with the translated texts, but when inserting it in the DOM, the entire structure disappears, leaving only the text.

The original Page

The result page after the response of the Google API (translate in Portuguese)

This is the code that I'm using:

function translate(lang) {
  var iframe = document.getElementById('mainIframe');
  var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
  var iframeBody = iframeDoc.body;
  var iframeHTML = iframeDoc.documentElement;
  var iframeText = iframeBody.innerText || iframeHTML.innerText;
  var url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=pt&dt=t&q=' + encodeURI(iframeText);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var response = JSON.parse(xhr.responseText);
      var translatedText = ''

    for (var i = 0; i < response[0].length; i++) {
        translatedText += response[0][i][0];
    }

      iframeDoc.body.innerHTML = translatedText;
    }
  };
  xhr.send();
}

How can I not affect the structure within the Iframe (Not to be like the second image I sent above)? Just replace the original text with what comes in the response and leave the original look.

I've already tried using functions to find the original text in the DOM to replace it with the translated text but without success. In this case, the idea was just to replace the text correspondence literally.

Thanks for your help and thanks in advance


问:
Resizing Image Without Average Color
I would like to be able to reduce a (300 x 300) photo to (10 x 10) size, while maintaining the cell colors with the original, and the positioning of the cells to be approximately at the same position.

I have a (300 x 300) pixels image that is in a heatmap format. I have reduced the colors of the heatmap to only 3 colors for easier representation:

.

Now I have to resize it in a (10 x 10). If I do it using

```<code>resized = cv2.resize(img, (ws,hs), interpolation = cv2.INTER_AREA)
</code>```

It gives me average color, which I do not want. I want my original 3 colors to stay is somewhat approximate place:

The closest I have reached is this image below, but the position of the pixels are somewhat messy. The average color image has the position of the pixels very close to the original photo.

My Code So Far:

```<code>normal = [68, 2, 85]
minor = [44, 114, 142]
major = [232, 228, 29]
</code>```

[A bit of explanation: The image is in (300 x 300) array, instead of rgb value, only r value is saved, but as there are only 3 colors with different reds, a new image can be reproduced easily. (300 x 300) array is divided and iterated by a 30*30 draft array, which takes total of 900 pixel values, and converts it into 1 cell for the (10 x 10) array. The priority for color goes: Major>Minor>Normal. If Major is found in the (30 x 30) array, the cell of (10 x 10) is colored as major and so on]

[data_2_2_dim is the (300 x 300) array, and data_3_2_dim is the (10 x 10) array]

iter1 = 0
iter2 = 0

for i in range(data_3_2_dim.shape[0]):
    for j in range(data_3_2_dim.shape[1]):
        draft = np.zeros((30, 30))
        val_no = 0
        val_minor = 0
        val_major = 0
        for k in range(30):
            for l in range(30):
                # val = 68
                if data_2_2_dim[iter1][iter2] == 44 and data_2_2_dim[iter1][iter2] != 232:
                    val = 44

                if data_2_2_dim[iter1][iter2] == 232:
                    val = 232

                if data_2_2_dim[iter1][iter2] == 68 and data_2_2_dim[iter1][iter2] != 232 and data_2_2_dim[iter1][iter2] != 44:
                    val = 68

                draft[k][l] = val

            iter1+=1

        major = False
        minor = False

        for p in range(draft.shape[0]):
            for q in range(draft.shape[1]):
                if draft[p][q] == 232:
                    major = True
                if draft[p][q] == 44:
                    minor = True

        if minor == True and major == False:
            data_3_2_dim[j][i] = 44
        elif major == True:
            data_3_2_dim[j][i] = 232
        else:
            data_3_2_dim[j][i] = 68

        iter2+=1
    iter1 = 0

from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np

fig, ax = plt.subplots()
ax.imshow(data_3_2_dim)
plt.show()
```

Title: Resizing Image Without Average Color

Body:
I would like to be able to reduce a (300 x 300) photo to (10 x 10) size, while maintaining the cell colors with the original, and the positioning of the cells to be approximately at the same position.

I have a (300 x 300) pixels image that is in a heatmap format. I have reduced the colors of the heatmap to only 3 colors for easier representation:

.

Now I have to resize it in a (10 x 10). If I do it using

resized = cv2.resize(img, (ws,hs), interpolation = cv2.INTER_AREA)

It gives me average color, which I do not want. I want my original 3 colors to stay is somewhat approximate place:

The closest I have reached is this image below, but the position of the pixels are somewhat messy. The average color image has the position of the pixels very close to the original photo.

My Code So Far:

normal = [68, 2, 85]
minor = [44, 114, 142]
major = [232, 228, 29]

[A bit of explanation: The image is in (300 x 300) array, instead of rgb value, only r value is saved, but as there are only 3 colors with different reds, a new image can be reproduced easily. (300 x 300) array is divided and iterated by a 30*30 draft array, which takes total of 900 pixel values, and converts it into 1 cell for the (10 x 10) array. The priority for color goes: Major>Minor>Normal. If Major is found in the (30 x 30) array, the cell of (10 x 10) is colored as major and so on]

[data_2_2_dim is the (300 x 300) array, and data_3_2_dim is the (10 x 10) array]

iter1 = 0
iter2 = 0

for i in range(data_3_2_dim.shape[0]):
    for j in range(data_3_2_dim.shape[1]):
        draft = np.zeros((30, 30))
        val_no = 0
        val_minor = 0
        val_major = 0
        for k in range(30):
            for l in range(30):
                # val = 68
                if data_2_2_dim[iter1][iter2] == 44 and data_2_2_dim[iter1][iter2] != 232:
                    val = 44

                if data_2_2_dim[iter1][iter2] == 232:
                    val = 232

                if data_2_2_dim[iter1][iter2] == 68 and data_2_2_dim[iter1][iter2] != 232 and data_2_2_dim[iter1][iter2] != 44:
                    val = 68

                draft[k][l] = val

            iter1+=1

        major = False
        minor = False

        for p in range(draft.shape[0]):
            for q in range(draft.shape[1]):
                if draft[p][q] == 232:
                    major = True
                if draft[p][q] == 44:
                    minor = True

        if minor == True and major == False:
            data_3_2_dim[j][i] = 44
        elif major == True:
            data_3_2_dim[j][i] = 232
        else:
            data_3_2_dim[j][i] = 68

        iter2+=1
    iter1 = 0

from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np

fig, ax = plt.subplots()
ax.imshow(data_3_2_dim)
plt.show()


问:
Wrong Month from dateUtils.keyToMoment
I am trying to get year, month and day from below code but getting wrong.

```<code> import dateUtils from 'app/utils/date-utils';

 const today = dateUtils.momentToKey();

 const todayMoment = this.dateUtils.keyToMoment(today);
 const newYear = todayMoment.year();
 const newMonth = todayMoment.month();
 const newDay = todayMoment.date();

 console.log('newYear : ', newYear);
 console.log('newMonth : ', newMonth);
 console.log('newDay : ', newDay);
</code>```

Month showing wrong -

Could you guide me what's wrong in code?

Title: Wrong Month from dateUtils.keyToMoment

Body:
I am trying to get year, month and day from below code but getting wrong.

 import dateUtils from 'app/utils/date-utils';

 const today = dateUtils.momentToKey();

 const todayMoment = this.dateUtils.keyToMoment(today);
 const newYear = todayMoment.year();
 const newMonth = todayMoment.month();
 const newDay = todayMoment.date();

 console.log('newYear : ', newYear);
 console.log('newMonth : ', newMonth);
 console.log('newDay : ', newDay);

Month showing wrong -

Could you guide me what's wrong in code?


问:
Swiper js when i fill slides with for loop i can't use arrows
I am using swiper js to create slides and I fill the slides with canvas element using chartjs.Below are the codes and photos.slides render properly but only one is visible and arrows are not working. Please help me how can i fix this.  getCaseDemands function called six times.
codes
wiev

```<code> <div class="competition-slider" >
                    <div class="swiper compSwiper">
                        <div class="swiper-wrapper">

                        </div>
                        <!-- <div class="swiper-pagination"></div> -->
                        <div class="swiper-button-next"></div>
                        <div class="swiper-button-prev"></div>
                    </div>
</div>

<template id="competition-slide-template">
    <div class="swiper-slide">
        <h5 class="title">{title}</h5>
        <canvas class="resultChart"></canvas>
    </div>
</template>
</code>```
```<code>var compSwiper = new Swiper(".compSwiper", {
                navigation: {
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev",
                },

            });
</code>```
```<code>function getCaseDemands(slide, countOfSlide) {
    $.ajax({
        type: "GET",
        url: url,
        data: {
            case_id: slide?.case_unique_id
        },
        success: function(res) {
            console.log(res, "res")
            const compSlideTemplate = $($("#competition-slide-template").clone().html());
            compSlideTemplate.html(compSlideTemplate.html().replaceAll("{title}", `${slide?.case_name}`));
            const data = {
               labels: res.map((item) => item.case_demand),
                datasets: [{label: "",
                            data: res.map((item) => parseInt(item.case_value)),
                                backgroundColor: ["rgba(131, 178, 214,0.5)",],
                                borderColor: ["rgba(31, 121, 184,1)"],
                                borderWidth: 3,
                                },
                            ],
                        };
                        const config = {
                            type: "radar",
                            data: data,
                            options: {
                                responsive: true,
                                scales: {
                                    r: {
                                        max: 100,
                                        min: 0,
                                        ticks: {
                                            stepSize: 20,
                                            display: false,
                                        },
                                        grid: {
                                            color: "#9FD1F6",
                                        },
                                        angleLines: {
                                            color: "#9FD1F6",
                                        },
                                        pointLabels: {
                                            font: {
                                                size: 13,
                                                family: "Poppins",
                                                weight: "500",
                                            },
                                        },
                                    },
                                },
                                elements: {
                                    point: {
                                        color: "red",
                                    },
                                },
                                plugins: {
                                    legend: {
                                        display: false,
                                    },
                                },
                            },
                        };

                        const resultChartElement =
                            compSlideTemplate.find(".resultChart")[0];
                        const myChart = new Chart(resultChartElement, config);
                        $(".compSwiper .swiper-wrapper").append(
                            compSlideTemplate
                        );
                        compSwiper.update();.....
</code>```
```<code>function settingSlides() {
     $('.competition-slider').each(function() {
         new Swiper($(this).find('.compSwiper')[0], {
             navigation: {
               nextEl: '.swiper-button-next',
               prevEl: '.swiper-button-prev',
              },

              })

         });

     }
</code>```

After creating all the slides I wanted to run and configure this function, this time it didn't work. Some slides were not visible. Some slides were not visible when I wanted to do it using dummy data.
I've been dealing with this problem for 3 days, I couldn't find the solution anywhere. I'm waiting for your help and suggestions.I tried every solution I could find, thanks in advance for your help

Body:
I am using swiper js to create slides and I fill the slides with canvas element using chartjs.Below are the codes and photos.slides render properly but only one is visible and arrows are not working. Please help me how can i fix this.  getCaseDemands function called six times.
codes
wiev

<template id="competition-slide-template">

{title}

        <canvas class="resultChart"></canvas>

</template>

var compSwiper = new Swiper(".compSwiper", {
                navigation: {
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev",
                },

            });

function getCaseDemands(slide, countOfSlide) {
    $.ajax({
        type: "GET",
        url: url,
        data: {
            case_id: slide?.case_unique_id
        },
        success: function(res) {
            console.log(res, "res")
            const compSlideTemplate = $($("#competition-slide-template").clone().html());
            compSlideTemplate.html(compSlideTemplate.html().replaceAll("{title}", `${slide?.case_name}`));
            const data = {
               labels: res.map((item) => item.case_demand),
                datasets: [{label: "",
                            data: res.map((item) => parseInt(item.case_value)),
                                backgroundColor: ["rgba(131, 178, 214,0.5)",],
                                borderColor: ["rgba(31, 121, 184,1)"],
                                borderWidth: 3,
                                },
                            ],
                        };
                        const config = {
                            type: "radar",
                            data: data,
                            options: {
                                responsive: true,
                                scales: {
                                    r: {
                                        max: 100,
                                        min: 0,
                                        ticks: {
                                            stepSize: 20,
                                            display: false,
                                        },
                                        grid: {
                                            color: "#9FD1F6",
                                        },
                                        angleLines: {
                                            color: "#9FD1F6",
                                        },
                                        pointLabels: {
                                            font: {
                                                size: 13,
                                                family: "Poppins",
                                                weight: "500",
                                            },
                                        },
                                    },
                                },
                                elements: {
                                    point: {
                                        color: "red",
                                    },
                                },
                                plugins: {
                                    legend: {
                                        display: false,
                                    },
                                },
                            },
                        };

                        const resultChartElement =
                            compSlideTemplate.find(".resultChart")[0];
                        const myChart = new Chart(resultChartElement, config);
                        $(".compSwiper .swiper-wrapper").append(
                            compSlideTemplate
                        );
                        compSwiper.update();.....

function settingSlides() {
     $('.competition-slider').each(function() {
         new Swiper($(this).find('.compSwiper')[0], {
             navigation: {
               nextEl: '.swiper-button-next',
               prevEl: '.swiper-button-prev',
              },

              })

         });

     }

After creating all the slides I wanted to run and configure this function, this time it didn't work. Some slides were not visible. Some slides were not visible when I wanted to do it using dummy data.
I've been dealing with this problem for 3 days, I couldn't find the solution anywhere. I'm waiting for your help and suggestions.I tried every solution I could find, thanks in advance for your help


问:
what jquery version is compatiable with angular 8?
I need to find compatible versions for some dependencies in angular 8. Dependencies like:

jquery-2.1.3.js

jquery.min.js

jquery.dataTables.min.js

@angular/core

ajv

ansi

How to find these compatible versions?
I tried finding on the internet but I couldn't find

```<code> "dependencies": {
 ...
 "jquery": "^3.4.1",
 ...
 }
</code>```

Body:
I need to find compatible versions for some dependencies in angular 8. Dependencies like:

jquery-2.1.3.js

jquery.min.js

jquery.dataTables.min.js

@angular/core

ajv

ansi

How to find these compatible versions?
I tried finding on the internet but I couldn't find

 "dependencies": {
 ...
 "jquery": "^3.4.1",
 ...
 }


问:
Popover on table rendering multiple instances in Vue3
I am trying to create a Vue component which wraps a Popoverfrom headlessui

I am trying to toggle open close using the slot binding as suggested in the popover docs. I cannot get this to work. Nothing appears in the UI, even if I had it working ok from within the  element itself, granted that is neither a good place to put it because the elements render as many rows there are in the table.

Does anyone have any wisdom surrounding headless UI popovers in Vue3 on a table row?

EDIT:
Ok adding static to the PopoverPanelmakes it render when open=true
, the issue now being that multiple instances render based on the number of elements in the table. So this is a new issue.

```<code><template>
  <div>
    <Popover :slot="{pop}">
      <transition
        enter-active-class="transition duration-200 ease-out"
        enter-from-class="translate-y-1 opacity-0"
        enter-to-class="translate-y-0 opacity-100"
        leave-active-class="transition duration-150 ease-in"
        leave-from-class="translate-y-0 opacity-100"
        leave-to-class="translate-y-1 opacity-0"
      >
        <PopoverPanel static class="absolute z-9 mt-3 max-w-sm -translate-x-1/2 transform sm:px-0 lg:max-w-3xl">
      <div class="rounded-lg shadow-lg w-full m-2">
        <div
          v-if="pop"
          ref="popover"
          class="flex flex-col p-2"
        >
          <ButtonTemp label="Send reminder" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-left text-caption hover:bg-neutral-900 hover:text-neutral-100" icon-left>
            <IconsMail />
          </ButtonTemp>
          <ButtonTemp label="Share candidate" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-caption hover:bg-neutral-900 hover:text-neutral-100" icon-left>
          <IconsExternalLink />
          </ButtonTemp>
          <ButtonTemp label="Remove from assignment" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-caption hover:bg-danger-100 hover:text-neutral-100" icon-left>
          <IconsUserMinus />
          </ButtonTemp>
        </div>
      </div>
    </PopoverPanel>
  </transition>
</Popover>
</code>```

```<code><script setup lang="ts">
import { Ref } from '@vue/runtime-core';
import { Popover, PopoverButton, PopoverPanel } from '@headlessui/vue';
import { ButtonTemp, IconsMail, IconsExternalLink, IconsUserMinus } from '@/.nuxt/components';

const pop: Ref<boolean> = ref(true);

interface IContextMenu {
  open: boolean;
}

const props = defineProps<IContextMenu>();
const isOpen = toRef(props, 'open');

watch(isOpen, (is) => {
  if (is) {
   console.log('open', is);
   pop.value = !pop.value;
 }
});

onMounted(() => {
  pop.value = true;
});

</script>
</code>```

Component where it is to be used:
......

```<code><td class="group-hover:text-neutral-100 rounded-r">
        <button
          class="m-auto h-8 w-8 rounded-sm flex justify-center items-center group-hover:bg-neutral-700 cursor-pointer"
          @click="handleClick(candidate.id, '')"
        >
          <ContextMenu :open="open" /> // Popover wrapped component

          <IconsVerticalMenu />
        </button>
      </td>
    </tr>
</code>```

Body:
I am trying to create a Vue component which wraps a Popoverfrom headlessui

I am trying to toggle open close using the slot binding as suggested in the popover docs. I cannot get this to work. Nothing appears in the UI, even if I had it working ok from within the  element itself, granted that is neither a good place to put it because the elements render as many rows there are in the table.

Does anyone have any wisdom surrounding headless UI popovers in Vue3 on a table row?

EDIT:
Ok adding static to the PopoverPanelmakes it render when open=true
, the issue now being that multiple instances render based on the number of elements in the table. So this is a new issue.

<template>

    <Popover :slot="{pop}">
      <transition
        enter-active-class="transition duration-200 ease-out"
        enter-from-class="translate-y-1 opacity-0"
        enter-to-class="translate-y-0 opacity-100"
        leave-active-class="transition duration-150 ease-in"
        leave-from-class="translate-y-0 opacity-100"
        leave-to-class="translate-y-1 opacity-0"
      >
        <PopoverPanel static class="absolute z-9 mt-3 max-w-sm -translate-x-1/2 transform sm:px-0 lg:max-w-3xl">

          <ButtonTemp label="Send reminder" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-left text-caption hover:bg-neutral-900 hover:text-neutral-100" icon-left>
            <IconsMail />
          </ButtonTemp>
          <ButtonTemp label="Share candidate" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-caption hover:bg-neutral-900 hover:text-neutral-100" icon-left>
          <IconsExternalLink />
          </ButtonTemp>
          <ButtonTemp label="Remove from assignment" btn-type="m-0.5 bg-neutral-200 text-neutral-900 text-caption hover:bg-danger-100 hover:text-neutral-100" icon-left>
          <IconsUserMinus />
          </ButtonTemp>

    </PopoverPanel>
  </transition>
</Popover>

Component where it is to be used:
......

        <button
          class="m-auto h-8 w-8 rounded-sm flex justify-center items-center group-hover:bg-neutral-700 cursor-pointer"
          @click="handleClick(candidate.id, '')"
        >
          <ContextMenu :open="open" /> // Popover wrapped component

          <IconsVerticalMenu />
        </button>


问:
Application icon not showing oracle APEX?
I installed oracle database 19c and apex version 22.2 ,

and I make menu page but some icons not showing

what is the reason ?

see the application image and table data :

open the image please and see HIS home page , OPD system and emergency department the icon not appear next to the name but the other icons appeared for MRN registration and inpatient system

I got the icons names from the following site :

```<code>https://fontawesome.com/search
</code>```

Body:
I installed oracle database 19c and apex version 22.2 ,

and I make menu page but some icons not showing

what is the reason ?

see the application image and table data :

open the image please and see HIS home page , OPD system and emergency department the icon not appear next to the name but the other icons appeared for MRN registration and inpatient system

I got the icons names from the following site :

https://fontawesome.com/search


问:
How to install offline ng2-pdfjs-viewer package under the Angular application
How can I install and use the ng2-pdfjs-viewer offline in angular, because I do not want to install it every time and how can I build for production with an offline package of it?


问:
On Edit Data Store Preferences the execution complete but ui stuck
code execute the higlighted line but did not send any response to the caller code due to which ui stucked. try lots of different scenario but did not get success.

Please help me already wasted 2 days in fixing this.

Aleady check with multiple coroutines like new launch , run blocking.
With flow it releases the UI but data is not saving in datastore.


问:
.NET 6 Console App: A second operation was started on this context instance before a previous operation completed
I'm working with .NET 6 console app.
I have Program.cs where the DBContext is instantiated.

```<code>public class Program
{
    static ProcedureService procservice;

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        string onlineConnectionString = "Server = localhost; Database = DB; Trusted_Connection = True;";

        services.AddDbContext<DBContext>(o => o.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
        services.AddScoped<ProcedureService , ProcedureService>();
        var serviceProvider = services.BuildServiceProvider();
        procservice = serviceProvider.GetService<ProcedureService>();
    }
}
</code>```

I also have an internal class that would call another service to do the logic and save something on the DB.

the service looks like this

```<code>public class Service
{
    ProcedureService procservice;

    public Service(ProcedureService procservice)
    {
        this.procservice = procservice;
    }
}
</code>```

and inside this service I have a method who also calls the ProcedureService and that's the time I had encounter "A second operation was started on this context instance before a previous operation completed."

ProcedureService

```<code>public ProcedureService(DBContext context)
    {
        this.context = context;
    }
</code>```

Body:
I'm working with .NET 6 console app.
I have Program.cs where the DBContext is instantiated.

public class Program
{
    static ProcedureService procservice;

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        string onlineConnectionString = "Server = localhost; Database = DB; Trusted_Connection = True;";

        services.AddDbContext<DBContext>(o => o.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
        services.AddScoped<ProcedureService , ProcedureService>();
        var serviceProvider = services.BuildServiceProvider();
        procservice = serviceProvider.GetService<ProcedureService>();
    }
}

I also have an internal class that would call another service to do the logic and save something on the DB.

the service looks like this

public class Service
{
    ProcedureService procservice;

    public Service(ProcedureService procservice)
    {
        this.procservice = procservice;
    }
}

and inside this service I have a method who also calls the ProcedureService and that's the time I had encounter "A second operation was started on this context instance before a previous operation completed."

ProcedureService

public ProcedureService(DBContext context)
    {
        this.context = context;
    }


问:
How to get my azure free subscription back
I logged in today and I could see my subscription, while learning I created an Azure Active Directory Tenant and linked to my subscription. Later I deleted my tenant but this action has deleted both my Tenant and my Subscription. Now portal is not showing my free subscription, When I try to create new, it does not allow me to create new subscription.

I still have

Credits remaining
$199.97
$0.03 used of $200


问:
Fuzzy Inference System IF-THEN Rules
I am currently doing a fuzzy inference system project in Python, however, a question came up.
I have to do it the hard way, that is, do it step by step, as done here: https://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem.html.
When we define the rules we use IF-THEN rules which I suppose is an implication (a->b = ~a OR b).
However, on this website they do the following;

For the rules:

If the food is bad OR the service is poor, then the tip will be low

If the service is acceptable, then the tip will be medium

If the food is great OR the service is amazing, then the tip will be high.

They write:

```<code>```python
# Now we take our rules and apply them. Rule 1 concerns bad food OR
service.
# The OR operator means we take the maximum of these two.
active_rule1 = np.fmax(qual_level_lo, serv_level_lo)

# Now we apply this by clipping the top off the corresponding output
# membership function with `np.fmin`
tip_activation_lo = np.fmin(active_rule1, tip_lo)  # removed entirely to 0

# For rule 2 we connect acceptable service to medium tipping
tip_activation_md = np.fmin(serv_level_md, tip_md)

# For rule 3 we connect high service OR high food with high tipping
active_rule3 = np.fmax(qual_level_hi, serv_level_hi)
tip_activation_hi = np.fmin(active_rule3, tip_hi)
tip0 = np.zeros_like(x_tip)
```
</code>```

This code gives the result it is supposed to. However, the line where they compute "active_rule" doesn't make sense to me, because they are doing "np.min" which is not an implication. I tried replacing it with "np.fmax(~a,b)" but the defuzzification result gives wrong.
Any idea how to know if they are actually making an implication or not?

Thank you in advance

Title: Fuzzy Inference System IF-THEN Rules

Body:
I am currently doing a fuzzy inference system project in Python, however, a question came up.
I have to do it the hard way, that is, do it step by step, as done here: https://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem.html.
When we define the rules we use IF-THEN rules which I suppose is an implication (a->b = ~a OR b).
However, on this website they do the following;

For the rules:

If the food is bad OR the service is poor, then the tip will be low

If the service is acceptable, then the tip will be medium

If the food is great OR the service is amazing, then the tip will be high.

They write:

```python
# Now we take our rules and apply them. Rule 1 concerns bad food OR
service.
# The OR operator means we take the maximum of these two.
active_rule1 = np.fmax(qual_level_lo, serv_level_lo)

# Now we apply this by clipping the top off the corresponding output
# membership function with `np.fmin`
tip_activation_lo = np.fmin(active_rule1, tip_lo)  # removed entirely to 0

# For rule 2 we connect acceptable service to medium tipping
tip_activation_md = np.fmin(serv_level_md, tip_md)

# For rule 3 we connect high service OR high food with high tipping
active_rule3 = np.fmax(qual_level_hi, serv_level_hi)
tip_activation_hi = np.fmin(active_rule3, tip_hi)
tip0 = np.zeros_like(x_tip)
```

This code gives the result it is supposed to. However, the line where they compute "active_rule" doesn't make sense to me, because they are doing "np.min" which is not an implication. I tried replacing it with "np.fmax(~a,b)" but the defuzzification result gives wrong.
Any idea how to know if they are actually making an implication or not?

Thank you in advance