问:
How to implement this .htaccess in firebase?
I have this .htaccess for a PWA

```<code>Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
</code>```

I want to migrate the app to firebase, basically what it does is let's say I shared this link

example.com/pwa/giftLink

He gets redirected to PWA

example.com/pwa

And the PWA redirects him to giftLink. I don't want to do it via code, I prefer doing it via firebase.json

答:
In Firebase Hosting rewrites, the equivalent would be:</p>

```<code>"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    "source": "/pwa{,/**}",
    "destination": "/pwa/index.html"
  } ]
}
</code>```

Body:
I have this .htaccess for a PWA

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

I want to migrate the app to firebase, basically what it does is let's say I shared this link

example.com/pwa/giftLink

He gets redirected to PWA

example.com/pwa

And the PWA redirects him to giftLink. I don't want to do it via code, I prefer doing it via firebase.json

Body:
In Firebase Hosting rewrites, the equivalent would be:

"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    "source": "/pwa{,/**}",
    "destination": "/pwa/index.html"
  } ]
}


来源: stackexchange

问:
Weird behaviour awk last character "]"
I encountered a weird awk behaviour when trying to bracketerise some column in my file:

```<code>batch ID        tumor_reads2_fastqgzs   tumor_reads_fastqgzs    tumor_reads2_fastqgzs ID        tumor_reads_fastqgzs ID
9_S8    9_S8_L001_R2_001.fastq.gz       9_S8_L001_R1_001.fastq.gz       file-Fk3BgVj4yBGZqQvF2VV2Q2Z4   file-Fk3BgfQ4yBGYz756BGvbzkP8
7_S6    7_S6_L001_R2_001.fastq.gz       7_S6_L001_R1_001.fastq.gz       file-Fk3Bg884yBGYF4xXJjpf08f8   file-Fk3Bg1j4yBGvbp9VK2ZQ76G3
10_S9   10_S9_L001_R2_001.fastq.gz      10_S9_L001_R1_001.fastq.gz      file-Fk3Bfg84yBGq9g7zJk5kv435   file-Fk3BfVQ4yBGxxPZy6pjxv635
3_S3    3_S3_L001_R2_001.fastq.gz       3_S3_L001_R1_001.fastq.gz       file-Fk3Bf3Q4yBGq9g7zJk5kv42z   file-Fk3BfB04yBGYz756BGvbzkGk
15_S14  15_S14_L001_R2_001.fastq.gz     15_S14_L001_R1_001.fastq.gz     file-Fk3Bbp04yBGkyPqy2073BKf7   file-Fk3BbV84yBGq00fKK3j5KjG5
</code>```

Here is my file, and i wanted to put brackets around columns 4 and 5 so:

```<code>awk -v OFS="\t" '{if($0 ~ /^batch/){print $0}else{print $1, $2, $3, "["$4"]", "["$5"]";}}' myfile
</code>```

But it outputted this:

```<code>batch ID        tumor_reads2_fastqgzs   tumor_reads_fastqgzs    tumor_reads2_fastqgzs ID        tumor_reads_fastqgzs ID
]_S8    9_S8_L001_R2_001.fastq.gz       9_S8_L001_R1_001.fastq.gz       [file-Fk3BgVj4yBGZqQvF2VV2Q2Z4] [file-Fk3BgfQ4yBGYz756BGvbzkP8
]_S6    7_S6_L001_R2_001.fastq.gz       7_S6_L001_R1_001.fastq.gz       [file-Fk3Bg884yBGYF4xXJjpf08f8] [file-Fk3Bg1j4yBGvbp9VK2ZQ76G3
]0_S9   10_S9_L001_R2_001.fastq.gz      10_S9_L001_R1_001.fastq.gz      [file-Fk3Bfg84yBGq9g7zJk5kv435] [file-Fk3BfVQ4yBGxxPZy6pjxv635
]_S3    3_S3_L001_R2_001.fastq.gz       3_S3_L001_R1_001.fastq.gz       [file-Fk3Bf3Q4yBGq9g7zJk5kv42z] [file-Fk3BfB04yBGYz756BGvbzkGk
]5_S14  15_S14_L001_R2_001.fastq.gz     15_S14_L001_R1_001.fastq.gz     [file-Fk3Bbp04yBGkyPqy2073BKf7] [file-Fk3BbV84yBGq00fKK3j5KjG5
</code>```

The last bracket replaces the first character for some reason. Any idea why? How can i fix that?
I tried using sub() also but it did the same thing

答:
Your code worked for me. IMHO there are chances of having control M characters in your Input_file, so you could add a piece of code to remove them, could you please try following.</p>

```<code>awk -v OFS="\t" '{gsub(/\r/,"");if($0 ~ /^batch/){print $0}else{print $1, $2, $3, "["$4"]", "["$5"]";}}' Input_file
</code>```

ContentLicense: CC BY-SA 4.0

Title: Weird behaviour awk last character "]"

Body:
I encountered a weird awk behaviour when trying to bracketerise some column in my file:

batch ID        tumor_reads2_fastqgzs   tumor_reads_fastqgzs    tumor_reads2_fastqgzs ID        tumor_reads_fastqgzs ID
9_S8    9_S8_L001_R2_001.fastq.gz       9_S8_L001_R1_001.fastq.gz       file-Fk3BgVj4yBGZqQvF2VV2Q2Z4   file-Fk3BgfQ4yBGYz756BGvbzkP8
7_S6    7_S6_L001_R2_001.fastq.gz       7_S6_L001_R1_001.fastq.gz       file-Fk3Bg884yBGYF4xXJjpf08f8   file-Fk3Bg1j4yBGvbp9VK2ZQ76G3
10_S9   10_S9_L001_R2_001.fastq.gz      10_S9_L001_R1_001.fastq.gz      file-Fk3Bfg84yBGq9g7zJk5kv435   file-Fk3BfVQ4yBGxxPZy6pjxv635
3_S3    3_S3_L001_R2_001.fastq.gz       3_S3_L001_R1_001.fastq.gz       file-Fk3Bf3Q4yBGq9g7zJk5kv42z   file-Fk3BfB04yBGYz756BGvbzkGk
15_S14  15_S14_L001_R2_001.fastq.gz     15_S14_L001_R1_001.fastq.gz     file-Fk3Bbp04yBGkyPqy2073BKf7   file-Fk3BbV84yBGq00fKK3j5KjG5

Here is my file, and i wanted to put brackets around columns 4 and 5 so:

awk -v OFS="\t" '{if($0 ~ /^batch/){print $0}else{print $1, $2, $3, "["$4"]", "["$5"]";}}' myfile

But it outputted this:

batch ID        tumor_reads2_fastqgzs   tumor_reads_fastqgzs    tumor_reads2_fastqgzs ID        tumor_reads_fastqgzs ID
]_S8    9_S8_L001_R2_001.fastq.gz       9_S8_L001_R1_001.fastq.gz       [file-Fk3BgVj4yBGZqQvF2VV2Q2Z4] [file-Fk3BgfQ4yBGYz756BGvbzkP8
]_S6    7_S6_L001_R2_001.fastq.gz       7_S6_L001_R1_001.fastq.gz       [file-Fk3Bg884yBGYF4xXJjpf08f8] [file-Fk3Bg1j4yBGvbp9VK2ZQ76G3
]0_S9   10_S9_L001_R2_001.fastq.gz      10_S9_L001_R1_001.fastq.gz      [file-Fk3Bfg84yBGq9g7zJk5kv435] [file-Fk3BfVQ4yBGxxPZy6pjxv635
]_S3    3_S3_L001_R2_001.fastq.gz       3_S3_L001_R1_001.fastq.gz       [file-Fk3Bf3Q4yBGq9g7zJk5kv42z] [file-Fk3BfB04yBGYz756BGvbzkGk
]5_S14  15_S14_L001_R2_001.fastq.gz     15_S14_L001_R1_001.fastq.gz     [file-Fk3Bbp04yBGkyPqy2073BKf7] [file-Fk3BbV84yBGq00fKK3j5KjG5

The last bracket replaces the first character for some reason. Any idea why? How can i fix that?
I tried using sub() also but it did the same thing

Body:
Your code worked for me. IMHO there are chances of having control M characters in your Input_file, so you could add a piece of code to remove them, could you please try following.

awk -v OFS="\t" '{gsub(/\r/,"");if($0 ~ /^batch/){print $0}else{print $1, $2, $3, "["$4"]", "["$5"]";}}' Input_file


问:
Converting string to IP Address in java(android)
When i convert string ("192.168.0.105") to InetAddress in java (android). I am getting "/192.168.0.105". An extra "/" is coming in InetAddress, which causes the socket not to be created.

How do i get rid of "/".

Regards,

Syed Mustehsan Ikram

答:
You can use getHostAddress() method of InetAddress to get host address without /.

And if you are using InetSocketAddress then use getAddress().getHostAddress() to get host ip without /.

```<code>InetAddress inetAddress = InetAddress.getByName("192.168.0.105");
System.out.println(inetAddress.getHostAddress());

InetSocketAddress address = new InetSocketAddress("192.168.0.105", 5555);
System.out.println(address.getAddress().getHostAddress());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use getHostAddress() method of InetAddress to get host address without /.

And if you are using InetSocketAddress then use getAddress().getHostAddress() to get host ip without /.

InetAddress inetAddress = InetAddress.getByName("192.168.0.105");
System.out.println(inetAddress.getHostAddress());

InetSocketAddress address = new InetSocketAddress("192.168.0.105", 5555);
System.out.println(address.getAddress().getHostAddress());


问:
Laravel join(): Argument must be an array
I'm trying to read 2 tables in my view. Now I am trying to join an other table like this in my sslcontroller.php

```<code><?php

namespace App\Http\Controllers;

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

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        join('users');
        return view('SSL',['data'=>$data]);
    }
}
</code>```

Now I want to get data from the SSL table but also from the users table.
How to do this?

答:
this should work for you:</p>

```<code>$data = DB::table('SSL')->where('userID', Auth::id())
->join('users', 'users.id', '=', 'SSL.userID');
->get();
</code>```

Body:
I'm trying to read 2 tables in my view. Now I am trying to join an other table like this in my sslcontroller.php

<?php

namespace App\Http\Controllers;

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

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        join('users');
        return view('SSL',['data'=>$data]);
    }
}

Now I want to get data from the SSL table but also from the users table.
How to do this?

Body:
this should work for you:

$data = DB::table('SSL')->where('userID', Auth::id())
->join('users', 'users.id', '=', 'SSL.userID');
->get();


问:
multiple refs for inputs, works only last one
I'm trying to make a editable table using ref.

In this case I can only get last input's value through ref, but created multiple refs for it.

Why is it any ideas?

Please let me know if you need more info about it.

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Table = props => {
  const materials = Array(7).fill({
    a: "a",
    b: "b",
    aref: useRef(null),
    bref: useRef(null)
  });
  const handle = (index, key, ref) => {
    console.log(index, ref.current.value);
  };
  return (
    <>

            a
            b

          {materials.map((item, index) => {
            return (

                  <input
                    onChange={e => handle(index, "a", item.aref)}
                    type="text"
                    ref={item.aref}
                  />

                  <input
                    onChange={e => handle(index, "b", item.bref)}
                    type="text"
                    ref={item.bref}
                  />

            );
          })}

    </>
  );
};

function App() {
  return (

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

```

codesandbox: https://codesandbox.io/s/upbeat-breeze-sm7c6

答: I faced the same issue once, after a while i've realized that i was creating the refs inside a static defaultProps, therefore all the references were the same for all elements, and the same bug would appear

Body:
I'm trying to make a editable table using ref.

In this case I can only get last input's value through ref, but created multiple refs for it.

Why is it any ideas?

Please let me know if you need more info about it.

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Table = props => {
  const materials = Array(7).fill({
    a: "a",
    b: "b",
    aref: useRef(null),
    bref: useRef(null)
  });
  const handle = (index, key, ref) => {
    console.log(index, ref.current.value);
  };
  return (
    <>

            a
            b

          {materials.map((item, index) => {
            return (

                  <input
                    onChange={e => handle(index, "a", item.aref)}
                    type="text"
                    ref={item.aref}
                  />

                  <input
                    onChange={e => handle(index, "b", item.bref)}
                    type="text"
                    ref={item.bref}
                  />

            );
          })}

    </>
  );
};

function App() {
  return (

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox: https://codesandbox.io/s/upbeat-breeze-sm7c6


问:
How to handle different post sources in Asp.NET MVC with a strongly typed view
Say I have a model that maps a person and I want to build a view for this model having some text inputs and a series of drop-downs to select state, province, city.

I'm adding @onchange = "this.form.submit()" in each @Html.DropDownListFor to post back to the server and drill-down the selection on those drop-downs.

How can I understand in my controller the source of said post? How do I distinguish the post coming from a drop-down change to the one coming from a submit button?

答:
While not being able to understand the exact source of the postback, based on this question and answers I'm at least able to check if the source was one of the submit buttons by simply checking:

```<code>if(Request.Form["submitButtonNameAttribute"] != null)
</code>```

When multiple buttons are available, only the clicked one is != null at postback.

Still, this is not a complete solution related to the original answer, but while a button may indicate an action to be run, other changes in the view may just invoke some sync work on the model.

Body:
While not being able to understand the exact source of the postback, based on this question and answers I'm at least able to check if the source was one of the submit buttons by simply checking:

if(Request.Form["submitButtonNameAttribute"] != null)

When multiple buttons are available, only the clicked one is != null at postback.

Still, this is not a complete solution related to the original answer, but while a button may indicate an action to be run, other changes in the view may just invoke some sync work on the model.


问:
init() function not run in shared library?
I'm building my package with -buildmode=c-shared and find that the init() functions in imported packages don't seem to be run. Is that intended behavior, a bug, or am I just stupid?
I'm using go1.13.7 on linux/amd64. The function in question looks like this:

```<code>func init() {
    jsonrpc.HandleFunc("create-context", ContextHandler)
}
</code>```

jsonrpc is a package I wrote and the function adds an entry to an unexported global map there.

答:
I tried with:

```<code>package main

import "C"

import "fmt"

func init() {
        fmt.Println("in init")
}

//export Yo
func Yo() {
        fmt.Println("that's what's up")
}

func main() {
        fmt.Println("vim-go")
}
</code>```

With go build -buildmode=c-shared lib.go I got a a lib.h

```<code>#include <stdio.h>
#include "lol.h"

int main() {
    Yo();
}
</code>```

I compiled with: gcc -o client main.c ./lib.so

And I got a:

```<code>in init
that's what's up
</code>```

So it seems to me that it works.

Body:
I'm building my package with -buildmode=c-shared and find that the init() functions in imported packages don't seem to be run. Is that intended behavior, a bug, or am I just stupid?
I'm using go1.13.7 on linux/amd64. The function in question looks like this:

func init() {
    jsonrpc.HandleFunc("create-context", ContextHandler)
}

jsonrpc is a package I wrote and the function adds an entry to an unexported global map there.

Body:
I tried with:

package main

import "C"

import "fmt"

func init() {
        fmt.Println("in init")
}

//export Yo
func Yo() {
        fmt.Println("that's what's up")
}

func main() {
        fmt.Println("vim-go")
}

With go build -buildmode=c-shared lib.go I got a a lib.h

#include <stdio.h>
#include "lol.h"

int main() {
    Yo();
}

I compiled with: gcc -o client main.c ./lib.so

And I got a:

in init
that's what's up

So it seems to me that it works.


问:
Iteration on DataFrame

Hi guys,
I have a dataframe with 3 columns : 0,1,2.

for the row with "None" values of the column 2 , i want to copy this "None" values on the column 0. Only for the row with None Values. I want the other row of the column 0 to remain the same.

so the columns 0 should be that way :

```<code>par besoin
None
None
None
par ligne
...
teint
</code>```

Thank you so much

答:
Given a dataframe named df:

df.loc[df[2].isnull(), 0] = None

Where df.loc[df[2].isnull() finds rows where the value in column 2 equals None, and the remainder, , 0] = None sets the value in the column 0 for those rows to None.

Title: Iteration on DataFrame

Body:
Hi guys,
I have a dataframe with 3 columns : 0,1,2.

for the row with "None" values of the column 2 , i want to copy this "None" values on the column 0. Only for the row with None Values. I want the other row of the column 0 to remain the same.

so the columns 0 should be that way :

par besoin
None
None
None
par ligne
...
teint

Thank you so much


问:
convert all times to 0:00
How would I convert all dates which are currently YYYY-MM-DD Time, where the Time is 00:00.

Below is my code and I attach a pic

```<code>    select* from(SELECT
    Date,
    Depot,
     Vehicle,
     Quantity as [Ltrs],
     OdoReadingMiles,
     LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage
     ,OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles]
     ,(OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG]
     ,case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10 then 1 else 0 end as [Anomaly]
     FROM [Fleet].[DwhTriscanChargeouts] )as x
     WHERE x.Anomaly=0
     ORDER BY 2,1
</code>```

答:
Convert first to date, and then back to datetime. The time part will be lost leaving it to 00:00</p>

```<code>select convert(datetime, convert(date, datetimecol)) as datetimecol
</code>```

Title: convert all times to 0:00

Body:
How would I convert all dates which are currently YYYY-MM-DD Time, where the Time is 00:00.

Below is my code and I attach a pic

    select* from(SELECT
    Date,
    Depot,
     Vehicle,
     Quantity as [Ltrs],
     OdoReadingMiles,
     LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage
     ,OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles]
     ,(OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG]
     ,case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10 then 1 else 0 end as [Anomaly]
     FROM [Fleet].[DwhTriscanChargeouts] )as x
     WHERE x.Anomaly=0
     ORDER BY 2,1

Body:
Convert first to date, and then back to datetime. The time part will be lost leaving it to 00:00

select convert(datetime, convert(date, datetimecol)) as datetimecol


问:
y-axis scale as percents in ggplotly
I'm using scale_y_continuous to format my y-axis in percentage:

```<code>library(ggplot2)
ggplot(tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) +
  geom_point() +
  scale_y_continuous(limits=c(0,1), labels=scales::percent)

plotly::ggplotly()
</code>```

However, how can I keep this format in the plotly tooltip (which shows y as floats)?

答:
You can access the tooltip text as

```<code>ply$x$data[[1]]$text
</code>```

So the code below might be useful

```<code>library(ggplot2)
pl = ggplot(dplyr::tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) +
geom_point() +
scale_y_continuous(limits=c(0,1), labels=scales::percent)

ply = plotly::ggplotly(pl)

tip = ply$x$data[[1]]$text
tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x){paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
ply$x$data[[1]]$text = tip
</code>```

Edit - put it in a function

```<code>prc_ggplotly = function(pl = ggplot2::last_plot(), i = 1)
{
  ply = plotly::ggplotly(pl)

  if(any(grepl('%', ply$x$layout$yaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x) {paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
    ply$x$data[[i]]$text = tip
  }

  if(any(grepl('%', ply$x$layout$xaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, '<'), function(x) { paste0(paste0(x[1], '%'), '<', x[2])}  ))
    ply$x$data[[i]]$text = tip
  }

  return(ply)
}
</code>```

Hope this helps

Title: y-axis scale as percents in ggplotly

Body:
I'm using scale_y_continuous to format my y-axis in percentage:

library(ggplot2)
ggplot(tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) +
  geom_point() +
  scale_y_continuous(limits=c(0,1), labels=scales::percent)

plotly::ggplotly()

However, how can I keep this format in the plotly tooltip (which shows y as floats)?

Body:
You can access the tooltip text as

ply$x$data[[1]]$text

So the code below might be useful

library(ggplot2)
pl = ggplot(dplyr::tibble(x=c(0,5,10),y=c(0,0.5,0.75)), aes(x=x,y=y)) +
geom_point() +
scale_y_continuous(limits=c(0,1), labels=scales::percent)

ply = plotly::ggplotly(pl)

tip = ply$x$data[[1]]$text
tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x){paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
ply$x$data[[1]]$text = tip

Edit - put it in a function

prc_ggplotly = function(pl = ggplot2::last_plot(), i = 1)
{
  ply = plotly::ggplotly(pl)

  if(any(grepl('%', ply$x$layout$yaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, 'y:'), function(x) {paste0(x[1], 'y:',paste0(x[2], '%'))}  ))
    ply$x$data[[i]]$text = tip
  }

  if(any(grepl('%', ply$x$layout$xaxis$ticktext)))
  {
    tip = ply$x$data[[i]]$text
    tip = do.call('c', lapply(strsplit(tip, '<'), function(x) { paste0(paste0(x[1], '%'), '<', x[2])}  ))
    ply$x$data[[i]]$text = tip
  }

  return(ply)
}

Hope this helps


问:
YouTube may disable your inactive project's access to the YouTube Data API Service
I was using Youtube Data APIto get youtube video but after getting mail from youtube which says api is disable due to inactive.

Youtube Data api not working since it was disabled by youtube because of inactive for 90 Days. I am not able to call(It is enable in API Console) it even with delete and add new delete back. Please help.

Error shows when i am calling from Web Browsers with api Key i also tried to generate new API key also delete and regenerate new api key but still no luck.

"Access Not Configured. YouTube Data API has not been used in project
  264969722993 before or it is disabled. Enable it by visiting
  https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=264969722993
  then retry. If you enabled this API recently, wait a few minutes for
  the action to propagate to our systems and retry."

答:
I'm in the same position, disabled for no calls in 90 days. You can request an exemption but after about 25 back and forth emails it's clear that it is just a smokescreen. After explaining what it's used for they then wanted screenshots, then videos of you using the application, how we use the videos we pull up, and then a shot of the room where it was being used. They even asked who made the video we were looking at (we have no idea!). They want your whole business model and what you do. It was just never ending questions and more stuff to send them. After about 2 1/2 months of slow back and forth, I get a message saying I am out of compliance.

Our application uses YouTube to pull up videos for manufacturers product for research and training in a small training/conference room for internal use only. That's all!
Nothing was out of compliance.

This is the email we received:

Hello ,

We have reviewed your quota extension request for project number

  #### and have revoked the allocated quota for your API Client(s) as it is out of compliance on the following YouTube API Services -

Developer Policy:

Policy F. 1 (User Experience - YouTube Look and Feel)  Please do not
  reply to this email, you may complete and submit this form to re-apply
  once the above concern has been addressed.

Thanks, YouTube API Services team

The form link in the email is just a link to start the whole process over again.


问:
Array Should Only Contains Values From Other Array
I Have Two Arrays.

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");
</code>```

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

```<code>$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}
</code>```

答:
Use array_diff. If result is empty, it is OK, else not.

```<code>if (array_diff($uploaded_array, $allowed_array)) {
    echo "not ok";
}
</code>```

Body:
I Have Two Arrays.

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}

Body:
Use array_diff. If result is empty, it is OK, else not.

if (array_diff($uploaded_array, $allowed_array)) {
    echo "not ok";
}


问:
Xcode 4 libxml/... not found, new problem
I have searched the net and the consensus seems to be to add ${SDK_DIR}/usr/lib/libxml2 to the 'Header Search Paths'. I have done this and I can see in the project inspector that it expands the to correct full path name. I'm still getting errors that it can't find libxml/tree.h, etc. I have also tried using just /usr/lib/libxml2. That didn't work either. In both cases when I look at the command line generated by Xcode I don't see a -I with my Header Search Paths.</p>

答: Try adding $SDK_DIR/usr/include/libxml2 to Header Search Paths.</p>

ContentLicense: CC BY-SA 2.5


问:
Write a function called operations that takes as input two positive integers h and w, makes two random matrices A and B, of size h x w
I am trying to solve below practice question and stuck.

Q> Write a function called operations that takes as input two positive integers h and w, makes two random matrices A and B, of size h x w, and returns A,B, and s, the sum of A and B.

```<code>import numpy as np
def operations(h, w):
    if h>0 and w>0 and type(h)==int and type(w)==int:
        A = np.random.rand(h, w)
        B = np.random.rand(h, w)
        s = (A, B, A+B)
        return A
        return B
        return s
x=int(input("Enter a positive number for x: "))
y=int(input("Enter a positive number for y: "))
r=operations(x, y)
print(r)
</code>```

答:
```<code>import numpy as np
def operations(h, w):
    if h>0 and w>0 and type(h)==int and type(w)==int:
        A = np.random.rand(h, w)
        B = np.random.rand(h, w)
        s = A+B
        return A,B,s
x=int(input("Enter a positive number for x: "))
y=int(input("Enter a positive number for y: "))
A,B,s=operations(x, y)
print('A = ')
print(A)
print('B = ')
print(B)
print('Sum A and B = ')
print(s)
</code>```

Body:
I am trying to solve below practice question and stuck.

Q> Write a function called operations that takes as input two positive integers h and w, makes two random matrices A and B, of size h x w, and returns A,B, and s, the sum of A and B.

import numpy as np
def operations(h, w):
    if h>0 and w>0 and type(h)==int and type(w)==int:
        A = np.random.rand(h, w)
        B = np.random.rand(h, w)
        s = (A, B, A+B)
        return A
        return B
        return s
x=int(input("Enter a positive number for x: "))
y=int(input("Enter a positive number for y: "))
r=operations(x, y)
print(r)


问:
What am I doing wrong? - Uncaught TypeError: Object(...) is not a function - React GraphQL
I read in other posts that to solve this issue I need to install "react": "16.8.0" and "react-dom": "16.8.0", I already did that and the error persists-

This is the first time messing with GraphQL, here is my code (simplified)

```<code>import React from 'react'
import { Query } from 'react-apollo'
import { gql } from 'graphql-tag'

const Header = () => (
      <Query query={
         gql`
          {
            menu(id: "TWVudToy") {
              menuId
            }
          }`
      }>

        {
          ({ loading, error, data }) => {
            console.log(data)
            return <div>ff</div>
        }

        }
      </Query>

)

export default Header
</code>```

The full error is

```<code>Uncaught TypeError: Object(...) is not a function
    at Header (index.js:40)
    at renderWithHooks (react-dom.development.js:12740)
    at mountIndeterminateComponent (react-dom.development.js:14670)
    at beginWork (react-dom.development.js:15194)
    at performUnitOfWork (react-dom.development.js:18780)
    at workLoop (react-dom.development.js:18820)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:18052)
</code>```

答:
If you are using GraphQL it should be a directive so this:

```<code><Query query={
   gql`
     {
       menu(id: "TWVudToy") {
...
</code>```

Should be

```<code><Query query={
  gql`
    query menu(id: 'TWVudToy') {
...
</code>```

That, and really you should be abstracting out the query code. So something like this:

```<code>const MY_QUERY = gql`
  ...
</code>```

Then it makes your query more readable:

```<code><Query query={MY_QUERY} variables={...
</code>```

Body:
I read in other posts that to solve this issue I need to install "react": "16.8.0" and "react-dom": "16.8.0", I already did that and the error persists-

This is the first time messing with GraphQL, here is my code (simplified)

import React from 'react'
import { Query } from 'react-apollo'
import { gql } from 'graphql-tag'

const Header = () => (
      <Query query={
         gql`
          {
            menu(id: "TWVudToy") {
              menuId
            }
          }`
      }>

        {
          ({ loading, error, data }) => {
            console.log(data)
            return
ff

        }

        }
      </Query>

)

export default Header

The full error is

Uncaught TypeError: Object(...) is not a function
    at Header (index.js:40)
    at renderWithHooks (react-dom.development.js:12740)
    at mountIndeterminateComponent (react-dom.development.js:14670)
    at beginWork (react-dom.development.js:15194)
    at performUnitOfWork (react-dom.development.js:18780)
    at workLoop (react-dom.development.js:18820)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:18052)

Body:
If you are using GraphQL it should be a directive so this:

<Query query={
   gql`
     {
       menu(id: "TWVudToy") {
...

Should be

<Query query={
  gql`
    query menu(id: 'TWVudToy') {
...

That, and really you should be abstracting out the query code. So something like this:

const MY_QUERY = gql`
  ...

Then it makes your query more readable:

<Query query={MY_QUERY} variables={...


问:
Spark dataFrame for-if loop taking a Long time
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

```<code>val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}
</code>```

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

答:
Here is my try. You can use a window to separate the sentence by counting the number of . for the following rows.

```<code>import org.apache.spark.sql.expressions.Window
val w = Window.orderBy("start_time").rowsBetween(Window.currentRow, Window.unboundedFollowing)
val df = Seq((132, 135, "Hi"),
             (135, 135, ","),
             (143, 152, "I"),
             (151, 152, "am"),
             (159, 169, "working"),
             (194, 197, "on"),
             (204, 211, "hadoop"),
             (211, 211, "."),
             (218, 212, "This"),
             (226, 229, "is"),
             (234, 239, "Spark"),
             (245, 249, "DF"),
             (253, 258, "coding"),
             (258, 258, "."),
             (276, 276, "I")).toDF("start_time", "end_time", "words")
df.withColumn("count", count(when(col("words") === ".", true)).over(w))
  .groupBy("count")
  .agg(min("start_time").as("start_time"), max("end_time").as("end_time"), concat_ws(" ", collect_list("words")).as("Sentences"))
  .drop("count").show(false)
</code>```

Then, this will give you the result as follows but it has some spaces between words and , or . as follows:

```<code>+----------+--------+-----------------------------+
|start_time|end_time|Sentences                    |
+----------+--------+-----------------------------+
|132       |211     |Hi , I am working on hadoop .|
|218       |258     |This is Spark DF coding .    |
|276       |276     |I                            |
+----------+--------+-----------------------------+
</code>```

Body:
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

Body:
Here is my try. You can use a window to separate the sentence by counting the number of . for the following rows.

import org.apache.spark.sql.expressions.Window
val w = Window.orderBy("start_time").rowsBetween(Window.currentRow, Window.unboundedFollowing)
val df = Seq((132, 135, "Hi"),
             (135, 135, ","),
             (143, 152, "I"),
             (151, 152, "am"),
             (159, 169, "working"),
             (194, 197, "on"),
             (204, 211, "hadoop"),
             (211, 211, "."),
             (218, 212, "This"),
             (226, 229, "is"),
             (234, 239, "Spark"),
             (245, 249, "DF"),
             (253, 258, "coding"),
             (258, 258, "."),
             (276, 276, "I")).toDF("start_time", "end_time", "words")
df.withColumn("count", count(when(col("words") === ".", true)).over(w))
  .groupBy("count")
  .agg(min("start_time").as("start_time"), max("end_time").as("end_time"), concat_ws(" ", collect_list("words")).as("Sentences"))
  .drop("count").show(false)

Then, this will give you the result as follows but it has some spaces between words and , or . as follows:

+----------+--------+-----------------------------+
|start_time|end_time|Sentences                    |
+----------+--------+-----------------------------+
|132       |211     |Hi , I am working on hadoop .|
|218       |258     |This is Spark DF coding .    |
|276       |276     |I                            |
+----------+--------+-----------------------------+


问:
Why must a variable be declared in a for loop initialization?

int v = 0;

for (v; v<2; v++) {
    ...

}
```

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

答:
According to the java doc

The general form of the for statement can be expressed as follows:

```<code>for (initialization; termination; increment) {
    statement(s)
}
</code>```

...

The three expressions of the for loop are optional

Means that you could create for loop and leave some of 3 expr empty. One of options is declare int v before loop:

```<code>int v = 0;
for(; v<2; v++)
</code>```

Body:
int v = 0;

for (v; v<2; v++) {
    ...

}

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

Body:
According to the java doc

The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) {
    statement(s)
}

...

The three expressions of the for loop are optional

Means that you could create for loop and leave some of 3 expr empty. One of options is declare int v before loop:

int v = 0;
for(; v<2; v++)


问:
Blazor NavigationManager NullReference error in code behind
Using Blazor in VS19 Professional I'm getting a NullReference exception when I try to use the NavigationManager.NavigateTo function from the code behind .razor.cs file.

I first inject the NaviagtionManager at the top of the .razor.cs file:

```<code>[Inject]
protected NavigationManager NavigationManager { get; set; }
</code>```

Then when the users clicks a submit button, data is saved to an SQL database (this part works fine) and then the page should then redirect to another page, but it fails due to "NavigationManager.get returned null" error.

This is the function saving the data and calling the NavigationManager:

```<code>public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("Bowling/2020");
    }
</code>```

I have been unable to find anything online to help me with this issue.

Does anyone have any idea how to solve this??

UPDATE WITH MORE CODE:

On the .razor page I have an EditForm which on submit calls an Update():

```<code><EditForm Model="@participant" OnValidSubmit="@Update">
</code>```

On the .razor.cs page, this is the Update() function:

```<code>public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("/Bowling/2020/");
    }
</code>```

The values in the database get updated correctly.

UPDATE:

Found the issue, see response below.

答:
This was a clear case of "don't leave anything out of your code example".

In my code I had this:

```<code>[Inject]
protected BowlingData Db { get; set; }
protected NavigationManager NavigationManager { get; set; }
</code>```

(Being new to Blazor, I figured that the [Inject] would include everything following it until my [Parameters] just under this code snip.

When I posted the question, I removed the

```<code>protected BowlingData Db {get; set;}
</code>```

line to minimize the amount of example code. If I hadn't done that, I'm sure my question would have been answered right away.

As soon as I added the second [inject] my code worked as it should:

```<code>[Inject]
protected BowlingData Db { get; set; }
[Inject]
protected NavigationManager NavigationManager { get; set; }
</code>```

Lessoned learned - both about Blazor and about posting questions :)

Body:
Using Blazor in VS19 Professional I'm getting a NullReference exception when I try to use the NavigationManager.NavigateTo function from the code behind .razor.cs file.

I first inject the NaviagtionManager at the top of the .razor.cs file:

[Inject]
protected NavigationManager NavigationManager { get; set; }

Then when the users clicks a submit button, data is saved to an SQL database (this part works fine) and then the page should then redirect to another page, but it fails due to "NavigationManager.get returned null" error.

This is the function saving the data and calling the NavigationManager:

public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("Bowling/2020");
    }

I have been unable to find anything online to help me with this issue.

Does anyone have any idea how to solve this??

UPDATE WITH MORE CODE:

On the .razor page I have an EditForm which on submit calls an Update():

<EditForm Model="@participant" OnValidSubmit="@Update">

On the .razor.cs page, this is the Update() function:

public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("/Bowling/2020/");
    }

The values in the database get updated correctly.

UPDATE:

Found the issue, see response below.

Body:
This was a clear case of "don't leave anything out of your code example".

In my code I had this:

[Inject]
protected BowlingData Db { get; set; }
protected NavigationManager NavigationManager { get; set; }

(Being new to Blazor, I figured that the [Inject] would include everything following it until my [Parameters] just under this code snip.

When I posted the question, I removed the

protected BowlingData Db {get; set;}

line to minimize the amount of example code. If I hadn't done that, I'm sure my question would have been answered right away.

As soon as I added the second [inject] my code worked as it should:

[Inject]
protected BowlingData Db { get; set; }
[Inject]
protected NavigationManager NavigationManager { get; set; }

Lessoned learned - both about Blazor and about posting questions :)


问:
Get missing numbers from mysql database between two numbers
I'd like to get the missing numbers from a mysql database between two numbers. The range is from 0000000001 to 9999999999. In my table I have two columns serial_start and serial_end. In the first row, values are 100 and 500 and in the second row, 501 and 9999999999. I want to get the missing values from 1 to 99.

![enter image description here][1]

答:
You can use lead() to get the missing values in-between rows and union all to bring in the first one:

```<code>select serial_start + 1, next_ss - 1
from (select t.*,
             lead(serial_start) over (partition by year order by serial_start) as next_ss
      from t
      where year = 2020
     ) t
where next_ss is not null or next_ss <> ss + 1
union all
select 1, min(serial_start) - 1
from t
where year = 2020
group by year
having min(serial_start) <> 1;
</code>```

Body:
You can use lead() to get the missing values in-between rows and union all to bring in the first one:

select serial_start + 1, next_ss - 1
from (select t.*,
             lead(serial_start) over (partition by year order by serial_start) as next_ss
      from t
      where year = 2020
     ) t
where next_ss is not null or next_ss <> ss + 1
union all
select 1, min(serial_start) - 1
from t
where year = 2020
group by year
having min(serial_start) <> 1;


问:
How to add new framework version in Installment Requirement page of InstallShield?
As you see from Project Assistant->Installment Requirement screenshot of InstallShield, It is showing only till .NET Framework 4.6 in the list.

How do I add other frameworks like 4.7 and above?

答:
You can add this file:
Condition file
to path: C:\Program Files (x86)\InstallShield\20xx\SetupPrerequisites</p>


问:
Fixing UnboundLocalError: local variable 'name' referenced before assignment in python
Reading a text file with names and birthdays in a function printBook(), returning name, birthday and referencing it later on in another function I get:

UnboundLocalError: local variable 'name' referenced before assignment

Code:

```<code>with open("scratch.txt") as file:

    def printBook():
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

    def givenMonthPrintsElse(monthGiven):
        obj = printBook()
        if monthGiven == obj[1]:
            print("Name:", obj[0], "Day:", obj[2])

    printBook()
    givenMonthPrintsElse("Feb")
</code>```

答:
Although there is already an accepted answer, I believe it does not deal with the real issue in the question.
Elton's answer will prevent the exception from being thrown, but will not render the desired output, from what I understood of the question.

The Real Issue

The issue here is that when calling the printBook() function inside the givenMonthPrintsElse() function, there is nothing left to read in the file, therefore leading to no line objects, which skips the for loop, returning three unassigned variables (name, month and date).

This happens because the with ... open statement is misplaced. Once the file object is read on the printBook() function, the cursor is at EOF (end of file), thus nothing left to be read. Calling again another function that requires the output of printBook() under the same with ... open statement results in empty output. You can confirm this by commenting out the first call to printBook(), and you should get the desired output.

Solution (okay)

The simplest way I can think that solves it is moving the with ... open statement inside the printBook() function, like this:

def printBook():
    with open("scratch.txt") as file:
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

def givenMonthPrintsElse(monthGiven):
    obj = printBook()
    if monthGiven == obj[1]:
        print("Name:", obj[0], "Day:", obj[2])

printBook()
givenMonthPrintsElse("Feb")
```

<p>An important remark here is that, although it solves the issue, I suppose this is not the <strong>real</strong> intent of the OP, since it only allows to use the <strong>last</strong> line of the file (even though it reads through all of them). That is because <code>name</code>, <code>month</code> and <code>date</code> are overwritten at each iteration/line of the file, and only the last ones are returned by <code>printBook()</code>.</p>

<h1>Solution (better)</h1>

<p>So, as following, a simple structure allows to access any line of the file:</p>

<pre class="lang-py prettyprint-override"><code>def fileToList(fileName):
    with open(fileName) as file:
        values = file.readlines()
    return values

def printNameDate(fileList, monthGiven, entry=1):
    if monthGiven in fileList[entry-1]:
        name, month, date = fileList[entry-1].split(",")
        print("Name:", name, "\nDay:", date)

book = fileToList("scratch.txt")
printNameDate(book, "Feb")
</code>```

This way, in the book object you have a list of the content of all the lines, as strings, that afterwards you can split and process as desired. The printNameDate() function uses a list of strings (as the one returned by fileToList() and a line number (named entry)) to get the desired output.

Body:
Reading a text file with names and birthdays in a function printBook(), returning name, birthday and referencing it later on in another function I get:

UnboundLocalError: local variable 'name' referenced before assignment

Code:

with open("scratch.txt") as file:

    def printBook():
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

    def givenMonthPrintsElse(monthGiven):
        obj = printBook()
        if monthGiven == obj[1]:
            print("Name:", obj[0], "Day:", obj[2])

    printBook()
    givenMonthPrintsElse("Feb")

Body:
Although there is already an accepted answer, I believe it does not deal with the real issue in the question.
Elton's answer will prevent the exception from being thrown, but will not render the desired output, from what I understood of the question.

The Real Issue

The issue here is that when calling the printBook() function inside the givenMonthPrintsElse() function, there is nothing left to read in the file, therefore leading to no line objects, which skips the for loop, returning three unassigned variables (name, month and date).

This happens because the with ... open statement is misplaced. Once the file object is read on the printBook() function, the cursor is at EOF (end of file), thus nothing left to be read. Calling again another function that requires the output of printBook() under the same with ... open statement results in empty output. You can confirm this by commenting out the first call to printBook(), and you should get the desired output.

Solution (okay)

The simplest way I can think that solves it is moving the with ... open statement inside the printBook() function, like this:

def printBook():
    with open("scratch.txt") as file:
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

def givenMonthPrintsElse(monthGiven):
    obj = printBook()
    if monthGiven == obj[1]:
        print("Name:", obj[0], "Day:", obj[2])

printBook()
givenMonthPrintsElse("Feb")

An important remark here is that, although it solves the issue, I suppose this is not the real intent of the OP, since it only allows to use the last line of the file (even though it reads through all of them). That is because name, month and date are overwritten at each iteration/line of the file, and only the last ones are returned by printBook().

Solution (better)

So, as following, a simple structure allows to access any line of the file:

def fileToList(fileName):
    with open(fileName) as file:
        values = file.readlines()
    return values

def printNameDate(fileList, monthGiven, entry=1):
    if monthGiven in fileList[entry-1]:
        name, month, date = fileList[entry-1].split(",")
        print("Name:", name, "\nDay:", date)

book = fileToList("scratch.txt")
printNameDate(book, "Feb")

This way, in the book object you have a list of the content of all the lines, as strings, that afterwards you can split and process as desired. The printNameDate() function uses a list of strings (as the one returned by fileToList() and a line number (named entry)) to get the desired output.


问:
How can I animate items of an array in JSX
I have a list of chats in an array, that is updated live, when a user chats with a chatbot.
When a new message arrives, the newest message is moved to the top.

I now want to animate this behaviour. Does anybody know, how I can add a animation or transition to the element, that is moved to the top?

My Component:

```<code>import { Component, h, Prop } from '@stencil/core';
import { BotUserModel } from '../../global/models/BotUserModel';
import { ChatCategory } from '../../global/models/ChatCategory';

@Component({
  tag: 'chathub-pool-column',
  styleUrl: 'pool-column.scss',
  shadow: true,
})
export class PoolColumn {
  @Prop()
  category: ChatCategory;

  render() {
    return (
      <div key={this.category.title}>
        <p>{this.category.title} | {this.category.chats.length}</p>
        <div>
          {this.category.chats.map((botUser: BotUserModel) => (
            <div key={botUser._id}
              class={
                'card text-white bg-primary mb-3 p-2 poolCard rounded-0'
              }
            >
              <div class={'card-header'}>{botUser._id}</div>
              <div class={'card-body d-flex flex-row ' +
              'justify-content-between align-items-center'}>
                <span class={'w-100 mr-2'}>
                  {botUser.incomingMessages.length > 0
                    ? botUser.incomingMessages[
                    botUser.incomingMessages.length - 1
                      ].text
                    : 'No message has arrived'}
                </span>
                <i class={'fa-plus'} />
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

}
</code>```

Here is how this looks in the Browser

EDIT:

To clarify: My ideal solution would be, that the chat with the newest Message moves to the top, while the other entries go one step lower. Like you would sort a list per drag and drop. My initial idea was to use CSS-Transitions, but I don't know which attribute to listen on in this case.

With some help/inspiration of Christian (see comments) I made a simple blink effect that triggers, when a new message arrives.

```<code>.blink {
  animation: pulse .5s;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.75;
  }

  100% {
    opacity: 1;
  }
}
</code>```

The code Method in the component (I changed the initial code quite a bit."this.card" refers to the div, that is created with this.category.chats.map)

```<code>  @Watch('timestamp')
  handleTextChange() {
    this.card.classList.add('blink');
    this.card.onanimationend = () => {
      this.card.classList.remove('blink');
    };
  }
</code>```

This is fine, but if you have an idea, how I could achieve my ideal solution, I would be very grateful.

答:
I would go with a CSS animation. In my point of view that is the most easiest way to achieve an animation that doesn't mess up your code. Sadly I can't see your CSS properties and I'm not sure which of your classes is suitable for this but my idea would be something like:

```<code>.card {
  /*Your properties*/

  animation-duration: .3s;
  animation-name: slidein;
  animation-fill-mode: forwards;
  width: 0%;
  overflow: hidden;

  /*Your properties*/
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 0%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}
</code>```

But as I mentioned above - that depends a on your already written CSS.
A really good website in my opinion to get a real quick start for ready to use animations would be this:

https://animista.net/play/entrances

Addition

I think it's not necessary in your case but you can run the animations one by one:

```<code>  {this.category.chats.map((botUser: BotUserModel, index) => (
    <div key={botUser._id}
      class={
        'card text-white bg-primary mb-3 p-2 poolCard rounded-0'
      }
      style={{'animation-delay': index+'s'}}
    >
</code>```

So the two differences are using the index of the map function and than using inline style tag with the animation delay. The first one has 1s delay, second 2s delay and so on.

Body:
I have a list of chats in an array, that is updated live, when a user chats with a chatbot.
When a new message arrives, the newest message is moved to the top.

I now want to animate this behaviour. Does anybody know, how I can add a animation or transition to the element, that is moved to the top?

My Component:

import { Component, h, Prop } from '@stencil/core';
import { BotUserModel } from '../../global/models/BotUserModel';
import { ChatCategory } from '../../global/models/ChatCategory';

@Component({
  tag: 'chathub-pool-column',
  styleUrl: 'pool-column.scss',
  shadow: true,
})
export class PoolColumn {
  @Prop()
  category: ChatCategory;

  render() {
    return (

{this.category.title} | {this.category.chats.length}

          {this.category.chats.map((botUser: BotUserModel) => (

{botUser._id}

                  {botUser.incomingMessages.length > 0
                    ? botUser.incomingMessages[
                    botUser.incomingMessages.length - 1
                      ].text
                    : 'No message has arrived'}

          ))}

    );
  }

}

Here is how this looks in the Browser

EDIT:

To clarify: My ideal solution would be, that the chat with the newest Message moves to the top, while the other entries go one step lower. Like you would sort a list per drag and drop. My initial idea was to use CSS-Transitions, but I don't know which attribute to listen on in this case.

With some help/inspiration of Christian (see comments) I made a simple blink effect that triggers, when a new message arrives.

.blink {
  animation: pulse .5s;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.75;
  }

  100% {
    opacity: 1;
  }
}

The code Method in the component (I changed the initial code quite a bit."this.card" refers to the div, that is created with this.category.chats.map)

  @Watch('timestamp')
  handleTextChange() {
    this.card.classList.add('blink');
    this.card.onanimationend = () => {
      this.card.classList.remove('blink');
    };
  }

This is fine, but if you have an idea, how I could achieve my ideal solution, I would be very grateful.

Body:
I would go with a CSS animation. In my point of view that is the most easiest way to achieve an animation that doesn't mess up your code. Sadly I can't see your CSS properties and I'm not sure which of your classes is suitable for this but my idea would be something like:

.card {
  /*Your properties*/

  animation-duration: .3s;
  animation-name: slidein;
  animation-fill-mode: forwards;
  width: 0%;
  overflow: hidden;

  /*Your properties*/
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 0%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

But as I mentioned above - that depends a on your already written CSS.
A really good website in my opinion to get a real quick start for ready to use animations would be this:

https://animista.net/play/entrances

Addition

I think it's not necessary in your case but you can run the animations one by one:

  {this.category.chats.map((botUser: BotUserModel, index) => (
    <div key={botUser._id}
      class={
        'card text-white bg-primary mb-3 p-2 poolCard rounded-0'
      }
      style={{'animation-delay': index+'s'}}
    >

So the two differences are using the index of the map function and than using inline style tag with the animation delay. The first one has 1s delay, second 2s delay and so on.


问:
How to convert a dictionary object to Node in py2neo?
I have a dictionary object like the following

```<code>node_info = {'id':'2344','name':'xyz'}
</code>```

I want to convert it to py2neo Node so that it can be created using graph.create(). Node.cast() is no longer supported. Any other way

答:
According to the definition for py2neo v4.0's Node class:

class py2neo.data.Node(*labels, **properties)

which means you can pass any number of labels:

Node("Person", "Professor")

and any number of labelled/named properties:

Node(id=10, name="Long John Silver")

Answering your question

You can achieve the above with either a list (for labels) and dict (for named properties):

labels = ["Person", "Professor"]
props  = {"id": 10, "name": "Long John Silver"}
print(Node(*labels, **props))
```

will yield:

(:Person:Professor {id: 10, name: 'Long John Silver'})

This is because of Python's *args and **kwargs in python Geeks4Geeks ref

Body:
I have a dictionary object like the following

node_info = {'id':'2344','name':'xyz'}

I want to convert it to py2neo Node so that it can be created using graph.create(). Node.cast() is no longer supported. Any other way

Body:
According to the definition for py2neo v4.0's Node class:

class py2neo.data.Node(*labels, **properties)

which means you can pass any number of labels:

Node("Person", "Professor")

and any number of labelled/named properties:

Node(id=10, name="Long John Silver")

Answering your question

You can achieve the above with either a list (for labels) and dict (for named properties):

labels = ["Person", "Professor"]
props  = {"id": 10, "name": "Long John Silver"}
print(Node(*labels, **props))

will yield:

(:Person:Professor {id: 10, name: 'Long John Silver'})

This is because of Python's *args and **kwargs in python Geeks4Geeks ref


问:
Handle MouseEvent.CLICK, MOUSE_DOWN in subclasses
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

```<code>this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);
</code>```

It's done at the creation stage.

In my subclasses I override handleMouse handler.

```<code>override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}
</code>```

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

```<code>this.rowChildren.addChild(button);
</code>```

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

答:
call the superclass method like so</p>

```<code>override protected handleMouse(event:MouseEvent) : void
{
  super.handleMouse(event);
  // subclass specific handling
}
</code>```

Body:
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);

It's done at the creation stage.

In my subclasses I override handleMouse handler.

override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

this.rowChildren.addChild(button);

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

Body:
call the superclass method like so

override protected handleMouse(event:MouseEvent) : void
{
  super.handleMouse(event);
  // subclass specific handling
}


答:
Your loop declaration is valid if you remove the extraneous v in the declaration (assuming v was declared beforehand):

Change it to for(; v < 2; v++)

All three modifiers in the traditional for loop are optional in Java.

Alternatives examples:

Below is the same as a while (true) loop:

```<code>for (;;) {

}
</code>```

Adding extra increments:

```<code>int j = 0;
for (int k = 0; k < 10; k++, j++) {

}
</code>```

Adding extra conditions to terminate the loop:

```<code>int j = 0;
for (int k = 0; k < 10 || j < 10; k++, j++) {

}
</code>```

Declaring multiple of the same type variable:

```<code>for (int k = 0, j = 0; k < 10 || j < 10; k++, j++) {

}
</code>```

And obviously you can mix and match any of these as you want, completely leaving out whichever ones you want.

Title: Why must a variable be declared in a for loop initialization?

Body:
Your loop declaration is valid if you remove the extraneous v in the declaration (assuming v was declared beforehand):

Change it to for(; v < 2; v++)

All three modifiers in the traditional for loop are optional in Java.

Alternatives examples:

Below is the same as a while (true) loop:

for (;;) {

}

Adding extra increments:

int j = 0;
for (int k = 0; k < 10; k++, j++) {

}

Adding extra conditions to terminate the loop:

int j = 0;
for (int k = 0; k < 10 || j < 10; k++, j++) {

}

Declaring multiple of the same type variable:

for (int k = 0, j = 0; k < 10 || j < 10; k++, j++) {

}

And obviously you can mix and match any of these as you want, completely leaving out whichever ones you want.


问:
Unable to track location (TYPE_LOCATION_SAMPLE) with Google Fit for Android
I'm trying to track location using the recording client for Google Fit on Android, but I'm unsure if it's even possible using TYPE_LOCATION_SAMPLE. Recording steps (TYPE_STEP_COUNT_DELTA) and activity segments (TYPE_ACTIVITY_SEGMENT) works fine, but subscribing to TYPE_LOCATION_SAMPLE doesn't seem to do anything.

I can successfully subscribe to the data type TYPE_LOCATION_SAMPLE and I have a data source, but if I query the history client for data, there is nothing there. Again, this works for steps and activities - just not for location.

I've made sure the location permission is granted. I've moved around to change location. I've tried with GoogleSignIn.getAccountForExtension as well, still nothing. Is it not possible to record location like this, or am I just going about it the wrong way?

I'm subscribing to location data like this:

```<code>Fitness
    .getRecordingClient(activity, GoogleSignIn.getLastSignedInAccount(activity.applicationContext)!!)
    .subscribe(DataType.TYPE_LOCATION_SAMPLE)
</code>```

I'm requesting the history data like this:

```<code>val readRequest = DataReadRequest.Builder()
    .read(DataType.TYPE_LOCATION_SAMPLE)
    .setTimeRange(from.timeInMillis, to.timeInMillis, TimeUnit.MILLISECONDS)
    .build()

Fitness
    .getHistoryClient(activity, GoogleSignIn.getLastSignedInAccount(activity.applicationContext)!!)
    .readData(readRequest)
    .addOnSuccessListener { dataReadResponse ->
         //returns 1 empty dataset
    }
</code>```

Update: I've tried inserting locations manually with HistoryClient.insertData just to see if I could get something to work that way. I still can't get any data when querying the history, but the distance delta has changed based on the locations I've added, so something is happening. But I still can't get the actual locations from history.

答:
You can only read location data that your app wrote.

This is described in the Exceptions section in the Public Data Types documentation.

Body:
I'm trying to track location using the recording client for Google Fit on Android, but I'm unsure if it's even possible using TYPE_LOCATION_SAMPLE. Recording steps (TYPE_STEP_COUNT_DELTA) and activity segments (TYPE_ACTIVITY_SEGMENT) works fine, but subscribing to TYPE_LOCATION_SAMPLE doesn't seem to do anything.

I can successfully subscribe to the data type TYPE_LOCATION_SAMPLE and I have a data source, but if I query the history client for data, there is nothing there. Again, this works for steps and activities - just not for location.

I've made sure the location permission is granted. I've moved around to change location. I've tried with GoogleSignIn.getAccountForExtension as well, still nothing. Is it not possible to record location like this, or am I just going about it the wrong way?

I'm subscribing to location data like this:

Fitness
    .getRecordingClient(activity, GoogleSignIn.getLastSignedInAccount(activity.applicationContext)!!)
    .subscribe(DataType.TYPE_LOCATION_SAMPLE)

I'm requesting the history data like this:

val readRequest = DataReadRequest.Builder()
    .read(DataType.TYPE_LOCATION_SAMPLE)
    .setTimeRange(from.timeInMillis, to.timeInMillis, TimeUnit.MILLISECONDS)
    .build()

Fitness
    .getHistoryClient(activity, GoogleSignIn.getLastSignedInAccount(activity.applicationContext)!!)
    .readData(readRequest)
    .addOnSuccessListener { dataReadResponse ->
         //returns 1 empty dataset
    }

Update: I've tried inserting locations manually with HistoryClient.insertData just to see if I could get something to work that way. I still can't get any data when querying the history, but the distance delta has changed based on the locations I've added, so something is happening. But I still can't get the actual locations from history.


问:
Getting a segmentation fault while implementing Trie in c++
Another day another seg fault I don't understand, I'm trying to implement tries for the first time and it is proving to be quite some challenge, I think it would be very helpful if someone could tell me what I'm doing wrong, would probably help me understand OOP better too I suppose, because I think the error is related to that.

The fault happens while searching and I wasn't able to understand it using the debugger myself.

Here is the code:

```<code>#include <vector>
#include <iostream>

using std::string, std::cout, std::vector;

class TrieNode {
    private:
        bool isLeaf;
        vector<TrieNode*> ar = vector<TrieNode*>(26);

    public:
        TrieNode() {
            isLeaf = false;
            for(int i = 0; i < 26; i++) ar[i] = nullptr;
        }

    void insert(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                crawl->ar[key[i]] = new TrieNode();
            }
            crawl = crawl->ar[key[i]];
        }
        crawl->isLeaf = true;
    }

    bool search(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                return false;
            }
            crawl = crawl->ar[key[i]];
        }
        return crawl->isLeaf;
    }
};

int main() {
    TrieNode* head = new TrieNode();
    head->insert(head, "hello");
    cout << head->search(head, "hello");
}
</code>```

答:
Make your ar[key[i]] to something like ar[key[i]-'a'] if your string is say always lower-case.

Basically, key[i] is a char in the range of ['a'-'z']. When it's implicitly converted to an int, it's not in the range of [0,25], but rather equal to their ascii values.

Body:
Another day another seg fault I don't understand, I'm trying to implement tries for the first time and it is proving to be quite some challenge, I think it would be very helpful if someone could tell me what I'm doing wrong, would probably help me understand OOP better too I suppose, because I think the error is related to that.

The fault happens while searching and I wasn't able to understand it using the debugger myself.

Here is the code:

#include <vector>
#include <iostream>

using std::string, std::cout, std::vector;

class TrieNode {
    private:
        bool isLeaf;
        vector<TrieNode*> ar = vector<TrieNode*>(26);

    public:
        TrieNode() {
            isLeaf = false;
            for(int i = 0; i < 26; i++) ar[i] = nullptr;
        }

    void insert(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                crawl->ar[key[i]] = new TrieNode();
            }
            crawl = crawl->ar[key[i]];
        }
        crawl->isLeaf = true;
    }

    bool search(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                return false;
            }
            crawl = crawl->ar[key[i]];
        }
        return crawl->isLeaf;
    }
};

