问:
Entity Framework does not seed entity relationship
As I'm trying to get my head around with Entity Framework code-first and how to set relationships between entities. I encountered an issue when I was trying to insert (seed) some data into my database. I'm trying to insert a product object inside the buys (order) object. That product property in buys is virtual to state that it is a navigation property. Is there a different way of approaching what I wanted to achieve?

I run Add-Migration initial and I get an error:

The seed entity for entity type 'Buys' cannot be added because it has the navigation 'Customer' set. To seed relationships you need to add the related entity seed to 'Customer' and specify the foreign key values {'customerID'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values

Below is the seeding method which runs in the data context class.

```<code>private void SeedDatabase(ModelBuilder builder)
{
        // Construct Data
        var productType = new ProductType()
        {
            typeName = "Operating System"
        };

        var product = new Product()
        {
            typeID = productType.typeID,
            productName = "Windows",
            productVersion = "10 Home",
            productDescription = "This version of windows is the Home 10 edition",
            keyPrice = 10,
            license = "ASDEW-2342-SDE34-FGR35",
            ProductType = productType
        };

        var customer = new Customer()
        {
            customerEmail = "test-customer@gmail.com",
            customerFullname = "John Derek"
        };

        var transaction = new Transaction()
        {
            paid = true,
            transactionAmount = 10
        };

        var order = new Buys()
        {
            customerID = customer.customerID,
            TransactionID = transaction.transcationID,
            quantity = 1,
            Date = new DateTime().Date,
            Transaction = transaction,
            Customer = customer,
            Product = product,
            productID = product.productID
        };

        transaction.Buy = order;
        System.Collections.Generic.List<Buys> orders = new System.Collections.Generic.List<Buys>() { order };
        product.customerBuys = orders;

        builder.Entity<ProductType>()
            .HasData(productType);

        builder.Entity<Product>()
           .HasData(product);

        builder.Entity<Customer>()
           .HasData(customer);

        builder.Entity<Transaction>()
           .HasData(transaction);

        builder.Entity<Buys>()
           .HasData(orders);
    }
</code>```

And here are the 2 models that is mentioning about.

```<code>public class Customer
{
    public Customer()
    {
        customerID = Guid.NewGuid().ToString();
    }

    [Key]
    public string customerID { get; set; }
    public string customerFullname { get; set; }
    public string customerEmail { get; set; }
    public virtual ICollection<Buys> customerBuys { get; set; }
}

// This is a join table between product and customer.
// Product can have many customers
// One customer can purchase many products
public class Buys
{
    public Buys()
    {
        buyID = Guid.NewGuid().ToString();
    }

    [Key]
    public string buyID { get; set; }
    public string productID { get; set; }
    public virtual Product Product { get; set; }
    public string customerID { get; set; }
    public virtual Customer Customer { get; set; }
    public int quantity { get; set; }
    public DateTime Date { get; set; }
    public string TransactionID { get; set; }
    public virtual Transaction Transaction { get; set; }
}
</code>```

答:
The Id fields are strings and you are not populating them anywhere.  Try seeding those IDs before passing the object to HasData().

Example:

```<code>var productType = new ProductType()
{
    Id = Guid.NewGuid().ToString(), //If they are supposed to be GUIDs
    typeName = "Operating System"
};
</code>```

Body:
As I'm trying to get my head around with Entity Framework code-first and how to set relationships between entities. I encountered an issue when I was trying to insert (seed) some data into my database. I'm trying to insert a product object inside the buys (order) object. That product property in buys is virtual to state that it is a navigation property. Is there a different way of approaching what I wanted to achieve?

I run Add-Migration initial and I get an error:

The seed entity for entity type 'Buys' cannot be added because it has the navigation 'Customer' set. To seed relationships you need to add the related entity seed to 'Customer' and specify the foreign key values {'customerID'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values

Below is the seeding method which runs in the data context class.

private void SeedDatabase(ModelBuilder builder)
{
        // Construct Data
        var productType = new ProductType()
        {
            typeName = "Operating System"
        };

        var product = new Product()
        {
            typeID = productType.typeID,
            productName = "Windows",
            productVersion = "10 Home",
            productDescription = "This version of windows is the Home 10 edition",
            keyPrice = 10,
            license = "ASDEW-2342-SDE34-FGR35",
            ProductType = productType
        };

        var customer = new Customer()
        {
            customerEmail = "test-customer@gmail.com",
            customerFullname = "John Derek"
        };

        var transaction = new Transaction()
        {
            paid = true,
            transactionAmount = 10
        };

        var order = new Buys()
        {
            customerID = customer.customerID,
            TransactionID = transaction.transcationID,
            quantity = 1,
            Date = new DateTime().Date,
            Transaction = transaction,
            Customer = customer,
            Product = product,
            productID = product.productID
        };

        transaction.Buy = order;
        System.Collections.Generic.List<Buys> orders = new System.Collections.Generic.List<Buys>() { order };
        product.customerBuys = orders;

        builder.Entity<ProductType>()
            .HasData(productType);

        builder.Entity<Product>()
           .HasData(product);

        builder.Entity<Customer>()
           .HasData(customer);

        builder.Entity<Transaction>()
           .HasData(transaction);

        builder.Entity<Buys>()
           .HasData(orders);
    }

And here are the 2 models that is mentioning about.

public class Customer
{
    public Customer()
    {
        customerID = Guid.NewGuid().ToString();
    }

    [Key]
    public string customerID { get; set; }
    public string customerFullname { get; set; }
    public string customerEmail { get; set; }
    public virtual ICollection<Buys> customerBuys { get; set; }
}

// This is a join table between product and customer.
// Product can have many customers
// One customer can purchase many products
public class Buys
{
    public Buys()
    {
        buyID = Guid.NewGuid().ToString();
    }

    [Key]
    public string buyID { get; set; }
    public string productID { get; set; }
    public virtual Product Product { get; set; }
    public string customerID { get; set; }
    public virtual Customer Customer { get; set; }
    public int quantity { get; set; }
    public DateTime Date { get; set; }
    public string TransactionID { get; set; }
    public virtual Transaction Transaction { get; set; }
}

Body:
The Id fields are strings and you are not populating them anywhere.  Try seeding those IDs before passing the object to HasData().

Example:

var productType = new ProductType()
{
    Id = Guid.NewGuid().ToString(), //If they are supposed to be GUIDs
    typeName = "Operating System"
};


来源: stackexchange

问:
How to convert my string '310519' to date object?
I have strings with dates in format '310519' ( it's 05/31/2019 ). How to convert my strings to date object?  new Date('310519') not working.

答:
The moment library can handle dates in whatever format you specify:

const source = "310519";
const date = moment(source, "DDMMYY");
console.log(date);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
The moment library can handle dates in whatever format you specify:

const source = "310519";
const date = moment(source, "DDMMYY");
console.log(date);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>


问:
"ERROR: Validation error" message when executing two Sequelize commands in "pretest" script
I'm writing tests for my project. It uses Sequelize and I thought about doing the following:

```<code>"pretest": "NODE_ENV=testing yarn sequelize db:migrate && yarn sequelize db:seed:all",
"test": "mocha --require @babel/register 'src/tests/**/*.spec.js'",
"posttest": "NODE_ENV=testing yarn sequelize db:migrate:undo:all"
</code>```

But the following shows:

```<code>❯ yarn test
yarn run v1.19.2
$ NODE_ENV=testing yarn sequelize db:migrate && yarn sequelize db:seed:all
$ /home/gabriel/Workspace/graphql-apollo/node_modules/.bin/sequelize db:migrate

Sequelize CLI [Node: 12.13.1, CLI: 5.5.1, ORM: 5.21.2]

Loaded configuration file "src/config/database.js".
== 20191123132531-create-users: migrating =======
== 20191123132531-create-users: migrated (0.047s)

== 20191123132658-create-messages: migrating =======
== 20191123132658-create-messages: migrated (0.028s)

$ /home/gabriel/Workspace/graphql-apollo/node_modules/.bin/sequelize db:seed:all

Sequelize CLI [Node: 12.13.1, CLI: 5.5.1, ORM: 5.21.2]

Loaded configuration file "src/config/database.js".
== 20191123132945-users: migrating =======

ERROR: Validation error

error Command failed with exit code 1.
</code>```

If I execute the migration and seeding command separately, it works fine.  I also tried to use concurrently, but the same happens.

```<code>"pretest": "concurrently 'NODE_ENV=testing yarn sequelize db:migrate' 'yarn sequelize db:seed:all'",
</code>```

答:
I had the same problem and managed to solve it as follows:

Wrong: "pretest": "NODE_ENV=test sequelize db:migrate && sequelize db:seed:all"

Right: "pretest": "NODE_ENV=test sequelize db:migrate && NODE_ENV=test sequelize db:seed:all"

Body:
I'm writing tests for my project. It uses Sequelize and I thought about doing the following:

"pretest": "NODE_ENV=testing yarn sequelize db:migrate && yarn sequelize db:seed:all",
"test": "mocha --require @babel/register 'src/tests/**/*.spec.js'",
"posttest": "NODE_ENV=testing yarn sequelize db:migrate:undo:all"

But the following shows:

❯ yarn test
yarn run v1.19.2
$ NODE_ENV=testing yarn sequelize db:migrate && yarn sequelize db:seed:all
$ /home/gabriel/Workspace/graphql-apollo/node_modules/.bin/sequelize db:migrate

Sequelize CLI [Node: 12.13.1, CLI: 5.5.1, ORM: 5.21.2]

Loaded configuration file "src/config/database.js".
== 20191123132531-create-users: migrating =======
== 20191123132531-create-users: migrated (0.047s)

== 20191123132658-create-messages: migrating =======
== 20191123132658-create-messages: migrated (0.028s)

$ /home/gabriel/Workspace/graphql-apollo/node_modules/.bin/sequelize db:seed:all

Sequelize CLI [Node: 12.13.1, CLI: 5.5.1, ORM: 5.21.2]

Loaded configuration file "src/config/database.js".
== 20191123132945-users: migrating =======

ERROR: Validation error

error Command failed with exit code 1.

If I execute the migration and seeding command separately, it works fine.  I also tried to use concurrently, but the same happens.

"pretest": "concurrently 'NODE_ENV=testing yarn sequelize db:migrate' 'yarn sequelize db:seed:all'",


问:
Ignoring Blanks in Power BI Query Invoke Custom Function
I'm using the following code in a Blank Query in Power BI Desktop:

```<code>(InitialDate as date, FinalDate as date ) as number =>
let
DaysBetweenDates = Duration.Days(FinalDate-InitialDate),
DaysList = List.Dates(List.Min({InitialDate,FinalDate}),Number.Abs(DaysBetweenDates), Duration.From(1)),
WeekDaysList = List.Select(DaysList, each (Date.DayOfWeek(_, Day.Monday) < 5) ),
WorkingDays = (if DaysBetweenDates < 0 then -1 else 1) * List.Count(WeekDaysList)
in
WorkingDays
</code>```

It's code to calculate the working days (that is, excluding Saturday and Sunday) between 2 given dates. I use it using the Invoke Custom Function when adding a column to the query, as shown below:

Invoke Custom Function

The problem is that, when one or the two dates are empty (blank) the Invoked Function returns Error. See below:

Error

How can I change the code in order to ignore the cases where one or the two dates are empty/blank, and just return blank?

If not possible, is there a way to make the same function in DAX?

Thank you!

答:
Power Query has error handling. Maybe this is how you can solve this.

Here is about error handling
https://learn.microsoft.com/en-us/powerquery-m/errors

You can just do something like this

```<code>DaysList = try List.Dates(List.Min({InitialDate,FinalDate}),Number.Abs(DaysBetweenDates), Duration.From(1)),
WeekDaysList = if DaysList[HasError] then <handle this somehow> else List.Select(DaysList[Value], each (Date.DayOfWeek(_, Day.Monday) < 5) ),
</code>```

Body:
I'm using the following code in a Blank Query in Power BI Desktop:

(InitialDate as date, FinalDate as date ) as number =>
let
DaysBetweenDates = Duration.Days(FinalDate-InitialDate),
DaysList = List.Dates(List.Min({InitialDate,FinalDate}),Number.Abs(DaysBetweenDates), Duration.From(1)),
WeekDaysList = List.Select(DaysList, each (Date.DayOfWeek(_, Day.Monday) < 5) ),
WorkingDays = (if DaysBetweenDates < 0 then -1 else 1) * List.Count(WeekDaysList)
in
WorkingDays

It's code to calculate the working days (that is, excluding Saturday and Sunday) between 2 given dates. I use it using the Invoke Custom Function when adding a column to the query, as shown below:

Invoke Custom Function

The problem is that, when one or the two dates are empty (blank) the Invoked Function returns Error. See below:

Error

How can I change the code in order to ignore the cases where one or the two dates are empty/blank, and just return blank?

If not possible, is there a way to make the same function in DAX?

Thank you!

Body:
Power Query has error handling. Maybe this is how you can solve this.

Here is about error handling
https://learn.microsoft.com/en-us/powerquery-m/errors

You can just do something like this

DaysList = try List.Dates(List.Min({InitialDate,FinalDate}),Number.Abs(DaysBetweenDates), Duration.From(1)),
WeekDaysList = if DaysList[HasError] then <handle this somehow> else List.Select(DaysList[Value], each (Date.DayOfWeek(_, Day.Monday) < 5) ),


问:
Django nested transactions and exceptions
For simplicity I have a nested atomic transaction in my code, basically if adding people to the movie fails (see first for loop) I'd like to display an exception specifically saying that this action failed and also roll back movie.save(), same for studios (see second for loop). But for some reason when either one fails movie.save() doesn't roll back, I get a movie saved in my database without any people or studios attached to it.

```<code>people = ['Mark', 'John', 'Mark']
studios = ['Universal Studios', 'Longcross Studios']

try:
    with transaction.atomic():
        movie = Movie(title=title, description=summary, pub_date=pub_date)
        movie.save()

        # iterate through people list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for p in people:
                    person = Person.objects.get(name=p)
                    movie.people.add(person)

        except Person.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more performers from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(people)))
            continue

        # iterate through studio list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for s in studios:
                    studio = Studio.objects.get(name=s)
                    movie.studios.add(studio)
        except Studio.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more studios from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(studios)))
            continue

        movie.save()
        self.stdout.write(self.style.NOTICE('Successfully added movie %s' % title))

except Exception as e:
    self.stdout.write(self.style.ERROR('Failed to add movie to the database.'))
</code>```

答: Rollback happens when an atomic block is exited by an exception. But you're catching the exceptions and suppressing them, so rollback doesn't happen. To let the exception propagate after logging the message you need to use raise, not continue.

Body:
For simplicity I have a nested atomic transaction in my code, basically if adding people to the movie fails (see first for loop) I'd like to display an exception specifically saying that this action failed and also roll back movie.save(), same for studios (see second for loop). But for some reason when either one fails movie.save() doesn't roll back, I get a movie saved in my database without any people or studios attached to it.

people = ['Mark', 'John', 'Mark']
studios = ['Universal Studios', 'Longcross Studios']

try:
    with transaction.atomic():
        movie = Movie(title=title, description=summary, pub_date=pub_date)
        movie.save()

        # iterate through people list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for p in people:
                    person = Person.objects.get(name=p)
                    movie.people.add(person)

        except Person.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more performers from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(people)))
            continue

        # iterate through studio list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for s in studios:
                    studio = Studio.objects.get(name=s)
                    movie.studios.add(studio)
        except Studio.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more studios from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(studios)))
            continue

        movie.save()
        self.stdout.write(self.style.NOTICE('Successfully added movie %s' % title))

