问:
Using Bool In Struct in SwiftUI
I have a problem when trying to use a bool as part of a swift struct.

```<code>struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    var isShown: Bool

}
</code>```

An array of these prefs are provided by a store to a swift-UI view

```<code>class MapPrefsStore : ObservableObject {

    var willChange = PassthroughSubject<Void, Never>()

    @Published var MapPrefs: [MapPrefs] {
        didSet { willChange.send(()) }
    }

    init(mapPrefs: [MapPrefs]) {
        self.MapPrefs = mapPrefs
    }

}
</code>```

The Settings View Observes the Store and passes the array to a cell view

```<code>struct SettingsView: View {

    @ObservedObject var mapPrefsStore = MapPrefsStore(mapPrefs: MapPrefsTestData)

    var body: some View {

        NavigationView {
            List {

                 Section(header: Text("Map Preferences"), footer: Text("")) {

                    ForEach(mapPrefsStore.MapPrefs) { mapPrefs in
                        MapPrefsCell(mapPrefs: mapPrefs)
                    }
                    .onMove(perform: moveMap)
                                }
                .background(Color.clear)
            }
            .navigationBarTitle(Text("Settings"))
            .navigationBarItems(trailing: EditButton())
            .listStyle(GroupedListStyle())
        }
    }
    func moveMap(from source: IndexSet, to destination: Int) {
        guard let sourceIndex = Array(source).first else { return }
        mapPrefsStore.MapPrefs.insert(mapPrefsStore.MapPrefs.remove(at: sourceIndex), at: destination)
    }
}

struct MapPrefsCell : View {
    let mapPrefs: MapPrefs

    var body: some View {

        Toggle(isOn: mapPrefs.isShown) {
            Text(mapPrefs.name)
        }
    }
}
}
</code>```

this gives me the following error

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

I can't figure out how to allow the called function (MapPrefsCell) the ability to access the isShown property.  I tried various combinations of adding the $ sign.

答:
isShown is declared as Bool. Passing it with $ won't work as you can not convert it to Binding<Bool>.

You could declare it as @State in your struct:

```<code>struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    @State var isShown: Bool

}
</code>```

and then pass it as Binding...

```<code>Toggle(isOn: mapPrefs.$isShown) {
    Text(mapPrefs.name)
}
</code>```

Edit:

You can also create a custom State and use the value of your mapPrefs for that State. But then you will need to store changes to your object afterwards. In this case you do not need to declare it as @State

```<code>struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    var isShown: Bool

}

struct MapPrefsCell : View {
    let mapPrefs: MapPrefs

    @State var toggle : Bool

    init(mapPrefs: MapPrefs)
    {
        //create State with initial value here
        self._toggle = State(initialValue: self.mapPrefs.isShown)
    }

    var body: some View {

        Toggle(isOn: $toggle) {
            Text(mapPrefs.name)
        }
    }
}
</code>```

Title: Using Bool In Struct in SwiftUI

Body:
I have a problem when trying to use a bool as part of a swift struct.

struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    var isShown: Bool

}

An array of these prefs are provided by a store to a swift-UI view

class MapPrefsStore : ObservableObject {

    var willChange = PassthroughSubject<Void, Never>()

    @Published var MapPrefs: [MapPrefs] {
        didSet { willChange.send(()) }
    }

    init(mapPrefs: [MapPrefs]) {
        self.MapPrefs = mapPrefs
    }

}

The Settings View Observes the Store and passes the array to a cell view

struct SettingsView: View {

    @ObservedObject var mapPrefsStore = MapPrefsStore(mapPrefs: MapPrefsTestData)

    var body: some View {

        NavigationView {
            List {

                 Section(header: Text("Map Preferences"), footer: Text("")) {

                    ForEach(mapPrefsStore.MapPrefs) { mapPrefs in
                        MapPrefsCell(mapPrefs: mapPrefs)
                    }
                    .onMove(perform: moveMap)
                                }
                .background(Color.clear)
            }
            .navigationBarTitle(Text("Settings"))
            .navigationBarItems(trailing: EditButton())
            .listStyle(GroupedListStyle())
        }
    }
    func moveMap(from source: IndexSet, to destination: Int) {
        guard let sourceIndex = Array(source).first else { return }
        mapPrefsStore.MapPrefs.insert(mapPrefsStore.MapPrefs.remove(at: sourceIndex), at: destination)
    }
}

struct MapPrefsCell : View {
    let mapPrefs: MapPrefs

    var body: some View {

        Toggle(isOn: mapPrefs.isShown) {
            Text(mapPrefs.name)
        }
    }
}
}

this gives me the following error

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

I can't figure out how to allow the called function (MapPrefsCell) the ability to access the isShown property.  I tried various combinations of adding the $ sign.

Body:
isShown is declared as Bool. Passing it with $ won't work as you can not convert it to Binding<Bool>.

You could declare it as @State in your struct:

struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    @State var isShown: Bool

}

and then pass it as Binding...

Toggle(isOn: mapPrefs.$isShown) {
    Text(mapPrefs.name)
}

Edit:

You can also create a custom State and use the value of your mapPrefs for that State. But then you will need to store changes to your object afterwards. In this case you do not need to declare it as @State

struct MapPrefs: Identifiable {
    var id = UUID()
    var name: String
    var isShown: Bool

}

struct MapPrefsCell : View {
    let mapPrefs: MapPrefs

    @State var toggle : Bool

    init(mapPrefs: MapPrefs)
    {
        //create State with initial value here
        self._toggle = State(initialValue: self.mapPrefs.isShown)
    }

    var body: some View {

        Toggle(isOn: $toggle) {
            Text(mapPrefs.name)
        }
    }
}


来源: stackexchange

问:
C# Unity Engine, how to limit UI Slider
i need to limit UI Slider.

Now i want the Slider to Stop, if the Limit is 0, but being able to slide back and decrease their value.

like:

```<code>Min = 0;
Max = 20;
Limit = Max-SliderValues;

SliderValues = Slider1.value+Slider2.value+Slider3.value+slider4.value;
Slider1.value = 10;
Slider2.value = 2;
Slider3.value = 2;
Slider4.value = max 6;
</code>```

Can this be done with Unity?

Example:

One slider can reach max and if so, no slider can be moved until the maxed slider has been decreased. I'll give an example:

```<code>Workers in Sum: 100;
Assigned workers: Mining+Fishing+Crafting+Gym;
Workers available : 100-Assigned workers;
</code>```

You have 4 Sliders: Mining, Fishing, Crafting, Gym

Each slider decreases Worker Available and increases Assigned Workers.
The theoretical maximum is 100, practical Workers available.
The Sliders need to stop when WA = 0, but the Problem is, with the decreasing Value, the Slider stops at half and all Sliders will jump back to 0 if you try to push them further as the value allows.

答:
It's very simple, just use:
Slider1.minValue = desiredMinValue;
or
Slider1.maxValue = desiredMaxValue;

Here's the documentation for UI sliders if you have anymore issues with them: https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Slider.html

ContentLicense: CC BY-SA 4.0

Title: C# Unity Engine, how to limit UI Slider

Body:
i need to limit UI Slider.

Now i want the Slider to Stop, if the Limit is 0, but being able to slide back and decrease their value.

like:

Min = 0;
Max = 20;
Limit = Max-SliderValues;

SliderValues = Slider1.value+Slider2.value+Slider3.value+slider4.value;
Slider1.value = 10;
Slider2.value = 2;
Slider3.value = 2;
Slider4.value = max 6;

Can this be done with Unity?

Example:

One slider can reach max and if so, no slider can be moved until the maxed slider has been decreased. I'll give an example:

Workers in Sum: 100;
Assigned workers: Mining+Fishing+Crafting+Gym;
Workers available : 100-Assigned workers;

You have 4 Sliders: Mining, Fishing, Crafting, Gym

Each slider decreases Worker Available and increases Assigned Workers.
The theoretical maximum is 100, practical Workers available.
The Sliders need to stop when WA = 0, but the Problem is, with the decreasing Value, the Slider stops at half and all Sliders will jump back to 0 if you try to push them further as the value allows.


问:
How to create a visual data table in R to quickly screen the data visually
I have a following data set in txt form:

```<code>        Column1 Column2 Column3 etc
        A1 5 7
        A2 4 2
        ..
        A12 5 4
        B1 2 9
        B2 2 8
        ..
        B12 11 5
        ..
        H1 0 3
        H2 4 54
        ..
        H12 4 31
</code>```

I would like to create a visual data table with A through H rows by 12 columns, with each cell filled with a corresponding value (value from column 2 or 3)  and gradient colored (like a heat map) based on its value. What is the best approach to do this?

答:
Here's an approach with dplyr and tidyr for data wrangling and gt for visualization:

Note that "Column2" is specified invalues_from`, but you could change that to visualize other columns.

```<code>library(dplyr)
library(tidyr)
library(dt)
library(scales)
data %>%
  separate(1, into = c("Column1","Name"),
           sep = "(?<=[A-Z])(?=\\d)") %>%
  pivot_wider(id_cols = 1, names_from = "Name",
              values_from = "Column2") %>%
  gt() %>%
  data_color(columns = 2:13,
             colors = col_numeric(palette = c("green","yellow","red"),
                                  domain = c(10,1000)))