int main() {
    TrieNode* head = new TrieNode();
    head->insert(head, "hello");
    cout <search(head, "hello");
}


问:
Bash - replace in file strings from first array with strings from second array
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

```<code>file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done
</code>```

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

答:
I found a way to fix this.

I am deleting string from the first array once replaced.

```<code>file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                        delete="${array1[$i]}"
                        array1=( "${array1[@]/$delete}" )
                 fi
        done
done
</code>```

Body:
I have two arrays. The first one is filled with values greped from the file that I want to replace with the new ones downloaded.

Please note that I don't know exactly how the first array will look like, meaning some values will have _, other - and some won't have any of that and immediately after the name will be placed : (colon).

Example arrays:

array1:

[account:123 shoppingcart-1:123 notification-core_1:123 notification-dispatcher_core_1:123 notification-dispatcher-smschannel_core_1:123]

array2:

[account_custom_2:124 shoppingcart_custom_2:124 notification_custom_2:124 notification-dispatcher_custom_2:124 notification-dispatcher-smschannel_custom_2:124]

Those arrays are the only example, there are more than 50 values to replace.

I am doing a comparison of every item in the second array with every item in the first array as shown below:

file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                 fi
        done
done

Here I substring only the first part for every item in the second array so I can compare it with the item in the first array.