except Exception as e:
    self.stdout.write(self.style.ERROR('Failed to add movie to the database.'))


问:
How can I remove an existing <Marker> component from <Map> in react js?
I have the following return :

```<code>import {Map, Marker} from 'google-maps-react';
class SimpleMap extends Component{
  constructor(props) {
    super(props);
    this.state = {
        marker: {
            available: false,
            position: {
                lat: lathere,
                lng: lnghere
            }
        }
    };
  }
  onClick = (t, map, coord) => {
      const {latLng} = coord;
      let {marker} = this.state;
      marker.position.lat = latLng.lat();
      marker.position.lng = latLng.lng();
      this.setState({marker});
};
  render(){
  const {marker} = this.state;
  return (<Map
     google={this.props.google}
     zoom={8}
     initialCenter={{position here}}
     onClick={this.onClick}>
        <Marker position={marker.position}/>
  </Map>);
}}
</code>```

How can I remove the current marker when I click again on the map? I've searched for some solutions but in each of them there were objects instantiated with new google.maps.map & new google.maps.marker  saved as global variables and use reference from one to another so they could remove the marker's map. How can I do that in ReactJS?

答:
Solved thanks to HMehmood1's answer here. You just need to explicitly add the lat and lng in <Marker>. E.g:

```<code><Marker position={{ lat: marker.position.lat, lng: marker.position.lng }}/>
</code>```

Body:
I have the following return :

import {Map, Marker} from 'google-maps-react';
class SimpleMap extends Component{
  constructor(props) {
    super(props);
    this.state = {
        marker: {
            available: false,
            position: {
                lat: lathere,
                lng: lnghere
            }
        }
    };
  }
  onClick = (t, map, coord) => {
      const {latLng} = coord;
      let {marker} = this.state;
      marker.position.lat = latLng.lat();
      marker.position.lng = latLng.lng();
      this.setState({marker});
};
  render(){
  const {marker} = this.state;
  return (<Map
     google={this.props.google}
     zoom={8}
     initialCenter={{position here}}
     onClick={this.onClick}>
        <Marker position={marker.position}/>
  </Map>);
}}

How can I remove the current marker when I click again on the map? I've searched for some solutions but in each of them there were objects instantiated with new google.maps.map & new google.maps.marker  saved as global variables and use reference from one to another so they could remove the marker's map. How can I do that in ReactJS?

