问:
How to create a new table with partition key and sort key with AWS-Amplify?
I need to add a sort key and partition key to an existing dynamo db table... I created a new table with a partition key and sort key manual. But when I try to get one separate from the table it gives an error called "The provided key element does not match the schema". For that reason, I want to create a new table with a partition key and sort key. How can I edit my graphql schema and do a amplify push to create a new table? Please help... following is my graphql schema   </p>

```<code>type Idea @model
 {
  id: ID!
  title: String!
  userName: String
  category: String!
  status:String
  OtherCategory: String
  description: String
  subCategory: String
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
  comments: [Comment] @connection(name: "IdeaComments")
}
</code>```

答: Take a look at the new @key directive that was added to Amplify's GraphQL Transformer: https://aws-amplify.github.io/docs/cli/graphql#key

Body:
I need to add a sort key and partition key to an existing dynamo db table... I created a new table with a partition key and sort key manual. But when I try to get one separate from the table it gives an error called "The provided key element does not match the schema". For that reason, I want to create a new table with a partition key and sort key. How can I edit my graphql schema and do a amplify push to create a new table? Please help... following is my graphql schema

type Idea @model
 {
  id: ID!
  title: String!
  userName: String
  category: String!
  status:String
  OtherCategory: String
  description: String
  subCategory: String
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
  comments: [Comment] @connection(name: "IdeaComments")
}


来源: stackexchange

问:
Issues with a setter in a class, assigns None value to attribute
I'm learning about classes and inheritance and trying to create a simple abstract class called human and a subclass child, which has to inherit from the parent class. The parent and subclass both have only two attributes - name and age.

I've added a couple of setter methods to verify if the age and the name provided meet certain criteria e.g. if the length of the name is less than 2 characters, whether the age is positive or less than 15 for the subclass. The checks in the setter methods work properly, however, when I provide valid data both attributes in the sub-class assume None value.

```<code>
from abc import ABC, abstractmethod

class Hooman(ABC):
    @abstractmethod
    def __init__(self, age, name):
        self.age = self.set_age(age)
        self.name = self.set_name(name)

    @abstractmethod
    def set_age(self, age):
        pass

    @abstractmethod
    def set_name(self, name):
        pass

class LilHooman(Hooman):
    def __init__(self, age, name):
        super().__init__(age, name)

    def set_age(self, age):
        if age < 0:
            raise Exception("Age must be positive!")
        elif age > 14:
            raise Exception("Child's age must be less than 15!")
        else:
            self.age = age

    def set_name(self, name):
        if len(name) < 3:
            raise Exception("Name's length should not be less than 3 symbols!")
        else:
            self.name = name

    def __str__(self):
        return "Name: %s, Age: %d" % (self.name, self.age)

a = input()
b = int(input())

A1 = LilHooman(b, a)
print(A1.age, A1.name)
</code>```

With the following input:

```<code>Mike
14
</code>```

Output:

```<code>"None None"
</code>```

What am I doing wrong?

答:
Your methods set_age and set_name do not return anything.  So this code is not going to work:

```<code>def __init__(self, age, name):
    self.age = self.set_age(age)
    self.name = self.set_name(name)
</code>```

Instead you should use:

```<code>def __init__(self, age, name):
    self.set_age(age)
    self.set_name(name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm learning about classes and inheritance and trying to create a simple abstract class called human and a subclass child, which has to inherit from the parent class. The parent and subclass both have only two attributes - name and age.

I've added a couple of setter methods to verify if the age and the name provided meet certain criteria e.g. if the length of the name is less than 2 characters, whether the age is positive or less than 15 for the subclass. The checks in the setter methods work properly, however, when I provide valid data both attributes in the sub-class assume None value.

from abc import ABC, abstractmethod

class Hooman(ABC):
    @abstractmethod
    def __init__(self, age, name):
        self.age = self.set_age(age)
        self.name = self.set_name(name)

    @abstractmethod
    def set_age(self, age):
        pass

    @abstractmethod
    def set_name(self, name):
        pass

class LilHooman(Hooman):
    def __init__(self, age, name):
        super().__init__(age, name)

    def set_age(self, age):
        if age < 0:
            raise Exception("Age must be positive!")
        elif age > 14:
            raise Exception("Child's age must be less than 15!")
        else:
            self.age = age

    def set_name(self, name):
        if len(name) < 3:
            raise Exception("Name's length should not be less than 3 symbols!")
        else:
            self.name = name

    def __str__(self):
        return "Name: %s, Age: %d" % (self.name, self.age)

a = input()
b = int(input())

A1 = LilHooman(b, a)
print(A1.age, A1.name)

With the following input:

Mike
14

Output:

"None None"

What am I doing wrong?

Body:
Your methods set_age and set_name do not return anything.  So this code is not going to work:

def __init__(self, age, name):
    self.age = self.set_age(age)
    self.name = self.set_name(name)

Instead you should use:

def __init__(self, age, name):
    self.set_age(age)
    self.set_name(name)


问:
generate file with correct output python?
I have a python code which I am using to generate the batch file and the input is coming from txt file

```<code>def create_bat_file(lp=None):
  with open(r"test.txt", "r+") as file:
    currentDir = os.path.abspath(".")
    data = file.readlines()
    for line in data:
      a = line.split('=')
      b = a[0]
      f = a[1]
      bk = a[2]
      reldat = a[3]
      f= open("{}.bat".format(f),"w+")
      f.write("@ECHO OFF\n")
      f.write("SET lp="'"{}"'"\n".format(lp))
      if b == "RB":
          f.write("SET reldat="'"{}"'"".format(reldat))
      if b == "RB":
        f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
      else:
        f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
      f.close()
</code>```

test.txt file is having below input

```<code>CL=TEST14=https://test.com.org/latst/queue/TEST-R=2020-12-22
</code>```

Below is the output

```<code>@ECHO OFF
SET lp="test"
SET reldate="2020-12-22
"C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
</code>```

Issue is when it creates the batch file (TEST14.bat)

```<code>Wrong:

SET reldate="2020-12-22
    "C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
</code>```

in output the end double quote comes to the next line
it should be always like

```<code>Correct:

SET reldate="2020-12-22"
C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR
</code>```

答:
The last character of line is the newline character \n. The last character of reldat is also the newline character. Therefore, on the line:

```<code>f.write("SET reldat="'"{}"'"".format(reldat))
</code>```

You end up adding a \n before the last ".

To fix, you can strip the \n from line and add the missing one where it is needed:

```<code>def create_bat_file(lp=None):
  with open(r"test.txt", "r+") as file:
    currentDir = os.path.abspath(".")
    data = file.readlines()
    for line in data:
      line = line[:-1]  #### STRIP NEWLINE CHARACTER ####
      a = line.split('=')
      b = a[0]
      f = a[1]
      bk = a[2]
      reldat = a[3]
      f= open("{}.bat".format(f),"w+")
      f.write("@ECHO OFF\n")
      f.write("SET lp="'"{}"'"\n".format(lp))
      if b == "RB":
          f.write('SET reldat="{}"\n'.format(reldat))  #### ADD MISSING NEWLINE ####
      if b == "RB":
        f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
      else:
        f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
      f.close()
</code>```

I also took the freedom to use single quotes around the string, it looks much better!

Body:
I have a python code which I am using to generate the batch file and the input is coming from txt file

def create_bat_file(lp=None):
  with open(r"test.txt", "r+") as file:
    currentDir = os.path.abspath(".")
    data = file.readlines()
    for line in data:
      a = line.split('=')
      b = a[0]
      f = a[1]
      bk = a[2]
      reldat = a[3]
      f= open("{}.bat".format(f),"w+")
      f.write("@ECHO OFF\n")
      f.write("SET lp="'"{}"'"\n".format(lp))
      if b == "RB":
          f.write("SET reldat="'"{}"'"".format(reldat))
      if b == "RB":
        f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
      else:
        f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
      f.close()

test.txt file is having below input

CL=TEST14=https://test.com.org/latst/queue/TEST-R=2020-12-22

Below is the output

@ECHO OFF
SET lp="test"
SET reldate="2020-12-22
"C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR

Issue is when it creates the batch file (TEST14.bat)

Wrong:

SET reldate="2020-12-22
    "C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR

in output the end double quote comes to the next line
it should be always like

Correct:

SET reldate="2020-12-22"
C:\a.exe POST -d "best.variable.cp"=cp https://test.com.org/rest/api/latest/queue/TEST-RR

Body:
The last character of line is the newline character \n. The last character of reldat is also the newline character. Therefore, on the line:

f.write("SET reldat="'"{}"'"".format(reldat))

You end up adding a \n before the last ".

To fix, you can strip the \n from line and add the missing one where it is needed:

def create_bat_file(lp=None):
  with open(r"test.txt", "r+") as file:
    currentDir = os.path.abspath(".")
    data = file.readlines()
    for line in data:
      line = line[:-1]  #### STRIP NEWLINE CHARACTER ####
      a = line.split('=')
      b = a[0]
      f = a[1]
      bk = a[2]
      reldat = a[3]
      f= open("{}.bat".format(f),"w+")
      f.write("@ECHO OFF\n")
      f.write("SET lp="'"{}"'"\n".format(lp))
      if b == "RB":
          f.write('SET reldat="{}"\n'.format(reldat))  #### ADD MISSING NEWLINE ####
      if b == "RB":
        f.write("{}\\a.exe POST -d "'"best.variable.lp=lp"'"" " " "{}".format(currentDir,bk))
      else:
        f.write("{}\\a.exe POST -d "'"best.variable.cp=cp"'"" " " "{}".format(currentDir,bk))
      f.close()

I also took the freedom to use single quotes around the string, it looks much better!


问:
Perform an Action when the app comes to foreground
I am developing an app which has to perform some background work. For that reason, I am using a Service. Now what I want to achieve suppose the user start the background work and while the work is loading then the user has an option to either minizine the app or wait till the loading is over.

After the loading is over I want to open another Activity. Now my issue supposes the user starts the loading and minimizes the app then when the loading is over the user has not yet returned to the app then if I start the Screen without even the user having my app in his view then the user might get interrupted with his work.

So what I want is when the loading is over, I want to only open if my app is visible to the user and if the app is not visible to the user then I want to wait till the user return back and only when the user returns back I want to open the Screen if the loading is over.

Now what I have thought is I should have a boolean which will track whether the app is visible to the user. On onStop I will set the boolean value to false and onStart I will set the value to true. And again onStart I will check if the loading is finished and if yes then I will open the Screen.

But I want to know whether there is a better way to achieve this? If yes then how. The reason I am looking for a better way is that I want to write a clean code for my app which might avoid bugs and crashes.

答: That is exactly the scenario LiveData and RxJava are for. Your activity will get the data only when the activity is visible. Your Viwemodel will provide your live data to the activity only when your activity is available and it's lifecycle aware. You can also consider using WorkManager if your app needs to continue to work even after your user closed your app, even if user restarts your app. It also comes with Constraints to optimize your work based on Network, Battery life...and provides livedata for your Viewmodel to consume.</p>


问:
How to add vanilla JavaScript to vue.js project?
Good Day, I'm very new to Vue.js and want a navbar, which is transparent by default, but changes its background on scrolling. Unfortunately, it does not work. I tried few solutions, but none of this worked. So this JavaScript code is an example from Stack Overflow, which works in a Fiddle. If you need more information and/or code, please let me know.

Navigation.vue

```<code><template>
    <div id="navigation">
        <nav class="nav-items">
            <router-link class="item" to="/home">Home</router-link>
            <router-link class="item" to="/about">About</router-link>
            <router-link class="item" to="/japan">Japan</router-link>
        </nav>
    </div>