e.g. account_custom_2:124 -> account or notification-dispatcher_custom_2:124 -> notification-dispatcher.

This works nice but I encounter problem when notification is in notification-core_1:123 and notification-dispatcher_core_1:123 and notification-dispatcher-smschannel_core_1:123.

Can you please give advice on how to fix this or if you can suggest another approach to this?

Body:
I found a way to fix this.

I am deleting string from the first array once replaced.

file_name="<path_to_file>/file.txt"
for i in "${!array1[@]}"
do
        for j in "${!array2[@]}"
        do
                array_2_base="`echo ${array2[$j]} | awk -F_ '{print $1}'`"
                if [[ "${array1[$i]}" == *"$array_2_base"* ]]
                then
                        sed -i "s=${array1[$i]}=${array2[$j]}=g" $file_name
                        delete="${array1[$i]}"
                        array1=( "${array1[@]/$delete}" )
                 fi
        done
done


问:
Can not create a new database by using pgadmin4
I was trying to create a new database on pgadmin4 on my Ubuntu computer, but I got two errors.

The first one: "Error saving properties";

The second one: "Error retrieving the information - INTERNAL SERVER ERROR".

I have been looking for an answer and I found nothing but tutorials to create without error.
I am starting to learn SQL and need to get it working as soon as possible to carry on my course.