Body:
Solved thanks to HMehmood1's answer here. You just need to explicitly add the lat and lng in <Marker>. E.g:

<Marker position={{ lat: marker.position.lat, lng: marker.position.lng }}/>


问:
COUNTIF with partial criteria doesn't work
I am trying to use simple formula with Countif and the criteria is partial text
Example: say the range is A25:A32

```<code>10060019
10060020
10060021
10060022
10060023
10060024
10060025
10060026
</code>```

And when I used this formula

=COUNTIF(A25:A32,"*" & 1006 & "*")

I got 0.. And that's weird for me as this was working for me before.

I am using Office 365 32 Bit.

Is there a bug in that version .. or what?

答:
If Range A25:A32 has Number format , use this formula istead : =COUNTIF(A25:A32,">" & 1006) .
otherwise you should renew A25:A32 values to Text format to use formula : =COUNTIF(A25:A32,"*1006*")

Body:
I am trying to use simple formula with Countif and the criteria is partial text
Example: say the range is A25:A32

10060019
10060020
10060021
10060022
10060023
10060024
10060025
10060026

And when I used this formula

=COUNTIF(A25:A32,"*" & 1006 & "*")

I got 0.. And that's weird for me as this was working for me before.

I am using Office 365 32 Bit.

Is there a bug in that version .. or what?


问:
Is there a better algorithm for exercise 9.3 in 《Think Python: How to Think Like a Computer Scientist》
The exercise 9.3 in this book ask the reader to find a combination of 5 forbidden letters that excludes the smallest number of words in this file.

Below is my solution for the first part, I think there is no problem for them

```<code># if the word contain any letter in letters, return True,
# otherwise return False
def contain(word, letters):
    for letter in letters:
        if letter in word:
            return True
    return False

# return the number of words contain any letter in letters
def ncont(words, letters):
    count = 0
    for word in words:
        if contain(word, letters):
            count += 1
return count
</code>```

But for the question above, I can only think of a brute-force algorithm, that is, try every kind of possible combination, there are exactly 26! / 5! = 65780 kind of combination, below is the implementation:

```<code>def get_lset(nlt, alphabet, cur_set):
    global min_n, min_set
    # when get enough letters
    if nlt <= 0:
        cur_n = ncont(words, ''.join(cur_set))
        if min_n == -1 or cur_n < min_n:
            min_n = cur_n
            min_set = cur_set.copy()
        print(''.join(cur_set), cur_n, ' *->', min_n, ''.join(min_set))
    # otherwise find the result letters in a recursive way
    else:
        cur_set.append(None)
        for i in range(len(alphabet)):
            cur_set[-1] = alphabet[i]
            get_lset(nlt-1, alphabet[i+1:], cur_set)
        cur_set.pop()
</code>```

and then call the above function like this:

```<code>if __name__ == '__main__':
    min_n = -1
    min_set = []
    with open('words.txt', 'r') as fin:
        words = [line.strip() for line in fin]
    get_lset(5, list(string.ascii_lowercase), [])
    print(min_set, min_n)
</code>```

but this solution is very slow, and I'd like to know is there a better algorithm for this question? Any suggestion will be good!

答:
My solution here:</p>

```<code>    def smallest_set(filename):
        avoid_dict = dict.fromkeys(ascii_letters.lower(), 0)
        with open(filename) as file_handler:
            for line in file_handler:
                for key in avoid_dict:
                    if key not in line:
                        avoid_dict[key] += 1
        avoid_stats_sorted = sorted(avoid_dict, key=avoid_dict.get,
reverse=True)
        return ''.join([item for item in avoid_stats_sorted[:5]])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The exercise 9.3 in this book ask the reader to find a combination of 5 forbidden letters that excludes the smallest number of words in this file.

Below is my solution for the first part, I think there is no problem for them

# if the word contain any letter in letters, return True,
# otherwise return False
def contain(word, letters):
    for letter in letters:
        if letter in word:
            return True
    return False

# return the number of words contain any letter in letters
def ncont(words, letters):
    count = 0
    for word in words:
        if contain(word, letters):
            count += 1
return count

But for the question above, I can only think of a brute-force algorithm, that is, try every kind of possible combination, there are exactly 26! / 5! = 65780 kind of combination, below is the implementation:

def get_lset(nlt, alphabet, cur_set):
    global min_n, min_set
    # when get enough letters
    if nlt <= 0:
        cur_n = ncont(words, ''.join(cur_set))
        if min_n == -1 or cur_n < min_n:
            min_n = cur_n
            min_set = cur_set.copy()
        print(''.join(cur_set), cur_n, ' *->', min_n, ''.join(min_set))
    # otherwise find the result letters in a recursive way
    else:
        cur_set.append(None)
        for i in range(len(alphabet)):
            cur_set[-1] = alphabet[i]
            get_lset(nlt-1, alphabet[i+1:], cur_set)
        cur_set.pop()

and then call the above function like this:

if __name__ == '__main__':
    min_n = -1
    min_set = []
    with open('words.txt', 'r') as fin:
        words = [line.strip() for line in fin]
    get_lset(5, list(string.ascii_lowercase), [])
    print(min_set, min_n)

but this solution is very slow, and I'd like to know is there a better algorithm for this question? Any suggestion will be good!

Body:
My solution here:

    def smallest_set(filename):
        avoid_dict = dict.fromkeys(ascii_letters.lower(), 0)
        with open(filename) as file_handler:
            for line in file_handler:
                for key in avoid_dict:
                    if key not in line:
                        avoid_dict[key] += 1
        avoid_stats_sorted = sorted(avoid_dict, key=avoid_dict.get,
reverse=True)
        return ''.join([item for item in avoid_stats_sorted[:5]])


问:
for what use dot after comand "ls" in linux? ~ ls
using the command ~ls allows you to list files, which is difference if I add dot ~ls . ?

sorry for my english, I am practicing

答: dot shows the folder you are in. If u re in downloads. ls . shows downloads. In your situation, ls (without a directory argument) is going to list directories and files under the current directory(pwd).


问:
Firebase: child of child extract value

how can I extract all the "name" values contained in DATA?

I tried this to extract a single name but it doesn't work:

```<code>DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("name").equalTo("pluto");
</code>```

答:
Two problems:

The code you shared only declares a query. It doesn't read anything from Firebase yet.

You're trying to order/filter in a child property, but are not specifying the full path to that property.

The second one is easiest to fix:

```<code>DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("DATA/name").equalTo("pluto");
</code>```

And then you can read the results with:

```<code>query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            Log.i("Firebase", snapshot.getKey());
            Log.i("Firebase", snapshot.child("name").getValue(String.class));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}
</code>```

Title: Firebase: child of child extract value

Body:
how can I extract all the "name" values contained in DATA?

I tried this to extract a single name but it doesn't work:

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("name").equalTo("pluto");

Body:
Two problems:

The code you shared only declares a query. It doesn't read anything from Firebase yet.

You're trying to order/filter in a child property, but are not specifying the full path to that property.

The second one is easiest to fix:

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("DATA/name").equalTo("pluto");

And then you can read the results with:

query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            Log.i("Firebase", snapshot.getKey());
            Log.i("Firebase", snapshot.child("name").getValue(String.class));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}


问:
How to adjust TextField width?
I'm re-writing a simple app which calculates averages. However, I have a hard time with a TextField. I would like it to be exactly as on a first screenshot.

The TextField's width is stretched, I don't want that. I want it to be exactly as it is on the screenshot.

Desired look:

What I have:

Code:

import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';

class ArithmeticAverageScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('arithmetic_average_title').tr(),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.help),
                      title: Text('arithmetic_average_help').tr(),
                      subtitle: Text('arithmetic_average_help_content').tr(),
                    )
                  ],
                ),
              )
            ),
            SizedBox(height: 16.0),
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grade', style: Theme.of(context).textTheme.subtitle2).tr(),
                    TextField()
                  ],
                ),
              ),
            )
          ],
        ),
      )
    );
  }
}
```

答:
You can try to wrap your TextField and Button with two Flexible widgets and apply desired proportions, e.g. 1:2 which would give you following result:

```<code>                Row(
                  children: [
                    Flexible(
                      flex: 1,
                      child: TextField(),
                    ),
                    Flexible(
                      flex: 2,
                      child: RaisedButton(
                          child: Text('Hello'), onPressed: () {}),
                    )
                  ],
                )
              ],
</code>```

You can also replace the first Flexible with SizedBox and set an exact value, e.g:

```<code>                Row(
                  children: [
                    SizedBox(
                      width: 100.0,
                      child: TextField(),
                    ),
                    Flexible(
                      flex: 2,
                      child: RaisedButton(
                          child: Text('Hello'), onPressed: () {}),
                    )
                  ],
                )
              ],
</code>```

TextField doesn't have an intrinsic size (width) constraint so it will always try to occupy all horizontal space. Flexible allows to constraint it to desired width in a Row.

Full example on DartPad.

Title: How to adjust TextField width?