</code>```

Sample Data

```<code>set.seed(3)
data <- data.frame(Column1 = paste0(rep(LETTERS[1:8],each=12),rep(1:12,time=8)),sapply(c(10,20),function(x){round(runif(12*8,x,x*100),0)}))
names(data) <- paste0("Column",1:3)
</code>```

Body:
I have a following data set in txt form:

        Column1 Column2 Column3 etc
        A1 5 7
        A2 4 2
        ..
        A12 5 4
        B1 2 9
        B2 2 8
        ..
        B12 11 5
        ..
        H1 0 3
        H2 4 54
        ..
        H12 4 31

I would like to create a visual data table with A through H rows by 12 columns, with each cell filled with a corresponding value (value from column 2 or 3)  and gradient colored (like a heat map) based on its value. What is the best approach to do this?

Body:
Here's an approach with dplyr and tidyr for data wrangling and gt for visualization:

Note that "Column2" is specified invalues_from`, but you could change that to visualize other columns.

library(dplyr)
library(tidyr)
library(dt)
library(scales)
data %>%
  separate(1, into = c("Column1","Name"),
           sep = "(?<=[A-Z])(?=\\d)") %>%
  pivot_wider(id_cols = 1, names_from = "Name",
              values_from = "Column2") %>%
  gt() %>%
  data_color(columns = 2:13,
             colors = col_numeric(palette = c("green","yellow","red"),
                                  domain = c(10,1000)))

Sample Data

set.seed(3)
data <- data.frame(Column1 = paste0(rep(LETTERS[1:8],each=12),rep(1:12,time=8)),sapply(c(10,20),function(x){round(runif(12*8,x,x*100),0)}))
names(data) <- paste0("Column",1:3)


问:
IE 6 problems... help?
http://tendonaid.com/

That's the website.

The top and bottom navigation seem to be off in IE 6. What can I do to fix that?

答:
Couple of things that might help you:
IE6 does not recognise well html5 tags like  and

There's a few solutions to fix this. You could try John Resig' shiv

Then if that's not enough, you can add an IE6-only stylesheet to fix up the layout for that browser.

See this article about it.

OwnerDisplayName: Maddy Osman

ContentLicense: CC BY-SA 3.0

Title: IE 6 problems... help?

Body:
Couple of things that might help you:
IE6 does not recognise well html5 tags like <header> and <footer>

There's a few solutions to fix this. You could try John Resig' shiv

Then if that's not enough, you can add an IE6-only stylesheet to fix up the layout for that browser.

See this article about it.


问:
Cannot assign "'Math'": "SubjectClas.subject" must be a "Subject" instance
So, I have some problems witn my django project. Im wanting to assign Subject from droplist(that formed from database called Subject) to another database called SubjectClas but Im keep getting this error.  Any suggestions? Thanks.

Cannot assign "'Math'": "SubjectClas.subject" must be a "Subject" instance.

My  code from html

```<code>{% block add %}
<form action="{% url 'marks:addsubject' class.id%}" method="POST">
            {% csrf_token %}
            <select required name="sub">
                {% for d in subjectslist %}
                  <option value='{{d.id}}'>{{d.SubjectName}}</option>
                {% endfor %}
            </select>
            <button type="submit">готово</button>
</form>
{% endblock %}

</code>```

My  models.py

```<code>from django.db import models
class Class(models.Model):
    classtitle = models.CharField('класс', max_length = 50)
    def __str__(self):
        return self.classtitle
class Subject(models.Model):
    SubjectName = models.CharField('Предмет', max_length =50)
    def __str__(self):
        return self.SubjectName
class SubjectClas(models.Model):
    subject = models.ForeignKey(Subject, null=True, on_delete= models.SET_NULL)
    clas = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)

</code>```

My views.py

```<code>def addsubject(request, classid):
    try:
        a = Class.objects.get( id = classid )
    except:
        raise Http404("Http404")
    SubjectClas.objects.create(subject = request.POST['sub'], clas = a)

</code>```

Thanks.

答:
subject is a ForeignKey to the Subject model, so by passing a string, that will not work.

You can however create or obtain a Subject object, for example with .get_or_create(…) [Django-doc]:

```<code>from django.shortcuts import redirect
from django.views.decorators.http import <b>require_http_methods</b>

@require_http_methods(['POST'])
def addsubject(request, classid):
    subject, __ = Subject.objects.get_or_create(name=request.POST['sub'])
    SubjectClas.objects.create(subject=subject_id, clas_id=classid)
    return redirect(<i>'name-of-some-view'</i>)</code>```

Body:
So, I have some problems witn my django project. Im wanting to assign Subject from droplist(that formed from database called Subject) to another database called SubjectClas but Im keep getting this error.  Any suggestions? Thanks.

Cannot assign "'Math'": "SubjectClas.subject" must be a "Subject" instance.

My  code from html

{% block add %}
<form action="{% url 'marks:addsubject' class.id%}" method="POST">
            {% csrf_token %}
            <select required name="sub">
                {% for d in subjectslist %}
                  <option value='{{d.id}}'>{{d.SubjectName}}</option>
                {% endfor %}
            </select>
            <button type="submit">готово</button>
</form>
{% endblock %}

My  models.py

from django.db import models
class Class(models.Model):
    classtitle = models.CharField('класс', max_length = 50)
    def __str__(self):
        return self.classtitle
class Subject(models.Model):
    SubjectName = models.CharField('Предмет', max_length =50)
    def __str__(self):
        return self.SubjectName
class SubjectClas(models.Model):
    subject = models.ForeignKey(Subject, null=True, on_delete= models.SET_NULL)
    clas = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)

My views.py

def addsubject(request, classid):
    try:
        a = Class.objects.get( id = classid )
    except:
        raise Http404("Http404")
    SubjectClas.objects.create(subject = request.POST['sub'], clas = a)

Thanks.

Body:
subject is a ForeignKey to the Subject model, so by passing a string, that will not work.

You can however create or obtain a Subject object, for example with .get_or_create(…) [Django-doc]:

from django.shortcuts import redirect
from django.views.decorators.http import require_http_methods

@require_http_methods(['POST'])
def addsubject(request, classid):
    subject, __ = Subject.objects.get_or_create(name=request.POST['sub'])
    SubjectClas.objects.create(subject=subject_id, clas_id=classid)
    return redirect('name-of-some-view')


问:
Assigning json array to interface when string[] does not work
I have the following json file which holds a list of blacklist terms.

```<code>{
  "blacklist": [
    "term1",
    "term2",
    "term3",
    "term4",
    "term5"
   ]
}
</code>```

It is used in blacklist service:

```<code>@Injectable()
export class BlacklistService {
  private readonly BLACKLIST_TERMS_FOLDER = './assets/data/web-blacklist-terms';
  private readonly blacklistTerms1: any;
  private readonly blacklistTerms2: any;
}

constructor(
  public httpClient: HttpClient
) {
  this.blacklistTerms1 = this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);
}

public getAllBlackListTerms(): Observable<any> {
  return combineLatest([this.blacklistTerms1, this.blacklistTerms2])
}
</code>```

How would I add a type to blacklistTerms? I have tried string[] but it gives me the message Type 'Observable ' is missing the following properties from type 'string[]': length, pop, push, concat, and 27 more.

答:
```<code>this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`)
    .subscribe(x => this.blacklistTerms1 = x);
</code>```

You are trying to assign a Observable to a string[]. Does not work. Use subscribe.

Body:
I have the following json file which holds a list of blacklist terms.

{
  "blacklist": [
    "term1",
    "term2",
    "term3",
    "term4",
    "term5"
   ]
}

It is used in blacklist service:

@Injectable()
export class BlacklistService {
  private readonly BLACKLIST_TERMS_FOLDER = './assets/data/web-blacklist-terms';
  private readonly blacklistTerms1: any;
  private readonly blacklistTerms2: any;
}

constructor(
  public httpClient: HttpClient
) {
  this.blacklistTerms1 = this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`);
}

public getAllBlackListTerms(): Observable<any> {
  return combineLatest([this.blacklistTerms1, this.blacklistTerms2])
}

How would I add a type to blacklistTerms? I have tried string[] but it gives me the message Type 'Observable ' is missing the following properties from type 'string[]': length, pop, push, concat, and 27 more.

Body:
this.httpClient.get(`${this.BLACKLIST_TERMS_FOLDER}/terms.json`)
    .subscribe(x => this.blacklistTerms1 = x);

You are trying to assign a Observable to a string[]. Does not work. Use subscribe.


问:
Build CUDA kernel with Meson
I am trying to build an application that makes use of a Cuda kernel. For that, I am using the meson build system but without success. Basically what I am trying to do is the following:

```<code>//main.cpp

extern void kernel_function();

int main(int argc, char *argv[]){

  // some logic here...

  kernel_function();
  return 0;
}
</code>```

```<code>//kernel.cu

__global__ void kernel(){
  // some code here...
}

void kernel_function(){

  dim3 threads( 2, 1 );
  dim3 blocks( 1, 1 );

  kernel<<< blocks, threads >>>();
}
</code>```

I can compile the above code with the following commands:

```<code>g++ -c main.cpp
nvcc -c kernel.cu
nvcc -o main main.o kernel.o
</code>```

How can I replicate this compilation process that I do on the terminal with Meson?

答:
In the simplest case it could be something like:

```<code>project('cuda dependency', 'cpp', 'cuda')
executable('main', 'main.cpp', 'kernel.cu')
</code>```

And run with

```<code>$ CXX=g++ meson build
$ ninja -C build
</code>```

(based on example).

But down the road you might need to add dependencies like

```<code>dep = dependency('cuda', version : '>=10', modules : ['cublas'])
executable(..., dependencies: dep)
</code>```

or set some special compiler flags with the help of cuda module, check this reference on meson.

Title: Build CUDA kernel with Meson

Body:
I am trying to build an application that makes use of a Cuda kernel. For that, I am using the meson build system but without success. Basically what I am trying to do is the following:

//main.cpp

extern void kernel_function();

int main(int argc, char *argv[]){

  // some logic here...

  kernel_function();
  return 0;
}

//kernel.cu