------------OS------------

PostgreSQL 10

pgAdmin 4

Ubuntu 16.04 LTS 64-bit

答:
As stated in other answer before , this works:
clear Encoding field in Definitions tab

In my case the default was UTF8 , and I had to clear that to Nothing.


问:
Breakpoint-sass not loading in gulp setup, Susy is working fine
Hi I'm trying to get breakpoint-sass working with susy in my Gulp set-up

I have ran npm install breakpoint-sass --save-dev and linked it to the top of my sass file with  @import "./node_modules/breakpoint-sass/stylesheets/breakpoint"; (susy is working fine from @import "./node_modules/susy/sass/susy";)

my gulp sass task is this

```<code>gulp.task("styles", function() {
return gulp.src("scss/application.scss")
    .pipe( bulkSass())
    .pipe(maps.init())
    .pipe(sass())
    .pipe(sass({
        outputStyle: 'compressed',
        includePaths: ['node_modules/susy/sass', 'node_modules/breakpoint-sass/stylesheets/breakpoint'],
    }).on('error', sass.logError))
    .pipe(maps.write('./'))
    //.pipe(autoprefixer())
    .pipe(gulp.dest('./build/css/'))
    .pipe(reload({stream:true}))
});
</code>```

and my scss partial

```<code>@import "./node_modules/breakpoint-sass/stylesheets/breakpoint";
@import "./node_modules/susy/sass/susy";

  #main {
    @include span(12);
    background: $primary-color;
    text-align: center;
       h1 {
        color: green;
        height: 2em;
       }

        @include breakpoint(500px){
          h1{
            color: red;
       }

    }

 }
</code>```

