问:
How do I use variables from different methods
This is a grocery store problem that asks the user for what they are buying, how much of it and the price. The final price would then be calculated for each item (I have yet to do that for item 2 and 3)

I want to know how to use quantity1 and price1 from my getInfo() method into my calc() method.

The error code I get is :

```<code>   assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                          ^
      symbol:   variable quantity1
      location: class assignment_2
    assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                                      ^
      symbol:   variable price1
      location: class assignment_2
</code>```

My code :

```<code>import java.util.Scanner;
public class assignment_2
{
   public static void main(String[] args)
   {
      // Call methods here
      getInfo();
      calc();
   }

   public static void getInfo()
   {
      Scanner input = new Scanner(System.in);

      > Here I'm asking the user for the name of item 1
      // Item 1
      System.out.println("Name of item 1: ");
      String item1 = input.nextLine();

      > Here I'm asking the user for the quantity of item 1
      System.out.println("Quantity of item 1: ");
      int quantity1 = input.nextInt();

      > Here I'm asking the user for the price of item 1
      System.out.println("Price of item 1: ");
      double price1 = input.nextDouble();

      // Item 2
      Scanner input2 = new Scanner(System.in);

      System.out.println("Name of item 2: ");
      String item2 = input2.nextLine();

      System.out.println("Quantity of item 2: ");
      int quantity2 = input2.nextInt();

      System.out.println("Price of item 2: ");
      double price2 = input2.nextDouble();

      // Item 3
      Scanner input3 = new Scanner(System.in);

      System.out.println("Name of item 3: ");
      String item3 = input3.nextLine();

      System.out.println("Quantity of item 3: ");
      int quantity3 = input3.nextInt();

      System.out.println("Price of item 3: ");
      double price3 = input3.nextDouble();

      // Calculations
      // double total1 = quantity1 * price1;
      // System.out.println("Item 1 total: " + total1);

      // double total2 = quantity2 * price2;
      // System.out.println("Item 2 total: " + total2);

      // double total3 = quantity3 * price3;
      // System.out.println("Item 3 total: " + total3);
   }
   public static void calc()
   {
      double total1 = quantity1 * price1;
      System.out.println("Item 1 total: " + total1);
   }
}
</code>```

答:
Your variables that in getInfo() method are available just from that method. You could pass variables as parameters to calc(int quantiy, double price) or define your variables as class visible(global) variables.
 I strictly recomend to you check; scope of variables in java.

Body:
This is a grocery store problem that asks the user for what they are buying, how much of it and the price. The final price would then be calculated for each item (I have yet to do that for item 2 and 3)

I want to know how to use quantity1 and price1 from my getInfo() method into my calc() method.

The error code I get is :

   assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                          ^
      symbol:   variable quantity1
      location: class assignment_2
    assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                                      ^
      symbol:   variable price1
      location: class assignment_2

My code :

import java.util.Scanner;
public class assignment_2
{
   public static void main(String[] args)
   {
      // Call methods here
      getInfo();
      calc();
   }

   public static void getInfo()
   {
      Scanner input = new Scanner(System.in);

      > Here I'm asking the user for the name of item 1
      // Item 1
      System.out.println("Name of item 1: ");
      String item1 = input.nextLine();

      > Here I'm asking the user for the quantity of item 1
      System.out.println("Quantity of item 1: ");
      int quantity1 = input.nextInt();

      > Here I'm asking the user for the price of item 1
      System.out.println("Price of item 1: ");
      double price1 = input.nextDouble();

      // Item 2
      Scanner input2 = new Scanner(System.in);

      System.out.println("Name of item 2: ");
      String item2 = input2.nextLine();

      System.out.println("Quantity of item 2: ");
      int quantity2 = input2.nextInt();

      System.out.println("Price of item 2: ");
      double price2 = input2.nextDouble();

      // Item 3
      Scanner input3 = new Scanner(System.in);

      System.out.println("Name of item 3: ");
      String item3 = input3.nextLine();

      System.out.println("Quantity of item 3: ");
      int quantity3 = input3.nextInt();

      System.out.println("Price of item 3: ");
      double price3 = input3.nextDouble();

      // Calculations
      // double total1 = quantity1 * price1;
      // System.out.println("Item 1 total: " + total1);

      // double total2 = quantity2 * price2;
      // System.out.println("Item 2 total: " + total2);

      // double total3 = quantity3 * price3;
      // System.out.println("Item 3 total: " + total3);
   }
   public static void calc()
   {
      double total1 = quantity1 * price1;
      System.out.println("Item 1 total: " + total1);
   }
}


来源: stackexchange

问:
Subtracting time duration from timestamp column in pysaprk
I am trying to subtract a column with minutes stored from a timestamp column

And i know the following works for subtracting a fixed duration

```<code>from pyspark.sql.functions import current_timestamp, expr

(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + expr("INTERVAL 12 MINUTES")).alias("now_plus_twelve")))
</code>```

Is there a way to call this duration value from a column with stored value?

something like this :

```<code>(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + expr("INTERVAL col('duration_column) MINUTES")).alias("now_plus_twelve")))
</code>```

答:
I figured out this way it works :</p>

```<code>(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + col('duration_column')*expr("INTERVAL 1 minutes")).alias("now_plus_twelve")))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to subtract a column with minutes stored from a timestamp column

And i know the following works for subtracting a fixed duration

from pyspark.sql.functions import current_timestamp, expr

(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + expr("INTERVAL 12 MINUTES")).alias("now_plus_twelve")))

Is there a way to call this duration value from a column with stored value?

something like this :

(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + expr("INTERVAL col('duration_column) MINUTES")).alias("now_plus_twelve")))

Body:
I figured out this way it works :

(spark.range(1).select(
    current_timestamp().alias("now"),
    (current_timestamp() + col('duration_column')*expr("INTERVAL 1 minutes")).alias("now_plus_twelve")))


问:
Angular Component from a shared module not being recognised in Angular 9
I have a shared module that exports material components, reactive forms and other things but when I try to do that I get these kinds of errors:

If 'mat-menu' is an Angular component, then verify that it is part of
  this module.

Until now I've been trying but it doesn't fix. How can I solve it?

Below I will show all my modules so you understand what I'm trying to do. My pages.module and auth.module are the ones that has the components that are trying to use the shared.module.

App module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
//My imports
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
//import { HttpClientModule} from '@angular/common/http';
import { CoreModule } from './../app/core/core.module';
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    BrowserAnimationsModule,
    RouterModule,
    CoreModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p><strong><em>Material module</em></strong></p>

<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import {MatMenuModule} from '@angular/material/menu';
import {MatIconModule} from '@angular/material/icon';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatInputModule} from '@angular/material/input';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatRadioModule} from '@angular/material/radio';
import { FormsModule } from '@angular/forms';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatSnackBarModule} from '@angular/material/snack-bar';
const MaterialComponents = [
    MatMenuModule,
    MatIconModule,
    MatToolbarModule,
    MatButtonModule,
    MatCardModule,
    MatInputModule,
    MatCheckboxModule,
    MatRadioModule,
    FormsModule,
    MatGridListModule,
    MatProgressSpinnerModule,
    MatSnackBarModule,

];
@NgModule({
  imports: [
    MaterialComponents
  ],
  exports: [
    MaterialComponents
  ]
})
export class MaterialModule { }
</code>```

Shared module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from 'src/app/shared/material/material.module';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ],
  imports: [
    CommonModule,
    MaterialModule,
    ReactiveFormsModule,

  ],
  exports: [
    MaterialModule,
    ReactiveFormsModule,

  ]
})
export class SharedModule { }
```

<p><strong><em>Auth module</em></strong></p>

<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
//import { AuthRoutingModule } from './auth-routing.module';
import { HomeComponent } from 'src/app/auth/home/home.component';
import { HomeAdminComponent } from 'src/app/auth/home-admin/home-admin.component';
//import{ RoutingModule } from 'src/app/modules/routing.module';

@NgModule({
  declarations: [HomeComponent,HomeAdminComponent],
  imports: [
    CommonModule,
    SharedModule,
  ],
})
export class AuthModule { }
</code>```

Pages module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { AdminDashboardComponent } from 'src/app/pages/admin-dashboard/admin-dashboard.component';
import { UsersDashboardComponent } from 'src/app/pages/users-dashboard/users-dashboard.component';
import { RoutingAdminModule } from 'src/app/pages/routing-admin.module';
import { RoutingUsersModule } from 'src/app/pages/routing-users.module';

