问:
Module parse failed: Octal literal in strict mode
I am working in angular 7 and validating contact number using

```<code>"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"
</code>```

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

```<code>registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });
</code>```

Is there any way to replace \ character to make it work?

答:
This is an X-Y Problem. Everyone is focusing on your original question title, which asked about escaping literal \ in a regex. That's not the problem.

First, in JavaScript, numbers can be represented many ways. One of those is octal literal notation, indicated by prefixing a number (character code) with a \.

Your regex contains \1 which is being interpreted as an octal, which is your error message. Octal escape sequences have been deprecated which is why strictmode throws an error, which is the actual problem you're facing.

If you have resolved the compile error by escaping your \1 as \\1, you have generated this expression parsing which executes a negative look-ahead of any single digit, followed by a literal "\" character, followed by the number "1" any number of times.

You'll also notice that the area code parentheses are optional, but it requires a literal + (because it's escaped as \+) after the opening bracket. That's certainly not what you want.

The regex you want is probably the one of the answers from this question

```<code>"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$"
</code>```

which parses to this

Second, Angular's PatternValidator converts a string to a regular expression, so just pass in a string without bracketing it with forward slashes.

Body:
I am working in angular 7 and validating contact number using

"^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$"

regular expression but it is throwing the following error : Module parse failed: Octal literal in strict mode (10:76)

I have already tried \\ instead of \ because as per my finding the problem is with \ character.

registerForm = this.fb.group(
{
  email:['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+.com$')]],
  contact:['',[Validators.required, Validators.pattern('/^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$/')]],
  password:['',[Validators.required]],
  confirmPassword:['',[Validators.required]]
},{ validator: PasswordMatchValidator });

Is there any way to replace \ character to make it work?

Body:
This is an X-Y Problem. Everyone is focusing on your original question title, which asked about escaping literal \ in a regex. That's not the problem.

First, in JavaScript, numbers can be represented many ways. One of those is octal literal notation, indicated by prefixing a number (character code) with a \.

Your regex contains \1 which is being interpreted as an octal, which is your error message. Octal escape sequences have been deprecated which is why strictmode throws an error, which is the actual problem you're facing.

If you have resolved the compile error by escaping your \1 as \\1, you have generated this expression parsing which executes a negative look-ahead of any single digit, followed by a literal "\" character, followed by the number "1" any number of times.

You'll also notice that the area code parentheses are optional, but it requires a literal + (because it's escaped as \+) after the opening bracket. That's certainly not what you want.

The regex you want is probably the one of the answers from this question

"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$"

which parses to this

Second, Angular's PatternValidator converts a string to a regular expression, so just pass in a string without bracketing it with forward slashes.


来源: stackexchange

问:
Stacked Bar Chart With No Fill?
I have a dataset all set up and am just trying to get a stacked bar chart to show.

My X-Axis will show three bars: "left", "middle", and "right"

My Y-Axis will be the "total_completed_epa" associated with each of the bars.

The only problem is that "total_completed_epa" is a mutated variable created by the sum of two other columns in my data-set. I just want to show the proportion that each of the columns had on the "total_completed_epa" with a stacked bar chart.

The data is:

```<code>
pass_location Air_Epa_Play YAC_EPA_Play Total_Completed_EPA
middle         0.263         0.434           0.697
left           0.086         0.439           0.525
right          0.082         0.442           0.524
</code>```

Scraping The Data:

```<code>pass_epa <- pbp_2018 %>%
  filter(play_type %in% c("pass", "no_play", "qb_spike"),
         epa != is.na(epa)) %>%
  group_by (pass_location) %>%
  summarize(pass_epa = sum(epa),
            air_epa = sum(comp_air_epa),
            yac_epa = sum(comp_yac_epa),
            pass_plays = n ()) %>%
  ungroup() %>%
  mutate(EPA_Play = round(pass_epa / pass_plays, 3),
         Air_Epa_Play = round(air_epa / pass_plays, 3),
         YAC_EPA_Play = round(yac_epa / pass_plays, 3),
         Total_Completed_EPA = Air_Epa_Play + YAC_EPA_Play) %>%
  slice(-1) %>%
  arrange(-EPA_Play) %>%
  filter(pass_plays >= 80) %>%
  select(pass_location, Air_Epa_Play, YAC_EPA_Play, Total_Completed_EPA)
</code>```

So I have just the 4 columns in my data set. The Air_Epa_Play and YAC_EPA_Play is summed into a "Total_Completed_EPA".

Visualizing It:

```<code>ggplot(pass_epa, aes(x = pass_location, y = Total_Completed_EPA, fill = ?)) +
  geom_col(position = "dodge")
</code>```

I just cannot get the Air_EPA_Play and YAC_EPA_Play to stack in the barchart for Total_Completed_EPA

答:
Data

```<code>test <- data.frame(pass_location=c('middle','left','right'), Air_Epa_Play=c(0.263,0.086,0.082), YAC_Epa_Play=c(0.434,0.439,0.442), Total_Completed=c(0.697,0.525,0.524))

  pass_location Air_Epa_Play YAC_Epa_Play Total_Completed
1        middle        0.263        0.434           0.697
2          left        0.086        0.439           0.525
3         right        0.082        0.442           0.524
</code>```

You can ignore the Total_Completed column - select(-Total_Completed). ggplot does the stacking/summation for you so you don't have to calculate the total yourself. However, ggplot also likes data in long format (rather than wide format), so you'll need to gather() the relevant values (on y-axis) into a single column. Notice I use gather(..., -pass_location) to ignore the grouping column. Try the following with and without fill=var. Once you see that ggplot likes long formatted data, it becomes more intuitive to use it - at least it did for me.

```<code>library(tidyverse)
test %>%
  select(-Total_Completed) %>%
  gather(var, value, -pass_location) %>%
  ggplot(., aes(x=pass_location, y=value, fill=var)) +
  geom_col()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Stacked Bar Chart With No Fill?

Body:
I have a dataset all set up and am just trying to get a stacked bar chart to show.

My X-Axis will show three bars: "left", "middle", and "right"

My Y-Axis will be the "total_completed_epa" associated with each of the bars.

The only problem is that "total_completed_epa" is a mutated variable created by the sum of two other columns in my data-set. I just want to show the proportion that each of the columns had on the "total_completed_epa" with a stacked bar chart.

The data is:

pass_location Air_Epa_Play YAC_EPA_Play Total_Completed_EPA
middle         0.263         0.434           0.697
left           0.086         0.439           0.525
right          0.082         0.442           0.524

Scraping The Data:

pass_epa <- pbp_2018 %>%
  filter(play_type %in% c("pass", "no_play", "qb_spike"),
         epa != is.na(epa)) %>%
  group_by (pass_location) %>%
  summarize(pass_epa = sum(epa),
            air_epa = sum(comp_air_epa),
            yac_epa = sum(comp_yac_epa),
            pass_plays = n ()) %>%
  ungroup() %>%
  mutate(EPA_Play = round(pass_epa / pass_plays, 3),
         Air_Epa_Play = round(air_epa / pass_plays, 3),
         YAC_EPA_Play = round(yac_epa / pass_plays, 3),
         Total_Completed_EPA = Air_Epa_Play + YAC_EPA_Play) %>%
  slice(-1) %>%
  arrange(-EPA_Play) %>%
  filter(pass_plays >= 80) %>%
  select(pass_location, Air_Epa_Play, YAC_EPA_Play, Total_Completed_EPA)

So I have just the 4 columns in my data set. The Air_Epa_Play and YAC_EPA_Play is summed into a "Total_Completed_EPA".

Visualizing It:

ggplot(pass_epa, aes(x = pass_location, y = Total_Completed_EPA, fill = ?)) +
  geom_col(position = "dodge")

I just cannot get the Air_EPA_Play and YAC_EPA_Play to stack in the barchart for Total_Completed_EPA

Body:
Data

test <- data.frame(pass_location=c('middle','left','right'), Air_Epa_Play=c(0.263,0.086,0.082), YAC_Epa_Play=c(0.434,0.439,0.442), Total_Completed=c(0.697,0.525,0.524))

  pass_location Air_Epa_Play YAC_Epa_Play Total_Completed
1        middle        0.263        0.434           0.697
2          left        0.086        0.439           0.525
3         right        0.082        0.442           0.524

You can ignore the Total_Completed column - select(-Total_Completed). ggplot does the stacking/summation for you so you don't have to calculate the total yourself. However, ggplot also likes data in long format (rather than wide format), so you'll need to gather() the relevant values (on y-axis) into a single column. Notice I use gather(..., -pass_location) to ignore the grouping column. Try the following with and without fill=var. Once you see that ggplot likes long formatted data, it becomes more intuitive to use it - at least it did for me.

library(tidyverse)
test %>%
  select(-Total_Completed) %>%
  gather(var, value, -pass_location) %>%
  ggplot(., aes(x=pass_location, y=value, fill=var)) +
  geom_col()


问:
Rebinding Datacontext to update oxyplot graph
I want to be able to refresh the graph created by Oxyplot but am struggling to do so.

In theory the this.model.InvalidatePlot(true); should update it, but it does not want to.

MainPage.xaml.cs

```<code>using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;

namespace WeatherStation
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.BuildModel2();
            this.BuildModel();
        }

        public void BuildModel()
        {
            this.model = new PlotModel();

            LineSeries lineserie = new LineSeries();
            lineserie.Points.Add(new DataPoint(0, 0));
            lineserie.Points.Add(new DataPoint(1, 70));
            lineserie.Points.Add(new DataPoint(2, 20));
            lineserie.Points.Add(new DataPoint(3, 20));

            this.model.Series.Add(lineserie);
            this.model.InvalidatePlot(true);
            DataContext = this;
        }

        public void BuildModel2()
        {
            this.model = new PlotModel();

            LineSeries lineserie = new LineSeries();
            lineserie.Points.Add(new DataPoint(0, 0));
            lineserie.Points.Add(new DataPoint(1, 10));
            lineserie.Points.Add(new DataPoint(2, 80));
            lineserie.Points.Add(new DataPoint(3, 20));

            this.model.Series.Add(lineserie);
            this.model.InvalidatePlot(true);
            DataContext = this;
        }
        public PlotModel model { get; set; }
    }
}
</code>```

MainPage.xaml

```<code><Page
    x:Class="WeatherStation.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WeatherStation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:oxy="using:OxyPlot.Windows"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
        <oxy:PlotView Model="{Binding model, Mode=OneWay}"/>
    </Grid>