__global__ void kernel(){
  // some code here...
}

void kernel_function(){

  dim3 threads( 2, 1 );
  dim3 blocks( 1, 1 );

  kernel<<< blocks, threads >>>();
}

I can compile the above code with the following commands:

g++ -c main.cpp
nvcc -c kernel.cu
nvcc -o main main.o kernel.o

How can I replicate this compilation process that I do on the terminal with Meson?

Body:
In the simplest case it could be something like:

project('cuda dependency', 'cpp', 'cuda')
executable('main', 'main.cpp', 'kernel.cu')

And run with

$ CXX=g++ meson build
$ ninja -C build

(based on example).

But down the road you might need to add dependencies like

dep = dependency('cuda', version : '>=10', modules : ['cublas'])
executable(..., dependencies: dep)

or set some special compiler flags with the help of cuda module, check this reference on meson.


问:
Dropping a nested column from Spark DataFrame
I have a DataFrame with the schema

```<code>root
 |-- label: string (nullable = true)
 |-- features: struct (nullable = true)
 |    |-- feat1: string (nullable = true)
 |    |-- feat2: string (nullable = true)
 |    |-- feat3: string (nullable = true)
</code>```

While, I am able to filter the data frame using

```<code>  val data = rawData
     .filter( !(rawData("features.feat1") <=> "100") )
</code>```

I am unable to drop the columns using

```<code>  val data = rawData
       .drop("features.feat1")
</code>```

Is it something that I am doing wrong here? I also tried (unsuccessfully) doing drop(rawData("features.feat1")), though it does not make much sense to do so.

Thanks in advance,

Nikhil

答:
I will expand upon mmendez.semantic's answer here, and accounting for the issues described in the sub-thread.

```<code>  def dropSubColumn(col: Column, colType: DataType, fullColName: String, dropColName: String): Option[Column] = {
    if (fullColName.equals(dropColName)) {
      None
    } else if (dropColName.startsWith(s"$fullColName.")) {
      colType match {
        case colType: StructType =>
          Some(struct(
            colType.fields
                .flatMap(f =>
                  dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                  })
                : _*))
        case colType: ArrayType =>
          colType.elementType match {
            case innerType: StructType =>
              // we are potentially dropping a column from within a struct, that is itself inside an array
              // Spark has some very strange behavior in this case, which they insist is not a bug
              // see https://issues.apache.org/jira/browse/SPARK-31779 and associated comments
              // and also the thread here: https://stackoverflow.com/a/39943812/375670
              // this is a workaround for that behavior

              // first, get all struct fields
              val innerFields = innerType.fields
              // next, create a new type for all the struct fields EXCEPT the column that is to be dropped
              // we will need this later
              val preserveNamesStruct = ArrayType(StructType(
                innerFields.filterNot(f => s"$fullColName.${f.name}".equals(dropColName))
              ))
              // next, apply dropSubColumn recursively to build up the new values after dropping the column
              val filteredInnerFields = innerFields.flatMap(f =>
                dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                }
              )
              // finally, use arrays_zip to unwrap the arrays that were introduced by building up the new. filtered
              // struct in this way (see comments in SPARK-31779), and then cast to the StructType we created earlier
              // to get the original names back
              Some(arrays_zip(filteredInnerFields:_*).cast(preserveNamesStruct))
          }

        case _ => Some(col)
      }
    } else {
      Some(col)
    }
  }

  def dropColumn(df: DataFrame, colName: String): DataFrame = {
    df.schema.fields.flatMap(f => {
      if (colName.startsWith(s"${f.name}.")) {
        dropSubColumn(col(f.name), f.dataType, f.name, colName) match {
          case Some(x) => Some((f.name, x))
          case None => None
        }
      } else {
        None
      }
    }).foldLeft(df.drop(colName)) {
      case (df, (colName, column)) => df.withColumn(colName, column)
    }
  }
</code>```

Usage in spark-shell:

```<code>// if defining the functions above in your spark-shell session, you first need imports
import org.apache.spark.sql._
import org.apache.spark.sql.types._

// now you can paste the function definitions

// create a deeply nested and complex JSON structure
val jsonData = """{
      "foo": "bar",
      "top": {
        "child1": 5,
        "child2": [
          {
            "child2First": "one",
            "child2Second": 2,
            "child2Third": -19.51
          }
        ],
        "child3": ["foo", "bar", "baz"],
        "child4": [
          {
            "child2First": "two",
            "child2Second": 3,
            "child2Third": 16.78
          }
        ]
      }
    }"""

// read it into a DataFrame
val df = spark.read.option("multiline", "true").json(Seq(jsonData).toDS())

// remove a sub-column
val modifiedDf = dropColumn(df, "top.child2.child2First")

modifiedDf.printSchema
root
 |-- foo: string (nullable = true)
 |-- top: struct (nullable = false)
 |    |-- child1: long (nullable = true)
 |    |-- child2: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)
 |    |-- child3: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- child4: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2First: string (nullable = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)

modifiedDf.show(truncate=false)
+---+------------------------------------------------------+
|foo|top                                                   |
+---+------------------------------------------------------+
|bar|[5, [[2, -19.51]], [foo, bar, baz], [[two, 3, 16.78]]]|
+---+------------------------------------------------------+
</code>```

Body:
I have a DataFrame with the schema

root
 |-- label: string (nullable = true)
 |-- features: struct (nullable = true)
 |    |-- feat1: string (nullable = true)
 |    |-- feat2: string (nullable = true)
 |    |-- feat3: string (nullable = true)

While, I am able to filter the data frame using

  val data = rawData
     .filter( !(rawData("features.feat1") <=> "100") )

I am unable to drop the columns using

  val data = rawData
       .drop("features.feat1")

Is it something that I am doing wrong here? I also tried (unsuccessfully) doing drop(rawData("features.feat1")), though it does not make much sense to do so.

Thanks in advance,

Nikhil

Body:
I will expand upon mmendez.semantic's answer here, and accounting for the issues described in the sub-thread.

  def dropSubColumn(col: Column, colType: DataType, fullColName: String, dropColName: String): Option[Column] = {
    if (fullColName.equals(dropColName)) {
      None
    } else if (dropColName.startsWith(s"$fullColName.")) {
      colType match {
        case colType: StructType =>
          Some(struct(
            colType.fields
                .flatMap(f =>
                  dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                  })
                : _*))
        case colType: ArrayType =>
          colType.elementType match {
            case innerType: StructType =>
              // we are potentially dropping a column from within a struct, that is itself inside an array
              // Spark has some very strange behavior in this case, which they insist is not a bug
              // see https://issues.apache.org/jira/browse/SPARK-31779 and associated comments
              // and also the thread here: https://stackoverflow.com/a/39943812/375670
              // this is a workaround for that behavior

              // first, get all struct fields
              val innerFields = innerType.fields
              // next, create a new type for all the struct fields EXCEPT the column that is to be dropped
              // we will need this later
              val preserveNamesStruct = ArrayType(StructType(
                innerFields.filterNot(f => s"$fullColName.${f.name}".equals(dropColName))
              ))
              // next, apply dropSubColumn recursively to build up the new values after dropping the column
              val filteredInnerFields = innerFields.flatMap(f =>
                dropSubColumn(col.getField(f.name), f.dataType, s"$fullColName.${f.name}", dropColName) match {
                    case Some(x) => Some(x.alias(f.name))
                    case None => None
                }
              )
              // finally, use arrays_zip to unwrap the arrays that were introduced by building up the new. filtered
              // struct in this way (see comments in SPARK-31779), and then cast to the StructType we created earlier
              // to get the original names back
              Some(arrays_zip(filteredInnerFields:_*).cast(preserveNamesStruct))
          }

        case _ => Some(col)
      }
    } else {
      Some(col)
    }
  }

  def dropColumn(df: DataFrame, colName: String): DataFrame = {
    df.schema.fields.flatMap(f => {
      if (colName.startsWith(s"${f.name}.")) {
        dropSubColumn(col(f.name), f.dataType, f.name, colName) match {
          case Some(x) => Some((f.name, x))
          case None => None
        }
      } else {
        None
      }
    }).foldLeft(df.drop(colName)) {
      case (df, (colName, column)) => df.withColumn(colName, column)
    }
  }

Usage in spark-shell:

// if defining the functions above in your spark-shell session, you first need imports
import org.apache.spark.sql._
import org.apache.spark.sql.types._

// now you can paste the function definitions

// create a deeply nested and complex JSON structure
val jsonData = """{
      "foo": "bar",
      "top": {
        "child1": 5,
        "child2": [
          {
            "child2First": "one",
            "child2Second": 2,
            "child2Third": -19.51
          }
        ],
        "child3": ["foo", "bar", "baz"],
        "child4": [
          {
            "child2First": "two",
            "child2Second": 3,
            "child2Third": 16.78
          }
        ]
      }
    }"""

// read it into a DataFrame
val df = spark.read.option("multiline", "true").json(Seq(jsonData).toDS())

// remove a sub-column
val modifiedDf = dropColumn(df, "top.child2.child2First")

modifiedDf.printSchema
root
 |-- foo: string (nullable = true)
 |-- top: struct (nullable = false)
 |    |-- child1: long (nullable = true)
 |    |-- child2: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)
 |    |-- child3: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- child4: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- child2First: string (nullable = true)
 |    |    |    |-- child2Second: long (nullable = true)
 |    |    |    |-- child2Third: double (nullable = true)

modifiedDf.show(truncate=false)
+---+------------------------------------------------------+
|foo|top                                                   |
+---+------------------------------------------------------+
|bar|[5, [[2, -19.51]], [foo, bar, baz], [[two, 3, 16.78]]]|
+---+------------------------------------------------------+