Body:
You can try to wrap your TextField and Button with two Flexible widgets and apply desired proportions, e.g. 1:2 which would give you following result:

                Row(
                  children: [
                    Flexible(
                      flex: 1,
                      child: TextField(),
                    ),
                    Flexible(
                      flex: 2,
                      child: RaisedButton(
                          child: Text('Hello'), onPressed: () {}),
                    )
                  ],
                )
              ],

You can also replace the first Flexible with SizedBox and set an exact value, e.g:

                Row(
                  children: [
                    SizedBox(
                      width: 100.0,
                      child: TextField(),
                    ),
                    Flexible(
                      flex: 2,
                      child: RaisedButton(
                          child: Text('Hello'), onPressed: () {}),
                    )
                  ],
                )
              ],

TextField doesn't have an intrinsic size (width) constraint so it will always try to occupy all horizontal space. Flexible allows to constraint it to desired width in a Row.

Full example on DartPad.


问:
Memory Allocation C with pointers and structures
I'm trying to write to a pointer by accessing it and allocating memory from other function. But after a few iterations on the while statement, core dumped is thrown. I get the data from a file that it's ensured to be in the correct format.

It fails when there are still names to read from the file (checked with the debugger)

Main

```<code>Category *category = NULL;
memoryAllocate(&category);
</code>```

Memory Allocation

```<code>memoryAllocate(Category **category){

 int elements;
 char name[NAME];
 int i = 0;
 FILE *fPeces;

  [...]

    //Get the number of elements from the file
    fscanf(fPeces, "%d", &elements);
    *category = (Category *)malloc(sizeof(Category) * elements));
    if(*category == NULL){
        //ERROR
    }
    else{

        while(i < elements){

            fgets(name, NAME, fPeces);
            strcpy(category[i]->categoryName, name);
            i++;

        }
}
</code>```

Structure

```<code>typedef struct categoria {
    char categoryName[NAME];
    int part_num;
    Parts *parts;
} Category;
</code>```

FILE (first number is the number of categories and the rest are the names)

```<code>6
category 1
category 2
category 3
category 4
category 5
category 6
</code>```

答:
You're derefencing the wrong thing in your while loop. This line:

```<code>strcpy(category[i]->categoryName, name);
</code>```

Should be:

```<code>strcpy((*category)[i].categoryName, name);
</code>```

Editorial notes:

This problem is why I recommend minimizing the use of nested pointers where possible - it gets confusing fast. Instead of using *category all over the place, allocate that array locally:

```<code>Category *myArray = malloc(elements * sizeof *myArray);
</code>```

Do your work with it:

```<code>strcpy(myArray[i].name, name);
</code>```

And then only when you're done, copy that pointer into the output parameter:

```<code>*category = myArray;
</code>```

while(!feof(... is always wrong.

Don't cast the result of malloc.

Body:
I'm trying to write to a pointer by accessing it and allocating memory from other function. But after a few iterations on the while statement, core dumped is thrown. I get the data from a file that it's ensured to be in the correct format.

It fails when there are still names to read from the file (checked with the debugger)

Main

Category *category = NULL;
memoryAllocate(&category);

Memory Allocation

memoryAllocate(Category **category){

 int elements;
 char name[NAME];
 int i = 0;
 FILE *fPeces;

  [...]

    //Get the number of elements from the file
    fscanf(fPeces, "%d", &elements);
    *category = (Category *)malloc(sizeof(Category) * elements));
    if(*category == NULL){
        //ERROR
    }
    else{

        while(i < elements){

            fgets(name, NAME, fPeces);
            strcpy(category[i]->categoryName, name);
            i++;

        }
}

Structure

typedef struct categoria {
    char categoryName[NAME];
    int part_num;
    Parts *parts;
} Category;

FILE (first number is the number of categories and the rest are the names)

6
category 1
category 2
category 3
category 4
category 5
category 6

Body:
You're derefencing the wrong thing in your while loop. This line:

strcpy(category[i]->categoryName, name);

Should be:

strcpy((*category)[i].categoryName, name);

Editorial notes:

This problem is why I recommend minimizing the use of nested pointers where possible - it gets confusing fast. Instead of using *category all over the place, allocate that array locally:

Category *myArray = malloc(elements * sizeof *myArray);

Do your work with it:

strcpy(myArray[i].name, name);

And then only when you're done, copy that pointer into the output parameter:

*category = myArray;

while(!feof(... is always wrong.

Don't cast the result of malloc.


问:
Pandas Dataframe to PySpark Dataframe error with int32 array
I've been stuck with this problem whole day now, tried everything I found, I can't accomplish converting my Pandas dataframe, which looks like this, to PySpark dataframe:

```<code>  label     url_words_t                             url_words_lex
0   0       [ziyexing, picture, phto_fun, img_01]   [281518, 489596, 281519, 281520]
1   0       [animegiant, kimi, todoke]              [187613, 375314, 281521]
2   0       [bitsnoop, files, q873899, html]        [389091, 490613, 187614, 490676]
</code>```

With info:

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 300000 entries, 0 to 299999
Data columns (total 3 columns):
 #   Column         Non-Null Count   Dtype
---  ------         --------------   -----
 0   label          300000 non-null  int64
 1   url_words_t    300000 non-null  object
 2   url_words_lex  300000 non-null  object
dtypes: int64(1), object(2)
memory usage: 6.9+ MB
</code>```

In particular I am having trouble with the last column 'url_words_lex', which is a list of integers.

I create a schema:

```<code>schema_pdf = StructType([
    StructField('label', IntegerType(), True),
    StructField('url_words_t', ArrayType(StringType(), True), True),
    StructField('url_words_lex', ArrayType(LongType(), True), True)
])
</code>```

Lastly, try converting:

```<code>df_lex = spark.createDataFrame(pdf, schema_pdf)
</code>```

If I skip the last column 'url_words_lex' it converts just fine, but with it, I receive an error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-92-686967517920> in <module>
----> 1 df_lex = spark.createDataFrame(pdf, schema_pdf)

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in createDataFrame(self, data, schema, samplingRatio, verifySchema)
    746             rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)
    747         else:
--> 748             rdd, schema = self._createFromLocal(map(prepare, data), schema)
    749         jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())
    750         jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json())

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in _createFromLocal(self, data, schema)
    411         # make sure data could consumed multiple times
    412         if not isinstance(data, list):
--> 413             data = list(data)
    414
    415         if schema is None or isinstance(schema, (list, tuple)):

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in prepare(obj)
    728
    729             def prepare(obj):
--> 730                 verify_func(obj)
    731                 return obj
    732         elif isinstance(schema, DataType):

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_struct(obj)
   1368                                 "length of fields (%d)" % (len(obj), len(verifiers))))
   1369                 for v, (_, verifier) in zip(obj, verifiers):
-> 1370                     verifier(v)
   1371             elif hasattr(obj, "__dict__"):
   1372                 d = obj.__dict__

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_array(obj)
   1328             verify_acceptable_types(obj)
   1329             for i in obj:
-> 1330                 element_verifier(i)
   1331
   1332         verify_value = verify_array

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_default(obj)
   1381         def verify_default(obj):
   1382             assert_acceptable_types(obj)
-> 1383             verify_acceptable_types(obj)
   1384
   1385         verify_value = verify_default

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_acceptable_types(obj)
   1276         if type(obj) not in _acceptable_types[_type]:
   1277             raise TypeError(new_msg("%s can not accept object %r in type %s"
-> 1278                                     % (dataType, obj, type(obj))))
   1279
   1280     if isinstance(dataType, StringType):

TypeError: element in array field url_words_lex: LongType can not accept object 281518 in type <class 'numpy.int32'>
</code>```

I've tried using IntegerType, LongType - I've got the same error. I thing that I am mapping numpy.int32 with IntegerType of PySpark, but I just can't get around this...

It only converts without error with StringType, although, when I try to see the result

```<code>df_lex.show()
</code>```

I receive a different error:

```<code>Py4JJavaError: An error occurred while calling o642.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 32.0 failed 1 times, most recent failure: Lost task 0.0 in stage 32.0 (TID 57, localhost, executor driver): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype)
</code>```

I will be mostly grateful if you could share your ideas on solving this problem.

答: I've tried to explicitly cast these numbers to int() while appending to the list in 'url_words_lex' previously in the code and it worked!</p>

Body:
I've been stuck with this problem whole day now, tried everything I found, I can't accomplish converting my Pandas dataframe, which looks like this, to PySpark dataframe:

  label     url_words_t                             url_words_lex
0   0       [ziyexing, picture, phto_fun, img_01]   [281518, 489596, 281519, 281520]
1   0       [animegiant, kimi, todoke]              [187613, 375314, 281521]
2   0       [bitsnoop, files, q873899, html]        [389091, 490613, 187614, 490676]

With info:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 300000 entries, 0 to 299999
Data columns (total 3 columns):
 #   Column         Non-Null Count   Dtype
---  ------         --------------   -----
 0   label          300000 non-null  int64
 1   url_words_t    300000 non-null  object
 2   url_words_lex  300000 non-null  object
dtypes: int64(1), object(2)
memory usage: 6.9+ MB

In particular I am having trouble with the last column 'url_words_lex', which is a list of integers.

I create a schema:

schema_pdf = StructType([
    StructField('label', IntegerType(), True),
    StructField('url_words_t', ArrayType(StringType(), True), True),
    StructField('url_words_lex', ArrayType(LongType(), True), True)
])

Lastly, try converting:

df_lex = spark.createDataFrame(pdf, schema_pdf)

If I skip the last column 'url_words_lex' it converts just fine, but with it, I receive an error:

TypeError                                 Traceback (most recent call last)
<ipython-input-92-686967517920> in <module>
----> 1 df_lex = spark.createDataFrame(pdf, schema_pdf)

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in createDataFrame(self, data, schema, samplingRatio, verifySchema)
    746             rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)
    747         else:
--> 748             rdd, schema = self._createFromLocal(map(prepare, data), schema)
    749         jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())
    750         jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json())

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in _createFromLocal(self, data, schema)
    411         # make sure data could consumed multiple times
    412         if not isinstance(data, list):
--> 413             data = list(data)
    414
    415         if schema is None or isinstance(schema, (list, tuple)):

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/session.py in prepare(obj)
    728
    729             def prepare(obj):
--> 730                 verify_func(obj)
    731                 return obj
    732         elif isinstance(schema, DataType):

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_struct(obj)
   1368                                 "length of fields (%d)" % (len(obj), len(verifiers))))
   1369                 for v, (_, verifier) in zip(obj, verifiers):