the h1 tag is red at all screen widths and never green. I can't see why this is happening. I have used breakpoint before in a grunt project with ruby and had no issues.

Thanks

答: Thanks – just one small tweak to suggest for anyone who tried the good solution by @zisoft and couldn't get it to work, I used './node_modules/breakpoint-sass/stylesheets' with success, where without the ./ in front it would fail. Maybe obvious to some people, but wanted to make a note.

Body:
Hi I'm trying to get breakpoint-sass working with susy in my Gulp set-up

I have ran npm install breakpoint-sass --save-dev and linked it to the top of my sass file with  @import "./node_modules/breakpoint-sass/stylesheets/breakpoint"; (susy is working fine from @import "./node_modules/susy/sass/susy";)

my gulp sass task is this

gulp.task("styles", function() {
return gulp.src("scss/application.scss")
    .pipe( bulkSass())
    .pipe(maps.init())
    .pipe(sass())
    .pipe(sass({
        outputStyle: 'compressed',
        includePaths: ['node_modules/susy/sass', 'node_modules/breakpoint-sass/stylesheets/breakpoint'],
    }).on('error', sass.logError))
    .pipe(maps.write('./'))
    //.pipe(autoprefixer())
    .pipe(gulp.dest('./build/css/'))
    .pipe(reload({stream:true}))
});