@NgModule({
  declarations: [AdminDashboardComponent, UsersDashboardComponent],
  imports: [
    CommonModule,
    SharedModule,
    RoutingAdminModule,
    RoutingUsersModule,
  ]
})
export class PagesModule { }
```

答:
The problem is you accidentally nested the array with the Imports array. The way to fix it would be

```<code>@NgModule({
  imports: [
    ...MaterialComponents
  ],
  exports: [
    ...MaterialComponents
  ]
})
export class MaterialModule { }
</code>```

In your block of code, you are erroneously setting the first element of the imports array to an array you call "MaterialComponents"; you accidentally created an array within an array.

The difference between your code and the solution is the spread syntax (the three periods ...)

In this case, the spread syntax essentially just appends the elements of the "MaterialComponents" to the import array, which is what you want.

Body:
I have a shared module that exports material components, reactive forms and other things but when I try to do that I get these kinds of errors:

If 'mat-menu' is an Angular component, then verify that it is part of
  this module.

Until now I've been trying but it doesn't fix. How can I solve it?

Below I will show all my modules so you understand what I'm trying to do. My pages.module and auth.module are the ones that has the components that are trying to use the shared.module.

App module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
//My imports
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
//import { HttpClientModule} from '@angular/common/http';
import { CoreModule } from './../app/core/core.module';
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    BrowserAnimationsModule,
    RouterModule,
    CoreModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Material module

import { NgModule } from '@angular/core';
import {MatMenuModule} from '@angular/material/menu';
import {MatIconModule} from '@angular/material/icon';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatInputModule} from '@angular/material/input';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatRadioModule} from '@angular/material/radio';
import { FormsModule } from '@angular/forms';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatSnackBarModule} from '@angular/material/snack-bar';
const MaterialComponents = [
    MatMenuModule,
    MatIconModule,
    MatToolbarModule,
    MatButtonModule,
    MatCardModule,
    MatInputModule,
    MatCheckboxModule,
    MatRadioModule,
    FormsModule,
    MatGridListModule,
    MatProgressSpinnerModule,
    MatSnackBarModule,

];
@NgModule({
  imports: [
    MaterialComponents
  ],
  exports: [
    MaterialComponents
  ]
})
export class MaterialModule { }

Shared module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from 'src/app/shared/material/material.module';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ],
  imports: [
    CommonModule,
    MaterialModule,
    ReactiveFormsModule,

  ],
  exports: [
    MaterialModule,
    ReactiveFormsModule,

  ]
})
export class SharedModule { }

Auth module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
//import { AuthRoutingModule } from './auth-routing.module';
import { HomeComponent } from 'src/app/auth/home/home.component';
import { HomeAdminComponent } from 'src/app/auth/home-admin/home-admin.component';
//import{ RoutingModule } from 'src/app/modules/routing.module';

@NgModule({
  declarations: [HomeComponent,HomeAdminComponent],
  imports: [
    CommonModule,
    SharedModule,
  ],
})
export class AuthModule { }

Pages module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { AdminDashboardComponent } from 'src/app/pages/admin-dashboard/admin-dashboard.component';
import { UsersDashboardComponent } from 'src/app/pages/users-dashboard/users-dashboard.component';
import { RoutingAdminModule } from 'src/app/pages/routing-admin.module';
import { RoutingUsersModule } from 'src/app/pages/routing-users.module';

@NgModule({
  declarations: [AdminDashboardComponent, UsersDashboardComponent],
  imports: [
    CommonModule,
    SharedModule,
    RoutingAdminModule,
    RoutingUsersModule,
  ]
})
export class PagesModule { }

Body:
The problem is you accidentally nested the array with the Imports array. The way to fix it would be

@NgModule({
  imports: [
    ...MaterialComponents
  ],
  exports: [
    ...MaterialComponents
  ]
})
export class MaterialModule { }

In your block of code, you are erroneously setting the first element of the imports array to an array you call "MaterialComponents"; you accidentally created an array within an array.

The difference between your code and the solution is the spread syntax (the three periods ...)

In this case, the spread syntax essentially just appends the elements of the "MaterialComponents" to the import array, which is what you want.


问:
Getting black screen in visual studio after Installation completed
I was getting black screen after opening Visual studio each time. I got a solution from Stack overflow i.e code --disable-gpu. It is working fine but my main issue is when I use to code in vs code. I am not getting suggestions as intellisense is not working and I am unable to install any extensions from Visual studio code.  </p>

答:
Go to properties of visual studio
change target . Add --disable-gpu
make sure to add a space before --
it will resolve your issue.


问:
Vectors divisible by 3 and 4
Im trying to make 2 empty vectors C and D and if vector (1:n) will be divisible by 3%%==0 then its need to be divide by a and be written into vector C same with D but 4%%==0 and then divide by b and writte to D vector</p>

```<code>funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:lenght(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }
    print("vector C")
    print(C)
    print("vector D")
    print(D)
  }
}

funkcia(3,4,9)
</code>```

答:
I think this approach is close to what you originally intended:

```<code>funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:length(vektor)) {
    if(vektor[i]%%a==0)
      {
      C = c(C,vektor[i])
      }
    if (vektor[i]%%b==0)
      {
      D = c(D,vektor[i])
    }
  }
    print("vector C")
    print(C)
    print("vector D")
    print(D)

}
</code>```

```<code>funkcia(3,4,9)
[1] "vector C"
[1] 3 6 9
[1] "vector D"
[1] 4 8
</code>```

Here's an alternative approach without any loops:

```<code>factor <- function(a, b, n) {
  init <- seq(1,n)
  result <- list(init[init %% a == 0],
                 init[init %% b == 0])
  names(result) <- c(paste0("div_",a),paste0("div_",b))
  result
}
factor(3,4,9)
$div_3
[1] 3 6 9

$div_4
[1] 4 8
</code>```

Title: Vectors divisible by 3 and 4

Body:
Im trying to make 2 empty vectors C and D and if vector (1:n) will be divisible by 3%%==0 then its need to be divide by a and be written into vector C same with D but 4%%==0 and then divide by b and writte to D vector

funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:lenght(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }
    print("vector C")
    print(C)
    print("vector D")
    print(D)
  }
}

funkcia(3,4,9)

Body:
I think this approach is close to what you originally intended:

funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:length(vektor)) {
    if(vektor[i]%%a==0)
      {
      C = c(C,vektor[i])
      }
    if (vektor[i]%%b==0)
      {
      D = c(D,vektor[i])
    }
  }
    print("vector C")
    print(C)
    print("vector D")
    print(D)

}

funkcia(3,4,9)
[1] "vector C"
[1] 3 6 9
[1] "vector D"
[1] 4 8

Here's an alternative approach without any loops:

factor <- function(a, b, n) {
  init <- seq(1,n)
  result <- list(init[init %% a == 0],
                 init[init %% b == 0])
  names(result) <- c(paste0("div_",a),paste0("div_",b))
  result
}
factor(3,4,9)
$div_3
[1] 3 6 9

$div_4
[1] 4 8


问:
Using Rails and Rspec, how do you test that the database is not touched by a method
So I'm writing a test for a method which for performance reasons should achieve what it needs to achieve without using SQL queries.  I'm thinking all I need to know is what to stub:

```<code>describe SomeModel do
  describe 'a_getter_method' do
    it 'should not touch the database' do
      thing = SomeModel.create

      something_inside_rails.should_not_receive(:a_method_querying_the_database)

      thing.a_getter_method
    end
  end
end
</code>```

EDIT: to provide a more specific example:

```<code>class Publication << ActiveRecord::Base
end
class Book << Publication
end
class Magazine << Publication
end

class Student << ActiveRecord::Base
  has_many :publications

  def publications_of_type(type)
    #this is the method I am trying to test.
    #The test should show that when I do the following, the database is queried.

    self.publications.find_all_by_type(type)
  end
end

describe Student do
  describe "publications_of_type" do
    it 'should not touch the database' do
       Student.create()
       student = Student.first(:include => :publications)
       #the publications relationship is already loaded, so no need to touch the DB

       lambda {
         student.publications_of_type(:magazine)
       }.should_not touch_the_database
    end
  end