问:
SQL navigator - "insert into" statement not working on multiple rows
One row works fine:

```<code>insert into maalerverdi.evverdigrenser
(maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
values
(100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50)
</code>```

But adding one more row does not work:

```<code>insert into maalerverdi.evverdigrenser
(maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
values
(100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50),
(100126, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50);
</code>```

Error: SQL command not properly ended

答:
Your error message looks like Oracle's ORA-00933 (whose message is SQL command not properly ended). Indeed, this database (unlike many others) does not support the syntax you are using to insert multiple rows at once.

If you want to do this in a single statement, you can use the insert all syntax instead. Its purpose is to insert into one or multiple tables, so you need to repeat the table name and column list:

```<code>insert all
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50)
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100126, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50);
</code>```

Side note: you seem to be attempting to insert into date columns. If so, I would recommend using the standard syntax to declare date literals rather than this custom format (whether Oracle will successfully interpret it as a date depends on your database and session settings). That would be:

```<code>insert all
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100121, date '2019-01-01', date '2073-06-01', 202, -0.0001, 50)
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100126, date '2019-01-01', date '1973-06-01', 202, -0.0001, 50);
</code>```

Body:
One row works fine:

insert into maalerverdi.evverdigrenser
(maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
values
(100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50)

But adding one more row does not work:

insert into maalerverdi.evverdigrenser
(maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
values
(100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50),
(100126, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50);

Error: SQL command not properly ended

Body:
Your error message looks like Oracle's ORA-00933 (whose message is SQL command not properly ended). Indeed, this database (unlike many others) does not support the syntax you are using to insert multiple rows at once.

If you want to do this in a single statement, you can use the insert all syntax instead. Its purpose is to insert into one or multiple tables, so you need to repeat the table name and column list:

insert all
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100121, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50)
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100126, '01-jan-2019', '01-jun-2073', 202, -0.0001, 50);

Side note: you seem to be attempting to insert into date columns. If so, I would recommend using the standard syntax to declare date literals rather than this custom format (whether Oracle will successfully interpret it as a date depends on your database and session settings). That would be:

insert all
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100121, date '2019-01-01', date '2073-06-01', 202, -0.0001, 50)
    into maalerverdi.evverdigrenser
        (maalepktnr, fradato, tildato, telleverkartnr, minimum, maximum)
        values  (100126, date '2019-01-01', date '1973-06-01', 202, -0.0001, 50);


问:
Are allocator construct and destroy member functions allowed to throw exceptions from internal logic?
I'm writing my own container that requires nothrow movable and copyable types. I thought I could simplify logic a bit when it comes to exception safety. But I noticed that construct and destroy member functions of allocators have no wording about when they can and can't throw exceptions.

I'm pretty sure I've read the wording before. Otherwise, even if my type is nothrow movable, construct can still throw an exception from user-provided allocator when, say, I resize the buffer to increase capacity. This requires complex rollback code to guarantee strong exception safety that I really wanted to skip.

Is there a wording that allows to only throw exceptions from calling ctor/dtor or are allocators always require complex machinery to maintain exception safety?

答:
The allocator members can throw. If the standard doesn't say they can't throw, then they can throw.

But in practice, why would they?

Especially for std::allocator::construct and std::allocator::destroy, which do nothing more than just invoke a constructor or destructor. But you should be using std::allocator_traits<Alloc>::construct and std::allocator_traits<Alloc>::destroy anyway, and those do nothing more than call Alloc::construct / Alloc::destroy if that exists, and invoke a constructor/destructor otherwise.

In theory, a pathological allocator could throw in those members, but you should assume they don't. You can't defend against pathologically stupid types.


问:
NSTrackingArea yields different results when initialized with initWithRect:[self bounds] and [self frame]
--------- Question 1 ----------
Maybe I don't understand the frame object completely (or maybe it wasn't created correctly in my context), but as I was trying to implement a mouse event I encountered the situation where the call:

```<code>trackingArea=[ [NSTrackingArea alloc] initWithRect:[self frame] options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil ];
</code>```

Resulted in incorrect tracking area (only top right corner worked) - looking into the problem I found that 'frame' started somewhere in top right corner. This call was made in an overloaded initWithFrame defined as:

```<code>glView = [ [ Lesson17View alloc ] initWithFrame:[ glWindow frame ]
colorBits:16 depthBits:16 fullscreen:FALSE ];
</code>```

where glView is subclassed from NSOpenGLView. The above call is made in awakeFromNib, and glWindow is defined as:

IBOutlet NSWindow *glWindow;

When I replace bounds with frame, my application works - what is going on with the frame variable?

--------- Question 2 ----------

My second question involves how to handle the mouse events and correctly have my openGL view redraw - say I have:

```<code>- (void) mouseMoved:(NSEvent *)theEvent
{
NSPoint location=[self convertPoint:[theEvent locationInWindow] fromView:nil];
// send NSPoint to a printGL function I have that uses texture maps to display text?
}
</code>```

I'm guessing I shouldn't be sending this to a function that renders something in my openGL view (because this doesn't do anything -guessing because whenever I use drawRect whatever I drew during the mouse event is cleared). Currently all my drawing is perfomed in drawRect (contains a bunch of openGL calls) - what would be the appropriate call to make at this point?

Or should I set a flag (along with setting an instance variable NSPoint) to true that will allow printGL to be called only on mouseMoved events (I know - I'll use the mouseEntered/Exited functions but for now I'm trying to get a handle on this).

答:
A view's frame is where the view is located in its superview. This means most importantly that unless the view's origin is right on top of its superview's origin (i.e. at {0, 0}), the frame rectangle will be offset by that amount.

A view's bounds are the coordinates inside the view. Unless you've applied some transform to the view's coordinate system, the bounds origin will always be at {0, 0}.

So, why does this make a difference in your case? As noted in the docs for NSTrackingArea, the rect is interpreted as coordinates in the coordinate system of the tracking area's owner. The owner's bounds are in its coordinate system, while the frame is in coordinate system of the owner's superview. So you're giving the tracking area a rect from the wrong coordinate system.

I highly recommend reading the View Programming Guide. It explains all of this and more. There are a lot of subtle details to the Cocoa view system that you'll want to know when you're writing UI code.

(And for your second question: To tell a view to redraw, send it [view setNeedsDisplay:YES].)

Body:
--------- Question 1 ----------
Maybe I don't understand the frame object completely (or maybe it wasn't created correctly in my context), but as I was trying to implement a mouse event I encountered the situation where the call:

trackingArea=[ [NSTrackingArea alloc] initWithRect:[self frame] options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil ];

Resulted in incorrect tracking area (only top right corner worked) - looking into the problem I found that 'frame' started somewhere in top right corner. This call was made in an overloaded initWithFrame defined as:

glView = [ [ Lesson17View alloc ] initWithFrame:[ glWindow frame ]
colorBits:16 depthBits:16 fullscreen:FALSE ];

where glView is subclassed from NSOpenGLView. The above call is made in awakeFromNib, and glWindow is defined as:

IBOutlet NSWindow *glWindow;

When I replace bounds with frame, my application works - what is going on with the frame variable?

--------- Question 2 ----------

My second question involves how to handle the mouse events and correctly have my openGL view redraw - say I have:

- (void) mouseMoved:(NSEvent *)theEvent
{
NSPoint location=[self convertPoint:[theEvent locationInWindow] fromView:nil];
// send NSPoint to a printGL function I have that uses texture maps to display text?
}