and my scss partial

@import "./node_modules/breakpoint-sass/stylesheets/breakpoint";
@import "./node_modules/susy/sass/susy";

  #main {
    @include span(12);
    background: $primary-color;
    text-align: center;
       h1 {
        color: green;
        height: 2em;
       }

        @include breakpoint(500px){
          h1{
            color: red;
       }

    }

 }

the h1 tag is red at all screen widths and never green. I can't see why this is happening. I have used breakpoint before in a grunt project with ruby and had no issues.

Thanks


问:
Array Should Only Contains Values From Other Array
I Have Two Arrays.

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");
</code>```

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

```<code>$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}
</code>```

答:
```<code>$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}
</code>```

Somehow made it work myself. just eliminated duplicates from first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had element which is not present in second array.

Body:
I Have Two Arrays.

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}

Body:
$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}

Somehow made it work myself. just eliminated duplicates from first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had element which is not present in second array.


问:
Order of traversal given by std::filesystem directory_iterator
When iterating through a directory using std::filesystem::directory_iterator, are there any guarantees regarding the order of traversal?

答:
From the docs:

The iteration order is unspecified, except that each directory entry
  is visited only once. The special pathnames dot and dot-dot are
  skipped.


问:
Randomly select number (without repetition) for each group in R
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

```<code>group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5
</code>```

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

```<code>group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...
</code>```

any suggestions on how I can achieve this?

答:
In base R, if you have df like this...

```<code>df
  group elements
     1        3
     2        1
     3       14