end
</code>```

So the test should fail in this example, because the rails 'find_all_by' method relies on SQL.

答: I don't have enough points yet to comment, but following up on the answer left by @histocrat, and the comment left by @will-tomlins. If you stub ActiveRecord::Base.connection in place of the SomeModel.connection you will avoid getting the 'stack level too deep' message, and instead get an error from the matcher itself.

ContentLicense: CC BY-SA 3.0

Body:
So I'm writing a test for a method which for performance reasons should achieve what it needs to achieve without using SQL queries.  I'm thinking all I need to know is what to stub:

describe SomeModel do
  describe 'a_getter_method' do
    it 'should not touch the database' do
      thing = SomeModel.create

      something_inside_rails.should_not_receive(:a_method_querying_the_database)

      thing.a_getter_method
    end
  end
end

EDIT: to provide a more specific example:

class Publication << ActiveRecord::Base
end
class Book << Publication
end
class Magazine << Publication
end

class Student << ActiveRecord::Base
  has_many :publications

  def publications_of_type(type)
    #this is the method I am trying to test.
    #The test should show that when I do the following, the database is queried.

    self.publications.find_all_by_type(type)
  end
end

describe Student do
  describe "publications_of_type" do
    it 'should not touch the database' do
       Student.create()
       student = Student.first(:include => :publications)
       #the publications relationship is already loaded, so no need to touch the DB

       lambda {
         student.publications_of_type(:magazine)
       }.should_not touch_the_database
    end
  end
end

So the test should fail in this example, because the rails 'find_all_by' method relies on SQL.


问:
Javascript fetch doesn't return despite correct URL
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

```<code>this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}
</code>```

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

答:
response.json() returns a promise, not the content. So you will need to return await response.json()

Also, your server should return the data with the content-type being set to 'Content-Type': 'application/json'

Body:
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.


问:
unknown isc error 0 on Delphi XE TClientDataSet.Next
I have a DBXpress data structure connected to a Firebird database. I'm adding data pagination over a ClientDataSet, DataSetProvider and SQLQuery combination.
It was working well but recently it started to raise unknown isc error 0 exception after calling Next many times.

The pagination code is:

```<code>if not ClientDataSet.Active then
    ClientDataSet.Open;
RecNo := ClientDataSet.RecNo; // Keep track of selected record
ClientDataSet.DisableControls;
LastRecNo := GetLastRecNo;
if LastRecNo > -1 then
begin
    ClientDataSet.RecNo := LastRecNo;
    ClientDataSet.Next;
    while (not ClientDataSet.Eof) and (Result < DATA_PAGE_SIZE) do
    begin
         ...
         ClientDataSet.Next; // The exception is raised here
         Inc(Result);
    end;
end;
ClientDataSet.RecNo := RecNo;
ClientDataSet.EnableControls;
</code>```

The exception in intermittently raised, it could mean a connection issue, but the database is stored locally, the connection string is something like localhost:C:\Path\Base.FDB.

EDIT: This code is fired when user scrolls down the mouse, move down the scroll bar or navigates to the items that are next to the end of the list. On recent tests I've discovered the exception is only raised if the code is executed normally. If there is a break-point, or if I put there some sleeps, it executes normally.
I'm also sure I don't have any other thread changing the ClientDataSet.

答:
I found out that I was using FetchOnDemand = True and PacketRecords = 400. It is probably a concurrency issue on TClientDataset itself or some low-level Delphi implementation of fetching records on demand.

The glitch is gone if you set FetchOnDemand = False. I know it is not a solution if you have huge datasets, but that wasn't my case. I preferred to simply fetch the records at first and paginate over them already in-memory.

Body:
I have a DBXpress data structure connected to a Firebird database. I'm adding data pagination over a ClientDataSet, DataSetProvider and SQLQuery combination.
It was working well but recently it started to raise unknown isc error 0 exception after calling Next many times.

The pagination code is:

if not ClientDataSet.Active then
    ClientDataSet.Open;
RecNo := ClientDataSet.RecNo; // Keep track of selected record
ClientDataSet.DisableControls;
LastRecNo := GetLastRecNo;
if LastRecNo > -1 then
begin
    ClientDataSet.RecNo := LastRecNo;
    ClientDataSet.Next;
    while (not ClientDataSet.Eof) and (Result < DATA_PAGE_SIZE) do
    begin
         ...
         ClientDataSet.Next; // The exception is raised here
         Inc(Result);
    end;
end;
ClientDataSet.RecNo := RecNo;
ClientDataSet.EnableControls;

The exception in intermittently raised, it could mean a connection issue, but the database is stored locally, the connection string is something like localhost:C:\Path\Base.FDB.

EDIT: This code is fired when user scrolls down the mouse, move down the scroll bar or navigates to the items that are next to the end of the list. On recent tests I've discovered the exception is only raised if the code is executed normally. If there is a break-point, or if I put there some sleeps, it executes normally.
I'm also sure I don't have any other thread changing the ClientDataSet.


问:
Using Mutate and/or Apply Function on horse racing ratings dataframe to find average of two values
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

```<code>> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

</code>```

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

```<code>racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

</code>```

Gives:

```<code>
  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

</code>```

Thanks
Graham

答:
Here is a solution with dplyr. I also use pivot_longer to bring you data into a long format. Then I group the data by horse, keep only the top 2 rating values by horse and take the mean of these two ratings by horse:

```<code>library(tidyverse)
df %>%
  mutate(horse = 1:nrow(.)) %>%
  pivot_longer(DaH1:DaH3, values_to = "rating") %>%
  group_by(horse) %>%
  top_n(2, wt =rating) %>%
  summarise(mean_rating = mean(rating))

# A tibble: 7 x 2
  horse mean_rating
  <int>      <dbl>
1     1      122.
2     2      122.
3     3      124
4     4      122.
5     5       62.5
6     6        0
7     7      116.
</code>```

Data

```<code>df <- tibble::tribble(
  ~DaH1,~DaH2,~DaH3,
      0  ,124  ,121,
    124 , 117 , 119,
    121 , 125 , 123,
    123 , 120 , 119,
      0  ,125   ,NA,
     NA ,   0   , 0,
    110 ,  NA , 123,
  )
</code>```

Body:
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

Gives:

  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

Thanks
Graham

Body:
Here is a solution with dplyr. I also use pivot_longer to bring you data into a long format. Then I group the data by horse, keep only the top 2 rating values by horse and take the mean of these two ratings by horse:

library(tidyverse)
df %>%
  mutate(horse = 1:nrow(.)) %>%
  pivot_longer(DaH1:DaH3, values_to = "rating") %>%
  group_by(horse) %>%
  top_n(2, wt =rating) %>%
  summarise(mean_rating = mean(rating))

# A tibble: 7 x 2
  horse mean_rating
  <int>      <dbl>
1     1      122.
2     2      122.
3     3      124
4     4      122.
5     5       62.5
6     6        0
7     7      116.

Data

df <- tibble::tribble(
  ~DaH1,~DaH2,~DaH3,
      0  ,124  ,121,
    124 , 117 , 119,
    121 , 125 , 123,
    123 , 120 , 119,
      0  ,125   ,NA,
     NA ,   0   , 0,
    110 ,  NA , 123,
  )


问:
Rails 3: Setting ''role_ids' value to empty only when such a input area is present?
I have my User model, and a user can have many Roles.

In the User form i set roles to the user by doing this:

```<code>  <p><% for role in Role.all %>
        <%= check_box_tag "user[roles_ids][]", role.id, @user.roles.include?(role) %>
        <%= role.name %>
     <% end %>
  </p>