-> 1370                     verifier(v)
   1371             elif hasattr(obj, "__dict__"):
   1372                 d = obj.__dict__

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_array(obj)
   1328             verify_acceptable_types(obj)
   1329             for i in obj:
-> 1330                 element_verifier(i)
   1331
   1332         verify_value = verify_array

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify(obj)
   1387     def verify(obj):
   1388         if not verify_nullability(obj):
-> 1389             verify_value(obj)
   1390
   1391     return verify

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_default(obj)
   1381         def verify_default(obj):
   1382             assert_acceptable_types(obj)
-> 1383             verify_acceptable_types(obj)
   1384
   1385         verify_value = verify_default

~/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/types.py in verify_acceptable_types(obj)
   1276         if type(obj) not in _acceptable_types[_type]:
   1277             raise TypeError(new_msg("%s can not accept object %r in type %s"
-> 1278                                     % (dataType, obj, type(obj))))
   1279
   1280     if isinstance(dataType, StringType):

TypeError: element in array field url_words_lex: LongType can not accept object 281518 in type <class 'numpy.int32'>

I've tried using IntegerType, LongType - I've got the same error. I thing that I am mapping numpy.int32 with IntegerType of PySpark, but I just can't get around this...

It only converts without error with StringType, although, when I try to see the result

df_lex.show()

I receive a different error:

Py4JJavaError: An error occurred while calling o642.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 32.0 failed 1 times, most recent failure: Lost task 0.0 in stage 32.0 (TID 57, localhost, executor driver): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype)

I will be mostly grateful if you could share your ideas on solving this problem.


问:
JPA sorting query result after querying with Pageable
I am having an @Entity like this:

```<code>import java.time.LocalDateTime;
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Data@NoArgsConstructor@AllArgsConstructor
public class Message extends AbstractPersistable<Long> {

    private LocalDateTime messageDate = LocalDateTime.now();
    private String message;

}
</code>```

And a repository like this:

```<code>import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MessageRepository extends JpaRepository<Message, Long> {
    //List<Message> findAllByOrderByMessageDateAsc(Pageable pageable);
    // With this I am trying to re-sort what I get

}
</code>```

And a @Controller

```<code>@GetMapping("/messages")
    public String list(Model model) {
        Pageable limit = PageRequest.of(0, 5, Sort.by("messageDate").descending());
        model.addAttribute("messages", messageRepository.findAll(limit));
        //model.addAttribute("messages", messageRepository.findAllByOrderByMessageDateAsc(limit));
        return "messages";
    }
</code>```

I get five latest messages in descending order. But how do I get them in ascending order?

答:
What you need is the last 5 messages in ascending order by massage date.
Two ways to solve it.

Using Custom implementation of Pageable

You can't use offset properly for PageRequest. So,
you need to use a custom implementation of Pageable for offset.
You can use custom implementation OffsetBasedPageRequest. Then use it this way.

```<code>int totalCount = (int)serviceRepository.count();
Pageable pageable = new OffsetBasedPageRequest(totalCount - limit, limit, Sort.by("messageDate"));
messageRepository.findAll(pageable);
</code>```

After fetching Sort Page data

You can get the list from Page<T> using page.getContent() then sort manually the list.

```<code>Pageable pageable = PageRequest.of(0, limit, Sort.by("messageDate").descending());
List<Message> list = messageRepository.findAll(pageable ).getContent();
List<Message> sorted =list.stream().sorted(Comparator.comparing(r -> r.getMessageDate())).collect(Collectors.toList());
</code>```

Then again you have to create Page<Massage> if you want.

Body:
I am having an @Entity like this:

import java.time.LocalDateTime;
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Data@NoArgsConstructor@AllArgsConstructor
public class Message extends AbstractPersistable<Long> {

    private LocalDateTime messageDate = LocalDateTime.now();
    private String message;

}

And a repository like this:

import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MessageRepository extends JpaRepository<Message, Long> {
    //List<Message> findAllByOrderByMessageDateAsc(Pageable pageable);
    // With this I am trying to re-sort what I get

}

And a @Controller

@GetMapping("/messages")
    public String list(Model model) {
        Pageable limit = PageRequest.of(0, 5, Sort.by("messageDate").descending());
        model.addAttribute("messages", messageRepository.findAll(limit));
        //model.addAttribute("messages", messageRepository.findAllByOrderByMessageDateAsc(limit));
        return "messages";
    }

I get five latest messages in descending order. But how do I get them in ascending order?

Body:
What you need is the last 5 messages in ascending order by massage date.
Two ways to solve it.

Using Custom implementation of Pageable

You can't use offset properly for PageRequest. So,
you need to use a custom implementation of Pageable for offset.
You can use custom implementation OffsetBasedPageRequest. Then use it this way.

int totalCount = (int)serviceRepository.count();
Pageable pageable = new OffsetBasedPageRequest(totalCount - limit, limit, Sort.by("messageDate"));
messageRepository.findAll(pageable);

After fetching Sort Page data

You can get the list from Page<T> using page.getContent() then sort manually the list.

Pageable pageable = PageRequest.of(0, limit, Sort.by("messageDate").descending());
List<Message> list = messageRepository.findAll(pageable ).getContent();
List<Message> sorted =list.stream().sorted(Comparator.comparing(r -> r.getMessageDate())).collect(Collectors.toList());

Then again you have to create Page<Massage> if you want.


问:
Change kubernetes stroge class mounted value from another pod
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

```<code>kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi
</code>```

2-) sonarqube-deployment.yml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true
</code>```

3-)Sample plugins Dockerfile

```<code>FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR
</code>```

I tried that approach with sonar-plugin-deployment.yml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
</code>```

But didn't successed. And break something. This time my plugins directory became empty:

```<code>sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found
</code>```

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.

答:
Check Init Containers should suit your need.

You can populate volume with data using init container and when it's done you can run your app on this data.

Body:
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi

2-) sonarqube-deployment.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true

3-)Sample plugins Dockerfile

FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR

I tried that approach with sonar-plugin-deployment.yml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions

But didn't successed. And break something. This time my plugins directory became empty:

sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.


问:
Unable to pass 'page[size]' parameter to API request
I'm currently attempting to get the Flippa API to return a list of 50 listings, but the default page size is only 30. Their documentation states that the 'page[size]' parameter needs to be used in order to change this attribute, but nothing I've tried works. I can't simply use 'page[size]' as a filter parameter, because of the special characters, so that's not an option. I then noticed that 'page_size' and 'page_number' are attributes listed under the meta section of the response, so I tried those as parameters - but still no luck. When I try to use 'page_size', I receive a Bad Request error. My code for this attempt is below:

```<code>var express = require('express');
var app = express();
var Flippa = require('flippa');

app.use("/public", express.static('./public/'));

app.get("/", function (request, response) {

  response.sendFile(__dirname + '/index.html');
});

app.post("/getdata", function(req, res) {
  flippa = new Flippa();
  flippa
  .listings
  .list
  (
    {
      filter: {status: "won", premium: true, sale_method: "auction", page_size: 50}
    }
  )
  .then(function(response) {
    console.log(response.body);
  });

  res.end();
});

//-------------------------------------------------------------//

// listen for requests
var listener = app.listen('8888', function () {
  console.log('Your app is listening on port ' + listener.address().port);
});
</code>```

Everything works without the 'page_size' parameter (that is, no Bad Request). Here's a link to the relevant section of the Flippa documentation: https://developers.flippa.com/?javascript#pagination

If anyone could shed some light on how to implement this, I would appreciate it.

答:
"page_size" won't work cause that is what the response meta object have. Your request needs page[size]. </p>