I'm guessing I shouldn't be sending this to a function that renders something in my openGL view (because this doesn't do anything -guessing because whenever I use drawRect whatever I drew during the mouse event is cleared). Currently all my drawing is perfomed in drawRect (contains a bunch of openGL calls) - what would be the appropriate call to make at this point?

Or should I set a flag (along with setting an instance variable NSPoint) to true that will allow printGL to be called only on mouseMoved events (I know - I'll use the mouseEntered/Exited functions but for now I'm trying to get a handle on this).


问:
typeid gives types m, j and Pj
I'm trying to understand a piece of code and came across this

```<code>    size_t max = 3;
    unsigned trial {3};
    auto* primes { new unsigned[max] };
</code>```

I read that when you define something like unsigned int trial {3}; you get an int that can it's only positive. But this unsigned variables doesn't specify the type. So I tried to know what type they are with this:

```<code>
    cout << typeid(max).name() << endl;
    cout << typeid(trial).name() << endl;
    cout << typeid(primes).name() << endl;
</code>```

But got this weird output

```<code>m
j
Pj
</code>```

What's going on here?

答:
unsigned is short for unsigned int.

The strings returned from typeid::name are implementation-specific.

Since you seem to be on some Linux system, probably demangling could help you along: stdc++ demangling.

Title: typeid gives types m, j and Pj

Body:
I'm trying to understand a piece of code and came across this

    size_t max = 3;
    unsigned trial {3};
    auto* primes { new unsigned[max] };

I read that when you define something like unsigned int trial {3}; you get an int that can it's only positive. But this unsigned variables doesn't specify the type. So I tried to know what type they are with this:

    cout << typeid(max).name() << endl;
    cout << typeid(trial).name() << endl;
    cout << typeid(primes).name() << endl;

But got this weird output

m
j
Pj

What's going on here?


问:
No version of NDK matched the requested version
After updating to Android Gradle plugin 3.6.0 (released Feb 24, 2020), several project independently started failing with:

```<code>No version of NDK matched the requested version 20.0.5594570. Versions available locally: 21.0.6113669
</code>```

It's quite simple to "fix" this locally by installing the older expected ndk version:

```<code>sdkmanager 'ndk;20.0.5594570'
</code>```

However, my question is: Where and how is this older version specified? And how do I update it so it matches the latest version 21.0.6113669?

答:
In order to solve this problem, you must indicate to your IDE the version of your NDK in build.gradle. In this case, it should be version 21.0.6113669. For example:

```<code>defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.remed_mobile"
    minSdkVersion 16
    targetSdkVersion 28
    ndkVersion '21.1.6352462'
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}
</code>```

If you do not indicate your version number, then the IDE takes a default version. If you've upgraded gradle, then it might not find the right version.

Body:
After updating to Android Gradle plugin 3.6.0 (released Feb 24, 2020), several project independently started failing with:

No version of NDK matched the requested version 20.0.5594570. Versions available locally: 21.0.6113669

It's quite simple to "fix" this locally by installing the older expected ndk version:

sdkmanager 'ndk;20.0.5594570'

However, my question is: Where and how is this older version specified? And how do I update it so it matches the latest version 21.0.6113669?

Body:
In order to solve this problem, you must indicate to your IDE the version of your NDK in build.gradle. In this case, it should be version 21.0.6113669. For example:

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.remed_mobile"
    minSdkVersion 16
    targetSdkVersion 28
    ndkVersion '21.1.6352462'
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

If you do not indicate your version number, then the IDE takes a default version. If you've upgraded gradle, then it might not find the right version.


问:
Writing data to disc in seperate thread (in parallel)
I would like to start a function multiple times in a loop that each time acquire and image from a camera and writes the image to disc without the loop waiting for this process to finish. So every time this function is called it runs in parallel with the loop that started the function such that I can continue doing other time sensitive stuff in the meantime.

I have made this example which make the first "execution" of the function run in parallel with the loop and then fails the second time as I cannot .start() it twice. Can this be achieved by other means?

Example (original post - updated below)

```<code>import numpy as np
import threading
import time

def imacq():
    print('acquiring image...')
    time.sleep(1.8)
    print('saved image...')
    return

# Start image acqusition and writing to disc thread
imacq_thread = threading.Thread(target=imacq)

starttime = time.time()
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 5
running = True
flag = True
for cycles in range(1,20):
    print(cycles)
    if cycles%image_cycles == 0:
        if flag is True:
            imacq_thread.start() # this works well the first time as intended
            # imacq() # this does not work as everything is paused until imacp() returns
            flag = False
    else:
        flag = True
    time.sleep(0.4)
</code>```

EDIT: After feedback from Sylvaus:
I have made two different versions for triggering a function that eventually will be used to acquire and store and image on the drive in parallel with a main script that decides the time to send a trigger/execute the function. One version is based on Sylvaus' answer (threading) and another is based on multiprocessing.

Example based on Sylvaus's answer (Threading):

```<code>import matplotlib.pyplot as plt
import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor

def imacq():
    print('taking image')
    n = 10000
    np.ones((n, n))*np.ones((n, n))  # calculations taking time
    print('saving image')
    return

sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 20
max_cycles = 100
freq = 10
cycles = 1
sigSign = 1

running = True
flag = True
timeinc = []
tic = time.time()
tic2 = tic
timeinc = np.zeros(max_cycles)
starttime = time.time()
with ThreadPoolExecutor() as executor:
    while running:
        t = time.time()-starttime
        tim_arr[:-1] = tim_arr[1:]
        tim_arr[-1] = t
        signal = np.sin(freq*t*(2.0*np.pi))
        sig_arr[:-1] = sig_arr[1:]
        sig_arr[-1] = signal

        time.sleep(0.00001)
        # Calculate cycle number
        sigSignOld = sigSign
        sigSign = np.sign(sig_arr[-1]-sig_arr[-2])
        if sigSign == 1 and sigSignOld != sigSign:
            timeinc[cycles] = time.time()-tic
            cycles += 1
            print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
            tic = time.time()

        if cycles%image_cycles == 0:
            if flag is True:
                # The function is submitted and will be processed by a
                # a thread as soon as one is available
                executor.submit(imacq)
                flag = False
        else:
            flag = True
        if cycles >= max_cycles:
            running = False

print('total time: ', time.time()-tic2)

fig = plt.figure()
ax = plt.axes()
plt.plot(timeinc)
</code>```

Example based on multiprocessing:

```<code>import matplotlib.pyplot as plt
import numpy as np
import time
from multiprocessing import Process, Value, Lock

def trig_resp(running, trigger, p_count, pt, lock):
    while running.value == 1:  # note ".value" on each sharedctype variable
        time.sleep(0.0001)  # sleeping in order not to load CPU too excessively
        if trigger.value == 1:
            with lock:  # lock "global" variable before wrtting to it
                trigger.value = 0  # reset trigger
            tic = time.time()
            # Do a calculation that takes a significant time
            n = 10000; np.ones((n, n))*np.ones((n, n))
            with lock:
                pt.value = time.time() - tic  # calculate process time
                p_count.value += 1  # count number of finished processes
    return

if __name__ == "__main__":
    # initialize shared values (global accross processes/sharedctype).
    # Type 'i': integer, type 'd': double.
    trigger = Value('i', 0)  # used to trigger execution placed in trig_resp()
    running = Value('i', 1)  # A way to break the loop in trig_resp()
    p_count = Value('i', 0)  # process counter and flag that process is done
    pt = Value('d', 0.0)  # process time of latest finished process
    lock = Lock() # lock object used to avoid raise conditions when changing "global" values.
    p_count_old = p_count.value
    p1 = Process(target=trig_resp, args=(running, trigger, p_count, pt, lock))
    p1.start()  # Start process

    # A "simulated" sinusiodal signal
    array_len = 50
    sig_arr = np.zeros(array_len)  # Signal array
    tim_arr = np.zeros(array_len)  # Correpsonding time array
    freq = 10  # frequency of signal

    # trigger settings
    im_int = 20  # cycle interval for triggering (acquiring images)
    max_cycles = 100  # max number of cycles before stopping main

    # initializing counters etc.
    cycles = 1  # number of cycles counted
    sigSign = 1  # sign of signal gradient
    flag = 1  # used to only set trigger once for the current cycle count
    trigger_count = 0  # counts how many times a trigger has been set

    tic = time.time()
    tic2 = tic
    timeinc = np.zeros(max_cycles) # Array to keep track of time used for each main loop run
    starttime = time.time()
    while running.value == 1:
        time.sleep(0.00001)  # mimics sample time (real world signal)
        t = time.time()-starttime  # local time
        signal = np.sin(freq*t*(2.0*np.pi))  # simulated signal
        # Keeping the latest array_len values (FIFO) of t and signal.
        tim_arr[:-1] = tim_arr[1:]
        tim_arr[-1] = t
        sig_arr[:-1] = sig_arr[1:]
        sig_arr[-1] = signal

        if p_count.value == p_count_old + 1:  # process have finished
            print('Process counter: ', p_count.value,  'process_time: ', pt.value)
            p_count_old = p_count.value

        # Calculate cycle number by monotoring sign of the gradient
        sigSignOld = sigSign  # Keeping track of previous signal gradient sign
        sigSign = np.sign(sig_arr[-1]-sig_arr[-2])  # current gradient sign
        if sigSign == 1 and sigSignOld == -1:  # a local minimum just happened
            timeinc[cycles] = time.time()-tic
            cycles += 1
            print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
            tic = time.time()
            flag = 1

        if cycles % im_int == 0 and flag == 1:
            if cycles > 0:
                if trigger_count > p_count.value:
                    print('WARNING: Process: ', p_count.value,
                          'did not finish yet. Reduce freq or increase im_int')
                trigger.value = 1
                trigger_count += 1
                print('Trigger number: ', trigger_count)
                flag = 0

        if cycles >= max_cycles:
            running.value = 0

    print('total cycle time: ', time.time()-tic2)

    # Print the process time of the last run
    if p_count.value < max_cycles//im_int:
        if p_count.value == p_count_old + 1:
            print('process counter: ', p_count.value,  'process_time: ', pt.value)
            p_count_old = p_count.value

    print('total process time: ', time.time()-tic2)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(timeinc)
</code>```

I am on a windows 10 laptop so the timing (time increment in each loop of the main while loop "while running...:") is dependent on what else is happening on my computer, but the version based on multiprocessing seems less sensitive to this than the one based on threading. However the one based on multiprocessing is not very elegant and I am suspecting that a smarter solution is possible (simpler and less easy to make a mistake) that can achieve the same or better (consistent time increments with lower load on the CPU).

I have attached graphs of the time increments I get here for the Multiprocess and Threading example, respectively here:

Any feedback on improving the two solutions is much appreciated.

答:
You can use an Executor.This way, you can simply submit your tasks and they will be processed based on the type of Executor you are using.

I don't know what is in your imacq, so you may have to try ThreadPoolExecutor and ProcessPoolExecutor to find which one is the most fitting for your application.

Example:

import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor

def imacq():
    print('acquiring image...')
    time.sleep(1.8)
    print('saved image...')
    return

starttime = time.time()
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 5
running = True
flag = True

with ThreadPoolExecutor() as executor:
    for cycles in range(1,20):
        print(cycles)
        if cycles%image_cycles == 0:
            if flag is True:
                # The function is submitted and will be processed by a
                # a thread as soon as one is available
                executor.submit(imacq)
                flag = False
        else:
            flag = True
        time.sleep(0.4)
```

Body:
I would like to start a function multiple times in a loop that each time acquire and image from a camera and writes the image to disc without the loop waiting for this process to finish. So every time this function is called it runs in parallel with the loop that started the function such that I can continue doing other time sensitive stuff in the meantime.

I have made this example which make the first "execution" of the function run in parallel with the loop and then fails the second time as I cannot .start() it twice. Can this be achieved by other means?

Example (original post - updated below)

import numpy as np
import threading
import time

def imacq():
    print('acquiring image...')
    time.sleep(1.8)
    print('saved image...')
    return

# Start image acqusition and writing to disc thread
imacq_thread = threading.Thread(target=imacq)

starttime = time.time()
sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 5
running = True
flag = True
for cycles in range(1,20):
    print(cycles)
    if cycles%image_cycles == 0:
        if flag is True:
            imacq_thread.start() # this works well the first time as intended
            # imacq() # this does not work as everything is paused until imacp() returns
            flag = False
    else:
        flag = True
    time.sleep(0.4)

EDIT: After feedback from Sylvaus:
I have made two different versions for triggering a function that eventually will be used to acquire and store and image on the drive in parallel with a main script that decides the time to send a trigger/execute the function. One version is based on Sylvaus' answer (threading) and another is based on multiprocessing.

Example based on Sylvaus's answer (Threading):

import matplotlib.pyplot as plt
import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor

def imacq():
    print('taking image')
    n = 10000
    np.ones((n, n))*np.ones((n, n))  # calculations taking time
    print('saving image')
    return

sig_arr = np.zeros(100)
tim_arr = np.zeros(100)
image_cycles = 20
max_cycles = 100
freq = 10
cycles = 1
sigSign = 1

running = True
flag = True
timeinc = []
tic = time.time()
tic2 = tic
timeinc = np.zeros(max_cycles)
starttime = time.time()
with ThreadPoolExecutor() as executor:
    while running:
        t = time.time()-starttime
        tim_arr[:-1] = tim_arr[1:]
        tim_arr[-1] = t
        signal = np.sin(freq*t*(2.0*np.pi))
        sig_arr[:-1] = sig_arr[1:]
        sig_arr[-1] = signal

        time.sleep(0.00001)
        # Calculate cycle number
        sigSignOld = sigSign
        sigSign = np.sign(sig_arr[-1]-sig_arr[-2])
        if sigSign == 1 and sigSignOld != sigSign:
            timeinc[cycles] = time.time()-tic
            cycles += 1
            print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
            tic = time.time()

        if cycles%image_cycles == 0:
            if flag is True:
                # The function is submitted and will be processed by a
                # a thread as soon as one is available
                executor.submit(imacq)
                flag = False
        else:
            flag = True
        if cycles >= max_cycles:
            running = False

print('total time: ', time.time()-tic2)

fig = plt.figure()
ax = plt.axes()
plt.plot(timeinc)

Example based on multiprocessing:

import matplotlib.pyplot as plt
import numpy as np
import time
from multiprocessing import Process, Value, Lock

def trig_resp(running, trigger, p_count, pt, lock):
    while running.value == 1:  # note ".value" on each sharedctype variable
        time.sleep(0.0001)  # sleeping in order not to load CPU too excessively
        if trigger.value == 1:
            with lock:  # lock "global" variable before wrtting to it
                trigger.value = 0  # reset trigger
            tic = time.time()
            # Do a calculation that takes a significant time
            n = 10000; np.ones((n, n))*np.ones((n, n))
            with lock:
                pt.value = time.time() - tic  # calculate process time
                p_count.value += 1  # count number of finished processes
    return

if __name__ == "__main__":
    # initialize shared values (global accross processes/sharedctype).
    # Type 'i': integer, type 'd': double.
    trigger = Value('i', 0)  # used to trigger execution placed in trig_resp()
    running = Value('i', 1)  # A way to break the loop in trig_resp()
    p_count = Value('i', 0)  # process counter and flag that process is done
    pt = Value('d', 0.0)  # process time of latest finished process
    lock = Lock() # lock object used to avoid raise conditions when changing "global" values.
    p_count_old = p_count.value
    p1 = Process(target=trig_resp, args=(running, trigger, p_count, pt, lock))
    p1.start()  # Start process

    # A "simulated" sinusiodal signal
    array_len = 50
    sig_arr = np.zeros(array_len)  # Signal array
    tim_arr = np.zeros(array_len)  # Correpsonding time array
    freq = 10  # frequency of signal

    # trigger settings
    im_int = 20  # cycle interval for triggering (acquiring images)
    max_cycles = 100  # max number of cycles before stopping main

    # initializing counters etc.
    cycles = 1  # number of cycles counted
    sigSign = 1  # sign of signal gradient
    flag = 1  # used to only set trigger once for the current cycle count
    trigger_count = 0  # counts how many times a trigger has been set

    tic = time.time()
    tic2 = tic
    timeinc = np.zeros(max_cycles) # Array to keep track of time used for each main loop run
    starttime = time.time()
    while running.value == 1:
        time.sleep(0.00001)  # mimics sample time (real world signal)
        t = time.time()-starttime  # local time
        signal = np.sin(freq*t*(2.0*np.pi))  # simulated signal
        # Keeping the latest array_len values (FIFO) of t and signal.
        tim_arr[:-1] = tim_arr[1:]
        tim_arr[-1] = t
        sig_arr[:-1] = sig_arr[1:]
        sig_arr[-1] = signal

        if p_count.value == p_count_old + 1:  # process have finished
            print('Process counter: ', p_count.value,  'process_time: ', pt.value)
            p_count_old = p_count.value

        # Calculate cycle number by monotoring sign of the gradient
        sigSignOld = sigSign  # Keeping track of previous signal gradient sign
        sigSign = np.sign(sig_arr[-1]-sig_arr[-2])  # current gradient sign
        if sigSign == 1 and sigSignOld == -1:  # a local minimum just happened
            timeinc[cycles] = time.time()-tic
            cycles += 1
            print('cycles: ', cycles, ' time inc.: ', str(timeinc[cycles-1]))
            tic = time.time()
            flag = 1

        if cycles % im_int == 0 and flag == 1:
            if cycles > 0:
                if trigger_count > p_count.value:
                    print('WARNING: Process: ', p_count.value,
                          'did not finish yet. Reduce freq or increase im_int')
                trigger.value = 1
                trigger_count += 1
                print('Trigger number: ', trigger_count)
                flag = 0

        if cycles >= max_cycles:
            running.value = 0

    print('total cycle time: ', time.time()-tic2)

    # Print the process time of the last run
    if p_count.value < max_cycles//im_int:
        if p_count.value == p_count_old + 1:
            print('process counter: ', p_count.value,  'process_time: ', pt.value)
            p_count_old = p_count.value

    print('total process time: ', time.time()-tic2)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(timeinc)

I am on a windows 10 laptop so the timing (time increment in each loop of the main while loop "while running...:") is dependent on what else is happening on my computer, but the version based on multiprocessing seems less sensitive to this than the one based on threading. However the one based on multiprocessing is not very elegant and I am suspecting that a smarter solution is possible (simpler and less easy to make a mistake) that can achieve the same or better (consistent time increments with lower load on the CPU).

I have attached graphs of the time increments I get here for the Multiprocess and Threading example, respectively here:

Any feedback on improving the two solutions is much appreciated.


问:
How to retrieve the number of adults selected on a travel website with .getText() not working
I am practicing Selenium Webdriver using Java on the following website:
https://www.easyjet.com/en

I am trying to increase the number of Adults selected until 3 has been selected. Here is my code:

```<code>package d_practise;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class easyjetMenu5 {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\Work\\Drivers\\New folder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("https://www.easyjet.com/en");

        WebElement adultCount = driver.findElement(By.cssSelector("input[name='Adults']"));
        String count = adultCount.getText();

        while(!count.equalsIgnoreCase("3")) {
            driver.findElement(By.cssSelector("[passenger-type='Adults'] [alt='Add one passenger\\.']")).click();
        }

    }

};
</code>```

Here is an image of the number value I am trying to retrieve. Once I am able to get this number I can use it in the while loop to stop incrementing the number of adults selected:

答:
Try this code, its working.</p>

```<code>public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\Work\\Drivers\\New folder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

         driver.get("https://www.easyjet.com/en");