</Page>
</code>```

The general idea behind this code is that graph one gets drawn and then the next one should overwrite it. If that happens, I know I can update it by firing similar functions in the future.

答:
I've fixed it. I was too dumb to see the solution.

First of all we need this

```<code>public LineSeries lineserie { get; set; }
</code>```

We add that to both BuildModels:

```<code>    public void BuildModel()
    {
        this.model = new PlotModel();

        this.lineserie = new LineSeries();
        this.lineserie.Points.Add(new DataPoint(0, 0));
        this.lineserie.Points.Add(new DataPoint(1, 70));
        this.lineserie.Points.Add(new DataPoint(2, 20));
        this.lineserie.Points.Add(new DataPoint(3, 20));

        this.model.Series.Add(lineserie);
        this.DataContext = this;
    }
</code>```

Then we remove the old lineseries and add a new one, and then we update :)

```<code>    public void BuildModel2()
    {
        this.model.Series.Remove(this.lineserie);

        this.lineserie = new LineSeries();
        this.lineserie.Points.Add(new DataPoint(0, 0));
        this.lineserie.Points.Add(new DataPoint(1, 10));
        this.lineserie.Points.Add(new DataPoint(2, 80));
        this.lineserie.Points.Add(new DataPoint(3, 20));
        this.model.Series.Add(lineserie);
        this.model.InvalidatePlot(true);
    }
</code>```

And we are good to go. It's basically working with the same object all the time while updating said object, without creating a new one.

Body:
I want to be able to refresh the graph created by Oxyplot but am struggling to do so.

In theory the this.model.InvalidatePlot(true); should update it, but it does not want to.

MainPage.xaml.cs

using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;

namespace WeatherStation
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.BuildModel2();
            this.BuildModel();
        }

        public void BuildModel()
        {
            this.model = new PlotModel();

            LineSeries lineserie = new LineSeries();
            lineserie.Points.Add(new DataPoint(0, 0));
            lineserie.Points.Add(new DataPoint(1, 70));
            lineserie.Points.Add(new DataPoint(2, 20));
            lineserie.Points.Add(new DataPoint(3, 20));

            this.model.Series.Add(lineserie);
            this.model.InvalidatePlot(true);
            DataContext = this;
        }

        public void BuildModel2()
        {
            this.model = new PlotModel();

            LineSeries lineserie = new LineSeries();
            lineserie.Points.Add(new DataPoint(0, 0));
            lineserie.Points.Add(new DataPoint(1, 10));
            lineserie.Points.Add(new DataPoint(2, 80));
            lineserie.Points.Add(new DataPoint(3, 20));

            this.model.Series.Add(lineserie);
            this.model.InvalidatePlot(true);
            DataContext = this;
        }
        public PlotModel model { get; set; }
    }
}

MainPage.xaml

<Page
    x:Class="WeatherStation.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WeatherStation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:oxy="using:OxyPlot.Windows"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
        <oxy:PlotView Model="{Binding model, Mode=OneWay}"/>
    </Grid>
</Page>

The general idea behind this code is that graph one gets drawn and then the next one should overwrite it. If that happens, I know I can update it by firing similar functions in the future.

Body:
I've fixed it. I was too dumb to see the solution.

First of all we need this

public LineSeries lineserie { get; set; }

We add that to both BuildModels:

    public void BuildModel()
    {
        this.model = new PlotModel();

        this.lineserie = new LineSeries();
        this.lineserie.Points.Add(new DataPoint(0, 0));
        this.lineserie.Points.Add(new DataPoint(1, 70));
        this.lineserie.Points.Add(new DataPoint(2, 20));
        this.lineserie.Points.Add(new DataPoint(3, 20));

        this.model.Series.Add(lineserie);
        this.DataContext = this;
    }

Then we remove the old lineseries and add a new one, and then we update :)

    public void BuildModel2()
    {
        this.model.Series.Remove(this.lineserie);

        this.lineserie = new LineSeries();
        this.lineserie.Points.Add(new DataPoint(0, 0));
        this.lineserie.Points.Add(new DataPoint(1, 10));
        this.lineserie.Points.Add(new DataPoint(2, 80));
        this.lineserie.Points.Add(new DataPoint(3, 20));
        this.model.Series.Add(lineserie);
        this.model.InvalidatePlot(true);
    }

And we are good to go. It's basically working with the same object all the time while updating said object, without creating a new one.


问:
Eclipse Java Missing required source folder: 'src'
I imported a jar file into workspace and this is the error I get:

Description   Resource    Path    Location    Type

  Project 'Interpreter1' is missing required source folder: 'src'   Interpreter1        Build path  Build Path Problem

How can i get rid of this error?

答: Create the src folder in the project.</p>

ContentLicense: CC BY-SA 3.0

Body: Create the src folder in the project.


问:
JavaScript: Write Function That Executes Pig Latin on Phrase; Looping Through Appears to Give Strange Output
I am trying to write code that does pig latin.  The two main rules are as follows:

Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.

Rule 2: If a word begins with a consonant sound, move the consonant to the end of the word. Then finish by adding an "ay" sound to the end of the word.

There are some edge case rules that I'm not going to spell out here but are included in my code.

const pigify = (str) => {
  let sentSplit = str.split(' ')
  let newArray = [];

  for (let i = 0; i < sentSplit.length; i++) {
    let element = sentSplit[i]
    console.log(element)
    // counts 'qu' as a consonant even when it's preceded by a consonant
    if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) && (element.slice(1, 3) === 'qu')) {
      newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
    }

    // translates a word beginning with three consonants
    // counts 'sch' as a single phoneme
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[1]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[2]) ||
      (element.slice(0, 3) === 'sch')
    ) {
      newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
    }

    // translates a word beginning with two consonants
    // counts 'qu' as a single phoneme
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[1]) ||
      (element.slice(0, 2) === 'qu')
    ) {
      newArray.push(`${str.slice(2)}${str.slice(0,2)}ay`)
    }

    // translates a word beginning with a consonant
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
      newArray.push(`${str.slice(1)}${str[0]}ay`)
    }

    // translates a word beginning with a vowel
    else if (['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
      newArray.push(`${element}ay`)
    }
  }
  return newArray.join('')
}

const pigLatinString = pigify('the quick brown fox');
console.log(pigLatinString);```
</div>
</div>
</p>

<p>I expect the output of variable pigLatinString to be: </p>

```ethay ickquay ownbray oxfay
```

<p>but instead my code returns: </p>

```'e quick brown foxthaye quick brown foxthaye quick brown foxthayhe quick brown foxtay'
```

What am I doing wrong?

答:
Doesn't cover edge cases:

Consider breaking up different "tasks" into different "functions" for readability and debugging purposes.

  const startsWithVowel = letter => {
    const vowels = ['a', 'e', 'i', 'o', 'u'];
    if (vowels.includes(letter)) return true;
  };

  const turnPigLatin = str => {
    const firstLetter = str.charAt(0);
    if (startsWithVowel(firstLetter)) {
      return str + 'yay';
    } else {
      return str.substr(1) + str.charAt(0) + 'ay';
    }
  };

  const pigify = sentence => {
    const words = sentence.split(' ');
    return words.map(word => turnPigLatin(word)).join(' ');
  };

  console.log(pigify('The quick brown fox'));```

Body:
I am trying to write code that does pig latin.  The two main rules are as follows:

Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.

Rule 2: If a word begins with a consonant sound, move the consonant to the end of the word. Then finish by adding an "ay" sound to the end of the word.

There are some edge case rules that I'm not going to spell out here but are included in my code.

const pigify = (str) => {
  let sentSplit = str.split(' ')
  let newArray = [];

  for (let i = 0; i < sentSplit.length; i++) {
    let element = sentSplit[i]
    console.log(element)
    // counts 'qu' as a consonant even when it's preceded by a consonant
    if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) && (element.slice(1, 3) === 'qu')) {
      newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
    }

    // translates a word beginning with three consonants
    // counts 'sch' as a single phoneme
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[1]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[2]) ||
      (element.slice(0, 3) === 'sch')
    ) {
      newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
    }

    // translates a word beginning with two consonants
    // counts 'qu' as a single phoneme
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
      !['a', 'e', 'i', 'o', 'u'].includes(element[1]) ||
      (element.slice(0, 2) === 'qu')
    ) {
      newArray.push(`${str.slice(2)}${str.slice(0,2)}ay`)
    }

    // translates a word beginning with a consonant
    else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
      newArray.push(`${str.slice(1)}${str[0]}ay`)
    }

    // translates a word beginning with a vowel
    else if (['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
      newArray.push(`${element}ay`)
    }
  }
  return newArray.join('')
}

const pigLatinString = pigify('the quick brown fox');
console.log(pigLatinString);

I expect the output of variable pigLatinString to be:

ethay ickquay ownbray oxfay

but instead my code returns:

'e quick brown foxthaye quick brown foxthaye quick brown foxthayhe quick brown foxtay'

What am I doing wrong?


问:
API call working with `curl` does not work in Swift
I am getting a json file back from a http request:

```<code>[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]
</code>```

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }
```

<p>How can I get the array's item's content as a <code>[String:String]</code> dictionary? When I print <code>natRules</code>, the result looks like this:</p>

```[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]
```

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

答:
I failed to give an accurate enough sample of my json repsonse -- if there are key / value pairs with non-string values, a cast to [[String:Any]] is necessary:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [[String:Any]]
  else { return }
```

Thanks for all the valuable answers.

Body:
I am getting a json file back from a http request:

[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }

How can I get the array's item's content as a [String:String] dictionary? When I print natRules, the result looks like this:

[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

Body:
I failed to give an accurate enough sample of my json repsonse -- if there are key / value pairs with non-string values, a cast to [[String:Any]] is necessary:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [[String:Any]]
  else { return }

Thanks for all the valuable answers.


问:
How can I put Javascript code into a component of React?
How can I put this piece of code in only one of my React components?

```<code>
<!--
  Create a button that your customers click to complete their purchase. Customize the styling to suit your branding.