<p>You can add page[size] by doing "page[size]" but maybe it expects page[size] as separate key instead of one inside filter. </p>

```<code>}
  filter: {status: "won", premium: true, sale_method: "auction"},
  "page[size]": 50
}
</code>```

Body:
I'm currently attempting to get the Flippa API to return a list of 50 listings, but the default page size is only 30. Their documentation states that the 'page[size]' parameter needs to be used in order to change this attribute, but nothing I've tried works. I can't simply use 'page[size]' as a filter parameter, because of the special characters, so that's not an option. I then noticed that 'page_size' and 'page_number' are attributes listed under the meta section of the response, so I tried those as parameters - but still no luck. When I try to use 'page_size', I receive a Bad Request error. My code for this attempt is below:

var express = require('express');
var app = express();
var Flippa = require('flippa');

app.use("/public", express.static('./public/'));

app.get("/", function (request, response) {

  response.sendFile(__dirname + '/index.html');
});

app.post("/getdata", function(req, res) {
  flippa = new Flippa();
  flippa
  .listings
  .list
  (
    {
      filter: {status: "won", premium: true, sale_method: "auction", page_size: 50}
    }
  )
  .then(function(response) {
    console.log(response.body);
  });

  res.end();
});

//-------------------------------------------------------------//

// listen for requests
var listener = app.listen('8888', function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

Everything works without the 'page_size' parameter (that is, no Bad Request). Here's a link to the relevant section of the Flippa documentation: https://developers.flippa.com/?javascript#pagination

If anyone could shed some light on how to implement this, I would appreciate it.

Body:
"page_size" won't work cause that is what the response meta object have. Your request needs page[size].

You can add page[size] by doing "page[size]" but maybe it expects page[size] as separate key instead of one inside filter.

}
  filter: {status: "won", premium: true, sale_method: "auction"},
  "page[size]": 50
}


问:
How do i add a parent constructor to a child constructor with parameters. I have tried the parent::__construct but still has an error
//here is the parent class code and constructor
//I know that I should use the parent::__construct() method but it is still coming up with an error. How //do i set the car class to have the manufacturer class variables. </p>

```<code>class Manufacturer {

    public $tradingAsName;
    public $baseName;
    public $country;

    function __construct($tradingAsName,$baseName,$country){

        $this->tradingAsName =$tradingAsName;
        $this->baseName=$baseName;
        $this->country=$country;

    }

class car extends Manufacturer{

    public $carName;
    public $yearMade;

    function __construct($carName,$yearMade){
        parent::__construct();
        $this ->title = $carName;
        $this->yearMade=$yearMade;

    }
</code>```

答:
As noted in the comments to OP, a car is definitely not a type of manufacturer. It would be better to add an already-instantiated manufacturer object into your car, as follows:

```<code>class Car {
    public $manufacturer;

    function __construct($carName,$yearMade, $manufacturer){
        $this->manufacturer = $manufacturer;
    }
}

$man = new Manufacturer($tradingAsName,$baseName,$country);
$car = new Car($carName,$yearMade, $manufacturer);
</code>```

And then you would access manufacturer details like this:

```<code>$carMadeIn = $car->manufacturer->country;
</code>```

Here, we're using composition instead of inheritance, as one should when associating related but functionally divergent objects. (You might end up dealing with car and computer manufacturers, etc.) Now, to illustrate a more proper use of "extends", one might for example have:

```<code>class ElectricCar extends Car {
    public $batteryAmps;

    public function __construct($carName,$yearMade, $manufacturer, $batteryAmps) {
        // In a context like this, you can use the parent constructor:
        parent::__construct($carName,$yearMade, $manufacturer);
        $this->batteryAmps = $batteryAmps;
    }
}
</code>```

Your Car class might reasonably extend a Vehicle parent class, which would handle all things common to types of vehicles (boats, bikes, etc.). To gloss the logic of OOP class extension and structure/hierarchy (from more abstract to more specific) in a nutshell for you. (O_o)p

Body:
//here is the parent class code and constructor
//I know that I should use the parent::__construct() method but it is still coming up with an error. How //do i set the car class to have the manufacturer class variables.

class Manufacturer {

    public $tradingAsName;
    public $baseName;
    public $country;

    function __construct($tradingAsName,$baseName,$country){

        $this->tradingAsName =$tradingAsName;
        $this->baseName=$baseName;
        $this->country=$country;

    }

class car extends Manufacturer{

    public $carName;
    public $yearMade;

    function __construct($carName,$yearMade){
        parent::__construct();
        $this ->title = $carName;
        $this->yearMade=$yearMade;

    }

Body:
As noted in the comments to OP, a car is definitely not a type of manufacturer. It would be better to add an already-instantiated manufacturer object into your car, as follows:

class Car {
    public $manufacturer;

    function __construct($carName,$yearMade, $manufacturer){
        $this->manufacturer = $manufacturer;
    }
}

$man = new Manufacturer($tradingAsName,$baseName,$country);
$car = new Car($carName,$yearMade, $manufacturer);

And then you would access manufacturer details like this:

$carMadeIn = $car->manufacturer->country;

Here, we're using composition instead of inheritance, as one should when associating related but functionally divergent objects. (You might end up dealing with car and computer manufacturers, etc.) Now, to illustrate a more proper use of "extends", one might for example have:

class ElectricCar extends Car {
    public $batteryAmps;

    public function __construct($carName,$yearMade, $manufacturer, $batteryAmps) {
        // In a context like this, you can use the parent constructor:
        parent::__construct($carName,$yearMade, $manufacturer);
        $this->batteryAmps = $batteryAmps;
    }
}

Your Car class might reasonably extend a Vehicle parent class, which would handle all things common to types of vehicles (boats, bikes, etc.). To gloss the logic of OOP class extension and structure/hierarchy (from more abstract to more specific) in a nutshell for you. (O_o)p


问:
For loop to change dataframe columns
I have a dataframe with multiple columns that have null values. I used the following code to get the specific columns as well as their datatypes. My dataframe is called data here.

```<code>missing = data.columns[data.isnull().any()].tolist()

data_type_dict = {}
for i in missing:
    print({i:data[i].isnull().sum()})
    data_type_dict.update({i:data[i].dtypes})
print(data_type_dict)
</code>```

Now I want to get replace the null values with medians for my numeric columns, and with mode for type object. I was hoping to split this into first based on data type, so float is separate and object is separate. This is what I did for that. I'm only posting one, which is shorter, there were two dfs that I made.

```<code>lisnum = data[['MasVnrArea','GarageYrBlt']]
</code>```

Now, firstly, the other one is much longer, so its not just a question of two columns. For this, I want to get each column's median and replace the null values with the median. I was hoping to do this in a for loop.
Essentially I want to do something like this:

```<code>data['MasVnrArea'].fillna(median, inplace = True)
</code>```

but with a for loop for each column that lisnum has.

答:
No need for a for loop

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2, np.nan, 4,5,6],
                'y': [1,2,4,5,6, np.nan],
                'z': [np.nan, 1,0,1,0,1]})
df.fillna(df.median(), inplace=True)
</code>```

this works, for all columns at once.

Title: For loop to change dataframe columns

Body:
I have a dataframe with multiple columns that have null values. I used the following code to get the specific columns as well as their datatypes. My dataframe is called data here.

missing = data.columns[data.isnull().any()].tolist()

data_type_dict = {}
for i in missing:
    print({i:data[i].isnull().sum()})
    data_type_dict.update({i:data[i].dtypes})
print(data_type_dict)

Now I want to get replace the null values with medians for my numeric columns, and with mode for type object. I was hoping to split this into first based on data type, so float is separate and object is separate. This is what I did for that. I'm only posting one, which is shorter, there were two dfs that I made.

lisnum = data[['MasVnrArea','GarageYrBlt']]

Now, firstly, the other one is much longer, so its not just a question of two columns. For this, I want to get each column's median and replace the null values with the median. I was hoping to do this in a for loop.
Essentially I want to do something like this:

data['MasVnrArea'].fillna(median, inplace = True)

but with a for loop for each column that lisnum has.

Body:
No need for a for loop

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2, np.nan, 4,5,6],
                'y': [1,2,4,5,6, np.nan],
                'z': [np.nan, 1,0,1,0,1]})
df.fillna(df.median(), inplace=True)

this works, for all columns at once.


问:
Dynamically Updating a Variable in JS
My page has multiple videos on it and I'm trying to enable seeking through the YouTube API on all of them. These videos are generated dynamically, so I can't pre-define them all at once, unfortunately. If I could, the following would work:

```<code><script>
function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
      player2 = new YT.Player('ytplayer3', {
      });
      player3 = new YT.Player('ytplayer3', {
      });
      etc. etc.
}
function onPlayerReady(event) {
    event.target.playVideo();
}
function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}

</script>
</code>```

But because each page will have a different number of dynamically generated videos, I'm running into an issue.

I can make the first and last videos work using the following code:

```<code>#Initial javascript + first video
<script>
function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
}
function onPlayerReady(event) {
    event.target.playVideo();
}
function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}
var old_foo = onYouTubePlayerAPIReady;
</script>