</code>```

and then in the controller i have the following to ensure that its cleared out when the user has no roles selected:

```<code>params[:user][:role_ids] ||= []
</code>```

This all works great, however i want to have an if statement in the controller to only empty out the role_ids when such values are returned, the reason is that for some users the roles addition check boxes are not displayed so they are not allowed to set roles, however when they make changes to other attributes it clears all the previous associations with any roles that were present before the update.

How can i get around this?

Thanks

答:
Hi I think if you have users with different roles decision either update ids or not should be based on user role and not on form data so you can do sth like </p>

```<code>params[ :user ][ :roles_ids ] = current_user.roles_ids unless current_user.has_role? :admin
</code>```

Body:
I have my User model, and a user can have many Roles.

In the User form i set roles to the user by doing this:

<% for role in Role.all %>
        <%= check_box_tag "user[roles_ids][]", role.id, @user.roles.include?(role) %>
        <%= role.name %>
     <% end %>

and then in the controller i have the following to ensure that its cleared out when the user has no roles selected:

params[:user][:role_ids] ||= []

This all works great, however i want to have an if statement in the controller to only empty out the role_ids when such values are returned, the reason is that for some users the roles addition check boxes are not displayed so they are not allowed to set roles, however when they make changes to other attributes it clears all the previous associations with any roles that were present before the update.

How can i get around this?

Thanks

Body:
Hi I think if you have users with different roles decision either update ids or not should be based on user role and not on form data so you can do sth like

params[ :user ][ :roles_ids ] = current_user.roles_ids unless current_user.has_role? :admin


问:
How to find prime numbers between 0 - 100?
In Javascript how would i find prime numbers between 0 - 100? i have thought about it, and i am not sure how to find them. i thought about doing x % x but i found the obvious problem with that.
this is what i have so far:
but unfortunately it is the worst code ever.</p>

```<code>var prime = function (){
var num;
for (num = 0; num < 101; num++){
    if (num % 2 === 0){
        break;
    }
    else if (num % 3 === 0){
        break;
    }
    else if (num % 4=== 0){
        break;
    }
    else if (num % 5 === 0){
        break;
    }
    else if (num % 6 === 0){
        break;
    }
    else if (num % 7 === 0){
        break;
    }
    else if (num % 8 === 0){
        break;
    }
    else if (num % 9 === 0){
        break;
    }
    else if (num % 10 === 0){
        break;
    }
    else if (num % 11 === 0){
        break;
    }
    else if (num % 12 === 0){
        break;
    }
    else {
        return num;
    }
}
};
console.log(prime());
</code>```

答:
```<code>function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num ;
}
function primes(n){
  var array_of_primes=[];
for(var i = 2; i < n; i++){
    if(isPrime(i)) array_of_primes.push(i)>1;
     }
   return array_of_primes;
}
document.write(primes(10000));
</code>```

Body:
In Javascript how would i find prime numbers between 0 - 100? i have thought about it, and i am not sure how to find them. i thought about doing x % x but i found the obvious problem with that.
this is what i have so far:
but unfortunately it is the worst code ever.

var prime = function (){
var num;
for (num = 0; num < 101; num++){
    if (num % 2 === 0){
        break;
    }
    else if (num % 3 === 0){
        break;
    }
    else if (num % 4=== 0){
        break;
    }
    else if (num % 5 === 0){
        break;
    }
    else if (num % 6 === 0){
        break;
    }
    else if (num % 7 === 0){
        break;
    }
    else if (num % 8 === 0){
        break;
    }
    else if (num % 9 === 0){
        break;
    }
    else if (num % 10 === 0){
        break;
    }
    else if (num % 11 === 0){
        break;
    }
    else if (num % 12 === 0){
        break;
    }
    else {
        return num;
    }
}
};
console.log(prime());


问:
Unpacking bytes from a pattern
How to unpack an array of bytes according to a pattern? eg. "uint:16,uint:12,uint:12"

In Python, there is bitstring module with unpack method, but I can't find any Java equivalent.

答:
Am not certain which version of Java you are using...

here's the link to the java reference for the BitSet class : BitSet.html

You can use the valueOf() function with a byte array to get a BitSet.  Then use the BitSet.get() funciton to extract out the bits for a specific range

so assuming you have a byte array...

```<code>byte[] bytes;

BitSet bigSet = BitSet(bytes);

BitSet uint16set = bigSet.get(0,16);
BitSet uint12set1 = bigSet.get(16, 16+12);
BitSet uint12.set2 = bigSet.get(28, 28+12);

long uint16Long = uint16set.toLongArray()[0];
long uint12Long1 = uint12set1.toLongArray()[0];
long uint12Long2 = uint12set2.toLongArray()[0];
</code>```

Title: Unpacking bytes from a pattern

Body:
Am not certain which version of Java you are using...

here's the link to the java reference for the BitSet class : BitSet.html

You can use the valueOf() function with a byte array to get a BitSet.  Then use the BitSet.get() funciton to extract out the bits for a specific range

so assuming you have a byte array...

byte[] bytes;

BitSet bigSet = BitSet(bytes);

BitSet uint16set = bigSet.get(0,16);
BitSet uint12set1 = bigSet.get(16, 16+12);
BitSet uint12.set2 = bigSet.get(28, 28+12);

long uint16Long = uint16set.toLongArray()[0];
long uint12Long1 = uint12set1.toLongArray()[0];
long uint12Long2 = uint12set2.toLongArray()[0];


问:
SQL query to display Count of records based in range from another table
I have two tables Range and Employee.

Range table consists of columns

```<code>minimum_salary, maximum salary, program
</code>```

(Available programs for that salary like platinum and silver etc).

Employee table has columns

```<code>Emp_Id, Emp_Name, Salary
</code>```

https://i.stack.imgur.com/RKaXP.png

I want to write a SQL query in such a way that it gets the  count of employees who fall under the given salary range in range table, please refer screenshot for tables and result set.

Any help is appreciated. Thanks

答:
You can join on inequality conditions:</p>

```<code>select r.program, count(e.emp_id) no_employees
from ranges r
left join employees e on e.salary between r.min_salary and r.max_salary
group by r.program
</code>```

Body:
I have two tables Range and Employee.

Range table consists of columns

minimum_salary, maximum salary, program

(Available programs for that salary like platinum and silver etc).

Employee table has columns

Emp_Id, Emp_Name, Salary

https://i.stack.imgur.com/RKaXP.png

I want to write a SQL query in such a way that it gets the  count of employees who fall under the given salary range in range table, please refer screenshot for tables and result set.

Any help is appreciated. Thanks

Body:
You can join on inequality conditions:

select r.program, count(e.emp_id) no_employees
from ranges r
left join employees e on e.salary between r.min_salary and r.max_salary
group by r.program


问:
How do I remove duplicates from a list, while preserving order?
How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order.
Is there a built-in or a Pythonic idiom?</p>

答:
One liner list comprehension:</p>
```<code>values_non_duplicated = [value for index, value in enumerate(values) if value not in values[ : index]]
</code>```

OwnerDisplayName: jmglov

LastEditorDisplayName: J.F. Sebastian

Body:
One liner list comprehension:

values_non_duplicated = [value for index, value in enumerate(values) if value not in values[ : index]]


问:
React- too many renders
this code:

```<code>const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    let bar = foo(1);

    return (
        <div>
            TEST
        </div>
    )
}
</code>```

runs foo twice. Why? My guess was that the second one is triggered by useState but when I created another useState it did not increase amount of the foo calls. So I am confused...

答:
In React js Render method called every property change but not every other method, like as componentDidmount, WillMount, etc. in update React use React Hooks with the functional component. just one function use to solve it "useEffect" here the snippet or visite the link Codesandbox

const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    useEffect(()=>{
       let bar = foo(1);
    },[])

    return (

            TEST

    )
}```

Title: React- too many renders

Body:
this code:

const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    let bar = foo(1);

    return (

            TEST

    )
}

runs foo twice. Why? My guess was that the second one is triggered by useState but when I created another useState it did not increase amount of the foo calls. So I am confused...

Body:
In React js Render method called every property change but not every other method, like as componentDidmount, WillMount, etc. in update React use React Hooks with the functional component. just one function use to solve it "useEffect" here the snippet or visite the link Codesandbox

const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    useEffect(()=>{
       let bar = foo(1);
    },[])

    return (
        <div>
            TEST
        </div>
    )
}


问:
fopen in binary mode returns null to existing file
I have a binary file ('''simdisk.bin'''). I opened it in  'r'  mode and i've no problems to read it. Now, i want to open it in binary mode (rb+) to write and read in binary, but i get a nill pointer.

I made a test.c file to try it with this main:

```<code>int main(int argc, char const *argv[])
{
 fp = fopen("simdisk.bin", "rb+");
 printf("Ptr: %p\n", fp);
 fclose(fp);
}
</code>```

答:
My guess is you don't have permission to write to the file, which is what you're requesting with the + modifier, and it has nothing to do with the binary thing (the b modifier).

Try this, which will tell you the reason why it's unable to open the file - not found? no permission? etc.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[])
{
   FILE *fp = fopen("simdisk.bin", "rb+");

   if (fp == 0)
   {
       printf("Cannot open file: error=%s\n", strerror(errno));
       exit(EXIT_FAILURE);
   }
   printf("Ptr: %p\n", fp);
   fclose(fp);

   return EXIT_SUCCESS;
}
</code>```

You can also test by changing the mode to "rb" - which wants read+binary but not update - and it's likely to work just fine because you're not asking to write to the file.

Body:
I have a binary file ('''simdisk.bin'''). I opened it in  'r'  mode and i've no problems to read it. Now, i want to open it in binary mode (rb+) to write and read in binary, but i get a nill pointer.

I made a test.c file to try it with this main:

int main(int argc, char const *argv[])
{
 fp = fopen("simdisk.bin", "rb+");
 printf("Ptr: %p\n", fp);
 fclose(fp);
}

Body:
My guess is you don't have permission to write to the file, which is what you're requesting with the + modifier, and it has nothing to do with the binary thing (the b modifier).

Try this, which will tell you the reason why it's unable to open the file - not found? no permission? etc.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[])
{
   FILE *fp = fopen("simdisk.bin", "rb+");

   if (fp == 0)
   {
       printf("Cannot open file: error=%s\n", strerror(errno));
       exit(EXIT_FAILURE);
   }
   printf("Ptr: %p\n", fp);
   fclose(fp);

   return EXIT_SUCCESS;
}

You can also test by changing the mode to "rb" - which wants read+binary but not update - and it's likely to work just fine because you're not asking to write to the file.


答:
I have found the solution by tweaking the Json key. Removed characters after "-" which left following Json File

```<code>"12":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`
</code>```