-->
<button
  style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
  id="checkout-button-sku_FAe7tbPK29byHW"
  role="link"
>
  Checkout
</button>

<div id="error-message"></div>

<script>
  var stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");
  var checkoutButton = document.getElementById(
    "checkout-button-sku_FAe7tbPK29byHW"
  );
  checkoutButton.addEventListener("click", function() {
    stripe
      .redirectToCheckout({
        items: [{ sku: "sku_FAe7tbPK29byHW", quantity: 1 }],
        successUrl:
          window.location.protocol + "//www.jobdirecto.com/jobConfirm",
        cancelUrl: window.location.protocol + "//www.jobdirecto.com/errorPage"
      })
      .then(function(result) {
        if (result.error) {
          var displayError = document.getElementById("error-message");
          displayError.textContent = result.error.message;
        }
      });
  });
</script>
</code>```

At the moment it is in index.js (where all the other script tags are) and it works correctly, but it appears in all the pages. I want it to appear only in one component but I'm not sure where to put it.

Should I create a function and put inside there? or should I put it somehow below the render part?

答:
To make that a React component it would become something like this:

```<code>import React, { useState } from 'react';

function Button() {
  const stripe = Stripe('pk_live_5PjwBk9dSdW7htTKHQ3HKrTd');

  const [error, setError] = useState();

  const handleClick = () => {
    stripe
      .redirectToCheckout({
        items: [{ sku: 'sku_FAe7tbPK29byHW', quantity: 1 }],
        successUrl: window.location.protocol + '//www.jobdirecto.com/jobConfirm',
        cancelUrl: window.location.protocol + '//www.jobdirecto.com/errorPage'
      }).then((result) => {
        if (result.error) {
          setError(result.error.message);
        }
      });
  }

  return (
    <div>
      <button onClick={handleClick}>Checkout</button>
      {!!error && <div>{error}</div>}
    </div>
  );
}

export default Button;
</code>```

Hope it helps you.

Body:
How can I put this piece of code in only one of my React components?

<button
  style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
  id="checkout-button-sku_FAe7tbPK29byHW"
  role="link"
>
  Checkout
</button>

At the moment it is in index.js (where all the other script tags are) and it works correctly, but it appears in all the pages. I want it to appear only in one component but I'm not sure where to put it.

Should I create a function and put inside there? or should I put it somehow below the render part?

Body:
To make that a React component it would become something like this:

import React, { useState } from 'react';

function Button() {
  const stripe = Stripe('pk_live_5PjwBk9dSdW7htTKHQ3HKrTd');

  const [error, setError] = useState();

  const handleClick = () => {
    stripe
      .redirectToCheckout({
        items: [{ sku: 'sku_FAe7tbPK29byHW', quantity: 1 }],
        successUrl: window.location.protocol + '//www.jobdirecto.com/jobConfirm',
        cancelUrl: window.location.protocol + '//www.jobdirecto.com/errorPage'
      }).then((result) => {
        if (result.error) {
          setError(result.error.message);
        }
      });
  }

  return (
    <div>
      <button onClick={handleClick}>Checkout</button>
      {!!error && <div>{error}</div>}
    </div>
  );
}

export default Button;

Hope it helps you.


问:
postgres truncate is slow
In postgres 9.2 (CentOS), TRUNCATE TABLE command occasionally took a really long time to run. One time, it took more than 1.5 hours to truncate a table with 100K records, even longer in other cases. This problem also happened when I used pgAdmin to truncate table. What is the possible cause? and how to improve the truncation performance?

There is 16GB of memory on the server and shared_buffers = 1536MB

答:
Check if the truncate was blocked by any query

```<code>SELECT
    activity.pid,
    activity.usename,
    activity.query,
    blocking.pid AS blocking_id,
    blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));
</code>```

If necessary terminate it
SELECT pg_terminate_backend(PID);

Title: postgres truncate is slow

Body:
Check if the truncate was blocked by any query

SELECT
    activity.pid,
    activity.usename,
    activity.query,
    blocking.pid AS blocking_id,
    blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));

If necessary terminate it
SELECT pg_terminate_backend(PID);


问:
convert from Color to brush
How do I convert a Color to a Brush in C#?

答:
This is for Color to Brush....

you can't convert it, you have to make a new brush....

```<code>SolidColorBrush brush = new SolidColorBrush( myColor );
</code>```

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

Title: convert from Color to brush

Body:
This is for Color to Brush....

you can't convert it, you have to make a new brush....

SolidColorBrush brush = new SolidColorBrush( myColor );

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding


问:
How to reload .bashrc settings without logging out and back in again?
If I make changes to .bashrc, how do I reload it without logging out and back in?

答:
exec bash is a great way to re-execute and launch a new shell to replace current. just to add to the answer, $SHELL returns the current shell which is bash. By using the following, it will reload the current shell, and not only to bash.

```<code>exec $SHELL -l;
</code>```

Body:
exec bash is a great way to re-execute and launch a new shell to replace current. just to add to the answer, $SHELL returns the current shell which is bash. By using the following, it will reload the current shell, and not only to bash.

exec $SHELL -l;


问:
My S3 life-cycle policy is not working, how can I debug?
I have a lifecycle policy setup in the AWS Console. In my S3 bucket, it has a folder called "backups". My policy has a prefix of "backups" and current and previous transition to glacier set to 1 day after creation. S3 files are still shown as Standard and nothing in Glacier.

I have waited a month to see if it was slow. But nothing happens.

答:
To test this, I did the following:

Created a new Amazon S3 bucket

Created a backups folder through the S3 management console

Uploaded a file to the backups folder

Added a Lifecycle Rule with a filter of backups (displayed in the console as "prefix backups" for current version to Glacier after 1 day

I then waited a couple of days and it transitioned to Glacier:

Bottom line: It can take a couple of days for the transition to happen.


问:
jquery terminal: how to echo to terminal upon AJAX completion?
jquery terminal should echo out to screen upon ajax GET completion. Currently, the terminal.echo wont fire inside a success callback

Tried setting CORS but still wont output. this is a client problem.

```<code>jQuery(function ($, undefined) {
    $('body').terminal({
        register: function (email, user, pw) {
            this.echo("register...")
            jQuery.ajax({
                url: "https://faf3fg.execute-api.us-west-2.amazonaws.com/api/register/" + email +
                    '/' + user + '/' + pw,
                crossDomain: true,
                success: function (result) {
                    this.echo(data);
                    console.log(data);
                },
                async: false
            });
        }
    },{
        greetings: 'say',
        name: 'sterm',
        height: $('body').height(),
        width: $('body').width(),
        prompt: 'sss> ',
        completion: true
    });
});
</code>```

I expected it to return the response of the AJAX request at a later time but this seems to be unsupported.

答:
The this keyword doesn't mean what you think it means here:

```<code>success: function (result) {
    this.echo(data);
    console.log(data);
}
</code>```

This code is invoked long after the code in which is was being set, and this no longer refers to your terminal instance.  It now refers to the jqXHR object (the internals of the AJAX request/response).

You can capture that instance in a variable, which would retain that reference for later.  Something like this:

```<code>var terminal = this;
terminal.echo("register...");
jQuery.ajax({
    //...
    success: function (result) {
        terminal.echo(data);
         console.log(data);
    }
});
</code>```

Side note: You should remove async:false from your code.  Not only is it a famously bad idea, but it's actively being deprecated from browsers.  I wouldn't be surprised if there are browsers in common use already which don't support it.

Keep your asynchronous code asynchronous.

Body:
jquery terminal should echo out to screen upon ajax GET completion. Currently, the terminal.echo wont fire inside a success callback

Tried setting CORS but still wont output. this is a client problem.

jQuery(function ($, undefined) {
    $('body').terminal({
        register: function (email, user, pw) {
            this.echo("register...")
            jQuery.ajax({
                url: "https://faf3fg.execute-api.us-west-2.amazonaws.com/api/register/" + email +
                    '/' + user + '/' + pw,
                crossDomain: true,
                success: function (result) {
                    this.echo(data);
                    console.log(data);
                },
                async: false
            });
        }
    },{
        greetings: 'say',
        name: 'sterm',
        height: $('body').height(),
        width: $('body').width(),
        prompt: 'sss> ',
        completion: true
    });
});

I expected it to return the response of the AJAX request at a later time but this seems to be unsupported.

Body:
The this keyword doesn't mean what you think it means here:

success: function (result) {
    this.echo(data);
    console.log(data);
}

This code is invoked long after the code in which is was being set, and this no longer refers to your terminal instance.  It now refers to the jqXHR object (the internals of the AJAX request/response).

You can capture that instance in a variable, which would retain that reference for later.  Something like this:

var terminal = this;
terminal.echo("register...");
jQuery.ajax({
    //...
    success: function (result) {
        terminal.echo(data);
         console.log(data);
    }
});

Side note: You should remove async:false from your code.  Not only is it a famously bad idea, but it's actively being deprecated from browsers.  I wouldn't be surprised if there are browsers in common use already which don't support it.

Keep your asynchronous code asynchronous.


问:
pyparsing how to use infixNotation for representing iif(cond, if true, if false)
I need to parse this using pyparsing: iif(condition,value if true,value if false), but this kind of ternary comparisson shall have another comparisson, I mean:

```<code>`iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)`
</code>```

I found this:

```<code>integer = Word(nums)
variable = Word(alphas, alphanums)
boolLiteral = oneOf("true false")
operand = boolLiteral | variable | integer
comparison_op = oneOf("== <= >= != < >")
QM,COLON = map(Literal,"?:")
expr = infixNotation(operand,
    [
    (comparison_op, 2, opAssoc.LEFT),
    ((QM,COLON), 3, opAssoc.LEFT),
    ])