</template>

<script>
export default {
    name: 'navigation'
}

import scroll from '../assets/js/scroll.js';

</script>
</code>```

scroll.js

```<code>const navbar = document.querySelector('#navigation')

window.addEventListener('scroll', function(e) {
  const lastPosition = window.scrollY
  if (lastPosition > 50 ) {
    navbar.classList.add('colored')
  } else if (navbar.classList.contains('colored')) {
    navbar.classList.remove('colored')
  } else {
    navbar.classList.remove('colored')
  }
})
</code>```

navigation.scss

FYI: I've removed unneccessary code here.

```<code>#navigation {
    background: transparent;

    .colored {
        background: #fff;
        transition: 0.3s;
    }

}
</code>```

答:
Note: To view how to import custom code in a Vue component (general case), scroll down past the last
.

Vue is a JavaScript framework and therefore you can insert vanilla code anywhere in it and it will run perfectly fine.

IMHO, you issue is not about importing vanilla code. It's about running it at the correct moment.

You have to run your code inside mounted() hook, because that's when #navigation exists in DOM:

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('navigation', {
  template: '#navigationTemplate',
  mounted() {
    window.addEventListener('scroll',
      () => document.querySelector('#navigation')
      .classList.toggle('colored', window.scrollY > 50)
    )
  }
})

new Vue({
  el: '#app'
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#app {
  min-height: 200vh;
  background: url("https://picsum.photos/id/237/1024/540") no-repeat center center /cover;
}

#navigation {
  background: transparent;
  position: fixed;
  top: 0;
  padding: 1rem;
  transition: 0.3s;
  width: 100%;
  box-sizing: border-box;
  color: white;
}

#navigation.colored {
  background: rgba(255, 255, 255, .85);
  color: black;
}

body {
  margin: 0;
}</code>```

  <navigation />

```
</div>
</div>
</p>
<hr />
<ol>
<li>your <code>scroll.js</code> can safely be written as:</li>
</ol>
<pre class="lang-js prettyprint-override"><code>window.addEventListener('scroll',
  () => document.querySelector('#navigation')
  .classList.toggle('colored', window.scrollY > 50)
)
</code>```

Your SCSS seems incorrect:

#navigation {
  .colored {
    declaration
  }
}
```
<p>will apply <code>declaration</code> to any element with a class of <code>.colored</code> that's <em><strong>inside</strong></em> an element with the <code>id</code> of <code>navigation</code>. But your code toggles the class <code>colored</code> <em><strong>on</strong></em> <code>#navigation</code>. Therefore your SCSS should look like this:</p>
```#navigation {
  &.colored {
    declaration
  }
}
```
<p>Might not seem like much, but the <code>&</code> makes your code apply (or not).</p>
<ol start="3">
<li>You probably want to apply <code>transition</code> to <code>#navigation</code>, as it should apply when it has the <code>colored</code> class <em><strong>and when it doesn't</strong></em>. If you don't, the return transition (from <code>.colored</code> to <code>:not(.colored)</code>) will not be animated.</li>
</ol>
<hr />
<p>For the record and to also answer your initial question, the <em><strong>proper way</strong></em> to import custom code into a Vue component is:</p>
<p>a) export your code as a function:<br />
(in scroll.js)</p>
```export function menuScroll = function() {
  /* your custom code here */
}
```
<p>b) import it:<br />
(in your component)</p>
```import { menuScroll } from 'path/to/scroll'
```
<p>c) run it exactly where you need it:<br />
(i.e: in mounted)</p>
```export default {
  name: 'navigation',
  mounted() {
    menuScroll();
  }
}
```
<p>Obviously, you want to rename the function in accordance with its purpose/role and the project's naming conventions.</p>
<p>Last, but not least, if your function needs to take params, you might want to use it as a method:</p>
```export function someName = function(...args) {
  /** do stuff with args **/
}
```
<p>... and, in component:</p>
```import { someName } from 'path/to/it'

export default {
  name: 'whatever',
  methods: {
    someName,
    /* more methods... */
  }
}
```

Body:
Good Day, I'm very new to Vue.js and want a navbar, which is transparent by default, but changes its background on scrolling. Unfortunately, it does not work. I tried few solutions, but none of this worked. So this JavaScript code is an example from Stack Overflow, which works in a Fiddle. If you need more information and/or code, please let me know.

Navigation.vue

<template>

            <router-link class="item" to="/home">Home</router-link>
            <router-link class="item" to="/about">About</router-link>
            <router-link class="item" to="/japan">Japan</router-link>

</template>

scroll.js

const navbar = document.querySelector('#navigation')

window.addEventListener('scroll', function(e) {
  const lastPosition = window.scrollY
  if (lastPosition > 50 ) {
    navbar.classList.add('colored')
  } else if (navbar.classList.contains('colored')) {
    navbar.classList.remove('colored')
  } else {
    navbar.classList.remove('colored')
  }
})

navigation.scss

FYI: I've removed unneccessary code here.

#navigation {
    background: transparent;

    .colored {
        background: #fff;
        transition: 0.3s;
    }

}

Body:
Note: To view how to import custom code in a Vue component (general case), scroll down past the last <hr>.

Vue is a JavaScript framework and therefore you can insert vanilla code anywhere in it and it will run perfectly fine.

IMHO, you issue is not about importing vanilla code. It's about running it at the correct moment.

You have to run your code inside mounted() hook, because that's when #navigation exists in DOM:

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('navigation', {
  template: '#navigationTemplate',
  mounted() {
    window.addEventListener('scroll',
      () => document.querySelector('#navigation')
      .classList.toggle('colored', window.scrollY > 50)
    )
  }
})

new Vue({
  el: '#app'
});

#app {
  min-height: 200vh;
  background: url("https://picsum.photos/id/237/1024/540") no-repeat center center /cover;
}

#navigation {
  background: transparent;
  position: fixed;
  top: 0;
  padding: 1rem;
  transition: 0.3s;
  width: 100%;
  box-sizing: border-box;
  color: white;
}

#navigation.colored {
  background: rgba(255, 255, 255, .85);
  color: black;
}

body {
  margin: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script id="navigationTemplate" type="text/template">
  <div id="navigation">
    <nav class="nav-items">
      <a class="item" to="/home">Home</a>
      <a class="item" to="/about">About</a>
      <a class="item" to="/japan">Japan</a>
    </nav>
  </div>
</script>
<div id="app">
  <navigation />
</div>

your scroll.js can safely be written as:

window.addEventListener('scroll',
  () => document.querySelector('#navigation')
  .classList.toggle('colored', window.scrollY > 50)
)

Your SCSS seems incorrect:

#navigation {
  .colored {
    declaration
  }
}

will apply declaration to any element with a class of .colored that's inside an element with the id of navigation. But your code toggles the class colored on #navigation. Therefore your SCSS should look like this:

#navigation {
  &.colored {
    declaration
  }
}

Might not seem like much, but the & makes your code apply (or not).

You probably want to apply transition to #navigation, as it should apply when it has the colored class and when it doesn't. If you don't, the return transition (from .colored to :not(.colored)) will not be animated.

For the record and to also answer your initial question, the proper way to import custom code into a Vue component is:

a) export your code as a function:

(in scroll.js)

export function menuScroll = function() {
  /* your custom code here */
}

b) import it:

(in your component)

import { menuScroll } from 'path/to/scroll'

c) run it exactly where you need it:

(i.e: in mounted)

export default {
  name: 'navigation',
  mounted() {
    menuScroll();
  }
}

Obviously, you want to rename the function in accordance with its purpose/role and the project's naming conventions.

Last, but not least, if your function needs to take params, you might want to use it as a method:

export function someName = function(...args) {
  /** do stuff with args **/
}

... and, in component:

import { someName } from 'path/to/it'

export default {
  name: 'whatever',
  methods: {
    someName,
    /* more methods... */
  }
}


问:
How can I use a pandas filter and unique for the test of an if loop?
I have a large DataFrame that I want to inspect a filter of one column for the presence of a unique value in a different column.

```<code>import pandas

df = pandas.DataFrame({'Site Name' : ['NYC','NYC','NYC','ATL'], 'Product Family' : [5,2,3,2]})
name = 'NYC'

if 5 in df[(df['Site Name'] == name & df['Product Family'].unique)]:
    print('All good')
else:
    print('nope')
</code>```

I get an error TypeError: unsupported operand type(s) for &: 'str' and 'method'.

I want to filter df['Site Name'] for one value ('NYC') and then check all of the rows for the presence of a value (5) in a different column df['Product Family']

答:
You may need add any

```<code>if any(df['Site Name'].isin([name])&df['Product Family'].isin([5])):
    print('All good')
else:
    print('nope')