And pulled only key names 12 with this code

```<code> //my Json data is stored in a txt file
    $catid= 12;
    $data= fopen($_SERVER['DOCUMENT_ROOT']."URL TO DATA",'r');
    $json = fgets($data);
    $subitems =json_decode($json, TRUE);
    $subitems =$subitems[$catid];
</code>```

Title: PHP JSON Search with key name

Body:
I have following JSON Data

"12-305":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12-270":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12-273":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15-19":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12-19":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15-20":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12-20":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`

I want to only grab rows that contains "catid":"12" or key is like "12-" is this posible with using php json?

Body:
I have found the solution by tweaking the Json key. Removed characters after "-" which left following Json File

"12":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`

And pulled only key names 12 with this code

 //my Json data is stored in a txt file
    $catid= 12;
    $data= fopen($_SERVER['DOCUMENT_ROOT']."URL TO DATA",'r');
    $json = fgets($data);
    $subitems =json_decode($json, TRUE);
    $subitems =$subitems[$catid];


问:
Add title to a div in code behind is not appeared
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

```<code>myDiv.Attributes["title"] = "some value";
</code>```

-

```<code><div id="myDiv" class="UsersDialogClass"
                       runat="server" style="display: none">
</code>```

Any idea!

答: You may use asp:Panel server control and set it ToolTip property - it will render in div with appropriate title attribute value.</p>

Body:
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

myDiv.Attributes["title"] = "some value";

-

Any idea!


问:
Set Index of Array (SwiftUI)
I am working through hackingwithswift doing the 100 Days of SwiftUI and currently on Day 35 which needs me to build a times table app.

Unfortunately, I have got stuck at a very early stage and feel stupid asking.

How can I make my array index start at 1 rather than 0?

Below is my code and screenshot of the canvas:

```<code>struct ContentView: View {
    @State private var number = 0
    @State private var question = Int.random(in: 0..<13)

    let numberRange = Array<Int>(1 ... 12)

    var body: some View {
        VStack {
            Picker("What times tables do you want to test your knowledge on?", selection: $number) {
                ForEach(0 ..< numberRange.count) {
                    Text("\(self.numberRange[$0])")
                }
            }
            .pickerStyle(SegmentedPickerStyle())

            Text("What is \(number) x \(question) = ")
        }
    }
}
</code>```

答:
From Apple documentation:

The first element of a nonempty array is always at index zero.

Basically you'd need to add +1 to your number variable.

```<code>var correctNumber: Int {
    number + 1
}
</code>```

And use this correctNumber when displaying values or performing calculations.

```<code>Text("What is \(correctNumber) x \(question)?")
</code>```

As correctNumber is a computed property it will always be up to date with number variable.

Title: Set Index of Array (SwiftUI)

Body:
I am working through hackingwithswift doing the 100 Days of SwiftUI and currently on Day 35 which needs me to build a times table app.

Unfortunately, I have got stuck at a very early stage and feel stupid asking.

How can I make my array index start at 1 rather than 0?

Below is my code and screenshot of the canvas:

struct ContentView: View {
    @State private var number = 0
    @State private var question = Int.random(in: 0..<13)

    let numberRange = Array<Int>(1 ... 12)

    var body: some View {
        VStack {
            Picker("What times tables do you want to test your knowledge on?", selection: $number) {
                ForEach(0 ..< numberRange.count) {
                    Text("\(self.numberRange[$0])")
                }
            }
            .pickerStyle(SegmentedPickerStyle())

            Text("What is \(number) x \(question) = ")
        }
    }
}

Body:
From Apple documentation:

The first element of a nonempty array is always at index zero.

Basically you'd need to add +1 to your number variable.

var correctNumber: Int {
    number + 1
}

And use this correctNumber when displaying values or performing calculations.

Text("What is \(correctNumber) x \(question)?")

As correctNumber is a computed property it will always be up to date with number variable.


问:
Why am I getting a 500 error upon uploading photo with correct model and controller information?
I'm not sure why I'm getting a 500 error when trying to make a file upload that's associates with the uploaded file to the current user that's logged in.  I've tried too many ways to jot down here.  I'm suspecting the 'file_path' => $request->file('fileToUpload')->getClientOriginalName() line but I'm not entirely sure.

My intention is to store the file_path information to the database along with the the user id.  What am I doing wrong and how can I fix it?

Here's my controller:

```<code>public function upload(Request $request, Photo $photo) {
    $uploadedPhoto = $request->user()->photos()->create([
        'file_path' => $request->file('fileToUpload')->getClientOriginalName()
    ]);

    return response()->json($photo->with('user')->find($uploadedPhoto->id));
}
</code>```

Here's photo model:

```<code>class Photo extends Model {
protected $fillable = ['file_path'];

public function user() {
    return $this->belongsTo(User::class);
  }
}
</code>```

Here's the User model:

```<code>public function photos() {
    return $this->hasMany(Photo::class);
}
</code>```

Here's my migration table:

```<code>public function up() {
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('file_path', 140);
        $table->integer('likes_amount')->unsigned();
        $table->timestamps();
        $table->foreign("id")->references('id')->on('users')->onDelete('cascade');
    });
}
</code>```

答:
Try like This In your controller:(Follow the step and change the code as your need )</p>

```<code>public function upload(Request $request, Photo $photo) {
    $data = $request->image; // image
    $destinationPath = 'images/'; // upload path
    $profilefile = $name . '.' . $data->getClientOriginalExtension();
    $data->move($destinationPath, $profilefile); //storing to folder the file
    return $profilefile;
}

</code>```

Body:
I'm not sure why I'm getting a 500 error when trying to make a file upload that's associates with the uploaded file to the current user that's logged in.  I've tried too many ways to jot down here.  I'm suspecting the 'file_path' => $request->file('fileToUpload')->getClientOriginalName() line but I'm not entirely sure.

My intention is to store the file_path information to the database along with the the user id.  What am I doing wrong and how can I fix it?

Here's my controller:

public function upload(Request $request, Photo $photo) {
    $uploadedPhoto = $request->user()->photos()->create([
        'file_path' => $request->file('fileToUpload')->getClientOriginalName()
    ]);

    return response()->json($photo->with('user')->find($uploadedPhoto->id));
}

Here's photo model:

class Photo extends Model {
protected $fillable = ['file_path'];

public function user() {
    return $this->belongsTo(User::class);
  }
}

Here's the User model:

public function photos() {
    return $this->hasMany(Photo::class);
}

Here's my migration table:

public function up() {
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('file_path', 140);
        $table->integer('likes_amount')->unsigned();
        $table->timestamps();
        $table->foreign("id")->references('id')->on('users')->onDelete('cascade');
    });
}

Body:
Try like This In your controller:(Follow the step and change the code as your need )

public function upload(Request $request, Photo $photo) {
    $data = $request->image; // image
    $destinationPath = 'images/'; // upload path
    $profilefile = $name . '.' . $data->getClientOriginalExtension();
    $data->move($destinationPath, $profilefile); //storing to folder the file
    return $profilefile;
}


问:
Replacing window.setTimeout
Guys,
   I'm thinking of replacing window.setTimeout with a function of my own (for example we could have a generic error handler for exceptions thrown in callbacks).

The code will be along these lines:

```<code>var nativeSetTimeout = window.setTimeout;
window.setTimeout = function(fn, interval){
    nativeSetTimeout(function(){
            try{
               fn();
            }catch(e){
                // handle errors coming from the execution of fn
            }
        }, interval);
}
</code>```

Given that my app will stay in a single iframe, is there any outstanding issue that I should be concerned about?

答:
I wouldn't do that because it's true it can help in your own development, but replacing standard functions could break third-party libraries.

Basically, using your own function without replacing standard one should be the way to go. Use it in your code.

Title: Replacing window.setTimeout

Body:
Guys,
   I'm thinking of replacing window.setTimeout with a function of my own (for example we could have a generic error handler for exceptions thrown in callbacks).

The code will be along these lines:

var nativeSetTimeout = window.setTimeout;
window.setTimeout = function(fn, interval){
    nativeSetTimeout(function(){
            try{
               fn();
            }catch(e){
                // handle errors coming from the execution of fn
            }
        }, interval);
}

Given that my app will stay in a single iframe, is there any outstanding issue that I should be concerned about?


问:
Missing parameters in Rails Controller when using multipart/form-data in React
I am using Rails and React with Axios to create a record. In my React app I collect all the data and put it inside of FormData like this:

const createVtc = () => {

        let data = new FormData()

        data.append('image', vtcImageToSend)
        data.append('name', vtcName)
        data.append('description', vtcDescription)
        data.append('main_color', vtcColor)
        data.append('minimum_age_to_join', vtcMinimumAge)

        axios.post(`${ROOT_API}/v1/vtcs/create`, data, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            console.log(res.data);
            history.push('/dashboard')
        }).catch(err => {
            console.log(err);
        })
    };
```

<p>This contains all the necessary data in order to create a record.</p>

<p>This is the Rails controller responsible for creating it:</p>

<pre class="lang-rb prettyprint-override"><code>def create
    vtc = Vtc.new(vtc_params)
    # other code is not important
  end
</code>```

And this is vtc_params private function:

  def vtc_params
    params.require(:vtc).permit(:id, :name, :description, :minimum_age_to_join, :main_color, :image)
  end
```

<p>Pretty standard stuff. It worked until I had to implement picture upload which made me switch to <code>FormData</code> upload and since then Rails throws this error:</p>

``` ActionController::ParameterMissing in V1::VtcsController#create
 param is missing or the value is empty: vtc
```

<p>I can assume what's the problem but I don't know how to fix it. Before <code>FormData</code> I used to send it like this:</p>

<pre class="lang-js prettyprint-override"><code>// other stuff
axios.post(`${ROOT_API}/v1/vtcs/create`, {
    "vtc": {
        "name": vtcName,
        // etc.
    }
}, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }
        })
// other stuff
</code>```

All of the data was inside of "vtc" object but now it's just data variable. I tried adding {"vtc": data} as Axios data which not surprisingly didn't work.

答:
Just wrap your data variable in an object with the key vtc:

```<code>  axios.post(`${ROOT_API}/v1/vtcs/create`, {vtc: data}, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }
</code>```

Body:
I am using Rails and React with Axios to create a record. In my React app I collect all the data and put it inside of FormData like this:

const createVtc = () => {

        let data = new FormData()

        data.append('image', vtcImageToSend)
        data.append('name', vtcName)
        data.append('description', vtcDescription)
        data.append('main_color', vtcColor)
        data.append('minimum_age_to_join', vtcMinimumAge)

        axios.post(`${ROOT_API}/v1/vtcs/create`, data, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            console.log(res.data);
            history.push('/dashboard')
        }).catch(err => {
            console.log(err);
        })
    };

This contains all the necessary data in order to create a record.

This is the Rails controller responsible for creating it:

def create
    vtc = Vtc.new(vtc_params)
    # other code is not important
  end

And this is vtc_params private function:

  def vtc_params
    params.require(:vtc).permit(:id, :name, :description, :minimum_age_to_join, :main_color, :image)
  end

Pretty standard stuff. It worked until I had to implement picture upload which made me switch to FormData upload and since then Rails throws this error:

 ActionController::ParameterMissing in V1::VtcsController#create
 param is missing or the value is empty: vtc

I can assume what's the problem but I don't know how to fix it. Before FormData I used to send it like this:

// other stuff
axios.post(`${ROOT_API}/v1/vtcs/create`, {
    "vtc": {
        "name": vtcName,
        // etc.
    }
}, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }
        })
// other stuff

All of the data was inside of "vtc" object but now it's just data variable. I tried adding {"vtc": data} as Axios data which not surprisingly didn't work.

Body:
Just wrap your data variable in an object with the key vtc:

  axios.post(`${ROOT_API}/v1/vtcs/create`, {vtc: data}, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'multipart/form-data'
            }


问:
Unit testing Kafka streams with groupByKey/windowedBy/count
My question is similar to: How to unit test a kafka stream application that uses session window

Topology looks like

```<code>.filter()
.groupByKey()
.windowedBy(SessionWindows.with(30).grace(5))
.count()
.toStream()
.selectKey((k, v)->k.key())
.to(outTopic)
</code>```

When I run this application, and send data like:

```<code>key1, {somejson}
key1, {somejson}
key1, {somejson}
</code>```

In the output topic, I correctly see the record after 30 seconds as expected

```<code>key1, 3
</code>```

When I write a unit test for the same (after reading the other question about advancedWallClockTime, my test code looks like:

```<code>final Instant now = Instant.now();

// Send messages with one second difference timestamps
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.plusMillis(1000L).toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.plusMillis(2000L).toEpochMilli()));

testDriver.advanceWallClockTime(35000L)
</code>```

Then I try to compare the results

```<code>ProducerRecord<String, Long> life = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
Assert.assertEquals(lifevalue, Long.valueOf(3));
</code>```

I expect it to be 3 but it seems its always 1. But if I write something like:

```<code>List<ProducerRecord<String, Long>> expectedList = Arrays.asList(
  new ProducerRecord<String, Long>(outputTopicName, "key1", 1L),
  new ProducerRecord<String, Long>(outputTopicName, "key1", 2L),
  new ProducerRecord<String, Long>(outputTopicName, "key1", 3L)
);

for (ProducerRecord<String, Long> expected : expectedList) {
    ProducerRecord<String, Long> actual = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
    Assert.assertEquals(expected.value(),  actual.value());
}
</code>```

then my test passes.

What I am doing wrong? Eventually, I would like to add data for two different keys and test that both of them are coming with count: 3L.

答:
The difference you see with regards to testing is how the TopologyTestDriver works.  It might help first to explain how Kafka Streams treats stateful operations for some context.

When you run the Kafka Streams application, "for real" records from stateful operations are buffered by the internal cache.  Kafka Streams flushes the internal cache when either of the two following conditions is met:

Committing records (default commit interval is 30 seconds)

The cache is full.

From what you describe above, you observe the count of 3 after streams commits the consumed offsets.  The first two records were replaced in the cache, and only the last count of 3 is emitted.

Now with the TopologyTestDriver, there is no internal caching; the test driver forwards each record. As a result, you'll have to call testDriver.readOutput for each record you've submitted.

So your line above

ProducerRecord<String, Long> life = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
```

<p>emits the first record you supplied via <code>testDriver.pipeInput</code>. As you only called <code>testDriver.readOutput</code> once. </p>

<p>You'll notice in your second code example:</p>

<pre class="lang-java prettyprint-override"><code>for (ProducerRecord<String, Long> expected : expectedList) {
    ProducerRecord<String, Long> actual = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
    Assert.assertEquals(expected.value(),  actual.value());
}
</code>```

You get the expected result because you execute testDriver.readOutput the same number of times as you've input test records.

HTH,

Bill

Body:
My question is similar to: How to unit test a kafka stream application that uses session window

Topology looks like

.filter()
.groupByKey()
.windowedBy(SessionWindows.with(30).grace(5))
.count()
.toStream()
.selectKey((k, v)->k.key())
.to(outTopic)

When I run this application, and send data like:

key1, {somejson}
key1, {somejson}
key1, {somejson}

In the output topic, I correctly see the record after 30 seconds as expected

key1, 3

When I write a unit test for the same (after reading the other question about advancedWallClockTime, my test code looks like:

final Instant now = Instant.now();

// Send messages with one second difference timestamps
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.plusMillis(1000L).toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, "key1", json, now.plusMillis(2000L).toEpochMilli()));

testDriver.advanceWallClockTime(35000L)

Then I try to compare the results

ProducerRecord<String, Long> life = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
Assert.assertEquals(lifevalue, Long.valueOf(3));

I expect it to be 3 but it seems its always 1. But if I write something like:

List<ProducerRecord<String, Long>> expectedList = Arrays.asList(
  new ProducerRecord<String, Long>(outputTopicName, "key1", 1L),
  new ProducerRecord<String, Long>(outputTopicName, "key1", 2L),
  new ProducerRecord<String, Long>(outputTopicName, "key1", 3L)
);

for (ProducerRecord<String, Long> expected : expectedList) {
    ProducerRecord<String, Long> actual = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
    Assert.assertEquals(expected.value(),  actual.value());
}

then my test passes.

What I am doing wrong? Eventually, I would like to add data for two different keys and test that both of them are coming with count: 3L.

Body:
The difference you see with regards to testing is how the TopologyTestDriver works.  It might help first to explain how Kafka Streams treats stateful operations for some context.

When you run the Kafka Streams application, "for real" records from stateful operations are buffered by the internal cache.  Kafka Streams flushes the internal cache when either of the two following conditions is met:

Committing records (default commit interval is 30 seconds)

The cache is full.

From what you describe above, you observe the count of 3 after streams commits the consumed offsets.  The first two records were replaced in the cache, and only the last count of 3 is emitted.

Now with the TopologyTestDriver, there is no internal caching; the test driver forwards each record. As a result, you'll have to call testDriver.readOutput for each record you've submitted.

So your line above

ProducerRecord<String, Long> life = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());

emits the first record you supplied via testDriver.pipeInput. As you only called testDriver.readOutput once.