</code>```

Then you can do this...

```<code>data.frame(group = rep(df$group,                     #repeat group no...
                       df$elements),                 #elements times
           number = unlist(sapply(df$elements,       #for each elements...
                                  sample.int,        #...sample <elements> numbers
                                  n=30,              #from 1 to 30
                                  replace = FALSE))) #without duplicates

   group number
1      1     19
2      1     15
3      1     28
4      2     15
5      3     20
6      3     18
7      3     27
8      3     10
9      3     23
10     3     12
11     3     25
12     3     11
13     3     14
14     3     13
15     3     16
16     3     26
17     3     22
18     3      7
</code>```

Body:
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...

any suggestions on how I can achieve this?

Body:
In base R, if you have df like this...

df
  group elements
     1        3
     2        1
     3       14

Then you can do this...

data.frame(group = rep(df$group,                     #repeat group no...
                       df$elements),                 #elements times
           number = unlist(sapply(df$elements,       #for each elements...
                                  sample.int,        #...sample <elements> numbers
                                  n=30,              #from 1 to 30
                                  replace = FALSE))) #without duplicates

   group number
1      1     19
2      1     15
3      1     28
4      2     15
5      3     20
6      3     18
7      3     27
8      3     10
9      3     23
10     3     12
11     3     25
12     3     11
13     3     14
14     3     13
15     3     16
16     3     26
17     3     22
18     3      7


问:
What does the ?. syntax mean in JavaScript?
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

```<code>{cart?.widgets?.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}
</code>```

My concern with above code is whether cart?.widgets?.items will raise any error or not.

答: It's Optional Chaining and it should not cause any error if you use polyfills.  "?." - is not supported by default yet</p>

Body:
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

{cart?.widgets?.items.map(widget => (

{widget.name}

{widget.value} $

 ))}

My concern with above code is whether cart?.widgets?.items will raise any error or not.


答: That is probably the optional chaining from Typescript.</p>

Title: What does the ?. syntax mean in JavaScript?


问:
one hot encode each column in a Int matrix in R
I have an issue of translating matrix into one hot encoding in R. I implemented in Matlab but i have difficulty in handling the object in R. Here i have an object of type 'matrix'.

I would like to apply one hot encoding to this matrix. I have problem with column names.

here is an example:

```<code>> set.seed(4)
> t <- matrix(floor(runif(10, 1,9)),5,5)

      [,1] [,2] [,3] [,4] [,5]