All good
</code>```

Body:
I have a large DataFrame that I want to inspect a filter of one column for the presence of a unique value in a different column.

import pandas

df = pandas.DataFrame({'Site Name' : ['NYC','NYC','NYC','ATL'], 'Product Family' : [5,2,3,2]})
name = 'NYC'

if 5 in df[(df['Site Name'] == name & df['Product Family'].unique)]:
    print('All good')
else:
    print('nope')

I get an error TypeError: unsupported operand type(s) for &: 'str' and 'method'.

I want to filter df['Site Name'] for one value ('NYC') and then check all of the rows for the presence of a value (5) in a different column df['Product Family']

Body:
You may need add any

if any(df['Site Name'].isin([name])&df['Product Family'].isin([5])):
    print('All good')
else:
    print('nope')

All good


问:
Observed Object not Registered as an Observer
I am having an issue when my array controller is refreshed with new data retrieved from a server request.

The Setup

I have an entity object (call it MyParent) which has a few properties:

```
name
age
description
widgetID
```

And an entity object (call it MyWidget) which has a few properties:

```
name
size
description
```

The size is a string representation of an NSSize object. It makes for easy storage and retrieval from the core data store and to the server and back in JSON. In order to represent the size in the UI, I have subclassed the MyWidget and provided a custom setter and getter as a category of the custom class (I did this so Xcode doesn't overwrite my changes if I need to make changes to the model):

```<code>-(void)setObjectWidth:(NSInteger)aValue {
    [self setObjectSize:NSMakeSize(aValue, [self objectHeight])];
}

-(void)setObjectHeight:(NSInteger)aValue {
    [self setObjectSize:NSMakeSize([self objectWidth], aValue)];
}

-(void)setObjectSize:(NSSize)aValue {
    [self setSize:NSStringFromSize(aValue)];
}

-(NSInteger)objectWidth {
    return [self objectSize].width;
}

-(NSInteger)objectHeight {
    return [self objectSize].height;
}

-(NSSize)objectSize {
    return NSSizeFromString([self size]);
}
</code>```

I get the widget by doing a lookup on the widgetId as a category method on the parent:

```<code>-(MyWidget *)widget {
    NSManagedObjectContext * moc = [[NSApp delegate] managedObjectContext];

    return [moc fetchObjectForEntityName:@"MyWidget"
                                 withUID:[self widgetID]];
}
</code>```

The fetchObjectForEntityName:withUID is a category on the managed object context.

Within the UI I have an array controller bound to a tableView of MyParent objects. Selecting an object presents the details in the UI which are bound to the appropriate values:

```
parentArrayController --> parentArray (managed objects in an array)
parentTable --> parentArrayController.arrangedObjects.name

uiWidthTextField --> parentArrayController.selection.widget.objectWidth
uiHeightTextField --> parentArrayController.selection.widget.objectHeight
```

The array controller is observed for changes so that it can fire off a notification for other parts of the app that need to know the selected object changed

What Works

Everything works well. I can make changes to the text fields within the UI and it sets and gets the size from the widget as you would expect. Adding a parent item is a simple task of creating a NSURLConnection and sending the appropriate params off to the server. When the server acknowledges the add, I request the list of parent items form the server again.

The list that comes down is compared to the existing list in core data and adds the new item and makes any other changes to other object values that are already there.

What's Broken

When the list comes back, it is parsed correctly, but the app complains when the array controller is being updated:

Serious application error.  Exception was caught during Core Data change processing: Cannot remove an observer  for the key path "widget.objectHeight" from  because it is not registered as an observer. with userInfo (null)

Cannot remove an observer  for the key path "widget.objectHeight" from  because it is not registered as an observer.

What I've Tried

I have tried to add a willChangeValueForKey: and didChangeValueForKey: wrapped around the setter of the objectHeight and objectWidth, but this seems to provide no recourse.

I believe the issue is because IB is bound to the widget.objectHeight and widget is a lookup on the parent as opposed to a true KVO/KVC property. However, I don't need a setter on widget (although I'll be trying that next).

I know I'm missing something, but can't place my finger on it.

The Plea

Any help or assistance with resolving this would be very much appreciated!

答:
You need to set objectWidth and objectHeight as non-modeled properties of MyWidget. You are having KVO problems because objectWidth and objectHeightare not keys of MyWidget but just have method names in the form of getters and setters.

Just add:

```<code>@property() NSInteger objectWidth;
@property() NSInteger objectHeight;
</code>```

to the MyWidget class and that should provide the keys for KVO to work. (Might want to double check my property form. It's been a while sense I had to write an integer property.)

ContentLicense: CC BY-SA 3.0

Body:
I am having an issue when my array controller is refreshed with new data retrieved from a server request.

The Setup

I have an entity object (call it MyParent) which has a few properties:

name
age
description
widgetID

And an entity object (call it MyWidget) which has a few properties:

name
size
description

The size is a string representation of an NSSize object. It makes for easy storage and retrieval from the core data store and to the server and back in JSON. In order to represent the size in the UI, I have subclassed the MyWidget and provided a custom setter and getter as a category of the custom class (I did this so Xcode doesn't overwrite my changes if I need to make changes to the model):

-(void)setObjectWidth:(NSInteger)aValue {
    [self setObjectSize:NSMakeSize(aValue, [self objectHeight])];
}

-(void)setObjectHeight:(NSInteger)aValue {
    [self setObjectSize:NSMakeSize([self objectWidth], aValue)];
}

-(void)setObjectSize:(NSSize)aValue {
    [self setSize:NSStringFromSize(aValue)];
}

-(NSInteger)objectWidth {
    return [self objectSize].width;
}

-(NSInteger)objectHeight {
    return [self objectSize].height;
}

-(NSSize)objectSize {
    return NSSizeFromString([self size]);
}

I get the widget by doing a lookup on the widgetId as a category method on the parent:

-(MyWidget *)widget {
    NSManagedObjectContext * moc = [[NSApp delegate] managedObjectContext];

    return [moc fetchObjectForEntityName:@"MyWidget"
                                 withUID:[self widgetID]];
}

The fetchObjectForEntityName:withUID is a category on the managed object context.

Within the UI I have an array controller bound to a tableView of MyParent objects. Selecting an object presents the details in the UI which are bound to the appropriate values:

parentArrayController --> parentArray (managed objects in an array)
parentTable --> parentArrayController.arrangedObjects.name

uiWidthTextField --> parentArrayController.selection.widget.objectWidth
uiHeightTextField --> parentArrayController.selection.widget.objectHeight

The array controller is observed for changes so that it can fire off a notification for other parts of the app that need to know the selected object changed

What Works

Everything works well. I can make changes to the text fields within the UI and it sets and gets the size from the widget as you would expect. Adding a parent item is a simple task of creating a NSURLConnection and sending the appropriate params off to the server. When the server acknowledges the add, I request the list of parent items form the server again.

The list that comes down is compared to the existing list in core data and adds the new item and makes any other changes to other object values that are already there.

What's Broken

When the list comes back, it is parsed correctly, but the app complains when the array controller is being updated:

Serious application error.  Exception was caught during Core Data change processing: Cannot remove an observer  for the key path "widget.objectHeight" from  because it is not registered as an observer. with userInfo (null)

Cannot remove an observer  for the key path "widget.objectHeight" from  because it is not registered as an observer.

What I've Tried

I have tried to add a willChangeValueForKey: and didChangeValueForKey: wrapped around the setter of the objectHeight and objectWidth, but this seems to provide no recourse.

I believe the issue is because IB is bound to the widget.objectHeight and widget is a lookup on the parent as opposed to a true KVO/KVC property. However, I don't need a setter on widget (although I'll be trying that next).

I know I'm missing something, but can't place my finger on it.

The Plea

Any help or assistance with resolving this would be very much appreciated!

Body:
You need to set objectWidth and objectHeight as non-modeled properties of MyWidget. You are having KVO problems because objectWidth and objectHeightare not keys of MyWidget but just have method names in the form of getters and setters.

Just add:

@property() NSInteger objectWidth;
@property() NSInteger objectHeight;

to the MyWidget class and that should provide the keys for KVO to work. (Might want to double check my property form. It's been a while sense I had to write an integer property.)


问:
How to secure requesting post - C# and PHP
I have a problems with C#, PHP, MYSQLi.
I made a form for Login & Registration system with

This a simple C# function for user registration.

IEnumerator registrar(
    string name,
    string username,
    string email,
    string password
) {

```<code>// This is what sends messages to our php script
WWWForm form = new WWWForm();

// The fields are the variables we are sending
form.AddField("name", name);
form.AddField("username", username);
form.AddField("email", email);
form.AddField("password", password);

//string url = "http://www.my-server.com/registrar.php";
string url = "http://localhost/registrar.php";

UnityWebRequest www = UnityWebRequest.Post(url, form);

// Wait for php to send something back to unity
yield return www.SendWebRequest();

if (
    www.isNetworkError || www.isHttpError
) {
    Debug.Log("Error!");
} else {
    Debug.Log("Complete!");
}}
</code>```

__

```<code>// Database variables
$db_host        = "localhost";
$db_user        = "root";
$db_password    = "test";
$db_name        = "test";

// Connect to database.
$db = mysqli_connect($db_host, $db_user, $db_password, $db_name);

// User variables
$name           = $db->real_escape_string($_POST["name"]);
$username       = $db->real_escape_string($_POST["username"]);
$email          = $db->real_escape_string($_POST["email"]);
$password       = $db->real_escape_string($_POST["password"]);
$password_hash  = password_hash($password, PASSWORD_DEFAULT);