WebDriverWait wait =new WebDriverWait(driver, 2000);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[contains(@id,'Adults')]/following-sibling::button"))));

      int numberOfAdults=3;

            for (int i = 2; i <=numberOfAdults ; i++) {
                driver.findElement(By.xpath("//*[contains(@id,'Adults')]/following-sibling::button")).click();

            }
        }
</code>```

Body:
I am practicing Selenium Webdriver using Java on the following website:
https://www.easyjet.com/en

I am trying to increase the number of Adults selected until 3 has been selected. Here is my code:

package d_practise;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class easyjetMenu5 {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\Work\\Drivers\\New folder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("https://www.easyjet.com/en");

        WebElement adultCount = driver.findElement(By.cssSelector("input[name='Adults']"));
        String count = adultCount.getText();

        while(!count.equalsIgnoreCase("3")) {
            driver.findElement(By.cssSelector("[passenger-type='Adults'] [alt='Add one passenger\\.']")).click();
        }

    }

};

Here is an image of the number value I am trying to retrieve. Once I am able to get this number I can use it in the while loop to stop incrementing the number of adults selected:

Body:
Try this code, its working.

public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\Work\\Drivers\\New folder\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

         driver.get("https://www.easyjet.com/en");
WebDriverWait wait =new WebDriverWait(driver, 2000);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[contains(@id,'Adults')]/following-sibling::button"))));

      int numberOfAdults=3;

            for (int i = 2; i <=numberOfAdults ; i++) {
                driver.findElement(By.xpath("//*[contains(@id,'Adults')]/following-sibling::button")).click();

            }
        }


问:
Variable data is lost during use

Background

I am building a mailer that accepts headings, labels, and data from a form then combines multiple sections into the email body and forwards it. in order to facilitate that, I created a class MailSection that includes a string, two lists of strings, and a bool. After adding the data to the class, I add that instance of the class to a list of that class and start the next section. Unfortunately, clearing the data before starting the next section clears the data from the previous instance, as well.

Sample Code

```<code>public class Mail Section
{
  public string SectionHeading {get; set;}
  public List<string> Labels {get; set;}
  public List<string> Data {get; set;
  public bool Table {get; set;}
}
</code>```

elsewhere in the code of the page.

```<code>List<string> labels = new List<string>();
List<string> data = new List<string>();
List<MailSection> mailSections = new List<MailSection>();

//section 1
labels.Add("Name");
data.Add("Some Customer");
labels.Add{"Email");
data.Add("Some.Customer@somedomain.com");
mailSections.Add(new MailSection("Customer Info",labels,data,false));
//Here, the data is still intact.
labels.Clear();
data.Clear();
//Here, I expect labels and data to be clear.
//Unfortunately, this also clears the data in any instance of mailSection
</code>```

What I have tried

I have tried making the MailSection class disposable, and I have tried using a separate instance of MailSection that I would add and reset.

答:
Yes because all instances of MailSection are pointing the same instance of labels and data.

Solution:

Create new instances of

```<code>List<string> labels = new List<string>();
List<string> data = new List<string>();
</code>```

everytime for a new instance of MailSection

Title: Variable data is lost during use

Body:
Background

I am building a mailer that accepts headings, labels, and data from a form then combines multiple sections into the email body and forwards it. in order to facilitate that, I created a class MailSection that includes a string, two lists of strings, and a bool. After adding the data to the class, I add that instance of the class to a list of that class and start the next section. Unfortunately, clearing the data before starting the next section clears the data from the previous instance, as well.

Sample Code

public class Mail Section
{
  public string SectionHeading {get; set;}
  public List<string> Labels {get; set;}
  public List<string> Data {get; set;
  public bool Table {get; set;}
}

elsewhere in the code of the page.

List<string> labels = new List<string>();
List<string> data = new List<string>();
List<MailSection> mailSections = new List<MailSection>();

//section 1
labels.Add("Name");
data.Add("Some Customer");
labels.Add{"Email");
data.Add("Some.Customer@somedomain.com");
mailSections.Add(new MailSection("Customer Info",labels,data,false));
//Here, the data is still intact.
labels.Clear();
data.Clear();
//Here, I expect labels and data to be clear.
//Unfortunately, this also clears the data in any instance of mailSection

What I have tried

I have tried making the MailSection class disposable, and I have tried using a separate instance of MailSection that I would add and reset.

Body:
Yes because all instances of MailSection are pointing the same instance of labels and data.

Solution:

Create new instances of

List<string> labels = new List<string>();
List<string> data = new List<string>();

everytime for a new instance of MailSection


问:
QML: how to specify image file path relative to application folder
We are developing our first Qt/QML application (trying technology). While technology looks very promising at a glance, we have faced so many unexpected weird issues that almost give up at very beginning.

Here one of such issue.

We want the following folders layout for our application:

```<code>--> ApplicationFolder
|--> qml        // QML files (also structured by subfolders)
|--> resources  // Application resources (images, sounds, data-files, etc.)
| |--> images   // Image resources (also structured by subfolders)
| |--> data     // Different data files
| |--> ...      // Other resources
|--> Application.exe   // Application executable
|--> *.dll             // DLLs application depends on
</code>```

The problem is that in order to specify image file for Image QML item we have to use path relative to QML file?! This is absolutely insane. During development files sometimes moved between folders (you move QML file and have to fix all the path it has?!); some different QML files have to refer to same image (same image resource but different actual path in different QML files).

So the question is: how to specify image path relative to application folder? Is it possible at all?

Thanks in advance!

PS. Using Qt's resource system (when resources are embedded into executable) is not an option in our case. We need raw resources on disk (including QML files itself, at least during development phase).

PPS. Wrote this question after spending a whole day to resolve the issue by myself via documentation/google/stackoverflow; no success at all (most examples use resource embedding, others are too simple and just use relative paths).

答:
Old questions, but got here from google. For me, it works simply with a relative path like this:

```<code>import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.3

[...]

Image {
    id: image
    source: "icons/brightness.svg" // simple relative path
    width: 22
    height: 22
    sourceSize.width: 22 // svg render resolution
    sourceSize.height: 22
    fillMode: Image.PreserveAspectFit // just in case to avoid stretching
}
</code>```

no .qrc needed.

Body:
We are developing our first Qt/QML application (trying technology). While technology looks very promising at a glance, we have faced so many unexpected weird issues that almost give up at very beginning.

Here one of such issue.

We want the following folders layout for our application:

--> ApplicationFolder
|--> qml        // QML files (also structured by subfolders)
|--> resources  // Application resources (images, sounds, data-files, etc.)
| |--> images   // Image resources (also structured by subfolders)
| |--> data     // Different data files
| |--> ...      // Other resources
|--> Application.exe   // Application executable
|--> *.dll             // DLLs application depends on

The problem is that in order to specify image file for Image QML item we have to use path relative to QML file?! This is absolutely insane. During development files sometimes moved between folders (you move QML file and have to fix all the path it has?!); some different QML files have to refer to same image (same image resource but different actual path in different QML files).

So the question is: how to specify image path relative to application folder? Is it possible at all?

Thanks in advance!

PS. Using Qt's resource system (when resources are embedded into executable) is not an option in our case. We need raw resources on disk (including QML files itself, at least during development phase).

PPS. Wrote this question after spending a whole day to resolve the issue by myself via documentation/google/stackoverflow; no success at all (most examples use resource embedding, others are too simple and just use relative paths).

Body:
Old questions, but got here from google. For me, it works simply with a relative path like this:

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.3

[...]

Image {
    id: image
    source: "icons/brightness.svg" // simple relative path
    width: 22
    height: 22
    sourceSize.width: 22 // svg render resolution
    sourceSize.height: 22
    fillMode: Image.PreserveAspectFit // just in case to avoid stretching
}

no .qrc needed.


问:
Convert date to PostgreSQL syntax
The following logic in SQL Server needs to be converted appropriately to PostgreSQL syntax. Please helpm me convert this over to the correct syntax so I can use it in PostgreSQL database:</p>

```<code>  convert(DATE, dateadd(m, -17, convert(DATE, getdate())))
</code>```

答:
The equivalent is:

```<code>current_date - interval '17 month'
</code>```

It is curious that the SQL Server code converts to date twice.

Title: Convert date to PostgreSQL syntax

Body:
The following logic in SQL Server needs to be converted appropriately to PostgreSQL syntax. Please helpm me convert this over to the correct syntax so I can use it in PostgreSQL database:

  convert(DATE, dateadd(m, -17, convert(DATE, getdate())))

Body:
The equivalent is:

current_date - interval '17 month'

It is curious that the SQL Server code converts to date twice.


问:
Position: fixed; moves element to the right
I have a button:

.b_next {
  border-radius: 50px;
  height: 45px;
  text-align: center;
  width: 100px;
  font-size: 20px;
  background-color: #cad2e7;
  color: #28284c;
  border-color: transparent;
  bottom: 30px;
}

.floatbtn {
  position: fixed;
  bottom: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="b_next floatbtn">Next</button></code>```

It is in a content wrapper has:

text-align: center;
```

However, my button is moved to the right when I add position: fixed, how do I fix this?

Expected Output

I want to button to be centered, at the bottom of the page, fixed.

答:
I do not completely understand your question, but if you want to position it entirely to the left or right, you can apply left: 0; or right: 0; to .floatbtn.

Update

Ah, you've added your expected output, then you can use the following to align your button in the middle(center):

```<code>.floatbtn {
    position: fixed;
    bottom: 100px;

    /* Below code aligns it to the center */
    left: 0;
    right: 0;
    margin: 0 auto;
}
</code>```

Body:
I have a button:

.b_next {
  border-radius: 50px;
  height: 45px;
  text-align: center;
  width: 100px;
  font-size: 20px;
  background-color: #cad2e7;
  color: #28284c;
  border-color: transparent;
  bottom: 30px;
}

.floatbtn {
  position: fixed;
  bottom: 100px;
}

<button class="b_next floatbtn">Next</button>

It is in a content wrapper has:

text-align: center;

However, my button is moved to the right when I add position: fixed, how do I fix this?

Expected Output

I want to button to be centered, at the bottom of the page, fixed.

Body:
I do not completely understand your question, but if you want to position it entirely to the left or right, you can apply left: 0; or right: 0; to .floatbtn.

Update

Ah, you've added your expected output, then you can use the following to align your button in the middle(center):

.floatbtn {
    position: fixed;
    bottom: 100px;

    /* Below code aligns it to the center */
    left: 0;
    right: 0;
    margin: 0 auto;
}


问:
"Type or Namespace definition, End of File expected" Error
I was working on a Unity project and I got the Titles Error I don't know what I did to get this error but it is painful for me trying to figure this Error on my own. I tried rewriting the area of code that made this error message and this did not work.

```<code>public class PlayerController : MonoBehaviour
{
    public Rigidbody2D theRB;

    public float movespeed = 5f;

    private Vector2 moveInput;
    private Vector2 mouseInput;

    public float mouseSensitivity = 1f;

    public Camera viewCam;

    public GameObject bulletImpact;

    public int currentAmmo;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Player movement
        moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        Vector3 moveHorizontal = transform.up * -moveInput.x;

        Vector3 moveVertical = transform.right * moveInput.y;
        theRB.velocity = (moveHorizontal + moveVertical) * movespeed;
        //player view control
        mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * mouseSensitivity;

        transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z - mouseInput.x);
        viewCam.transform.localRotation = Quaternion.Euler(viewCam.transform.localRotation.eulerAngles + new Vector3(0f, mouseInput.y, 0f));

        //Shooting Code
        if(Input.GetMouseButton(0))
        {
            if (currentAmmo > 0)
            {
                Ray ray = viewCam.ViewportPointToRay(new Vector3(.5f, .5f, 0f));
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    //Debug.Log("I'm looking at " + hit.transform.name);
                    Instantiate(bulletImpact, hit.point, transform.rotation);
                }
                else
                {
                    Debug.Log("Im looking at nothing");
                }
            }
            currentAmmo --;
            }
        }
    }
}