</code>```

which is able to parse this:
expr.parseString("(x==1? true: (y == 10? 100 : 200) )")

but I was unable to modify this code to fit my needs. How can I achieve this?

UPDATE

Thanks to Mr. Paul I came up with this solution:

```<code>arith_expr = Forward()

iif = CaselessKeyword("iif")
    open = Literal("(")
    close = Literal(")")

    var_name = pyparsing_common.identifier()
    fn_call = Group(iif + open - Group(Optional(delimitedList(arith_expr))) + close)
    arith_operand = fn_call | num

    rel_comparison_operator = oneOf("< > <= >=")
    eq_comparison_operator = oneOf("== !=")
    plus_minus_operator = oneOf("+ -")
    mult_div_operator = oneOf("* / %")

    arith_expr <<= infixNotation(arith_operand,
                                    [
                                        # add other operators here - in descending order of precedence
                                        # http://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm
                                        ('-', 1, opAssoc.RIGHT),
                                        (mult_div_operator, 2, opAssoc.LEFT,),
                                        (plus_minus_operator, 2, opAssoc.LEFT,),
                                        (rel_comparison_operator, 2, opAssoc.LEFT,),
                                        (eq_comparison_operator, 2, opAssoc.LEFT,),
                                    ]
                                    )
</code>```

I'm using some of my previous rules. Now I'm voting to close this post.

答:
As @sepp2k mentions in his comment, the string you are trying to parse isn't infix notation, although you may end up using as an operand in infix notation. And the arguments you pass to iif may themselves be infix notation expressions. So infix notation will definitely be part of this parser, but it won't be the part that parses your iif function call.

Here is how the function call would look in pyparsing:

```<code>fn_call = pp.Group(var_name + LPAREN - pp.Group(pp.Optional(pp.delimitedList(arith_expr))) + RPAREN)
</code>```

The operands you use to define an arithmetic expression could themselves include a function call, so the parser's recursion will require you to use pyparsing's Forward class.

```<code>arith_expr = pp.Forward()
</code>```

This will allow you to use arith_expr in other sub-expressions (like we just did in fn_call) before we have fully defined just what arith_expr looks like.

Cutting to the chase, here is a minimal parser to parse your iif function:

```<code>import pyparsing as pp

# for recursive infix notations, or those with many precedence levels, it is best to enable packrat parsing
pp.ParserElement.enablePackrat()
LPAREN, RPAREN = map(pp.Suppress, "()")

arith_expr= pp.Forward()

var_name = pp.pyparsing_common.identifier()
integer = pp.pyparsing_common.integer()
fn_call = pp.Group(var_name + LPAREN - pp.Group(pp.Optional(pp.delimitedList(arith_expr))) + RPAREN)
arith_operand = fn_call | var_name | integer

rel_comparison_operator = pp.oneOf("< > <= >=")
eq_comparison_operator = pp.oneOf("== !=")
plus_minus_operator = pp.oneOf("+ -")
mult_div_operator = pp.oneOf("* / %")

arith_expr <<= pp.infixNotation(arith_operand,
                                [
                                    # add other operators here - in descending order of precedence
                                    # http://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm
                                    (mult_div_operator, 2, pp.opAssoc.LEFT,),
                                    (plus_minus_operator, 2, pp.opAssoc.LEFT,),
                                    (rel_comparison_operator, 2, pp.opAssoc.LEFT,),
                                    (eq_comparison_operator, 2, pp.opAssoc.LEFT,),
                                ]
                                )
</code>```

Using runTests, we can try it out against a few test cases:

```<code>tests = """\
    cos(60)
    sqrt(1 - sin(60) * sin(60))
    divmod(a, 100)
    iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)
    """
arith_expr.runTests(tests)
</code>```

Prints:

```<code>cos(60)
[['cos', [60]]]
[0]:
  ['cos', [60]]
  [0]:
    cos
  [1]:
    [60]

sqrt(1 - sin(60) * sin(60))
[['sqrt', [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]]]
[0]:
  ['sqrt', [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]]
  [0]:
    sqrt
  [1]:
    [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]
    [0]:
      [1, '-', [['sin', [60]], '*', ['sin', [60]]]]
      [0]:
        1
      [1]:
        -
      [2]:
        [['sin', [60]], '*', ['sin', [60]]]
        [0]:
          ['sin', [60]]
          [0]:
            sin
          [1]:
            [60]
        [1]:
          *
        [2]:
          ['sin', [60]]
          [0]:
            sin
          [1]:
            [60]

divmod(a, 100)
[['divmod', ['a', 100]]]
[0]:
  ['divmod', ['a', 100]]
  [0]:
    divmod
  [1]:
    ['a', 100]

iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)
[['iif', [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']]]
[0]:
  ['iif', [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']]
  [0]:
    iif
  [1]:
    [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']
    [0]:
      [['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]]
      [0]:
        ['iif', ['condition1', 'value1', 'value2']]
        [0]:
          iif
        [1]:
          ['condition1', 'value1', 'value2']
      [1]:
        >
      [2]:
        ['iif', ['condition2', 'value1', 'value2']]
        [0]:
          iif
        [1]:
          ['condition2', 'value1', 'value2']
    [1]:
      value3
    [2]:
      value4
</code>```

Body:
I need to parse this using pyparsing: iif(condition,value if true,value if false), but this kind of ternary comparisson shall have another comparisson, I mean:

`iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)`

I found this:

integer = Word(nums)
variable = Word(alphas, alphanums)
boolLiteral = oneOf("true false")
operand = boolLiteral | variable | integer
comparison_op = oneOf("== <= >= != < >")
QM,COLON = map(Literal,"?:")
expr = infixNotation(operand,
    [
    (comparison_op, 2, opAssoc.LEFT),
    ((QM,COLON), 3, opAssoc.LEFT),
    ])

which is able to parse this:
expr.parseString("(x==1? true: (y == 10? 100 : 200) )")

but I was unable to modify this code to fit my needs. How can I achieve this?

UPDATE

Thanks to Mr. Paul I came up with this solution:

arith_expr = Forward()

iif = CaselessKeyword("iif")
    open = Literal("(")
    close = Literal(")")

    var_name = pyparsing_common.identifier()
    fn_call = Group(iif + open - Group(Optional(delimitedList(arith_expr))) + close)
    arith_operand = fn_call | num

    rel_comparison_operator = oneOf("< > <= >=")
    eq_comparison_operator = oneOf("== !=")
    plus_minus_operator = oneOf("+ -")
    mult_div_operator = oneOf("* / %")

    arith_expr <<= infixNotation(arith_operand,
                                    [
                                        # add other operators here - in descending order of precedence
                                        # http://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm
                                        ('-', 1, opAssoc.RIGHT),
                                        (mult_div_operator, 2, opAssoc.LEFT,),
                                        (plus_minus_operator, 2, opAssoc.LEFT,),
                                        (rel_comparison_operator, 2, opAssoc.LEFT,),
                                        (eq_comparison_operator, 2, opAssoc.LEFT,),
                                    ]
                                    )

I'm using some of my previous rules. Now I'm voting to close this post.

Body:
As @sepp2k mentions in his comment, the string you are trying to parse isn't infix notation, although you may end up using as an operand in infix notation. And the arguments you pass to iif may themselves be infix notation expressions. So infix notation will definitely be part of this parser, but it won't be the part that parses your iif function call.

Here is how the function call would look in pyparsing:

fn_call = pp.Group(var_name + LPAREN - pp.Group(pp.Optional(pp.delimitedList(arith_expr))) + RPAREN)

The operands you use to define an arithmetic expression could themselves include a function call, so the parser's recursion will require you to use pyparsing's Forward class.

arith_expr = pp.Forward()

This will allow you to use arith_expr in other sub-expressions (like we just did in fn_call) before we have fully defined just what arith_expr looks like.

Cutting to the chase, here is a minimal parser to parse your iif function:

import pyparsing as pp

# for recursive infix notations, or those with many precedence levels, it is best to enable packrat parsing
pp.ParserElement.enablePackrat()
LPAREN, RPAREN = map(pp.Suppress, "()")

arith_expr= pp.Forward()

var_name = pp.pyparsing_common.identifier()
integer = pp.pyparsing_common.integer()
fn_call = pp.Group(var_name + LPAREN - pp.Group(pp.Optional(pp.delimitedList(arith_expr))) + RPAREN)
arith_operand = fn_call | var_name | integer

rel_comparison_operator = pp.oneOf("< > <= >=")
eq_comparison_operator = pp.oneOf("== !=")
plus_minus_operator = pp.oneOf("+ -")
mult_div_operator = pp.oneOf("* / %")

arith_expr <<= pp.infixNotation(arith_operand,
                                [
                                    # add other operators here - in descending order of precedence
                                    # http://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm
                                    (mult_div_operator, 2, pp.opAssoc.LEFT,),
                                    (plus_minus_operator, 2, pp.opAssoc.LEFT,),
                                    (rel_comparison_operator, 2, pp.opAssoc.LEFT,),
                                    (eq_comparison_operator, 2, pp.opAssoc.LEFT,),
                                ]
                                )

Using runTests, we can try it out against a few test cases:

tests = """\
    cos(60)
    sqrt(1 - sin(60) * sin(60))
    divmod(a, 100)
    iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)
    """
arith_expr.runTests(tests)

Prints:

cos(60)
[['cos', [60]]]
[0]:
  ['cos', [60]]
  [0]:
    cos
  [1]:
    [60]

sqrt(1 - sin(60) * sin(60))
[['sqrt', [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]]]
[0]:
  ['sqrt', [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]]
  [0]:
    sqrt
  [1]:
    [[1, '-', [['sin', [60]], '*', ['sin', [60]]]]]
    [0]:
      [1, '-', [['sin', [60]], '*', ['sin', [60]]]]
      [0]:
        1
      [1]:
        -
      [2]:
        [['sin', [60]], '*', ['sin', [60]]]
        [0]:
          ['sin', [60]]
          [0]:
            sin
          [1]:
            [60]
        [1]:
          *
        [2]:
          ['sin', [60]]
          [0]:
            sin
          [1]:
            [60]

divmod(a, 100)
[['divmod', ['a', 100]]]
[0]:
  ['divmod', ['a', 100]]
  [0]:
    divmod
  [1]:
    ['a', 100]

iif(iif(condition1,value1,value2)>iif(condition2,value1,value2),value3,value4)
[['iif', [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']]]
[0]:
  ['iif', [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']]
  [0]:
    iif
  [1]:
    [[['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]], 'value3', 'value4']
    [0]:
      [['iif', ['condition1', 'value1', 'value2']], '>', ['iif', ['condition2', 'value1', 'value2']]]
      [0]:
        ['iif', ['condition1', 'value1', 'value2']]
        [0]:
          iif
        [1]:
          ['condition1', 'value1', 'value2']
      [1]:
        >
      [2]:
        ['iif', ['condition2', 'value1', 'value2']]
        [0]:
          iif
        [1]:
          ['condition2', 'value1', 'value2']
    [1]:
      value3
    [2]:
      value4


问:
How do I turn oddly shaped arrays into a tensor
I have a bunch of numpy arrays with different shapes and dimensions, and I need to turn it all into one tensorflow tensor as input to a neural network.

I'm trying to use this network on a reinforcement learning problem, and at each time step it needs a single tensor. I have six numpy arrays, here are their shapes: (26,) (7,) (2,) (7,) (2,) (9,7). I've put them all into one array of shape (6,), but when I try to create a tf.constant with them, I run into problems.

#here are the numpy arrays

in1_ = np.zeros((26,), dtype='int')
in2_ = np.zeros((7,), dtype='int')
in3_ = np.zeros((2,), dtype='int')
in4_ = np.zeros((7,), dtype='int')
in5_ = np.zeros((2,), dtype='int')
in6_ = np.zeros((9,7), dtype='int')

#in practice the arrays would contain data, not just zeros

final_array = np.array([in1_, in2_, in3_, in4_, in5_, in6_])
final_array.shape
>>>(6,)
#so I can create the big array, but I get an error when creating
#a tf.constant

const = tf.constant(final_array)
>>>TypeError: Expected binary or unicode string, got array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
```

I know that both tensors and numpy arrays have to be rectangular, so I thought that converting an array to a tensor would be simple. I can actually make it work if i use strings instead of arrays, but for my purposes it would be better not to do that.

答:
Instead of an array containing integers you have created an array containing other arrays (note that final_array.dtype is not dtype('int64')). This is possible for numpy arrays, but not possible for tensorflow arrays (a tensorflow array can't contain other tensorflow arrays). This is why you get an error when you try to convert it.

There is no way around this, tensorflow will not allow to have not matching dimension sizes. But since you want to use those arrays as an input to your network you can combine them into one array first and convert them afterwards:

```<code>final_array = np.concatenate((in1_, in2_, in3_, in4_, in5_, in6_.reshape(-1)))
const = tf.constant(final_array)
</code>```

Body:
I have a bunch of numpy arrays with different shapes and dimensions, and I need to turn it all into one tensorflow tensor as input to a neural network.

I'm trying to use this network on a reinforcement learning problem, and at each time step it needs a single tensor. I have six numpy arrays, here are their shapes: (26,) (7,) (2,) (7,) (2,) (9,7). I've put them all into one array of shape (6,), but when I try to create a tf.constant with them, I run into problems.

#here are the numpy arrays

in1_ = np.zeros((26,), dtype='int')
in2_ = np.zeros((7,), dtype='int')
in3_ = np.zeros((2,), dtype='int')
in4_ = np.zeros((7,), dtype='int')
in5_ = np.zeros((2,), dtype='int')
in6_ = np.zeros((9,7), dtype='int')

#in practice the arrays would contain data, not just zeros

final_array = np.array([in1_, in2_, in3_, in4_, in5_, in6_])
final_array.shape
>>>(6,)
#so I can create the big array, but I get an error when creating
#a tf.constant

const = tf.constant(final_array)
>>>TypeError: Expected binary or unicode string, got array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

I know that both tensors and numpy arrays have to be rectangular, so I thought that converting an array to a tensor would be simple. I can actually make it work if i use strings instead of arrays, but for my purposes it would be better not to do that.

Body:
Instead of an array containing integers you have created an array containing other arrays (note that final_array.dtype is not dtype('int64')). This is possible for numpy arrays, but not possible for tensorflow arrays (a tensorflow array can't contain other tensorflow arrays). This is why you get an error when you try to convert it.

There is no way around this, tensorflow will not allow to have not matching dimension sizes. But since you want to use those arrays as an input to your network you can combine them into one array first and convert them afterwards:

final_array = np.concatenate((in1_, in2_, in3_, in4_, in5_, in6_.reshape(-1)))
const = tf.constant(final_array)


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
Since you aren't changing the value of arr inside the function, there's no need to pass the address by reference.  If you did mean to change the value, you need to add a new line of code before the return newArray:

```<code>arr = newArray;
</code>```

If the typical calling pattern is

```<code>arr = expand(arr, arr_size);
</code>```

then you'll also need to watch out for options that ignore aliasing.  And you'll have to make assumptions within expand that size is always doubled, and keep track of that yourself outside of it.

Also, your code has a terrible bug.  size is doubled, and then used as the array limit for the source array.   Then it leaks the memory that was previously allocated for arr. This is a good reason why people use std::vector. :-)  Most of the bugs are out of that library, by now.

```<code>void expand_in_place(int *&arr, int& size)
{
    const new_size = size * 2;
    int *new_array = new int[new_size];

    for (int index = 0; index < size; index++)
        new_array[index] = arr[index];

    delete[] arr;
    arr = newArray;
    size = new_size;
}
</code>```

If you were using malloc and free instead of new [] and delete [], you could use realloc.

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}

Body:
Since you aren't changing the value of arr inside the function, there's no need to pass the address by reference.  If you did mean to change the value, you need to add a new line of code before the return newArray:

arr = newArray;

If the typical calling pattern is

arr = expand(arr, arr_size);

then you'll also need to watch out for options that ignore aliasing.  And you'll have to make assumptions within expand that size is always doubled, and keep track of that yourself outside of it.

Also, your code has a terrible bug.  size is doubled, and then used as the array limit for the source array.   Then it leaks the memory that was previously allocated for arr. This is a good reason why people use std::vector. :-)  Most of the bugs are out of that library, by now.

void expand_in_place(int *&arr, int& size)
{
    const new_size = size * 2;
    int *new_array = new int[new_size];

    for (int index = 0; index < size; index++)
        new_array[index] = arr[index];

    delete[] arr;
    arr = newArray;
    size = new_size;
}

If you were using malloc and free instead of new [] and delete [], you could use realloc.


问:
Xamarin In App Billing Plugin could not connect
I have used this plugin: https://github.com/jamesmontemagno/InAppBillingPlugin to implement the in app billing since the component was removed.
I have installed the nuget: Plugin.InAppBilling

In the Android, I have create a class called InAppBillingService where I implement here to get the products and purchase an item. Here are the codes:

```<code>var billing = CrossInAppBilling.Current;
var connected = await billing.ConnectAsync();
</code>```

And it returns false everytime. I could not connect.

I have added in my AndroidManifest this:

```<code>uses-permission android:name="com.android.vending.BILLING" />
</code>```

And in the MainActivity:

```<code>protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            InAppBillingImplementation.HandleActivityResult(requestCode, resultCode, data);
        }
</code>```

And in onCreate: CrossCurrentActivity.Current.Init(this, bundle);

Please advice what else I should do so that I could connect. And what are other reasons why it always return false when tried to connect. I'm testing in emulator. Thank you.

答:
I'm testing in emulator.

That's the reason of the problem. As written here, Billing does not work on Android emulators. Use a real device.

Body:
I have used this plugin: https://github.com/jamesmontemagno/InAppBillingPlugin to implement the in app billing since the component was removed.
I have installed the nuget: Plugin.InAppBilling

In the Android, I have create a class called InAppBillingService where I implement here to get the products and purchase an item. Here are the codes:

var billing = CrossInAppBilling.Current;
var connected = await billing.ConnectAsync();

And it returns false everytime. I could not connect.

I have added in my AndroidManifest this:

uses-permission android:name="com.android.vending.BILLING" />

And in the MainActivity:

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            InAppBillingImplementation.HandleActivityResult(requestCode, resultCode, data);
        }

And in onCreate: CrossCurrentActivity.Current.Init(this, bundle);

Please advice what else I should do so that I could connect. And what are other reasons why it always return false when tried to connect. I'm testing in emulator. Thank you.


问:
os.system('cls') opens up command prompt instead of clearing the shell?
I'm working on a text adventure game using Python that has character-by-character scrolling text. So, I made this to try and give off the illusion of adding one character every loop, and deleting the last, less complete string. However, instead of deleting the last screen, it opens up command prompt.

I've tried using print('n\ * 100') and other such printing tricks, but it doesn't have the result I'm looking for. I've also tried switching between 'cls' and 'clear' in case I've been doing it wrong, but even when I made an if statement citing a difference between the two I'm still getting errors.

while charcount < len(text):

```<code>if os.name == 'nt':

  os.system('cls')

else:

  os.system('clear')

newtext.append(text[charcount])

print("".join(newtext))

charcount += 1
</code>```

I expected the screen to clear and only print newtext's current iteration, but instead it ignores this, does not clear the screen, and repeatedly opens and closes command prompt.

答:
Your code works fine in CMD and PowerShell.

That makes me assume that you are using IDLE because the behavior you stated is reproducible only when I use IDLE.

If that's the case, it's not possible to clear IDLE window. You can still use CMD and it would work just fine.

Refer Any way to clear python's IDLE window?

Body:
I'm working on a text adventure game using Python that has character-by-character scrolling text. So, I made this to try and give off the illusion of adding one character every loop, and deleting the last, less complete string. However, instead of deleting the last screen, it opens up command prompt.

I've tried using print('n\ * 100') and other such printing tricks, but it doesn't have the result I'm looking for. I've also tried switching between 'cls' and 'clear' in case I've been doing it wrong, but even when I made an if statement citing a difference between the two I'm still getting errors.

while charcount < len(text):

if os.name == 'nt':

  os.system('cls')

else:

  os.system('clear')

newtext.append(text[charcount])

print("".join(newtext))

charcount += 1

I expected the screen to clear and only print newtext's current iteration, but instead it ignores this, does not clear the screen, and repeatedly opens and closes command prompt.


问:
Setting textbox encoding in Windows Forms
When I try to get some text from file and display it in textbox it is okay until I want to write Czech characters (e. g. čšž). They show up like: Moj� nejv�t�� z�libou je �e�en� koresponden�n�ch semin���

Should I set encoding to loaded text just before I assign it to textBox1.text or it is possible to change encoding of textBox1.Text itself?

I use following code:

```<code>textBox1.Text = File.ReadAllText(file);
</code>```

答:
Try to force the encoding (the machine default should be OK, if you don't know the correct one):

```<code>textBox1.Text = File.ReadAllText(file,Encoding.Default);
</code>```

Anyway, being Czech I guess your current default encoding is "Western European (Windows)" (you can get it also doing Encoding.GetEncoding(1252))

That is also the one on my pc (I have an Italian version of Win7).

Body:
When I try to get some text from file and display it in textbox it is okay until I want to write Czech characters (e. g. čšž). They show up like: Moj� nejv�t�� z�libou je �e�en� koresponden�n�ch semin���

Should I set encoding to loaded text just before I assign it to textBox1.text or it is possible to change encoding of textBox1.Text itself?

I use following code:

textBox1.Text = File.ReadAllText(file);

Body:
Try to force the encoding (the machine default should be OK, if you don't know the correct one):

textBox1.Text = File.ReadAllText(file,Encoding.Default);

Anyway, being Czech I guess your current default encoding is "Western European (Windows)" (you can get it also doing Encoding.GetEncoding(1252))

That is also the one on my pc (I have an Italian version of Win7).


问:
How can I overcome this list.append problem (list.pop)
I have come across a very interesting problem with list.append and list.pop as in the code below

```<code>x = [1,2]
y = []
y.append(x)
print(y)
print("------")
x.pop()
print(y)
</code>```

Output is

```<code>[[1, 2]]
------
[[1]]
</code>```

Is there any way to maintain print(y) as [[1,2]]
Thanks

EDIT: Also, does anyone know why this happens?

答:
When you do

```<code>y.append(x)
</code>```

You are adding a reference to the x object into the y list. When you do x.pop(), you are doing that operation on all references of x, which includes the one within  y.

To make a separate copy of that list, you can either do

```<code>y.append(x[:])
</code>```

Which is a slice returning all items in the list - a copy, essentially. If you do not like this syntax and you are in Python 3, you can use

```<code>y.append(x.copy())
</code>```

This may be a bit clearer in your code. See this answer for a few more alternatives to copy a list.

Body:
I have come across a very interesting problem with list.append and list.pop as in the code below

x = [1,2]
y = []
y.append(x)
print(y)
print("------")
x.pop()
print(y)

Output is

[[1, 2]]
------
[[1]]

Is there any way to maintain print(y) as [[1,2]]
Thanks

EDIT: Also, does anyone know why this happens?

Body:
When you do

y.append(x)

You are adding a reference to the x object into the y list. When you do x.pop(), you are doing that operation on all references of x, which includes the one within  y.

To make a separate copy of that list, you can either do

y.append(x[:])

Which is a slice returning all items in the list - a copy, essentially. If you do not like this syntax and you are in Python 3, you can use

y.append(x.copy())

This may be a bit clearer in your code. See this answer for a few more alternatives to copy a list.


问:
Why is Array.apply() setup resulting in an undefined index?
In a constructor, I'm creating a two dimensional array like so:

```<code>this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
</code>```

After i console.log(this.grid) I get a two-dimensional array with the objects and null properties. however if I try to console.log(JSON.stringify(this.grid[0][1])) there's an undefined error on [1]

class Grid {
  constructor() {
    this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
// used in another external class with require() and instantiated like:
let grid = new Grid();

console.log(grid);
console.log(JSON.stringify(grid[0][1]))```
</div>
</div>
</p>

<p>I understand some differences between constructing arrays with the constructor, and using Array.apply(). Maybe I'm using apply() incorrectly?</p>

<p>I've attempted constructing this array in multiple ways. from a nested for-loop where <code>.push()</code>ing the same objects to the second dimension and then each row the grid. </p>

```this.grid = []
    for(let i = 0; i < 3; ++i){
      let row = []
      for( let j =0; j< 3; ++j) {
        let obj = {
          key1: "property",
          key2: "property"
        }
        row.push(obj);
      }
      this.grid.push(row);
    }
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Grid {
  constructor() {
    this.grid = [];
    for (let i = 0; i < 3; ++i) {
      let row = [];
      for (let j = 0; j < 3; ++j) {
        let obj = {
          key1: null,
          key2: null
        };
        row.push(obj);
      }
      this.grid.push(row);
    }
  }
 }
 // used in another external class file with a require() and instantiation like so:
 let grid = new Grid();
console.log(JSON.stringify(grid[0][1]));</code>```

I expect the log to show the object at those respective indices. However, JSON.stringify(this.grid[0][1]) is still:

TypeError: Cannot read property '1' of undefined

答:
The variable named grid has a property named grid, which is the outer array containing the inner arrays. So, to reference the inner arrays, access grid.grid. Otherwise, just referencing grid gives you the instance, not the outer array.

class Grid {
  constructor() {
    this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
// used in another external class with require() and instantiated like:
let grid = new Grid();

console.log(JSON.stringify(grid.grid[0][1]))```
</div>
</div>
</p>

<p>It might be clearer if the instance had a method on it, like <code>printGrid</code> which printed the grid. Then, it would make sense that you would call <code>grid.printGrid</code> to print the grid, and you would reference <code>grid.grid</code> to get to the outer array (and <code>grid</code> itself is clearly just the instance).</p>

<p>To reduce this sort of confusion, you might consider using a different property name, like <code>outerArray</code> (or a different class name).</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Grid {
  constructor() {
    this.outerArray = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
const gridInstance = new Grid();

console.log(JSON.stringify(gridInstance.outerArray[0][1]))</code>```

Body:
In a constructor, I'm creating a two dimensional array like so:

this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });

After i console.log(this.grid) I get a two-dimensional array with the objects and null properties. however if I try to console.log(JSON.stringify(this.grid[0][1])) there's an undefined error on [1]

class Grid {
  constructor() {
    this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
// used in another external class with require() and instantiated like:
let grid = new Grid();

console.log(grid);
console.log(JSON.stringify(grid[0][1]))

I understand some differences between constructing arrays with the constructor, and using Array.apply(). Maybe I'm using apply() incorrectly?

I've attempted constructing this array in multiple ways. from a nested for-loop where .push()ing the same objects to the second dimension and then each row the grid.

this.grid = []
    for(let i = 0; i < 3; ++i){
      let row = []
      for( let j =0; j< 3; ++j) {
        let obj = {
          key1: "property",
          key2: "property"
        }
        row.push(obj);
      }
      this.grid.push(row);
    }

class Grid {
  constructor() {
    this.grid = [];
    for (let i = 0; i < 3; ++i) {
      let row = [];
      for (let j = 0; j < 3; ++j) {
        let obj = {
          key1: null,
          key2: null
        };
        row.push(obj);
      }
      this.grid.push(row);
    }
  }
 }
 // used in another external class file with a require() and instantiation like so:
 let grid = new Grid();
console.log(JSON.stringify(grid[0][1]));

I expect the log to show the object at those respective indices. However, JSON.stringify(this.grid[0][1]) is still:

TypeError: Cannot read property '1' of undefined

Body:
The variable named grid has a property named grid, which is the outer array containing the inner arrays. So, to reference the inner arrays, access grid.grid. Otherwise, just referencing grid gives you the instance, not the outer array.

class Grid {
  constructor() {
    this.grid = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
// used in another external class with require() and instantiated like:
let grid = new Grid();

console.log(JSON.stringify(grid.grid[0][1]))

It might be clearer if the instance had a method on it, like printGrid which printed the grid. Then, it would make sense that you would call grid.printGrid to print the grid, and you would reference grid.grid to get to the outer array (and grid itself is clearly just the instance).

To reduce this sort of confusion, you might consider using a different property name, like outerArray (or a different class name).

class Grid {
  constructor() {
    this.outerArray = Array.apply(null, Array(3)).map((el, i) => {
      return Array.apply(null, Array(3)).map((el, i) => {
        return {
          key1: null,
          key2: null
        };
      });
    });
  }
}
const gridInstance = new Grid();

console.log(JSON.stringify(gridInstance.outerArray[0][1]))


问:
Python: Unable to open excel file using openpyxl -- file exists and is in right location
I am trying to code a simple script to copy and paste data in an excel file. I am first changing the working directory to the directory with the excel file, and then attempting to open the only excel file in that folder with openpyxl. I am recieving an error in trying to do so. I will post my code, and the line of the openpyxl module that throws the error.

```<code>import openpyxl
import os

os.chdir('C:/Users/Emily Renda/Documents/ExcelWS/Driver Payroll/New Weeks')

wb = openpyxl.load_workbook("Python.xlsx")
sheet = wb.get_sheet_by_name("Payroll")
</code>```

This code fails on the "wb = .." line and throws the following error:

```<code>File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\drawing\image.py", line 27, in _import_image import Image as PILImage
ModuleNotFoundError: No module named 'Image'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\drawing\image.py", line 29, in _import_image
    from PIL import Image as PILImage
ModuleNotFoundError: No module named 'PIL'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Emily
Renda/PycharmProjects/payrollExcel/writeExcelFromJava.py", line 6, in
 <module>
    wb = openpyxl.load_workbook("Python.xlsx")
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\reader\excel.py", line 275, in load_workbook
     charts, images = find_images(archive, rel.target)
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
  packages\openpyxl\reader\drawings.py", line 47, in find_images
     image = Image(BytesIO(archive.read(dep.target)))
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
 packages\openpyxl\drawing\image.py", line 51, in __init__
    image = _import_image(img)
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
 packages\openpyxl\drawing\image.py", line 31, in _import_image
    raise ImportError('You must install PIL to fetch image objects')
 ImportError: You must install PIL to fetch image objects
</code>```

The line of code that throws this error is:

```<code>     self.fp = io.open(file, filemode)
</code>```

within the openpyxl module. I am coming here as a last resort, I have debugged for about an hour and cannot figure out how this error is occuring (although I am new to python)

答: Your excel file have an image. I had the same error code, deleted the images in the workbook and that worked out. </p>

Body:
I am trying to code a simple script to copy and paste data in an excel file. I am first changing the working directory to the directory with the excel file, and then attempting to open the only excel file in that folder with openpyxl. I am recieving an error in trying to do so. I will post my code, and the line of the openpyxl module that throws the error.

import openpyxl
import os

os.chdir('C:/Users/Emily Renda/Documents/ExcelWS/Driver Payroll/New Weeks')

wb = openpyxl.load_workbook("Python.xlsx")
sheet = wb.get_sheet_by_name("Payroll")

This code fails on the "wb = .." line and throws the following error:

File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\drawing\image.py", line 27, in _import_image import Image as PILImage
ModuleNotFoundError: No module named 'Image'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\drawing\image.py", line 29, in _import_image
    from PIL import Image as PILImage
ModuleNotFoundError: No module named 'PIL'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Emily
Renda/PycharmProjects/payrollExcel/writeExcelFromJava.py", line 6, in
 <module>
    wb = openpyxl.load_workbook("Python.xlsx")
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
packages\openpyxl\reader\excel.py", line 275, in load_workbook
     charts, images = find_images(archive, rel.target)
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
  packages\openpyxl\reader\drawings.py", line 47, in find_images
     image = Image(BytesIO(archive.read(dep.target)))
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
 packages\openpyxl\drawing\image.py", line 51, in __init__
    image = _import_image(img)
   File "C:\Users\Emily Renda\PycharmProjects\payrollExcel\venv\lib\site-
 packages\openpyxl\drawing\image.py", line 31, in _import_image
    raise ImportError('You must install PIL to fetch image objects')
 ImportError: You must install PIL to fetch image objects

The line of code that throws this error is:

     self.fp = io.open(file, filemode)

within the openpyxl module. I am coming here as a last resort, I have debugged for about an hour and cannot figure out how this error is occuring (although I am new to python)


问:
Embed PDF at full height
My question ... is it possible to embed a PDF in a HTML document where the height is always 100%. The problem is the actual height of the pdf could vary and the layout needs to respond to this. </p>

答:
I like the functionality that comes with the html objects for PDFs as opposed to some libraries like PDF.js for light projects. This is definitely not the best answer but I'm currently using JQuery with Bootstrap in an Angular 6 app so I modify height after the the view loads.

I set

```<code>        <object id="pdf" data="path.pdf" type="application/pdf" width="100%"></object>
</code>```

then in my component I adjust the height based on the ratio of the width to height.
For example, an 8 x 11.5 document would give the height 1.4375 x the width.

```<code>  ngAfterViewInit(): void {
    var width = $("#pdf").width();
    $("#pdf").prop("height", width * 1.4375 + "px");
   }
</code>```

Saw this post and figured I would post. Hope this helps and please correct me if you think this is bad coding practices.

Title: Embed PDF at full height

Body:
I like the functionality that comes with the html objects for PDFs as opposed to some libraries like PDF.js for light projects. This is definitely not the best answer but I'm currently using JQuery with Bootstrap in an Angular 6 app so I modify height after the the view loads.

I set

        <object id="pdf" data="path.pdf" type="application/pdf" width="100%"></object>

then in my component I adjust the height based on the ratio of the width to height.
For example, an 8 x 11.5 document would give the height 1.4375 x the width.

  ngAfterViewInit(): void {
    var width = $("#pdf").width();
    $("#pdf").prop("height", width * 1.4375 + "px");
   }

Saw this post and figured I would post. Hope this helps and please correct me if you think this is bad coding practices.


问:
null is not assignable to void when flag --strictNullChecks is enabled
As per the TypeScript Documentation:

However, when using the --strictNullChecks flag, null and undefined are only assignable to void and their respective types. This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined, you can use the union type string | null | undefined. Once again, more on union types later on.

But, when I tried following code snippets:

```<code>// This worked correctly
let voidIsUndefined: void = undefined;

// While following code thrown a compilation error "Type 'null' is not assignable to type 'void'."
let voidIsNull: void = null;
</code>```

It did not work completely as expected.

As per the docs, I should be able to assign null to void type. Can someone please clear this doubt?

答: The TypeScript docs are misleading and you're correct to feel confused. There is an issue about this here: https://github.com/microsoft/TypeScript-Handbook/issues/468</p>

Body:
As per the TypeScript Documentation:

However, when using the --strictNullChecks flag, null and undefined are only assignable to void and their respective types. This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined, you can use the union type string | null | undefined. Once again, more on union types later on.

But, when I tried following code snippets:

// This worked correctly
let voidIsUndefined: void = undefined;

// While following code thrown a compilation error "Type 'null' is not assignable to type 'void'."
let voidIsNull: void = null;

It did not work completely as expected.

As per the docs, I should be able to assign null to void type. Can someone please clear this doubt?


问:
I'm trying to delete a row using an array. Can you tell me the grammar of orm?
I'm trying to delete a row using an array.
Can you tell me the grammar of orm?

```<code>def todo_delete_ajax(request):

    todo_ids = request.POST.getlist('todo_arr[]')
    # result : todo_ids :  ['76', 97]

    if todo_ids:
        print("todo_ids : ", todo_ids)
        return redirect('/todo/')
    else:
        print("todo_ids : ", todo_ids)

    return redirect('/todo/')
</code>```

I want to use Django orm and delete 76,97 of todo model

Thank you if you let me know how.

答:
You can use:

```<code>Todo.objects.filter(<b>pk__in=todo_ids</b>)<b>.delete()</b></code>```

But the above is not very safe:

you do not verify that the AJAX request is performed by a logged in user; and

that the user has access to these Todo objects, for example if he/she is the owner.

This thus means that a hacker can "inject" primary keys of other users their Todo objects.

In case the Todo model has an owner field, you can prevent that with:

```<code><b>@login_required</b>
def todo_delete_ajax(request):
    todo_ids = request.POST.getlist('todo_arr[]')
    if todo_ids:
        Todo.objects.filter(pk__in=todo_ids<b>, owner=request.user</b>).delete()
    return redirect('/todo/')</code>```

You probably also want to use the name of the view in the redirect call, so:

```<code>@login_required
def todo_delete_ajax(request):
    todo_ids = request.POST.getlist('todo_arr[]')
    if todo_ids:
        Todo.objects.filter(pk__in=todo_ids, owner=request.user).delete()
    return redirect(<b>'name-of-todo-view'</b>)</code>```

since by using a hardcoded URL, if you change the path of that URL, or you run your server under a specific path, then the URL will turn invalid.

Body:
I'm trying to delete a row using an array.
Can you tell me the grammar of orm?

def todo_delete_ajax(request):

    todo_ids = request.POST.getlist('todo_arr[]')
    # result : todo_ids :  ['76', 97]

    if todo_ids:
        print("todo_ids : ", todo_ids)
        return redirect('/todo/')
    else:
        print("todo_ids : ", todo_ids)

    return redirect('/todo/')

I want to use Django orm and delete 76,97 of todo model

Thank you if you let me know how.

Body:
You can use:

Todo.objects.filter(pk__in=todo_ids).delete()

But the above is not very safe:

you do not verify that the AJAX request is performed by a logged in user; and

that the user has access to these Todo objects, for example if he/she is the owner.

This thus means that a hacker can "inject" primary keys of other users their Todo objects.

In case the Todo model has an owner field, you can prevent that with:

@login_required
def todo_delete_ajax(request):
    todo_ids = request.POST.getlist('todo_arr[]')
    if todo_ids:
        Todo.objects.filter(pk__in=todo_ids, owner=request.user).delete()
    return redirect('/todo/')

You probably also want to use the name of the view in the redirect call, so:

@login_required
def todo_delete_ajax(request):
    todo_ids = request.POST.getlist('todo_arr[]')
    if todo_ids:
        Todo.objects.filter(pk__in=todo_ids, owner=request.user).delete()
    return redirect('name-of-todo-view')

since by using a hardcoded URL, if you change the path of that URL, or you run your server under a specific path, then the URL will turn invalid.


问:
Angular 4 : Sending data to externel api
i am integrating a payment gateway and the only way to send data is http post request. so i am asking if there  are  a possible way to send data  to this  externel api using angular 4 ?

i used this form :

```<code><form [formGroup] = "form"  (ngSubmit) = "redirect(form.value)">
<input type="text" name="card_number"
formControlName="card_number" >
<input type="text" name="expiry_date" formControlName="expiry_date">
 <input type="text"
name="card_security_code"formControlName="card_security_code" >
<input type="submit" value="" id="submit2" name="submit">

</form>
</code>```

and this is my function:

```<code>  this.form =new FormGroup ({
    card_number: new FormControl(),
    expiry_date: new FormControl(),
    card_security_code: new FormControl()});

redirect= function (form) {

var body = "card_number=" + form.card_number+ "&expiry_date=" + form.expiry_date"&card_security_code=" +form.card_security_code;
this.http.post("https://sbcheckout.payfort.com/FortAPI/paymentPage", body).subscribe((data) => {});
 }
</code>```

i tried this form in ionic 3 but i got this CORS error, please can you advise guys?

```<code>Failed to load https://sbcheckout.payfort.com/FortAPI/paymentPage: Redirect
from 'https://sbcheckout.payfort.com/FortAPI/paymentPage' to
'https://sbcheckout.payfort.com/FortAPI/paymentPageC?
S=1&token=NAX906AB61K8IMC40AKWEKOVLJDN6D&' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Origin 'http://localhost:8100' is therefore not allowed access.
</code>```

答:
payfort forms should be submitted through http post, I added a sample for you to check below.

  /*
  calculateSignature(form) {
    // tslint:disable-next-line: max-line-length
    const sig = `${this.PaymentSchema.sig_key}access_code=${this.PaymentSchema.access_code}language=enmerchant_identifier=${this.PaymentSchema.merchant_identifier}merchant_reference=${this.PaymentSchema.merchant_reference}return_url=${this.PaymentSchema.return_url}service_command=TOKENIZATION${this.PaymentSchema.sig_key}`;
    this.generateSha_1(sig).then(res => {
      this.PaymentSchema.signature = res;
      setTimeout(() => {
        form.submit();
      }, 2000)
    });
  }

    async generateSha_1(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
  }

  */```
<pre class="snippet-code-html lang-html prettyprint-override"><code>payfort forms should be submitted through http post

    <form METHOD="post" ACTION="https://sbcheckout.payfort.com/FortAPI/paymentPage" #form id=form1 name=form1>

  <INPUT type="hidden" #service_command NAME="service_command" [(value)]="PaymentSchema.service_command">
  <INPUT type="hidden" #language NAME="language" [(value)]="PaymentSchema.language">
  <INPUT type="hidden" #merchant_identifier NAME="merchant_identifier" [(value)]="PaymentSchema.merchant_identifier">
  <INPUT type="hidden" #access_code NAME="access_code" [(value)]="PaymentSchema.access_code">
  <INPUT type="hidden" #signature NAME="signature" [(value)]="PaymentSchema.signature">
  <INPUT type="hidden" #return_url NAME="return_url" [(value)]="PaymentSchema.return_url">
  <INPUT type="hidden" #merchant_reference NAME="merchant_reference" [(value)]="PaymentSchema.merchant_reference">
  <INPUT type="text" #card_number NAME="card_number" [(value)]="PaymentSchema.card_number">
  <INPUT type="text" #expiry_date NAME="expiry_date" [(value)]="PaymentSchema.expiry_date">
  <INPUT type="text" #card_security_code NAME="card_security_code" [(value)]="PaymentSchema.card_security_code">
  <INPUT type="text" #card_holder_name NAME="card_holder_name" [(value)]="PaymentSchema.card_holder_name">
  <input type="submit" value="submit" id="submit2" (click)="calculateSignature(form)" name="">
</form></code>```

Body:
i am integrating a payment gateway and the only way to send data is http post request. so i am asking if there  are  a possible way to send data  to this  externel api using angular 4 ?

i used this form :

<form [formGroup] = "form"  (ngSubmit) = "redirect(form.value)">
<input type="text" name="card_number"
formControlName="card_number" >
<input type="text" name="expiry_date" formControlName="expiry_date">
 <input type="text"
name="card_security_code"formControlName="card_security_code" >
<input type="submit" value="" id="submit2" name="submit">

</form>

and this is my function:

  this.form =new FormGroup ({
    card_number: new FormControl(),
    expiry_date: new FormControl(),
    card_security_code: new FormControl()});

redirect= function (form) {

var body = "card_number=" + form.card_number+ "&expiry_date=" + form.expiry_date"&card_security_code=" +form.card_security_code;
this.http.post("https://sbcheckout.payfort.com/FortAPI/paymentPage", body).subscribe((data) => {});
 }

i tried this form in ionic 3 but i got this CORS error, please can you advise guys?

Failed to load https://sbcheckout.payfort.com/FortAPI/paymentPage: Redirect
from 'https://sbcheckout.payfort.com/FortAPI/paymentPage' to
'https://sbcheckout.payfort.com/FortAPI/paymentPageC?
S=1&token=NAX906AB61K8IMC40AKWEKOVLJDN6D&' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Origin 'http://localhost:8100' is therefore not allowed access.

Body:
payfort forms should be submitted through http post, I added a sample for you to check below.

  /*
  calculateSignature(form) {
    // tslint:disable-next-line: max-line-length
    const sig = `${this.PaymentSchema.sig_key}access_code=${this.PaymentSchema.access_code}language=enmerchant_identifier=${this.PaymentSchema.merchant_identifier}merchant_reference=${this.PaymentSchema.merchant_reference}return_url=${this.PaymentSchema.return_url}service_command=TOKENIZATION${this.PaymentSchema.sig_key}`;
    this.generateSha_1(sig).then(res => {
      this.PaymentSchema.signature = res;
      setTimeout(() => {
        form.submit();
      }, 2000)
    });
  }

    async generateSha_1(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
  }

  */

payfort forms should be submitted through http post

    <form METHOD="post" ACTION="https://sbcheckout.payfort.com/FortAPI/paymentPage" #form id=form1 name=form1>

  <INPUT type="hidden" #service_command NAME="service_command" [(value)]="PaymentSchema.service_command">
  <INPUT type="hidden" #language NAME="language" [(value)]="PaymentSchema.language">
  <INPUT type="hidden" #merchant_identifier NAME="merchant_identifier" [(value)]="PaymentSchema.merchant_identifier">
  <INPUT type="hidden" #access_code NAME="access_code" [(value)]="PaymentSchema.access_code">
  <INPUT type="hidden" #signature NAME="signature" [(value)]="PaymentSchema.signature">
  <INPUT type="hidden" #return_url NAME="return_url" [(value)]="PaymentSchema.return_url">
  <INPUT type="hidden" #merchant_reference NAME="merchant_reference" [(value)]="PaymentSchema.merchant_reference">
  <INPUT type="text" #card_number NAME="card_number" [(value)]="PaymentSchema.card_number">
  <INPUT type="text" #expiry_date NAME="expiry_date" [(value)]="PaymentSchema.expiry_date">
  <INPUT type="text" #card_security_code NAME="card_security_code" [(value)]="PaymentSchema.card_security_code">
  <INPUT type="text" #card_holder_name NAME="card_holder_name" [(value)]="PaymentSchema.card_holder_name">
  <input type="submit" value="submit" id="submit2" (click)="calculateSignature(form)" name="">
</form>


问:
How could I count bit from large number in javascript?
I have a large number stored in string.

```<code>let txt = '10000000000000041';
</code>```

So how could I count bit presenting in it's a binary format. for example, the binary format of 9 is 1001, and no of 1's is 2.

What I did so far:

const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1;
    c++;
  }
  return c;
}

console.log(countOne(+'9'));
console.log(countOne(+'10000000000000041'));```

This code is working fine, but not for large value, because Number in JavaScript cannot hold such large value, so it's giving the wrong answer.

I found similar questions but not for large value.

答:
For those who do not have the BigInt, here is a solution to convert to binary via an Euclidean division:

let txt ='10000000000000041'
,   bin = GetBinary(txt)
;
console.log('Base 10 = ', txt )
console.log('Base 2  = ', bin )
console.log('number of digits on 1 = ', bin.replace(/0/g,'').length )

function GetBinary(strNum)
{
  let Bin = ''
  ,   val = strNum
  ,   Rep = null
  ;
  for(let l=0;l<200;l++)  // loop limitation to 200 by security
  {
    Rep = Div_2(val)
    val = Rep.R
    Bin = Rep.D + Bin
    if (val==='') break;
  }
  if (val!=='') console.log( 'too much loops for conversion')
  return Bin
}

function Div_2(sNum)
{
  let D = R = ''                 // dividande, results
  ,   d = x = r = 0             // temp vals
  ;
  for(let p=0;p<sNum.length;p++)
  {
    D += sNum.charAt(p)
    d = parseInt(D,10)
    if ( d < 2 ) R += '0'
    else
    {
      x = Math.trunc(d / 2)
      r = d % 2
      D = r.toString(10)
      R += x.toString(10)
    }
  }
  R = R.replace(/\b0+/g, '')     // remove leading zeros
  D = parseInt(D,10).toString() // .except the last one
  return { R, D }
}```

[edit= minor errors corrected + info]

info : The number max of useful loops (in GetBinary()), is equal to

Math.ceil(Math.log2(Math.pow(10,n)))

where n is the number of digits in base 10.

The 'explanations' are here:

Is there a formula for calculating or estimating the number of digits of a binary integer?

(thanks to Jaromanda X)

Body:
I have a large number stored in string.

let txt = '10000000000000041';

So how could I count bit presenting in it's a binary format. for example, the binary format of 9 is 1001, and no of 1's is 2.

What I did so far:

const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1;
    c++;
  }
  return c;
}

console.log(countOne(+'9'));
console.log(countOne(+'10000000000000041'));

This code is working fine, but not for large value, because Number in JavaScript cannot hold such large value, so it's giving the wrong answer.

I found similar questions but not for large value.

Body:
For those who do not have the BigInt, here is a solution to convert to binary via an Euclidean division:

let txt ='10000000000000041'
,   bin = GetBinary(txt)
;
console.log('Base 10 = ', txt )
console.log('Base 2  = ', bin )
console.log('number of digits on 1 = ', bin.replace(/0/g,'').length )

function GetBinary(strNum)
{
  let Bin = ''
  ,   val = strNum
  ,   Rep = null
  ;
  for(let l=0;l<200;l++)  // loop limitation to 200 by security
  {
    Rep = Div_2(val)
    val = Rep.R
    Bin = Rep.D + Bin
    if (val==='') break;
  }
  if (val!=='') console.log( 'too much loops for conversion')
  return Bin
}

function Div_2(sNum)
{
  let D = R = ''                 // dividande, results
  ,   d = x = r = 0             // temp vals
  ;
  for(let p=0;p<sNum.length;p++)
  {
    D += sNum.charAt(p)
    d = parseInt(D,10)
    if ( d < 2 ) R += '0'
    else
    {
      x = Math.trunc(d / 2)
      r = d % 2
      D = r.toString(10)
      R += x.toString(10)
    }
  }
  R = R.replace(/\b0+/g, '')     // remove leading zeros
  D = parseInt(D,10).toString() // .except the last one
  return { R, D }
}

[edit= minor errors corrected + info]

info : The number max of useful loops (in GetBinary()), is equal to

Math.ceil(Math.log2(Math.pow(10,n)))

where n is the number of digits in base 10.

The 'explanations' are here:

Is there a formula for calculating or estimating the number of digits of a binary integer?

(thanks to Jaromanda X)