// E-mail can not be empty
if(
    !empty($email)
    &&
    !empty($username)
    &&
    !empty($password)
) {
    // Insert user data
    $db->query("INSERT INTO `user`(`username`, `name`, `email`, `password`) VALUES ('$username', '$name', '$email', '$password_hash')");

    // Display...
    echo "Success!";
} else {
    // Display an error
    echo "Error!";
}
?>
</code>```

Everything is OK, The PHP code are work to.

But my problem now what gonna happen if the hackers get the URL of registration page, And make for himself a form just like my form and use my URL of registration page and using.

This is my problem, This problem will hack the Game data Like (Score, Total play, Time play, Otherss data).

So how can I protect & secure (request post) Do I have do something in PHP or C#.

答:
At a glance I can identify some weaknesses in your code:

You are not using HTTPS. Traffic between the client and server could be intercepted and seen in clear.

You are not using prepared statements. While real_escape_string is probably ok, know that: 1) It is altering the data. 2) It depends on the character set configured for the database connection (which you do not seem to be setting).

You are not validating user registration (i.e. sending an email with a code and waiting for it to confirm). Which means that it is easy to create lots of fake accounts.

What you ask seem to be authenticating your application to the server. The server does not know if the client is valid (it could be third party software doing the requests), so you want to find a way to make sure.

No, there is no way to do it. Not if the user is in control of the client and can reverse engineer it.

Fredrik Schön answer offers an solution that is useful in a different context. The idea is there will be a "password" apikey that identifies your application, and the server will check if it is correct. This is useful if I want two applications to connect... however, when one application is on the user machine, this is not secure at all.

Remember that your client could be modified, or the apikey stolen, since it is running on the client machine.

You could add a digital signature to the client (to add an integrity check on your client, so that it can verify that it has not been modified), yet that can also be circumvented.

On this point, it is all mitigations. There is no way to do it.

hack the Game data Like (Score, Total play, Time play, Otherss data).

Never trust the client

There should be no API to do these. There should be no way for the client to set the score (or to set any other form of reward). Instead the client sends events to the server (they can be as granular as one per user input, this is what you would be doing on a multiplayer client-server game anyway), and the server decides on score, rewards, etc.

I repeat, there would be no API. There would be no way for the client to just send how much you played.

Removing the process is the only way to guarantee you removed a risk. Otherwise, it is all mitigations.

A search for Anti-Cheat at gamedev.stackexchange.com can give you some ideas.

Addendum:

The problem of a game client that accesses a web form and a malicious user that creates a custom client that accesses the same form... is not fundamentally different from the problem of a web browser that accesses a web form and a malicious user that creates a custom client that accesses the same form. All server side security measures for the web apply for the game. And please notice that basing this security on a particular browser is not a good idea.

What we want is not to prevent the creation of the third party custom client, nor to make it useless. Instead to make sure it can at best do the same things that the legitimate client can do.

There is an API between the client and the server. If there is something in that API that allows the client to do something that the client should not do (such as setting a fake score), then the server and its API must be reworked so that it is not possible.

Body:
I have a problems with C#, PHP, MYSQLi.
I made a form for Login & Registration system with

This a simple C# function for user registration.

IEnumerator registrar(
    string name,
    string username,
    string email,
    string password
) {

// This is what sends messages to our php script
WWWForm form = new WWWForm();

// The fields are the variables we are sending
form.AddField("name", name);
form.AddField("username", username);
form.AddField("email", email);
form.AddField("password", password);

//string url = "http://www.my-server.com/registrar.php";
string url = "http://localhost/registrar.php";

UnityWebRequest www = UnityWebRequest.Post(url, form);

// Wait for php to send something back to unity
yield return www.SendWebRequest();

if (
    www.isNetworkError || www.isHttpError
) {
    Debug.Log("Error!");
} else {
    Debug.Log("Complete!");
}}

__

// Database variables
$db_host        = "localhost";
$db_user        = "root";
$db_password    = "test";
$db_name        = "test";

// Connect to database.
$db = mysqli_connect($db_host, $db_user, $db_password, $db_name);

// User variables
$name           = $db->real_escape_string($_POST["name"]);
$username       = $db->real_escape_string($_POST["username"]);
$email          = $db->real_escape_string($_POST["email"]);
$password       = $db->real_escape_string($_POST["password"]);
$password_hash  = password_hash($password, PASSWORD_DEFAULT);

// E-mail can not be empty
if(
    !empty($email)
    &&
    !empty($username)
    &&
    !empty($password)
) {
    // Insert user data
    $db->query("INSERT INTO `user`(`username`, `name`, `email`, `password`) VALUES ('$username', '$name', '$email', '$password_hash')");

    // Display...
    echo "Success!";
} else {
    // Display an error
    echo "Error!";
}
?>

Everything is OK, The PHP code are work to.

But my problem now what gonna happen if the hackers get the URL of registration page, And make for himself a form just like my form and use my URL of registration page and using.

This is my problem, This problem will hack the Game data Like (Score, Total play, Time play, Otherss data).

So how can I protect & secure (request post) Do I have do something in PHP or C#.


问:
Ionic cache service npm
I was trying to implement Ionic cache service to my Ionic3 project. I have followed this tutorial Ionic Cache using npm. But when I run ionic serve it throws below error.

```<code>TypeError: Object(...) is not a function
at CacheService.watchNetworkInit (http://localhost:8101/build/vendor.js:81192:78)
at new CacheService (http://localhost:8101/build/vendor.js:81074:14)
at buildCacheService (http://localhost:8101/build/vendor.js:148296:12)
at _callFactory (http://localhost:8101/build/vendor.js:11645:20)
at _createProviderInstance$1 (http://localhost:8101/build/vendor.js:11595:26)
at resolveNgModuleDep (http://localhost:8101/build/vendor.js:11577:17)
at NgModuleRef_.get (http://localhost:8101/build/vendor.js:12814:16)
at resolveDep (http://localhost:8101/build/vendor.js:13304:45)
at createClass (http://localhost:8101/build/vendor.js:13174:32)
at createDirectiveInstance (http://localhost:8101/build/vendor.js:13011:37)
</code>```

can anyone help what I am missing or anything need to be added.

Below are Ionic details.

```<code>Ionic Framework: 3.9.2
Ionic App Scripts: 3.2.1
Angular Core: 5.2.11
Angular Compiler CLI: 5.2.11
Node: 6.9.1
</code>```

Thanks in advance.

答:
you need to downgrade the version of the plugin, the last version of it is 4.0.1, I tried to downgrade the version to 3.1.3 it's work 100%
my ionic version is 3.9</p>

Title: Ionic cache service npm

Body:
I was trying to implement Ionic cache service to my Ionic3 project. I have followed this tutorial Ionic Cache using npm. But when I run ionic serve it throws below error.

TypeError: Object(...) is not a function
at CacheService.watchNetworkInit (http://localhost:8101/build/vendor.js:81192:78)
at new CacheService (http://localhost:8101/build/vendor.js:81074:14)
at buildCacheService (http://localhost:8101/build/vendor.js:148296:12)
at _callFactory (http://localhost:8101/build/vendor.js:11645:20)
at _createProviderInstance$1 (http://localhost:8101/build/vendor.js:11595:26)
at resolveNgModuleDep (http://localhost:8101/build/vendor.js:11577:17)
at NgModuleRef_.get (http://localhost:8101/build/vendor.js:12814:16)
at resolveDep (http://localhost:8101/build/vendor.js:13304:45)
at createClass (http://localhost:8101/build/vendor.js:13174:32)
at createDirectiveInstance (http://localhost:8101/build/vendor.js:13011:37)

can anyone help what I am missing or anything need to be added.

Below are Ionic details.

Ionic Framework: 3.9.2
Ionic App Scripts: 3.2.1
Angular Core: 5.2.11
Angular Compiler CLI: 5.2.11
Node: 6.9.1

Thanks in advance.


问:
Generate RGB color set with highest diversity
I'm trying to create an algorithm that will output a set of different RGB color values, that should be as distinct as possible.
For Example:

following a set of 3 colors:

(255, 0, 0) [Red]

(0, 255, 0) [Green]

(0, 0, 255) [Blue]

the next 3 colors would be:

(255, 255, 0) [Yellow]

(0, 255, 255) [Cyan]

(255, 0, 255) [Purple]

The next colors should be in-between the new intervals. Basically, my idea is to traverse the whole color spectrum systematic intervals similar to this:

A set of 13 colors should include the color in between 1 and 7, continue that pattern infinitely.

I'm currently struggling to apply this pattern to an algorithm to RGB values as it does not seem trivial to me. I'm thankful for any hints that can point me to a solution.

答:
The Wikipedia article on color difference is worth reading, and so is the article on a “low-cost approximation” by CompuPhase linked therein. I will base my attempt on the latter.

You didn't specify a language, so I'll write it in not optimized Python (except for the integer optimizations already present in the reference article), in order for it to be readily translatable into other languages.

n_colors = 25
n_global_moves = 32

class Color:
    max_weighted_square_distance = (((512 + 127) * 65025) >> 8) + 4 * 65025 + (((767 - 127) * 65025) >> 8)

    def __init__(self, r, g, b):
        self.r, self.g, self.b = r, g, b

    def weighted_square_distance(self, other):
        rm = (self.r + other.r) // 2  # integer division
        dr =  self.r - other.r
        dg =  self.g - other.g
        db =  self.b - other.b
        return (((512 + rm) * dr*dr) >> 8) + 4 * dg*dg + (((767 - rm) * db*db) >> 8)

    def min_weighted_square_distance(self, index, others):
        min_wsd = self.max_weighted_square_distance
        for i in range(0, len(others)):
            if i != index:
                wsd = self.weighted_square_distance(others[i])
                if  min_wsd > wsd:
                    min_wsd = wsd
        return min_wsd

    def is_valid(self):
        return 0 <= self.r <= 255 and 0 <= self.g <= 255 and 0 <= self.b <= 255

    def add(self, other):
        return Color(self.r + other.r, self.g + other.g, self.b + other.b)

    def __repr__(self):
        return f"({self.r}, {self.g}, {self.b})"

colors = [Color(127, 127, 127) for i in range(0, n_colors)]

steps = [Color(dr, dg, db) for dr in [-1, 0, 1]
                           for dg in [-1, 0, 1]
                           for db in [-1, 0, 1] if dr or dg or db]  # i.e., except 0,0,0
moved = True
global_move_phase = False
global_move_count = 0
while moved or global_move_phase:
    moved = False
    for index in range(0, len(colors)):
        color = colors[index]
        if global_move_phase:
            best_min_wsd = -1
        else:
            best_min_wsd = color.min_weighted_square_distance(index, colors)
        for step in steps:
            new_color = color.add(step)
            if new_color.is_valid():
                new_min_wsd = new_color.min_weighted_square_distance(index, colors)
                if  best_min_wsd < new_min_wsd:
                    best_min_wsd = new_min_wsd
                    colors[index] = new_color
                    moved = True
    if not moved:
        if  global_move_count < n_global_moves:
            global_move_count += 1
            global_move_phase = True
    else:
        global_move_phase = False

print(f"n_colors: {n_colors}")
print(f"n_global_moves: {n_global_moves}")
print(colors)
```

<p>The colors are first set all to grey, i.e., put in the center of the RGB color cube, and then moved in the color cube in such a way as to hopefully maximize the minimum distance between colors.</p>

<p>To save CPU time the square of the distance is used instead of the distance itself, which would require the calculation of a square root.</p>

<p>Colors are moved one at a time, by a maximum of 1 in each of the 3 directions, to one of the adjacent colors that maximizes the minimum distance from the other colors. By so doing, the global minimum distance is (approximately) maximized.</p>

<p>The “global move” phases are needed in order to overcome situations where no color would move, but forcing all colors to move to a position which is not much worse than their current one causes the whole to find a better configuration with the subsequent regular moves. This can best be seen with 3 colors and no global moves, modifying the weighted square distance to be simply <code>rd*rd+gd*gd+bd*bd</code>: the configuration becomes</p>

```[(2, 0, 0), (0, 253, 255), (255, 255, 2)]
```

<p>while, by adding 2 global moves, the configuration becomes the expected one</p>

```[(0, 0, 0), (0, 255, 255), (255, 255, 0)]
```

The algorithm produces just one of several possible solutions. Unfortunately, since the metric used is not Euclidean, it's not possible to simply flip the 3 dimension in the 8 possible combinations (i.e., replace r→255-r and/or the same for g and/or b) to get equivalent solutions. It's probably best to introduce randomness in the order the color moving steps are tried out, and vary the random seed.

I have not corrected for the monitor's gamma, because its purpose is precisely that of altering the spacing of the brightness in order to compensate for the eyes' different sensitivity at high and low brightness. Of course, the screen gamma curve deviates from the ideal, and a (system dependent!) modification of the gamma would yield better results, but the standard gamma is a good starting point.

This is the output of the algorithm for 25 colors:

Note that the first 8 colors (the bottom row and the first 3 colors of the row above) are close to the corners of the RGB cube (they are not at the corners because of the non-Euclidean metric).

Body:
The Wikipedia article on color difference is worth reading, and so is the article on a “low-cost approximation” by CompuPhase linked therein. I will base my attempt on the latter.

You didn't specify a language, so I'll write it in not optimized Python (except for the integer optimizations already present in the reference article), in order for it to be readily translatable into other languages.

n_colors = 25
n_global_moves = 32

class Color:
    max_weighted_square_distance = (((512 + 127) * 65025) >> 8) + 4 * 65025 + (((767 - 127) * 65025) >> 8)

    def __init__(self, r, g, b):
        self.r, self.g, self.b = r, g, b

    def weighted_square_distance(self, other):
        rm = (self.r + other.r) // 2  # integer division
        dr =  self.r - other.r
        dg =  self.g - other.g
        db =  self.b - other.b
        return (((512 + rm) * dr*dr) >> 8) + 4 * dg*dg + (((767 - rm) * db*db) >> 8)

    def min_weighted_square_distance(self, index, others):
        min_wsd = self.max_weighted_square_distance
        for i in range(0, len(others)):
            if i != index:
                wsd = self.weighted_square_distance(others[i])
                if  min_wsd > wsd:
                    min_wsd = wsd
        return min_wsd

    def is_valid(self):
        return 0 <= self.r <= 255 and 0 <= self.g <= 255 and 0 <= self.b <= 255

    def add(self, other):
        return Color(self.r + other.r, self.g + other.g, self.b + other.b)

    def __repr__(self):
        return f"({self.r}, {self.g}, {self.b})"

colors = [Color(127, 127, 127) for i in range(0, n_colors)]

steps = [Color(dr, dg, db) for dr in [-1, 0, 1]
                           for dg in [-1, 0, 1]
                           for db in [-1, 0, 1] if dr or dg or db]  # i.e., except 0,0,0
moved = True
global_move_phase = False
global_move_count = 0
while moved or global_move_phase:
    moved = False
    for index in range(0, len(colors)):
        color = colors[index]
        if global_move_phase:
            best_min_wsd = -1
        else:
            best_min_wsd = color.min_weighted_square_distance(index, colors)
        for step in steps:
            new_color = color.add(step)
            if new_color.is_valid():
                new_min_wsd = new_color.min_weighted_square_distance(index, colors)
                if  best_min_wsd < new_min_wsd:
                    best_min_wsd = new_min_wsd
                    colors[index] = new_color
                    moved = True
    if not moved:
        if  global_move_count < n_global_moves:
            global_move_count += 1
            global_move_phase = True
    else:
        global_move_phase = False

print(f"n_colors: {n_colors}")
print(f"n_global_moves: {n_global_moves}")
print(colors)

The colors are first set all to grey, i.e., put in the center of the RGB color cube, and then moved in the color cube in such a way as to hopefully maximize the minimum distance between colors.

To save CPU time the square of the distance is used instead of the distance itself, which would require the calculation of a square root.

Colors are moved one at a time, by a maximum of 1 in each of the 3 directions, to one of the adjacent colors that maximizes the minimum distance from the other colors. By so doing, the global minimum distance is (approximately) maximized.

The “global move” phases are needed in order to overcome situations where no color would move, but forcing all colors to move to a position which is not much worse than their current one causes the whole to find a better configuration with the subsequent regular moves. This can best be seen with 3 colors and no global moves, modifying the weighted square distance to be simply rd*rd+gd*gd+bd*bd: the configuration becomes

[(2, 0, 0), (0, 253, 255), (255, 255, 2)]

while, by adding 2 global moves, the configuration becomes the expected one

[(0, 0, 0), (0, 255, 255), (255, 255, 0)]

The algorithm produces just one of several possible solutions. Unfortunately, since the metric used is not Euclidean, it's not possible to simply flip the 3 dimension in the 8 possible combinations (i.e., replace r→255-r and/or the same for g and/or b) to get equivalent solutions. It's probably best to introduce randomness in the order the color moving steps are tried out, and vary the random seed.

I have not corrected for the monitor's gamma, because its purpose is precisely that of altering the spacing of the brightness in order to compensate for the eyes' different sensitivity at high and low brightness. Of course, the screen gamma curve deviates from the ideal, and a (system dependent!) modification of the gamma would yield better results, but the standard gamma is a good starting point.

This is the output of the algorithm for 25 colors:

Note that the first 8 colors (the bottom row and the first 3 colors of the row above) are close to the corners of the RGB cube (they are not at the corners because of the non-Euclidean metric).


问:
Could not find the entrypoints file from Webpack: the file ".../public/build/entrypoints.json" does not exist
I'm trying to setup a symfony project i cloned from github, i'm new to setting up symfony and need help. I've done composer install but it won't come up with the webpage. It says it couldn't find the entrypoints

I've tried composer install, npm and not much else, as i'm new to symfony

The code it gives me with the error:

```<code>    <head>
        <meta charset="UTF-8">
        <title>{% block title %}CargoFM{% endblock %}</title>
        {% block stylesheets %}
            {{ encore_entry_link_tags('app') }}
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
        {% block javascripts %}
            {{ encore_entry_script_tags('app') }}
        {% endblock %}
    </body>
</html>
</code>```

It's probably a really small issue

Full error message: An exception has been thrown during the rendering of a template ("Could not find the entrypoints file from Webpack: the file "C:\laragon\www\cargofm/public/build/entrypoints.json" does not exist.").

Don't know what to do

答:
It seems your entrypoints.json has not generated by encore.

Do verify your webpack.config.js setup correctly(it will be present at root). Like

```<code>// webpack.config.js
var Encore = require('@symfony/webpack-encore');

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')

    .addEntry('app', './assets/js/app.js')

    // ...
;

// ...
</code>```

Then try run yarn encore dev --watch

Here you can follow for setting up project instructions.

https://symfony.com/doc/current/frontend/encore/simple-example.html

Body:
I'm trying to setup a symfony project i cloned from github, i'm new to setting up symfony and need help. I've done composer install but it won't come up with the webpage. It says it couldn't find the entrypoints

I've tried composer install, npm and not much else, as i'm new to symfony

The code it gives me with the error:

        <meta charset="UTF-8">
        <title>{% block title %}CargoFM{% endblock %}</title>
        {% block stylesheets %}
            {{ encore_entry_link_tags('app') }}
        {% endblock %}

        {% block body %}{% endblock %}
        {% block javascripts %}
            {{ encore_entry_script_tags('app') }}
        {% endblock %}

It's probably a really small issue

Full error message: An exception has been thrown during the rendering of a template ("Could not find the entrypoints file from Webpack: the file "C:\laragon\www\cargofm/public/build/entrypoints.json" does not exist.").

Don't know what to do

Body:
It seems your entrypoints.json has not generated by encore.

Do verify your webpack.config.js setup correctly(it will be present at root). Like

// webpack.config.js
var Encore = require('@symfony/webpack-encore');

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')

    .addEntry('app', './assets/js/app.js')

    // ...
;

// ...

Then try run yarn encore dev --watch

Here you can follow for setting up project instructions.

https://symfony.com/doc/current/frontend/encore/simple-example.html


问:
Disable certain Azure functions using any configuration
While using Azure functions, I have a situation where I want a few functions in "disabled" mode for a function app, while others to be enabled. The thing is, I don't want to do it manually using the functions screen where individual functions could be enabled/disabled easily. There is this article that says Functions 2.x supports this (Functions 1.x is not a choice for me).

https://learn.microsoft.com/en-us/azure/azure-functions/disable-function

It is just that the article is a little vague about what needs to be done. It says and I quote >

In Functions 2.x you disable a function by using an app setting. For example, to disable a function named QueueTrigger, you create an app setting named AzureWebJobs.QueueTrigger.Disabled, and set it to true. To enable the function, set the app setting to false.

I tried this, but it doesn't work as documented. I have a function app called foo and a function called bar. I have tried both:

disabled: true in function.json

as well as:

```<code>foo: {
  bar: {
    disabled: true
  }
}
</code>```

After making these changes and redeploying there is no effect on the UI. What am I missing?

答:
The recommended approach is by using app settings, which you can do by going to the portal. [Note: They don't mean function.json when they say app settings.]

Option 1: Using App Settings
In azure portal, navigate to your function app foo -> Confuguration, and you should see Application Settings tab with a few variables already defined. You need to create a new variable by clicking New application setting button. Set name as AzureWebJobs.bar.Disabled and value as true. Note that the function app name foo doesn't figure in the variable name.

Option 2: Using host.json
Because you are looking for disabling a function from code, you can try doing this in host.json. Note that this is intended for local development, and not recommended for prod, but it works.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-host-json#functions

{
    "functions": [ "function1", "function2" ] // Don't list function "bar" here, and it would get disabled.
}
```

<p>Note that the portal will not show this correctly, and list "bar" as enabled, but you will get 404 when hitting that function.</p>

<p><strong>Option 3: Using Disable attribute</strong>
If you are using C# You can also use the <code>[Disable]</code> attribute. This is a Functions 1.x construct, but it works in 2.x as well. Similar to above, the portal UI will not show this correctly.</p>

<pre class="lang-cs prettyprint-override"><code>    [Disable]
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
}
</code>```

Option 4: By removing FunctionName attribute
Only if you are using C#. This might sound counter-intuitive, but if you remove the FunctionName attribute from your function, it won't be treated as such.

    // [FunctionName("Function1")]  // Comment this or delete this line to disable this function
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
}
```

This should work in both runtimes. The function wouldn't show in the azure portal.

Body:
While using Azure functions, I have a situation where I want a few functions in "disabled" mode for a function app, while others to be enabled. The thing is, I don't want to do it manually using the functions screen where individual functions could be enabled/disabled easily. There is this article that says Functions 2.x supports this (Functions 1.x is not a choice for me).

https://learn.microsoft.com/en-us/azure/azure-functions/disable-function

It is just that the article is a little vague about what needs to be done. It says and I quote >

In Functions 2.x you disable a function by using an app setting. For example, to disable a function named QueueTrigger, you create an app setting named AzureWebJobs.QueueTrigger.Disabled, and set it to true. To enable the function, set the app setting to false.

I tried this, but it doesn't work as documented. I have a function app called foo and a function called bar. I have tried both:

disabled: true in function.json

as well as:

foo: {
  bar: {
    disabled: true
  }
}

After making these changes and redeploying there is no effect on the UI. What am I missing?

Body:
The recommended approach is by using app settings, which you can do by going to the portal. [Note: They don't mean function.json when they say app settings.]

Option 1: Using App Settings
In azure portal, navigate to your function app foo -> Confuguration, and you should see Application Settings tab with a few variables already defined. You need to create a new variable by clicking New application setting button. Set name as AzureWebJobs.bar.Disabled and value as true. Note that the function app name foo doesn't figure in the variable name.

Option 2: Using host.json
Because you are looking for disabling a function from code, you can try doing this in host.json. Note that this is intended for local development, and not recommended for prod, but it works.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-host-json#functions

{
    "functions": [ "function1", "function2" ] // Don't list function "bar" here, and it would get disabled.
}

Note that the portal will not show this correctly, and list "bar" as enabled, but you will get 404 when hitting that function.

Option 3: Using Disable attribute
If you are using C# You can also use the [Disable] attribute. This is a Functions 1.x construct, but it works in 2.x as well. Similar to above, the portal UI will not show this correctly.

    [Disable]
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
}

Option 4: By removing FunctionName attribute
Only if you are using C#. This might sound counter-intuitive, but if you remove the FunctionName attribute from your function, it won't be treated as such.

    // [FunctionName("Function1")]  // Comment this or delete this line to disable this function
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
}

This should work in both runtimes. The function wouldn't show in the azure portal.


问:
Python & Psycopg2 | Dynamic Query with varying WHERE clauses
I am trying to create a function that executes a query based on the arguments that are passed to it.

```<code>def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table
        WHERE filter1 = %s AND filter2 =%s AND filter3 = %s;'''
        cursor.fetchall()
</code>```

But whenever either of the filters is None, then I do not want that parameter to be part of the SQL query.

For example, if ONLY filter 1 is used then I would want the query to become:

```<code>def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table
        WHERE filter1 = %s;'''
        cursor.fetchall()
</code>```

How to do this such that the query is generated dynamically?

答:
Consider COALESCE as Python's None translates to SQL's NULL. Below method now uses optional args that default to None:

```<code>def sql_query(filter1=None, filter2=None, filter3=None):
    with ConnectionPool() as cursor:
        sql = '''SELECT * FROM table
                 WHERE filter1 = COALESCE(%s, filter1)
                   AND filter2 = COALESCE(%s, filter2)
                   AND filter3 = COALESCE(%s, filter3);
              '''
        cursor.execute(sql, (filter1, filter2, filter3))
        cursor.fetchall()
</code>```

Body:
I am trying to create a function that executes a query based on the arguments that are passed to it.

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table
        WHERE filter1 = %s AND filter2 =%s AND filter3 = %s;'''
        cursor.fetchall()

But whenever either of the filters is None, then I do not want that parameter to be part of the SQL query.

For example, if ONLY filter 1 is used then I would want the query to become:

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table
        WHERE filter1 = %s;'''
        cursor.fetchall()

How to do this such that the query is generated dynamically?

Body:
Consider COALESCE as Python's None translates to SQL's NULL. Below method now uses optional args that default to None:

def sql_query(filter1=None, filter2=None, filter3=None):
    with ConnectionPool() as cursor:
        sql = '''SELECT * FROM table
                 WHERE filter1 = COALESCE(%s, filter1)
                   AND filter2 = COALESCE(%s, filter2)
                   AND filter3 = COALESCE(%s, filter3);
              '''
        cursor.execute(sql, (filter1, filter2, filter3))
        cursor.fetchall()


问:
c# how to let web browser automatically load a url
I'm trying to load a web viewer that automatically, as the program starts, loads a url.

I've tried:

```<code>this.webBrowser1.Navigate("http://www.microsoft.com");
</code>```

some code

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.webBrowser1.Navigate("http://www.microsoft.com");

        }
    }
}
</code>```

I expect that when the brogram runs, that the web viewer automatically goes to a url.

答:
Try this code inside Form1_Load

```<code>// for initial loading of the page this doesn't have to be true, this is only for navigation after loading the 1st page
webBrowser1.AllowNavigation = true;

webBrowser1.DocumentCompleted += new
          WebBrowserDocumentCompletedEventHandler(WebBrowser1_DocumentCompleted);

webBrowser1.Navigate("http://www.microsoft.com");

</code>```

Body:
I'm trying to load a web viewer that automatically, as the program starts, loads a url.

I've tried:

this.webBrowser1.Navigate("http://www.microsoft.com");

some code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.webBrowser1.Navigate("http://www.microsoft.com");

        }
    }
}

I expect that when the brogram runs, that the web viewer automatically goes to a url.

Body:
Try this code inside Form1_Load

// for initial loading of the page this doesn't have to be true, this is only for navigation after loading the 1st page
webBrowser1.AllowNavigation = true;

webBrowser1.DocumentCompleted += new
          WebBrowserDocumentCompletedEventHandler(WebBrowser1_DocumentCompleted);

webBrowser1.Navigate("http://www.microsoft.com");


问:
How can I instantiate a lambda closure type in C++11/14?
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

```<code>#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}
</code>```

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

答:
As others have pointed out, empty lambdas will become default-constructible in C++20.

You cannot wait for / switch to it?

No problem, it's easily emulated, as long as your lambda isn't generic.

Simply convert the lambda to a function-pointer, and pack that into a std::integral_constant:

```<code>template <class T>
constexpr auto make_constant(T t) noexcept
-> std::integral_constant<decltype(+t), +t>
{ return {}; }
</code>```

Of course, in most cases where you can choose a function-objects type, you can also pass the initial value, which is a bit easier.

Body:
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

Body:
As others have pointed out, empty lambdas will become default-constructible in C++20.

You cannot wait for / switch to it?

No problem, it's easily emulated, as long as your lambda isn't generic.

Simply convert the lambda to a function-pointer, and pack that into a std::integral_constant:

template <class T>
constexpr auto make_constant(T t) noexcept
-> std::integral_constant<decltype(+t), +t>
{ return {}; }

Of course, in most cases where you can choose a function-objects type, you can also pass the initial value, which is a bit easier.


问:
Missing last line in file
Using the code below. It will not copy the last line in the file.

I have tried the following means of reading the file.

"while IFS=$'\n' read -d '' -r -a myLine" or "while IFS=$'\n' read -r -a myLine"

```<code>while read -a myLine
do
  for ((i=0;i<"${#myLine[@]}";i++))
  do
    temp_array[$i]+=" ${myLine[$i]}"
  done
done < $1
</code>```

File contains numbers like:

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

when echo is used to see what is in the array i get

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

this is where it drops off the last line.

答:
The problem is that on the last line, read hits the end of file rather an an end-of-line delimiter (newline character), so it returns a failure status and the loop exits. But it does put the content it read into the array variable, so check for that to make it process that last line:

```<code>while read -a myLine || [[ ${#myLine[@]} -gt 0 ]]
do
</code>```

This is very similar to the solution for read without -a; the only difference is how to test for a nonempty line after the last linefeed.

Title: Missing last line in file

Body:
Using the code below. It will not copy the last line in the file.

I have tried the following means of reading the file.

"while IFS=$'\n' read -d '' -r -a myLine" or "while IFS=$'\n' read -r -a myLine"

while read -a myLine
do
  for ((i=0;i<"${#myLine[@]}";i++))
  do
    temp_array[$i]+=" ${myLine[$i]}"
  done
done < $1

File contains numbers like:

1 2
3 4
5 6

when echo is used to see what is in the array i get

1 2
3 4

this is where it drops off the last line.

Body:
The problem is that on the last line, read hits the end of file rather an an end-of-line delimiter (newline character), so it returns a failure status and the loop exits. But it does put the content it read into the array variable, so check for that to make it process that last line:

while read -a myLine || [[ ${#myLine[@]} -gt 0 ]]
do

This is very similar to the solution for read without -a; the only difference is how to test for a nonempty line after the last linefeed.


问:
How do I populate a playlist qml type using a c++ model?
I'm building a music player and need to autofill the playlist using this c++ model:

```<code>static QStringList pathList;
int main(int argc, char *argv[]){
// ...
// ...
QDirIterator it("E:/", QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
        while (it.hasNext()){
            pathList.append(it.next());
        }
    QQmlContext *ctxt1 = engine.rootContext();
    ctxt1->setContextProperty("pathModel", QVariant::fromValue(pathList)); //used model pathmodel
// ...
// ...
}
</code>```

and my playlist code on the qml side:

```<code>Rectangle{
    width: page.width
    height: page.height
    Audio {
           id: player;
           playlist: Playlist {
               id: playlist
               PlaylistItem { source: "song1.ogg"; } //I want this process to be automated instead of doing it manually
           }
       }
       ListView {
           model: playlist;
           delegate: Text {
               font.pixelSize: 16;
               text: source;
           }
       }
       MouseArea {
           anchors.fill: parent;
           onPressed: {
               if (player.playbackState != Audio.PlayingState) {
                   player.play();
               } else {
                   player.pause();
               }
           }
       }
}
</code>```

I tried using App list view type but I only managed to play/pause a song on click and couldn't implement functions like autoplay next when a song finishes or stop the current one when another song is selected.
The qt documents are not clear on what needs to be done either nor available tutorials or demos

答:
There are several solutions depending on what you want to implement:

If you are going to load the list only at the beginning then you should only use a QList <QUrl>:

// ...
QList<QUrl> sources;
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    sources << QUrl::fromLocalFile(it.next());
}
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("sources", QVariant::fromValue(sources));
// ...
```

```// ...
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
        Component.onCompleted: playlist.addItems(sources)
    }
}
// ...
```

<ul>
<li>If you want to add and remove items during the execution of the program then you can use a model:</li>
</ul>

<pre class="lang-cpp prettyprint-override"><code>class SourceModel: public QStandardItemModel{
    Q_OBJECT
public:
    enum SourceRoles{
        SourceRole = Qt::UserRole + 1000
    };
    SourceModel(QObject *parent=nullptr):
        QStandardItemModel(parent)
    {
        QHash<int, QByteArray> roles;
        roles[SourceRole] = "source";
        setItemRoleNames(roles);
        connect(this, &QAbstractItemModel::rowsInserted, this, &SourceModel::onRowsInserted);
        connect(this, &QAbstractItemModel::rowsRemoved, this, &SourceModel::onRowsRemoved);
        connect(this, &QAbstractItemModel::modelReset, this, &SourceModel::reset);
    }
    void addSource(const QUrl & url){
        QStandardItem *item = new QStandardItem();
        item->setData(url, SourceRole);
        appendRow(item);
    }
Q_SIGNALS:
    void sourcesInserted(int first, QList<QUrl> sources);
    void sourcesRemoved(int first, int last);
    void reset();
private:
    void onRowsInserted(const QModelIndex &parent, int first, int last){
        QList<QUrl> sources;
        for (int i=first; i <= last; ++i) {
            QModelIndex ix = this->index(i, 0, parent);
            QVariant v = data(ix, SourceRole);
            sources << v.toUrl();
        }
        Q_EMIT sourcesInserted(first, sources);
    }
    void onRowsRemoved(const QModelIndex & /*parent*/, int first, int last){
        Q_EMIT sourcesRemoved(first, last);
    }
};

// ...
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("source_model", &source_model);
// ...
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    source_model.addSource(QUrl::fromLocalFile(it.next()));
}
// ...
</code>```

```<code>// ...
Connections{
    target: source_model
    onSourcesInserted: playlist.insertItems(first, sources)
    onSourcesRemoved: playlist.removeItems(first, last);
    onReset: playlist.clear()
}
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
    }
}
// ...
</code>```

Another option is to use a Q_PROPERTY:

class SourceManager: public QObject{
    Q_OBJECT
    Q_PROPERTY(QList<QUrl> sources READ sources  WRITE setSources  NOTIFY sourcesChanged)
public:
    using QObject::QObject;
    QList<QUrl> sources() const{
        return m_sources;
    }
    void setSources(QList<QUrl> sources){
        if (m_sources == sources)
            return;
        m_sources = sources;
        emit sourcesChanged();
    }
Q_SIGNALS:
    void sourcesChanged();
private:
    QList<QUrl> m_sources;
};
// ...
SourceManager source_manager;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("source_manager", &source_manager);
// ...
QList<QUrl> sources;
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    sources << QUrl::fromLocalFile(it.next());
}
source_manager.setSources(sources);
// ...
```

```// ...
Connections{
    target: source_manager
    onSourcesChanged: {
        playlist.clear();
        playlist.addItems(source_manager.sources)
    }
}
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
    }
}
// ...
```

Body:
I'm building a music player and need to autofill the playlist using this c++ model:

static QStringList pathList;
int main(int argc, char *argv[]){
// ...
// ...
QDirIterator it("E:/", QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
        while (it.hasNext()){
            pathList.append(it.next());
        }
    QQmlContext *ctxt1 = engine.rootContext();
    ctxt1->setContextProperty("pathModel", QVariant::fromValue(pathList)); //used model pathmodel
// ...
// ...
}

and my playlist code on the qml side:

Rectangle{
    width: page.width
    height: page.height
    Audio {
           id: player;
           playlist: Playlist {
               id: playlist
               PlaylistItem { source: "song1.ogg"; } //I want this process to be automated instead of doing it manually
           }
       }
       ListView {
           model: playlist;
           delegate: Text {
               font.pixelSize: 16;
               text: source;
           }
       }
       MouseArea {
           anchors.fill: parent;
           onPressed: {
               if (player.playbackState != Audio.PlayingState) {
                   player.play();
               } else {
                   player.pause();
               }
           }
       }
}

I tried using App list view type but I only managed to play/pause a song on click and couldn't implement functions like autoplay next when a song finishes or stop the current one when another song is selected.
The qt documents are not clear on what needs to be done either nor available tutorials or demos

Body:
There are several solutions depending on what you want to implement:

If you are going to load the list only at the beginning then you should only use a QList <QUrl>:

// ...
QList<QUrl> sources;
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    sources << QUrl::fromLocalFile(it.next());
}
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("sources", QVariant::fromValue(sources));
// ...

// ...
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
        Component.onCompleted: playlist.addItems(sources)
    }
}
// ...

If you want to add and remove items during the execution of the program then you can use a model:

class SourceModel: public QStandardItemModel{
    Q_OBJECT
public:
    enum SourceRoles{
        SourceRole = Qt::UserRole + 1000
    };
    SourceModel(QObject *parent=nullptr):
        QStandardItemModel(parent)
    {
        QHash<int, QByteArray> roles;
        roles[SourceRole] = "source";
        setItemRoleNames(roles);
        connect(this, &QAbstractItemModel::rowsInserted, this, &SourceModel::onRowsInserted);
        connect(this, &QAbstractItemModel::rowsRemoved, this, &SourceModel::onRowsRemoved);
        connect(this, &QAbstractItemModel::modelReset, this, &SourceModel::reset);
    }
    void addSource(const QUrl & url){
        QStandardItem *item = new QStandardItem();
        item->setData(url, SourceRole);
        appendRow(item);
    }
Q_SIGNALS:
    void sourcesInserted(int first, QList<QUrl> sources);
    void sourcesRemoved(int first, int last);
    void reset();
private:
    void onRowsInserted(const QModelIndex &parent, int first, int last){
        QList<QUrl> sources;
        for (int i=first; i <= last; ++i) {
            QModelIndex ix = this->index(i, 0, parent);
            QVariant v = data(ix, SourceRole);
            sources << v.toUrl();
        }
        Q_EMIT sourcesInserted(first, sources);
    }
    void onRowsRemoved(const QModelIndex & /*parent*/, int first, int last){
        Q_EMIT sourcesRemoved(first, last);
    }
};

// ...
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("source_model", &source_model);
// ...
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    source_model.addSource(QUrl::fromLocalFile(it.next()));
}
// ...

// ...
Connections{
    target: source_model
    onSourcesInserted: playlist.insertItems(first, sources)
    onSourcesRemoved: playlist.removeItems(first, last);
    onReset: playlist.clear()
}
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
    }
}
// ...

Another option is to use a Q_PROPERTY:

class SourceManager: public QObject{
    Q_OBJECT
    Q_PROPERTY(QList<QUrl> sources READ sources  WRITE setSources  NOTIFY sourcesChanged)
public:
    using QObject::QObject;
    QList<QUrl> sources() const{
        return m_sources;
    }
    void setSources(QList<QUrl> sources){
        if (m_sources == sources)
            return;
        m_sources = sources;
        emit sourcesChanged();
    }
Q_SIGNALS:
    void sourcesChanged();
private:
    QList<QUrl> m_sources;
};
// ...
SourceManager source_manager;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("source_manager", &source_manager);
// ...
QList<QUrl> sources;
QString folder = "E:/"
QDirIterator it(folder, QStringList() << "*.mp3", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
    sources << QUrl::fromLocalFile(it.next());
}
source_manager.setSources(sources);
// ...

// ...
Connections{
    target: source_manager
    onSourcesChanged: {
        playlist.clear();
        playlist.addItems(source_manager.sources)
    }
}
Audio {
    id: player;
    playlist: Playlist {
        id: playlist
    }
}
// ...


问:
How to find any file within a Directory of a Zipfile
I'm setting up a function where I collect a list of apk files, then inside a For-loop, I declare a ZipFile intense to check the ABI Directories under the lib folder, by checking if any file ends with ".so". The only option I can solution I can think of is to use regex String expressions

I've made several regex expression attempts with \b, [A-Za-z-0-9]*, but I keep getting NullPointerException. I researched solutions for using regex with File names, but not really cases for ZipFile and ZipEntry classes. At the moment, here is my current approach with Regex. (Sometimes the regex expressions make my head spin.)

```<code>public void createAPKList() throws ZipException, IOException {
    apkFileList =  new File("C:/eclipse/workspace/Appium-Side-Project/APKDir/APKFiles").listFiles();
    System.out.println(apkFileList[apkFileList.length-1].getPath());
    apkInstallOptions = storeAndSortFiles(apkFileList, apkInstallOptions);
}

private HashMap<String, File> storeAndSortFiles(File[] fileList, HashMap<String, File> storageList) throws ZipException, IOException{
    ZipFile apkDetails;
    //Example of calling specific ABI
    String aBI = "armeabi-v7a/";
    String patternStr = "^lib/"+aBI+"[(.*)].so$";
    for(File apk : fileList) {

        //how to initialize ZipEntry to assign the any file that ends with ".so" ?
        apkDetails = new ZipFile(apk);
        ZipEntry readFolders = apkDetails.getEntry(patternStr);
        System.out.println(readFolders.getName().startsWith("lib/armeabi-v7a/"));

    }
    return storageList;
}
</code>```

The current solution gives a NullPointerException since the ZipEntry value is null. I'm not sure if the error is from my regex expression or the expression is working, but for cases where more than one ".so" exists in the directory. Is it even possible to use Regex in ZipFile/ZipEntry?

答:
In a word: No.

Patterns are not supported, and in fact there is nothing in the documentation that implies a pattern is allowed.  You must iterate through all entries in the ZipFile, and check whether each one matches:

```<code>Enumeration<? extends ZipEntry> entries = apkDetails.entries();
while (entries.hasMoreElements()) {
    ZipEntry entry = entries.nextElement();
    String name = entry.getName();
    if (entry.startsWith("lib/armeabi-v7a/") && entry.endsWith(".so")) {
        // Matching entry found.
    }
}
</code>```

There’s an old saying that when one decides to solve a problem with regular expressions, one goes from having one problem to having two problems.  It’s best not to use regular expressions if you don’t need them.  In your case, startsWith and endsWith are sufficient.

I’m not sure if you need to do something with the matching entries, or if you just want to check for their existence.  If it’s the latter case, you can simplify the code using a Stream:

```<code>boolean hasMatchingEntries =
    apiDetails.stream().map(ZipEntry::getName).anyMatch(
        name -> name.startsWith("lib/armeabi-v7a/") && name.endsWith(".so"));
</code>```

Body:
I'm setting up a function where I collect a list of apk files, then inside a For-loop, I declare a ZipFile intense to check the ABI Directories under the lib folder, by checking if any file ends with ".so". The only option I can solution I can think of is to use regex String expressions

I've made several regex expression attempts with \b, [A-Za-z-0-9]*, but I keep getting NullPointerException. I researched solutions for using regex with File names, but not really cases for ZipFile and ZipEntry classes. At the moment, here is my current approach with Regex. (Sometimes the regex expressions make my head spin.)

public void createAPKList() throws ZipException, IOException {
    apkFileList =  new File("C:/eclipse/workspace/Appium-Side-Project/APKDir/APKFiles").listFiles();
    System.out.println(apkFileList[apkFileList.length-1].getPath());
    apkInstallOptions = storeAndSortFiles(apkFileList, apkInstallOptions);
}

private HashMap<String, File> storeAndSortFiles(File[] fileList, HashMap<String, File> storageList) throws ZipException, IOException{
    ZipFile apkDetails;
    //Example of calling specific ABI
    String aBI = "armeabi-v7a/";
    String patternStr = "^lib/"+aBI+"[(.*)].so$";
    for(File apk : fileList) {

        //how to initialize ZipEntry to assign the any file that ends with ".so" ?
        apkDetails = new ZipFile(apk);
        ZipEntry readFolders = apkDetails.getEntry(patternStr);
        System.out.println(readFolders.getName().startsWith("lib/armeabi-v7a/"));

    }
    return storageList;
}

The current solution gives a NullPointerException since the ZipEntry value is null. I'm not sure if the error is from my regex expression or the expression is working, but for cases where more than one ".so" exists in the directory. Is it even possible to use Regex in ZipFile/ZipEntry?

Body:
In a word: No.

Patterns are not supported, and in fact there is nothing in the documentation that implies a pattern is allowed.  You must iterate through all entries in the ZipFile, and check whether each one matches:

Enumeration<? extends ZipEntry> entries = apkDetails.entries();
while (entries.hasMoreElements()) {
    ZipEntry entry = entries.nextElement();
    String name = entry.getName();
    if (entry.startsWith("lib/armeabi-v7a/") && entry.endsWith(".so")) {
        // Matching entry found.
    }
}

There’s an old saying that when one decides to solve a problem with regular expressions, one goes from having one problem to having two problems.  It’s best not to use regular expressions if you don’t need them.  In your case, startsWith and endsWith are sufficient.

I’m not sure if you need to do something with the matching entries, or if you just want to check for their existence.  If it’s the latter case, you can simplify the code using a Stream:

boolean hasMatchingEntries =
    apiDetails.stream().map(ZipEntry::getName).anyMatch(
        name -> name.startsWith("lib/armeabi-v7a/") && name.endsWith(".so"));


问:
Vuetify, v-data-table headers value purpose
What is the purpose of the value property in headers array of objects for v-data-table?

In the documentation it says

```<code>An array of objects that each describe a header column. See the example below for a definition of all properties.

{
  text: string",
  value: string",
  align: 'left' | 'center' | 'right'",
  sortable: boolean",
  class: string[] | string",
  width: string"
}
</code>```

But it never actually explains the purpose of it.

Does the header object just need a unique key or can I can someone use that value in the html?

答:
When you define that column as sortable: true, it is the value, and not the text, that will be set on the pagination object.

For instance, my column is called Created at (text), and it's value is created_at. This allows me to watch the pagination object, and send the order by data directly without an extra mapping step, as my API expects the value of orderBy to be either created_at or nothing.

Body:
What is the purpose of the value property in headers array of objects for v-data-table?

In the documentation it says

An array of objects that each describe a header column. See the example below for a definition of all properties.

{
  text: string",
  value: string",
  align: 'left' | 'center' | 'right'",
  sortable: boolean",
  class: string[] | string",
  width: string"
}

But it never actually explains the purpose of it.

Does the header object just need a unique key or can I can someone use that value in the html?


问:
Is it necessary to use GC::KeepAlive in C++/CLI when the managed handle is held in a managed container (IList<Foo^>)?
I'm confused about when I need to use KeepAlive in my C++/CLI wrapper code and how lifetimes are handled in it. Consider the following code and note the places where I ask whether KeepAlive is needed.</p>

```<code>// convert from managed to native string
inline std::string ToStdString(String^ source)
{
    if (String::IsNullOrEmpty(source))
        return std::string();

    int len = ((source->Length+1) * 2);

    /*** Do I need GC::KeepAlive(source) here? ***/

    char *ch = new char[ len ];
    bool result ;
    {
        pin_ptr<const wchar_t> wch = PtrToStringChars( source );
        result = wcstombs( ch, wch, len ) != -1;
    }
    std::string target = ch;
    delete ch;
    if(!result)
        throw gcnew Exception("error converting System::String to std::string");
    return target;
}

// convert from native to managed string
inline String^ ToSystemString(const std::string& source)
{
    return gcnew String(source.c_str());
}

// unmanaged C++ class
struct NativeDog
{
    std::string name;
    std::string bark() const {return "woof";}
    void eat(std::string& food) const {food.clear();}
};

typedef shared_ptr<NativeDog> NativeDogPtr;

// C++/CLI wrapper class
ref class ManagedDog
{
    NativeDogPtr* base_;
    NativeDog& base() {return **base_;}
    ManagedDog() {base_ = new NativeDogPtr(new NativeDog);}
    ~ManagedDog() {if (base_) delete base_;}
    !ManagedDog() {delete this;}

    property String^ name
    {
        String^ get() {return ToSystemString(base().name);}
        void set(String^ name)
        {
              base().name = ToStdString(name);
              /*** Do I need GC::KeepAlive(name) here? ***/
        }
    }

    String^ bark() {return ToSystemString(base().bark());}
    void eat(String^ food)
    {
         std::string nativeFood = ToStdString(food);
         base().eat(nativeFood);
         food = ToSystemString(nativeFood);
         /*** Do I need GC::KeepAlive(food) here? ***/
    }
};

// unmanaged C++ class
struct NativeKennel
{
    vector<NativeDogPtr> dogs;
};

// C++/CLI wrapper class
ref class ManagedKennel
{
    NativeKennel* base_;
    NativeKennel& base() {return *base_;}
    IList<ManagedDog^>^ dogs;
    void addDog(ManagedDog^ dog)
    {
        base().dogs.push_back(*dog->base_);
        dogs->Add(dog);
        /*** Do I need GC::KeepAlive(dog) here? Will the IList manage the ManagedDog lifetimes? ***/
    }
};
</code>```

答:
None of the above!

If you access managed classes in C++/CLI, KeepAlive won't help. You need to pin the data in memory to stop it from relocating afer a garbage collect. In all of these examples, this is done implicitly by the functions you call.

KeepAlive has a different goal. References stored on the stack are subject to garbage collection immediately after the last time the object is dereferenced. KeepAlive prevents this from happening, by extending the lifetime of your object until after the KeepAlive call.

Body:
I'm confused about when I need to use KeepAlive in my C++/CLI wrapper code and how lifetimes are handled in it. Consider the following code and note the places where I ask whether KeepAlive is needed.

// convert from managed to native string
inline std::string ToStdString(String^ source)
{
    if (String::IsNullOrEmpty(source))
        return std::string();

    int len = ((source->Length+1) * 2);

    /*** Do I need GC::KeepAlive(source) here? ***/

    char *ch = new char[ len ];
    bool result ;
    {
        pin_ptr<const wchar_t> wch = PtrToStringChars( source );
        result = wcstombs( ch, wch, len ) != -1;
    }
    std::string target = ch;
    delete ch;
    if(!result)
        throw gcnew Exception("error converting System::String to std::string");
    return target;
}

// convert from native to managed string
inline String^ ToSystemString(const std::string& source)
{
    return gcnew String(source.c_str());
}

// unmanaged C++ class
struct NativeDog
{
    std::string name;
    std::string bark() const {return "woof";}
    void eat(std::string& food) const {food.clear();}
};

typedef shared_ptr<NativeDog> NativeDogPtr;

// C++/CLI wrapper class
ref class ManagedDog
{
    NativeDogPtr* base_;
    NativeDog& base() {return **base_;}
    ManagedDog() {base_ = new NativeDogPtr(new NativeDog);}
    ~ManagedDog() {if (base_) delete base_;}
    !ManagedDog() {delete this;}

    property String^ name
    {
        String^ get() {return ToSystemString(base().name);}
        void set(String^ name)
        {
              base().name = ToStdString(name);
              /*** Do I need GC::KeepAlive(name) here? ***/
        }
    }

    String^ bark() {return ToSystemString(base().bark());}
    void eat(String^ food)
    {
         std::string nativeFood = ToStdString(food);
         base().eat(nativeFood);
         food = ToSystemString(nativeFood);
         /*** Do I need GC::KeepAlive(food) here? ***/
    }
};

// unmanaged C++ class
struct NativeKennel
{
    vector<NativeDogPtr> dogs;
};

// C++/CLI wrapper class
ref class ManagedKennel
{
    NativeKennel* base_;
    NativeKennel& base() {return *base_;}
    IList<ManagedDog^>^ dogs;
    void addDog(ManagedDog^ dog)
    {
        base().dogs.push_back(*dog->base_);
        dogs->Add(dog);
        /*** Do I need GC::KeepAlive(dog) here? Will the IList manage the ManagedDog lifetimes? ***/
    }
};