<iframe id="ytplayer1" width="789" height="444" src="https://www.youtube.com/embed/p4vLPmVAwlo?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button type="button" onclick="player.seekTo(60)">60s</button>
<button type="button" onclick="player.seekTo(120)">120s</button>

#Second video plus the JS to go with it
<iframe id="ytplayer2" width="789" height="444" src="https://www.youtube.com/embed/_9ahu4c5zdI?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button type="button" onclick="player2.seekTo(60)">60s</button>
<button type="button" onclick="player2.seekTo(120)">120s</button>

<script>
function onYouTubePlayerAPIReady() {
  old_foo();
  player2 = new YT.Player('ytplayer2', {
  });
}

</script>
</code>```

But whenever I try to add another, the middle ones stop working. It seems like my final call of the onYouTubePlayerAPIReady function is overwriting everything before it, without executing the function at each step. I've tried updating my old_foo var, the onYouTubePlayerAPIReady function, defining a new var, etc. None of it seems to work! But I also suck at javascript so I'm sure I'm just missing something simple.

Help?

答:
Here's how you can add yt players dynamically with seekTo buttons

let players = [];
const button = document.querySelector("#button");
const newId = (() => {
  const prefix = "player";
  let id = 1;
  return () => {
    let newId = id;
    id = id + 1;

    return {
      id: newId,
      cssId: `${prefix}${newId}`
    }
  }
})()

const createButton = (text, clickEvent) => {
  const element = document.createElement("button");
  element.textContent = text;
  element.setAttribute("type", "button");
  element.addEventListener("click", clickEvent);
  return element;
}

const seekPlayer = (id, value) => {
  const player = players.find(pl => pl.id === id);
  player.seekTo(value);
}

const createPlayer = () => {
  const parent = document.body;
  const container = document.createElement("div");
  const playerPlaceholder = document.createElement("div");
  const result = newId();
  playerPlaceholder.setAttribute("id", result.cssId);

  const button1 = createButton('60s', () => seekPlayer(result.id, 60));
  const button2 = createButton('120s',() => seekPlayer(result.id, 120));
  container.appendChild(playerPlaceholder);
  container.appendChild(button1);
  container.appendChild(button2);

  parent.appendChild(container);

  const player = new YT.Player(result.cssId, {
    height: '100',
    width: '100',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': (event) => {

        players = [...players, {
          id: result.id,
          player: event.target
        }]
      },
    }
  });
}

button.addEventListener("click", () => {
  createPlayer();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.youtube.com/iframe_api"></script>
<button id="button">Add player</button></code>```

Title: Dynamically Updating a Variable in JS

Body:
My page has multiple videos on it and I'm trying to enable seeking through the YouTube API on all of them. These videos are generated dynamically, so I can't pre-define them all at once, unfortunately. If I could, the following would work:

But because each page will have a different number of dynamically generated videos, I'm running into an issue.

I can make the first and last videos work using the following code:

#Initial javascript + first video

<button type="button" onclick="player.seekTo(60)">60s</button>
<button type="button" onclick="player.seekTo(120)">120s</button>

#Second video plus the JS to go with it

<button type="button" onclick="player2.seekTo(60)">60s</button>
<button type="button" onclick="player2.seekTo(120)">120s</button>

But whenever I try to add another, the middle ones stop working. It seems like my final call of the onYouTubePlayerAPIReady function is overwriting everything before it, without executing the function at each step. I've tried updating my old_foo var, the onYouTubePlayerAPIReady function, defining a new var, etc. None of it seems to work! But I also suck at javascript so I'm sure I'm just missing something simple.

Help?

Body:
Here's how you can add yt players dynamically with seekTo buttons

let players = [];
const button = document.querySelector("#button");
const newId = (() => {
  const prefix = "player";
  let id = 1;
  return () => {
    let newId = id;
    id = id + 1;

    return {
      id: newId,
      cssId: `${prefix}${newId}`
    }
  }
})()

const createButton = (text, clickEvent) => {
  const element = document.createElement("button");
  element.textContent = text;
  element.setAttribute("type", "button");
  element.addEventListener("click", clickEvent);
  return element;
}

const seekPlayer = (id, value) => {
  const player = players.find(pl => pl.id === id);
  player.seekTo(value);
}

const createPlayer = () => {
  const parent = document.body;
  const container = document.createElement("div");
  const playerPlaceholder = document.createElement("div");
  const result = newId();
  playerPlaceholder.setAttribute("id", result.cssId);

  const button1 = createButton('60s', () => seekPlayer(result.id, 60));
  const button2 = createButton('120s',() => seekPlayer(result.id, 120));
  container.appendChild(playerPlaceholder);
  container.appendChild(button1);
  container.appendChild(button2);

  parent.appendChild(container);

  const player = new YT.Player(result.cssId, {
    height: '100',
    width: '100',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': (event) => {

        players = [...players, {
          id: result.id,
          player: event.target
        }]
      },
    }
  });
}

button.addEventListener("click", () => {
  createPlayer();
})

<script src="https://www.youtube.com/iframe_api"></script>
<button id="button">Add player</button>


问:
I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017

I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the elements of vector through the array.

My code is as below:

```<code> //vector.h

#pragma once
const int SIZE = 3;
#include<iostream>
using namespace std;
class vector
{
    int v[SIZE];
public:
    vector();
    vector(int *x);
    friend vector operator *(vector a, int b);
    friend vector operator *(int b,vector a);
    friend istream & operator >>(istream &input, vector &x);
    friend ostream & operator <<(ostream &output, vector &y);

};

    //vector.cpp

#include "vector.h"
#include<iostream>
using namespace std;

vector::vector()
{
    for (int i = 0; i < SIZE; i++)
        v[i] = 0;

}
vector::vector(int *x)
{
    for (int i = 0; i < SIZE; i++)
        v[i] = x[i];

}
vector operator *(vector a, int b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a.v[i]*b;
    return temp;

}
vector operator *(int a, vector b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a * b.v[i];
    return temp;
}
istream & operator >>(istream &input, vector &x) {
    for (int i = 0; i < SIZE; i++)
        input >> x.v[i];
    return (input);

}
ostream & operator <<(ostream &output, vector &y) {
    output << "(" << y.v[0];
    for (int i = 1; i < SIZE; i++)
        output <<","<< y.v[i];
    output << ")";
    return (output);

}

    //main.cpp

#include "vector.h"
#include<iostream>
using namespace std;
int x[SIZE] = { 2,4,6 };
int main() {

    vector m;
    vector v2 = x;
    cout << "Enter the elements of vector m:" << "\n";
    cin >> m;
    cout << "\n";
    vector m1, m2;
    m1 = m * 2;
    m2 = 2 * v2;
    cout << "m= "<<m<<"\n";
    cout << "\n";
    cout << "m1= " << m1 << "\n";
    cout << "m2= " << m2 << "\n";
    cin.get();

    return 0;

}
</code>```

答:
Probably your linker settings are incorrect. Go to menu item Project/Properties. Then in the dialog find Configuration Properties/Linker/System/Subsystem and make sure it says Console (/SUBSYSTEM:CONSOLE).

Evgeny is correct cin.get() is not guaranteed to halt your program because there are still characters waiting to be read from cin that are left over from previous reads.

Body:
I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the elements of vector through the array.

My code is as below:

 //vector.h

#pragma once
const int SIZE = 3;
#include<iostream>
using namespace std;
class vector
{
    int v[SIZE];
public:
    vector();
    vector(int *x);
    friend vector operator *(vector a, int b);
    friend vector operator *(int b,vector a);
    friend istream & operator >>(istream &input, vector &x);
    friend ostream & operator <<(ostream &output, vector &y);

};

    //vector.cpp

#include "vector.h"
#include<iostream>
using namespace std;

vector::vector()
{
    for (int i = 0; i < SIZE; i++)
        v[i] = 0;

}
vector::vector(int *x)
{
    for (int i = 0; i < SIZE; i++)
        v[i] = x[i];

}
vector operator *(vector a, int b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a.v[i]*b;
    return temp;

}
vector operator *(int a, vector b) {
    vector temp;
    for (int i = 0; i < SIZE; i++)
        temp.v[i] = a * b.v[i];
    return temp;
}
istream & operator >>(istream &input, vector &x) {
    for (int i = 0; i < SIZE; i++)
        input >> x.v[i];
    return (input);

}
ostream & operator <<(ostream &output, vector &y) {
    output << "(" << y.v[0];
    for (int i = 1; i < SIZE; i++)
        output <<","<< y.v[i];
    output << ")";
    return (output);

}

    //main.cpp

#include "vector.h"
#include<iostream>
using namespace std;
int x[SIZE] = { 2,4,6 };
int main() {

    vector m;
    vector v2 = x;
    cout << "Enter the elements of vector m:" << "\n";
    cin >> m;
    cout << "\n";
    vector m1, m2;
    m1 = m * 2;
    m2 = 2 * v2;
    cout << "m= "<<m<<"\n";
    cout << "\n";
    cout << "m1= " << m1 << "\n";
    cout << "m2= " << m2 << "\n";
    cin.get();

    return 0;

}