</code>```

it is the end bracket that is showing the red error squiggly lines.

答:
You have too many closing curly brackets. Try removing the curly bracket on the line immediately before
currentAmmo--;

Edit: adjusted answer based on comment below.

Body:
I was working on a Unity project and I got the Titles Error I don't know what I did to get this error but it is painful for me trying to figure this Error on my own. I tried rewriting the area of code that made this error message and this did not work.

public class PlayerController : MonoBehaviour
{
    public Rigidbody2D theRB;

    public float movespeed = 5f;

    private Vector2 moveInput;
    private Vector2 mouseInput;

    public float mouseSensitivity = 1f;

    public Camera viewCam;

    public GameObject bulletImpact;

    public int currentAmmo;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Player movement
        moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        Vector3 moveHorizontal = transform.up * -moveInput.x;

        Vector3 moveVertical = transform.right * moveInput.y;
        theRB.velocity = (moveHorizontal + moveVertical) * movespeed;
        //player view control
        mouseInput = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * mouseSensitivity;

        transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z - mouseInput.x);
        viewCam.transform.localRotation = Quaternion.Euler(viewCam.transform.localRotation.eulerAngles + new Vector3(0f, mouseInput.y, 0f));

        //Shooting Code
        if(Input.GetMouseButton(0))
        {
            if (currentAmmo > 0)
            {
                Ray ray = viewCam.ViewportPointToRay(new Vector3(.5f, .5f, 0f));
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    //Debug.Log("I'm looking at " + hit.transform.name);
                    Instantiate(bulletImpact, hit.point, transform.rotation);
                }
                else
                {
                    Debug.Log("Im looking at nothing");
                }
            }
            currentAmmo --;
            }
        }
    }
}

it is the end bracket that is showing the red error squiggly lines.


问:
Cloud function fails after changing Runtime to Node.js 10
I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:

Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined

Detailed error log:

```<code>2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
 insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"