[1,]    5    3    5    3    5
[2,]    1    6    1    6    1
[3,]    3    8    3    8    3
[4,]    3    8    3    8    3
[5,]    7    1    7    1    7
> class(t)
[1] "matrix"
</code>```

Expecting:

```<code>      1_1 1_3 1_5 1_7  2_1 2_3 2_6 2_8 ...
[1,]   0   0   1   0    0   1   0   0  ...
[2,]   1   0   0   0    0   0   1   0  ...
[3,]   0   1   0   0    0   0   0   1  ...
[4,]   0   1   0   0    0   0   0   1  ...
[5,]   0   0   0   1    1   0   0   0  ...
</code>```

I tried the following, but the matrix remains the same.

```<code>library(data.table)
library(mltools)
test_table <- one_hot(as.data.table(t))
</code>```

Any suggestions would be very much appreciated.

答:
There are probably more concise ways to do this but this should work (and is at least easy to read and understand ;)

Suggested solution using base R and double loop:

```<code>set.seed(4)
t <- matrix(floor(runif(10, 1,9)),5,5)

# initialize result object
#
t_hot <- NULL

# for each column in original matrix
#
for (col in seq_along(t[1,])) {
  # for each unique value in this column (sorted so the resulting
  # columns appear in order)
  #
  for (val in sort(unique(t[, col]))) {
    t_hot <- cbind(t_hot, ifelse(t[, col] == val, 1, 0))
    # make name for this column
    #
    colnames(t_hot)[ncol(t_hot)] <- paste0(col, "_", val)
  }
}
</code>```

This returns:

```<code>     1_1 1_3 1_5 1_7 2_1 2_3 2_6 2_8 3_1 3_3 3_5 3_7 4_1 4_3 4_6 4_8 5_1 5_3 5_5 5_7
[1,]   0   0   1   0   0   1   0   0   0   0   1   0   0   1   0   0   0   0   1   0
[2,]   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0   0
[3,]   0   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0
[4,]   0   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0
[5,]   0   0   0   1   1   0   0   0   0   0   0   1   1   0   0   0   0   0   0   1
</code>```

Body:
I have an issue of translating matrix into one hot encoding in R. I implemented in Matlab but i have difficulty in handling the object in R. Here i have an object of type 'matrix'.

I would like to apply one hot encoding to this matrix. I have problem with column names.

here is an example:

> set.seed(4)
> t <- matrix(floor(runif(10, 1,9)),5,5)

      [,1] [,2] [,3] [,4] [,5]
[1,]    5    3    5    3    5
[2,]    1    6    1    6    1
[3,]    3    8    3    8    3
[4,]    3    8    3    8    3
[5,]    7    1    7    1    7
> class(t)
[1] "matrix"

Expecting:

      1_1 1_3 1_5 1_7  2_1 2_3 2_6 2_8 ...
[1,]   0   0   1   0    0   1   0   0  ...
[2,]   1   0   0   0    0   0   1   0  ...
[3,]   0   1   0   0    0   0   0   1  ...
[4,]   0   1   0   0    0   0   0   1  ...
[5,]   0   0   0   1    1   0   0   0  ...

I tried the following, but the matrix remains the same.

library(data.table)
library(mltools)
test_table <- one_hot(as.data.table(t))

Any suggestions would be very much appreciated.

Body:
There are probably more concise ways to do this but this should work (and is at least easy to read and understand ;)

Suggested solution using base R and double loop:

set.seed(4)
t <- matrix(floor(runif(10, 1,9)),5,5)

# initialize result object
#
t_hot <- NULL

# for each column in original matrix
#
for (col in seq_along(t[1,])) {
  # for each unique value in this column (sorted so the resulting
  # columns appear in order)
  #
  for (val in sort(unique(t[, col]))) {
    t_hot <- cbind(t_hot, ifelse(t[, col] == val, 1, 0))
    # make name for this column
    #
    colnames(t_hot)[ncol(t_hot)] <- paste0(col, "_", val)
  }
}

This returns:

     1_1 1_3 1_5 1_7 2_1 2_3 2_6 2_8 3_1 3_3 3_5 3_7 4_1 4_3 4_6 4_8 5_1 5_3 5_5 5_7
[1,]   0   0   1   0   0   1   0   0   0   0   1   0   0   1   0   0   0   0   1   0
[2,]   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0   0
[3,]   0   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0
[4,]   0   1   0   0   0   0   0   1   0   1   0   0   0   0   0   1   0   1   0   0
[5,]   0   0   0   1   1   0   0   0   0   0   0   1   1   0   0   0   0   0   0   1