问:
Post Java-14 getter/setter naming convention
Java 14 introduced records feature. Record creates getter with the same name as field, so one would write print(person.name()) for example. But old Java bean convention dictates that one should name this method as getName().

Using both styles in the same code base does not look very nice. Migrating everything to records is not possible, as they are too limited to replace all use-cases.

Is there any official or semi-official guidelines how to name getters and setters after Java 14 in new code?

答:
In Java records, object fields must be private and final.
So there is just one kind of getter and one kind of setter possible.

In Java classes, object fields may be private or public.
In the latter type of field, one can get or set them simply by adding a period and the field name, e.g.

```<code> Employee emp = new Employee(); // Nullary constructor
 emp.name = "John Schmidt";     // Setter
 . . .
 . . .
 if (emp.name != "Buddy")       // Getter
 {
    emp.bonus = 100.00;
 }
</code>```

Non-private fields are used a lot in Android apps to save memory and time extracting data. But there's no reason not to use them in Java where it's safe to do so.

Now, if you change away from the usual way in Java classes to something like that used in record types, e.g.

```<code>String name = emp.name();  // New getter convention for private field
</code>```

you have a serious risk of confusion by code readers who might misinterpret this as a non-private object field.

And if you change the record getter to what is used in Java objects, i.e.

```<code>obj.getField()
</code>```

then there is a risk of confusion by coder reviewers and possibly a compiler may treat it as a Java object, depending on execution decision criteria.

In short, it's a different type of object to the normal Java class or enum. Its accessors indicate this new type unambiguously.
That's how I see it anyhow.
Maybe someone on the Java development committee may be able to enlighten us further.

Body:
In Java records, object fields must be private and final.
So there is just one kind of getter and one kind of setter possible.

In Java classes, object fields may be private or public.
In the latter type of field, one can get or set them simply by adding a period and the field name, e.g.

 Employee emp = new Employee(); // Nullary constructor
 emp.name = "John Schmidt";     // Setter
 . . .
 . . .
 if (emp.name != "Buddy")       // Getter
 {
    emp.bonus = 100.00;
 }

Non-private fields are used a lot in Android apps to save memory and time extracting data. But there's no reason not to use them in Java where it's safe to do so.

Now, if you change away from the usual way in Java classes to something like that used in record types, e.g.

String name = emp.name();  // New getter convention for private field

you have a serious risk of confusion by code readers who might misinterpret this as a non-private object field.

And if you change the record getter to what is used in Java objects, i.e.

obj.getField()

then there is a risk of confusion by coder reviewers and possibly a compiler may treat it as a Java object, depending on execution decision criteria.

In short, it's a different type of object to the normal Java class or enum. Its accessors indicate this new type unambiguously.
That's how I see it anyhow.
Maybe someone on the Java development committee may be able to enlighten us further.


问:
Delete duplicates from array C++
I am trying to create a simple program which calls on 2 functions. The first function takes a partially filled array, loops through it and deletes any duplicate values. When a value is deleted from the array, the remaining numbers are moved backwards to fill the gap i.e. when the function is finished, all null values of the array will be together at the end.

The second function prints the updated array.

My current code is below. At present when I run my code, the console shows:
2 6 0 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460. It should be showing: 1 2 5 6 if it worked correctly.

Also, I am not sure how to move the remaining elements of the array backwards so that the null values will be together at the end.

```<code>#include "pch.h"
#include <iostream>
using namespace std;
void deleteRepeats(int *arr, int arraySize, int& posUsed);
void printArray(int *arr, int arraySize);

int main()
{
int arr[10] = { 1, 2, 2, 5, 6, 1};
int posUsed = 6;
int arraySize = 10;

deleteRepeats(arr, arraySize, posUsed);
printArray(arr, arraySize);

return 0;
}

void deleteRepeats(int *arr, int arraySize, int& posUsed)
{
{
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = i; j < arraySize; j++)
        {
            if (arr[i] == arr[j])
            {
                for (int k = j; k < arraySize; k++)
                {
                    arr[k] = arr[k + 1];

                }
                posUsed--;

            }
            else
                j++;
        }
    }
}
}

void printArray(int *arr, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
    cout << arr[i] << "  ";
}
}
</code>```

答:
using two pointers

and if the array sorted

```<code>    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        int i = 0;

        for(int j = 1; j < nums.size(); j++)
            if(nums[j] != nums[i])  nums[++i] = nums[j];

        // return new array length
        return i + 1;
    }
</code>```

```<code>//input: [1, 1, 2, 1] (arr1)
//output: 2 (returned length)
// print unique element
for(int i = 0; i < output; i++) cout << arr1[i] << '\n';
// [1, 2]
</code>```

```<code>time complexity: O(N/2) -> O(N)
space complexity: O(1)
</code>```

Title: Delete duplicates from array C++

Body:
I am trying to create a simple program which calls on 2 functions. The first function takes a partially filled array, loops through it and deletes any duplicate values. When a value is deleted from the array, the remaining numbers are moved backwards to fill the gap i.e. when the function is finished, all null values of the array will be together at the end.

The second function prints the updated array.

My current code is below. At present when I run my code, the console shows:
2 6 0 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460. It should be showing: 1 2 5 6 if it worked correctly.

Also, I am not sure how to move the remaining elements of the array backwards so that the null values will be together at the end.

#include "pch.h"
#include <iostream>
using namespace std;
void deleteRepeats(int *arr, int arraySize, int& posUsed);
void printArray(int *arr, int arraySize);

int main()
{
int arr[10] = { 1, 2, 2, 5, 6, 1};
int posUsed = 6;
int arraySize = 10;

deleteRepeats(arr, arraySize, posUsed);
printArray(arr, arraySize);

return 0;
}

void deleteRepeats(int *arr, int arraySize, int& posUsed)
{
{
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = i; j < arraySize; j++)
        {
            if (arr[i] == arr[j])
            {
                for (int k = j; k < arraySize; k++)
                {
                    arr[k] = arr[k + 1];

                }
                posUsed--;

            }
            else
                j++;
        }
    }
}
}

void printArray(int *arr, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
    cout << arr[i] << "  ";
}
}

Body:
using two pointers

and if the array sorted

    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        int i = 0;

        for(int j = 1; j < nums.size(); j++)
            if(nums[j] != nums[i])  nums[++i] = nums[j];

        // return new array length
        return i + 1;
    }

//input: [1, 1, 2, 1] (arr1)
//output: 2 (returned length)
// print unique element
for(int i = 0; i < output; i++) cout << arr1[i] << '\n';
// [1, 2]

time complexity: O(N/2) -> O(N)
space complexity: O(1)


问:
Can I insert a node before current node in singly linked list using C?
Is this even possible, because singly linked list does not have pointer to previous, only next? I have a task to do where I have to write a function that inserts a node before current node, and I just can't seem to do it.

EDIT: I made this

```<code>    void before(List* list, int value) {
        Node * temp = new_node(value);
        temp->data = value;
        temp->next = NULL;
    if(list->size == 0){
        temp->next = list->current;
        list->current = temp;
        return;
    }else{
    for(Node * p = list->head->next; p == list->current; p = p->next){
        list->head = list->current;
        list->current =  list->current->next;
    }
 temp->next = list->head->next;
 list->head->next = temp;
    }
}
</code>```

But for input

```<code>    insert_after_current(list, 1);
    insert_after_current(list, 2);
    insert_after_current(list, 3);
    insert_after_current(list, 4);
    before(list, 5);
</code>```

I receive output

```<code>1 5 2 3 4
</code>```

Can someone explain why?

答:
```<code>typedef struct node
{
    struct node *next;
}node;

node *insert(node *parent, node *newnode)
{
    if(parent && newnode)
    {
        newnode -> next = parent -> next;
        parent -> next = newnode;
    }
}

node *insertbefore(node **haystack, node *needle, node *newnode)
{
    node *parent = *haystack;

    if(needle == *haystack)
    {
        newnode -> next = *haystack;
        *haystack = newnode;
    }
    else
    {
        while(parent -> next)
        {
            if(parent -> next == newnode)
            {
                insert(parent, newnode);
            }
            else
            {
                newnode = NULL;
            }
        }
    }
    return newnode;
}

</code>```

Body:
Is this even possible, because singly linked list does not have pointer to previous, only next? I have a task to do where I have to write a function that inserts a node before current node, and I just can't seem to do it.

EDIT: I made this

    void before(List* list, int value) {
        Node * temp = new_node(value);
        temp->data = value;
        temp->next = NULL;
    if(list->size == 0){
        temp->next = list->current;
        list->current = temp;
        return;
    }else{
    for(Node * p = list->head->next; p == list->current; p = p->next){
        list->head = list->current;
        list->current =  list->current->next;
    }
 temp->next = list->head->next;
 list->head->next = temp;
    }
}

But for input

    insert_after_current(list, 1);
    insert_after_current(list, 2);
    insert_after_current(list, 3);
    insert_after_current(list, 4);
    before(list, 5);

I receive output

1 5 2 3 4

Can someone explain why?