You'll notice in your second code example:

for (ProducerRecord<String, Long> expected : expectedList) {
    ProducerRecord<String, Long> actual = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
    Assert.assertEquals(expected.value(),  actual.value());
}

You get the expected result because you execute testDriver.readOutput the same number of times as you've input test records.

HTH,

Bill


问:
Google colab download - ConnectionResetError: [Errno 104] Connection reset by peer
I'm using google colab and I want to automatically download a file (which can be large : ~100Mo). For now, I'm using:

from google.colab import files

files.download('results.zip')
```

<p>But it is not consistent, and most of the time I get the error: <code>ConnectionResetError: [Errno 104] Connection reset by peer</code> :</p>

```Exception happened during processing of request from ('::ffff:127.0.0.1', 55642, 0, 0)
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 320, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 351, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
    self.handle()
  File "/usr/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "/usr/lib/python3.6/http/server.py", line 639, in do_GET
    self.copyfile(f, self.wfile)
  File "/usr/lib/python3.6/http/server.py", line 800, in copyfile
    shutil.copyfileobj(source, outputfile)
  File "/usr/lib/python3.6/shutil.py", line 82, in copyfileobj
    fdst.write(buf)
  File "/usr/lib/python3.6/socketserver.py", line 803, in write
    self._sock.sendall(b)
ConnectionResetError: [Errno 104] Connection reset by peer
```

How can I fix this ? Or is there any work around to automatically download a file from colab ?

Thank you !

答:
For improved reliability, I'd recommend using the file browser in the left-hand pane rather than files.download, particularly if your file is large.

Another option is to mount your Google Drive and then copy the results.zip file there. Google Drive sync is also likely to be faster than direct download.

Body:
I'm using google colab and I want to automatically download a file (which can be large : ~100Mo). For now, I'm using:

from google.colab import files

files.download('results.zip')

But it is not consistent, and most of the time I get the error: ConnectionResetError: [Errno 104] Connection reset by peer :

Exception happened during processing of request from ('::ffff:127.0.0.1', 55642, 0, 0)
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 320, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 351, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
    self.handle()
  File "/usr/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "/usr/lib/python3.6/http/server.py", line 639, in do_GET
    self.copyfile(f, self.wfile)
  File "/usr/lib/python3.6/http/server.py", line 800, in copyfile
    shutil.copyfileobj(source, outputfile)
  File "/usr/lib/python3.6/shutil.py", line 82, in copyfileobj
    fdst.write(buf)
  File "/usr/lib/python3.6/socketserver.py", line 803, in write
    self._sock.sendall(b)
ConnectionResetError: [Errno 104] Connection reset by peer

How can I fix this ? Or is there any work around to automatically download a file from colab ?

Thank you !


问:
Innodb Cluster upgradeMetadata on broken cluster
We have a cluster of 3 nodes, 2 of them are offline (missing) and I cannot get them to rejoin the cluster automatically only the master is Online.

Usually, you can use innodb admin:

var cluster = dba.getCluster();

but I cannot use the cluster instance because the metadata is not up to date. But I cannot upgrade the meta data because the missing members are required to be online to use dba.upgradeMetadata(). (Catch 22)

I tried to dissolve the cluster by using:

var cluster = dba.rebootClusterFromCompleteOutage();

cluster.dissolve({force:true});

but this requires the metadata to be updated as well.

Question is, how do I dissolve the cluster completely or upgrade the metadata so that I can use the cluster. methods.

答: If you have a cluster where each node upgrades to the latest version of mysql and the cluster isn't fully operational and you need to update your metadata for mysqlsh, you'll need to use an older version of mysqlsh for example, https://downloads.mysql.com/archives/shell/ to get the cluster back up and running. Once it is up and running you can use the dba.upgrademetadata on the R/W node - make sure you update all of your routers or they will lose connection.</p>


问:
Is it possible to build a HashMap of &str referencing environment variables?
I'm trying to make a read-only map of environment variables.

```<code>fn os_env_hashmap() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    use std::env;
    for (key,val) in env::vars_os() {
        let k = key.to_str();
        if k.is_none() { continue }
        let v = val.to_str();
        if v.is_none() { continue }
        k.unwrap();
        //map.insert( k.unwrap(), v.unwrap() );
    }
    return map;
}
</code>```

Can't seem to uncomment the "insert" line near the bottom without compiler errors about key,val,k, and v being local.

I might be able to fix the compiler error by using String instead of str, but str seems perfect for a read-only result.

Feel free to suggest a more idiomatic way to do this.

答:
This is unfortunately not straightforward using only the facilities of the Rust standard library.

If env::vars_os() returned an iterator over &'static OsStr instead of OsString, this would be trivial. Unfortunately, not all platforms allow creating an &OsStr to the contents of an environment variable. In particular, on Windows, the native encoding is UTF-16 but the encoding needed by OsStr is WTF-8. For this reason, there really is no OsStr anywhere you could take a reference to, until you create an OsString by iterating over env::vars_os().

The simplest thing, as the question comments mention, is to return owned Strings:

```<code>fn os_env_hashmap() -> HashMap<String, String> {
    let mut map = HashMap::new();
    use std::env;
    for (key, val) in env::vars_os() {
        // Use pattern bindings instead of testing .is_some() followed by .unwrap()
        if let (Ok(k), Ok(v)) = (key.into_string(), val.into_string()) {
            map.insert(k, v);
        }
    }
    return map;
}
</code>```

The result is not "read-only", but it is not shared, so you cannot cause data races or other weird bugs by mutating it.

See also

Is there any way to return a reference to a variable created in a function?

Return local String as a slice (&str)

Body:
I'm trying to make a read-only map of environment variables.

fn os_env_hashmap() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    use std::env;
    for (key,val) in env::vars_os() {
        let k = key.to_str();
        if k.is_none() { continue }
        let v = val.to_str();
        if v.is_none() { continue }
        k.unwrap();
        //map.insert( k.unwrap(), v.unwrap() );
    }
    return map;
}

Can't seem to uncomment the "insert" line near the bottom without compiler errors about key,val,k, and v being local.

I might be able to fix the compiler error by using String instead of str, but str seems perfect for a read-only result.

Feel free to suggest a more idiomatic way to do this.

Body:
This is unfortunately not straightforward using only the facilities of the Rust standard library.

If env::vars_os() returned an iterator over &'static OsStr instead of OsString, this would be trivial. Unfortunately, not all platforms allow creating an &OsStr to the contents of an environment variable. In particular, on Windows, the native encoding is UTF-16 but the encoding needed by OsStr is WTF-8. For this reason, there really is no OsStr anywhere you could take a reference to, until you create an OsString by iterating over env::vars_os().

The simplest thing, as the question comments mention, is to return owned Strings:

fn os_env_hashmap() -> HashMap<String, String> {
    let mut map = HashMap::new();
    use std::env;
    for (key, val) in env::vars_os() {
        // Use pattern bindings instead of testing .is_some() followed by .unwrap()
        if let (Ok(k), Ok(v)) = (key.into_string(), val.into_string()) {
            map.insert(k, v);
        }
    }
    return map;
}

The result is not "read-only", but it is not shared, so you cannot cause data races or other weird bugs by mutating it.

See also

Is there any way to return a reference to a variable created in a function?

Return local String as a slice (&str)


问:
Resizing JPG using PIL.resize gives a completely black image
I'm using PIL to resize a JPG. I'm expecting the same image, resized as output, but instead I get a correctly sized black box. The new image file is completely devoid of any information, just an empty file. Here is an excerpt for my script:

```<code>basewidth = 300
img = Image.open(path_to_image)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize))
img.save(dir + "/the_image.jpg")
</code>```

I've tried resizing with Image.LANCZOS as the second argument, (defaults to Image.NEAREST with 1 argument), but it didn't make a difference. I'm running Python3 on Ubunutu 16.04. Any ideas on why the image file is empty?

答:
I also encountered the same issue when trying to resize an image with transparent background. The "resize" works after I add a white background to the image.

Code to add a white background then resize the image:

from PIL import Image

im = Image.open("path/to/img")

if im.mode == 'RGBA':
    alpha = im.split()[3]
    bgmask = alpha.point(lambda x: 255-x)
    im = im.convert('RGB')
    im.paste((255,255,255), None, bgmask)

im = im.resize((new_width, new_height), Image.ANTIALIAS)
```

ref:

Other's code for making thumbnail

Python: Image resizing: keep proportion - add white background

Body:
I'm using PIL to resize a JPG. I'm expecting the same image, resized as output, but instead I get a correctly sized black box. The new image file is completely devoid of any information, just an empty file. Here is an excerpt for my script:

basewidth = 300
img = Image.open(path_to_image)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize))
img.save(dir + "/the_image.jpg")

I've tried resizing with Image.LANCZOS as the second argument, (defaults to Image.NEAREST with 1 argument), but it didn't make a difference. I'm running Python3 on Ubunutu 16.04. Any ideas on why the image file is empty?

Body:
I also encountered the same issue when trying to resize an image with transparent background. The "resize" works after I add a white background to the image.

Code to add a white background then resize the image:

from PIL import Image

im = Image.open("path/to/img")

if im.mode == 'RGBA':
    alpha = im.split()[3]
    bgmask = alpha.point(lambda x: 255-x)
    im = im.convert('RGB')
    im.paste((255,255,255), None, bgmask)

im = im.resize((new_width, new_height), Image.ANTIALIAS)

ref:

Other's code for making thumbnail

Python: Image resizing: keep proportion - add white background


问:
LinkedIn Share API not displaying large image thumbnails anymore
I've been using a plugin called Microblog Poster on my hosted Wordpress site to auto-publish blog entries to LinkedIn, Facebook, Twitter, etc.

I have made no changes to the plugin, the plugin hasn't updated, basically everything has been the exact same. However, within the past 5 days, LinkedIn has stopped displaying the shared image as a large image, when it has been consistently sharing it as a large image before.

It will share the image, but it's now a thumbnail, showing approx 140px x 70px to the left of the shared link's title. Normally, it should show as a large, 525px x 275px image above the shared link's title.

Again, no changes have been made to the plugin, my process, or anything. Facebook and Twitter are still displaying normally. I've even done several tests with different posts to confirm it was not a fluke.

Would love any thoughts on how to fix this, or if anyone else is having this issue.

答:
Take a look at the The Open Graph protocol.  You have the option to set the size of your image, as they show in their demo.  You already know about the og:image property, but what about og:image:width and og:image:height?  Check it out...

```<code><meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />
</code>```

This will show a preview of your image in a standard 400x300 format.  This should work, because LinkedIn says they read og: tags in determining share previews, according to the official documentation.  Although they don't mention :width and :height, I hope they would respect these tags, too, because they are part of the Open Graph Protocol.  Hope this helps!

Body:
Take a look at the The Open Graph protocol.  You have the option to set the size of your image, as they show in their demo.  You already know about the og:image property, but what about og:image:width and og:image:height?  Check it out...

<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />

This will show a preview of your image in a standard 400x300 format.  This should work, because LinkedIn says they read og: tags in determining share previews, according to the official documentation.  Although they don't mention :width and :height, I hope they would respect these tags, too, because they are part of the Open Graph Protocol.  Hope this helps!


问:
TypeScript a better way optional constructor parameter based on interface
Let's say I got this interface:

```<code>// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}
</code>```

and I use it here

```<code>// FooModel.ts
import IFoo from "./IFoo";

export default class FooModel implements IFoo {
  foo = 'hello';
  bar = 1;

  constructor(_fooModel?: IFoo) {
    if (_fooModel === undefined) return; // <-- this is what I am talking about
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar
  }
}
</code>```

is there a better (more elegant and readable to be specific) way to reproduce this? I'm mainly talking about the if undefined return statement. Which will apply their default values if it returns, of course.

答:
I think I'd use a destructured parameter with a default value, like this:

```<code>export default class FooModel implements IFoo {
    foo: string;
    bar: number;

    constructor({foo = "hello", bar = 1} : Partial<IFoo> = {}) {
// Prop defaults −−−−^^^^^^^^^−−−−−−^^^                  ^^^^−−−−− overall default
        this.foo = foo;
        this.bar = bar;
    }
}
</code>```

Playground link

In that example, the default expression isn't evaluated unless it's needed, so even an expensive expression is fine.

That also lets you assign partial IFoos (just foo or just bar). If you don't want that, move the default values into the overal initializer, like this:

```<code>    constructor({foo, bar}: IFoo = {foo: "hello", bar: 1}) {
</code>```

Playground link

FWIW, note that the values in the initializers on the properties in your original code will always be assigned, your constructor is currently effectively:

```<code>// Your current code, in effect
constructor(_fooModel?: IFoo) {
    this.foo = 'hello';
    this.bar = 1;
    if (_fooModel === undefined) return;
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar;
}
</code>```

That's just fine, but I thought I'd mention it in case there was an expensive expression being used instead.

Body:
Let's say I got this interface:

// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}

and I use it here

// FooModel.ts
import IFoo from "./IFoo";

export default class FooModel implements IFoo {
  foo = 'hello';
  bar = 1;

  constructor(_fooModel?: IFoo) {
    if (_fooModel === undefined) return; // <-- this is what I am talking about
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar
  }
}

is there a better (more elegant and readable to be specific) way to reproduce this? I'm mainly talking about the if undefined return statement. Which will apply their default values if it returns, of course.

Body:
I think I'd use a destructured parameter with a default value, like this:

export default class FooModel implements IFoo {
    foo: string;
    bar: number;

    constructor({foo = "hello", bar = 1} : Partial<IFoo> = {}) {
// Prop defaults −−−−^^^^^^^^^−−−−−−^^^                  ^^^^−−−−− overall default
        this.foo = foo;
        this.bar = bar;
    }
}

Playground link

In that example, the default expression isn't evaluated unless it's needed, so even an expensive expression is fine.

That also lets you assign partial IFoos (just foo or just bar). If you don't want that, move the default values into the overal initializer, like this:

    constructor({foo, bar}: IFoo = {foo: "hello", bar: 1}) {

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIDED2nkG8BQyyM2AXMgM5hSgDmA3IcgEZxTkgCuAts9IwF98+APQAqCAA8ADpihhkAEwjxOAGzBiRyBGrgUKyLJgCymZWuTBu0tRG4RwhjNjxMiJTOSo0QDdyxsHDx8UIwBCJggPpwIYHIAFLieADSBUALkLjgAvHie5ABEABYQamqYhWms7MgAjAIAlG5Era1gxcAUAHSeyHmejG1tHV3dNf3pQ61CQviR0QowdZMgEADuRthmFgmNjAsUmHbdFbQJy73Y+8gi2iVlFYXzUUcnZxd142w3d-XClz6eUKkkKjEuEzyABYAEwHV5LGGrDZbUzmMqffYvaLHCCnTDnGAwq6YX73STYt54j5E75QMnIWHCQ5LADMyM2xh2GNwTXot20AB4ciLkABRKBQORpbhdCh0ZAAA08iuQcBAiiVNUVQA" rel="nofollow noreferrer">Playground link

FWIW, note that the values in the initializers on the properties in your original code will always be assigned, your constructor is currently effectively:

// Your current code, in effect
constructor(_fooModel?: IFoo) {
    this.foo = 'hello';
    this.bar = 1;
    if (_fooModel === undefined) return;
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar;
}

That's just fine, but I thought I'd mention it in case there was an expensive expression being used instead.


问:
Override default android messaging application
I want to override the default android messaging application.
If I receive a sms or mms I want to send that to email but i don't want any notification on phone.
So basically I want to replace the default messaging application.

How can I make my application the default one that receive the sms?

Thanks a lot. That is exactly what I need. But I have one more problem.
I used the receiver to get the message ... but I don't know how to find the message in the phone and mark it as read.

```<code>public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

        //---find and mark the messages as read---
        Uri uriSms = Uri.parse("content://sms/inbox/");
       try{
        Cursor c = context.getContentResolver().query(uriSms, null,null,null,null);
            //---code to find the message by body and sender---
            ...

    }
</code>```

Is there any way in which I can identify the message like an id?
Now I find the message comparing the bofy and sender number for all messages in inbox.

Thanks,
Radu

答:
If you sent priority of your BroadcastReceiver high enough, your application is the first one receiving the message, BEFORE the message is stored in the database.
I guess the solution would be to store the message in the database yourself and call abortBroadcast();, but I didn't try this myself, yet.

Good luck!

Body:
I want to override the default android messaging application.
If I receive a sms or mms I want to send that to email but i don't want any notification on phone.
So basically I want to replace the default messaging application.

How can I make my application the default one that receive the sms?

Thanks a lot. That is exactly what I need. But I have one more problem.
I used the receiver to get the message ... but I don't know how to find the message in the phone and mark it as read.

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }
        //---display the new SMS message---
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

        //---find and mark the messages as read---
        Uri uriSms = Uri.parse("content://sms/inbox/");
       try{
        Cursor c = context.getContentResolver().query(uriSms, null,null,null,null);
            //---code to find the message by body and sender---
            ...

    }

Is there any way in which I can identify the message like an id?
Now I find the message comparing the bofy and sender number for all messages in inbox.

Thanks,
Radu