labels: {…}
 logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-27T05:31:31.171084310Z"

resource: {…}
 severity: "ERROR"
 textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
    at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
    at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
    at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
    at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
    at Array.forEach (<anonymous>)
    at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
    at FirestoreAdminClient.databasePath (/workspace/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
    at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
    at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:330:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)"
 timestamp: "2020-05-27T05:31:21.820Z"
 trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}
</code>```

My index.js is as below:

```<code>const firestore = require('@google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
  const databaseName = client.databasePath(
    process.env.GCLOUD_PROJECT,
    '(default)'
  );
return client
    .exportDocuments({
      name: databaseName,
      outputUriPrefix: bucket,
      // Leave collectionIds empty to export all collections
      // or define a list of collection IDs:
      // collectionIds: ['users', 'posts']
      collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
    })
    .then(responses => {
      const response = responses[0];
      console.log(`Operation Name: ${response['name']}`);
      return response;
    })
    .catch(err => {
      console.error(err);
    });
};
</code>```

答:
I had the same issue.  I fixed it by changing:

process.env.GCLOUD_PROJECT

to my actual Project ID (e.g. "my_app_37274")

Body:
I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:

Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined

Detailed error log:

2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
 insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"

labels: {…}
 logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-27T05:31:31.171084310Z"

resource: {…}
 severity: "ERROR"
 textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
    at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
    at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
    at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
    at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
    at Array.forEach (<anonymous>)
    at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
    at FirestoreAdminClient.databasePath (/workspace/node_modules/@google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
    at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
    at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:330:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)"
 timestamp: "2020-05-27T05:31:21.820Z"
 trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}

My index.js is as below:

const firestore = require('@google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
  const databaseName = client.databasePath(
    process.env.GCLOUD_PROJECT,
    '(default)'
  );
return client
    .exportDocuments({
      name: databaseName,
      outputUriPrefix: bucket,
      // Leave collectionIds empty to export all collections
      // or define a list of collection IDs:
      // collectionIds: ['users', 'posts']
      collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
    })
    .then(responses => {
      const response = responses[0];
      console.log(`Operation Name: ${response['name']}`);
      return response;
    })
    .catch(err => {
      console.error(err);
    });
};


问:
sbrk - Valgrind doesn't report the memory leak
I wrote this little version of malloc (no free):

#include <cstdio>
#include <cstddef>
#include <unistd.h>

#define word_size sizeof(intptr_t)
#define align(n) ((n + word_size - 1) & ~(word_size - 1))

void* my_malloc(size_t size) {
    void* p = sbrk(0);
    printf("before allocation: %p\n", p);
    if (sbrk(align(size)) == (void*) -1) {
        // failed to allocate memory
        return NULL;
    }
    printf("after allocation: %p\n", sbrk(0));
    return p;
}

int main() {
    int* foo = (int*) my_malloc(1);
    *foo = 100;
    printf("after allocation outside: %p\n", sbrk(0));
}
```

<p>Here is the output of the code:</p>

```before allocation: 0x1796000
after allocation: 0x1796008
after allocation outside: 0x1796008
```

<p>As you can see, the memory allocated by <code>my_malloc</code> has not been freed.
Yet when I run it through <code>valgrind</code> with this:</p>

```valgrind --leak-check=yes ./main
```

<p>I get this:</p>

```==1592== Memcheck, a memory error detector
==1592== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1592== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1592== Command: ./main
==1592== HEAP SUMMARY:
==1592==     in use at exit: 0 bytes in 0 blocks
==1592==   total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==1592==
==1592== All heap blocks were freed -- no leaks are possible
==1592==
==1592== For counts of detected and suppressed errors, rerun with: -v
==1592== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```

As you can see, valgrind didn't find any memory leaks! Am I using valgrind incorrectly, or is this a bug?

答:
Valgrind checks for memory leaks by linking in its own functions in place of malloc, calloc, realloc, and free.  You can see this when valgrind reports a memory leak:

==24877== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==24877==    at 0x4C29EA3: malloc (vg_replace_malloc.c:309)
==24877==    by 0x4EC3AA9: strdup (in /usr/lib64/libc-2.17.so)
==24877==    by 0x40058E: main (x1.c:9)
```

You can see here that the libc version of strdup is called but the valgrind  replacement for malloc is called instead of the libc malloc.

You're allocating memory at a lower level using sbrk.  Valgrind doesn't intercept that function, so it won't detect a leak.  In fact, according to the valgrind documentation, it lists sbrk as a dependency.  From section 1.1.4:

To find out which glibc symbols are used by Valgrind, reinstate the
  link flags -nostdlib -Wl,-no-undefined. This causes linking to fail,
  but will tell you what you depend on. I have mostly, but not entirely,
  got rid of the glibc dependencies; what remains is, IMO, fairly
  harmless. AFAIK the current dependencies are: memset, memcmp, stat,
  system, sbrk, setjmp and longjmp.

Body:
I wrote this little version of malloc (no free):

#include <cstdio>
#include <cstddef>
#include <unistd.h>

#define word_size sizeof(intptr_t)
#define align(n) ((n + word_size - 1) & ~(word_size - 1))

void* my_malloc(size_t size) {
    void* p = sbrk(0);
    printf("before allocation: %p\n", p);
    if (sbrk(align(size)) == (void*) -1) {
        // failed to allocate memory
        return NULL;
    }
    printf("after allocation: %p\n", sbrk(0));
    return p;
}

int main() {
    int* foo = (int*) my_malloc(1);
    *foo = 100;
    printf("after allocation outside: %p\n", sbrk(0));
}

Here is the output of the code:

before allocation: 0x1796000
after allocation: 0x1796008
after allocation outside: 0x1796008

As you can see, the memory allocated by my_malloc has not been freed.
Yet when I run it through valgrind with this:

valgrind --leak-check=yes ./main

I get this:

==1592== Memcheck, a memory error detector
==1592== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1592== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1592== Command: ./main
==1592== HEAP SUMMARY:
==1592==     in use at exit: 0 bytes in 0 blocks
==1592==   total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==1592==
==1592== All heap blocks were freed -- no leaks are possible
==1592==
==1592== For counts of detected and suppressed errors, rerun with: -v
==1592== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

As you can see, valgrind didn't find any memory leaks! Am I using valgrind incorrectly, or is this a bug?

Body:
Valgrind checks for memory leaks by linking in its own functions in place of malloc, calloc, realloc, and free.  You can see this when valgrind reports a memory leak:

==24877== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==24877==    at 0x4C29EA3: malloc (vg_replace_malloc.c:309)
==24877==    by 0x4EC3AA9: strdup (in /usr/lib64/libc-2.17.so)
==24877==    by 0x40058E: main (x1.c:9)

You can see here that the libc version of strdup is called but the valgrind  replacement for malloc is called instead of the libc malloc.

You're allocating memory at a lower level using sbrk.  Valgrind doesn't intercept that function, so it won't detect a leak.  In fact, according to the valgrind documentation, it lists sbrk as a dependency.  From section 1.1.4:

To find out which glibc symbols are used by Valgrind, reinstate the
  link flags -nostdlib -Wl,-no-undefined. This causes linking to fail,
  but will tell you what you depend on. I have mostly, but not entirely,
  got rid of the glibc dependencies; what remains is, IMO, fairly
  harmless. AFAIK the current dependencies are: memset, memcmp, stat,
  system, sbrk, setjmp and longjmp.