问:
Sorting nested Objects inside each other
I am having a hard time about inner sorting of nested objects. For example I have nested array object like below.

```<code>[
  {
    "project_id": "1155091124014397",
    "completed": [
       {
          "task_due_date": "2020-06-01",
       },
       {
          "task_due_date": "2020-20-01",
       },
       {
          "task_due_date": "2020-02-01",
       },
    ],
  },
  {
    "project_id": "1155091124012597",
    "completed": [
       {
          "task_due_date": "2020-22-01",
       },
       {
          "task_due_date": "2020-05-01",
       },
       {
          "task_due_date": "2020-01-01",
       },
    ],
  },
]
</code>```

So I am trying to sort each completed nested Array Object inside. But not to sure how to handle this. And tried something like below.

```<code>let sorted = array.map(element => {
   let nested = _.orderBy(element.completed, 'task_due_date');
   return nested
});

return sorted
</code>```

But not worked out.

expected results is

```<code>[
  {
    "project_id": "1155091124014397",
    "completed": [
       {
          "task_due_date": "2020-02-01",
       },
       {
          "task_due_date": "2020-06-01",
       },
       {
          "task_due_date": "2020-20-01",
       },
    ],
  },
  {
    "project_id": "1155091124012597",
    "completed": [
       {
          "task_due_date": "2020-01-01",
       },
       {
          "task_due_date": "2020-05-01",
       },
       {
          "task_due_date": "2020-22-01",
       },
    ],
  },
]
</code>```

Dates are sorted.

答:
First, you need to convert your date strings to date objects, and then you can sort based on those objects:

const arr = [
  {
    "project_id": "1155091124014397",
    "completed": [
       {
          "task_due_date": "2020-06-01",
       },
       {
          "task_due_date": "2020-20-01",
       },
       {
          "task_due_date": "2020-02-01",
       },
    ],
  },
  {
    "project_id": "1155091124012597",
    "completed": [
       {
          "task_due_date": "2020-22-01",
       },
       {
          "task_due_date": "2020-05-01",
       },
       {
          "task_due_date": "2020-01-01",
       },
    ],
  },
];

const toDate = dateStr => {
  const components = dateStr.split('-');
  const [year, date, month] = components;
  return new Date(`${year}-${month}-${date}`);
};

const sortByDate = (a, b) => {
  const aDate = toDate(a['task_due_date']);
  const bDate = toDate(b['task_due_date']);
  return aDate - bDate;
};

arr.forEach(el => {
  el.completed.sort(sortByDate);
});
console.log(arr);```

Body:
I am having a hard time about inner sorting of nested objects. For example I have nested array object like below.

[
  {
    "project_id": "1155091124014397",
    "completed": [
       {
          "task_due_date": "2020-06-01",
       },
       {
          "task_due_date": "2020-20-01",
       },
       {
          "task_due_date": "2020-02-01",
       },
    ],
  },
  {
    "project_id": "1155091124012597",
    "completed": [
       {
          "task_due_date": "2020-22-01",
       },
       {
          "task_due_date": "2020-05-01",
       },
       {
          "task_due_date": "2020-01-01",
       },
    ],
  },
]

So I am trying to sort each completed nested Array Object inside. But not to sure how to handle this. And tried something like below.

let sorted = array.map(element => {
   let nested = _.orderBy(element.completed, 'task_due_date');
   return nested
});

return sorted

But not worked out.

expected results is

[
  {
    "project_id": "1155091124014397",
    "completed": [
       {
          "task_due_date": "2020-02-01",
       },
       {
          "task_due_date": "2020-06-01",
       },
       {
          "task_due_date": "2020-20-01",
       },
    ],
  },
  {
    "project_id": "1155091124012597",
    "completed": [
       {
          "task_due_date": "2020-01-01",
       },
       {
          "task_due_date": "2020-05-01",
       },
       {
          "task_due_date": "2020-22-01",
       },
    ],
  },
]

Dates are sorted.


来源: stackexchange

问:
Angular ng-select load async data when (open) event is fired
I'm using ng-select custom server-side search to load data based on what the user types. Currently it only works if a keyword is actually pressed.

<ng-select [items]="filterValues$ | async"
    [typeahead]="filterValuesInput$"
    [multiple]="true"
    (open)="getFilterValues(pref.id)"
    [loading]="filterValuesLoading"
    bindLabel="name"
    [(ngModel)]="filter_values">
</ng-select>
```

<p>I want to trigger the API request when the select dropdown opens, <strong>even</strong> if no search term is provided.</p>

<pre class="lang-typescript prettyprint-override"><code>getFilterValues(filterId) {
    this.filterValues$ = concat(
      of([]), // default items
      this.filterValuesInput$.pipe(
        distinctUntilChanged(),
        tap(() => this.filterValuesLoading = true),
        switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
          map(res => res.filter_values),
          catchError(() => of([])), // empty list on error
          tap(() => this.filterValuesLoading = false)
        ))
      )
    );
}
</code>```

Any suggestions?

答:
This is happening because the concat is not emitting any value cause of the second observable. You can try using startWith operator for the initial loading

```<code>getFilterValues(filterId) {
    this.filterValues$ = concat(
      of([]), // default items
      this.filterValuesInput$.pipe(
        startWith(''),
        debounce(300),
        distinctUntilChanged(),
        tap(() => this.filterValuesLoading = true),
        switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
          map(res => res.filter_values),
          catchError(() => of([])), // empty list on error
          tap(() => this.filterValuesLoading = false)
        ))
      )
    );
}
</code>```

Hope this helps

ContentLicense: CC BY-SA 4.0

Body:
I'm using ng-select custom server-side search to load data based on what the user types. Currently it only works if a keyword is actually pressed.

<ng-select [items]="filterValues$ | async"
    [typeahead]="filterValuesInput$"
    [multiple]="true"
    (open)="getFilterValues(pref.id)"
    [loading]="filterValuesLoading"
    bindLabel="name"
    [(ngModel)]="filter_values">
</ng-select>

I want to trigger the API request when the select dropdown opens, even if no search term is provided.

getFilterValues(filterId) {
    this.filterValues$ = concat(
      of([]), // default items
      this.filterValuesInput$.pipe(
        distinctUntilChanged(),
        tap(() => this.filterValuesLoading = true),
        switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
          map(res => res.filter_values),
          catchError(() => of([])), // empty list on error
          tap(() => this.filterValuesLoading = false)
        ))
      )
    );
}

Any suggestions?

Body:
This is happening because the concat is not emitting any value cause of the second observable. You can try using startWith operator for the initial loading

getFilterValues(filterId) {
    this.filterValues$ = concat(
      of([]), // default items
      this.filterValuesInput$.pipe(
        startWith(''),
        debounce(300),
        distinctUntilChanged(),
        tap(() => this.filterValuesLoading = true),
        switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
          map(res => res.filter_values),
          catchError(() => of([])), // empty list on error
          tap(() => this.filterValuesLoading = false)
        ))
      )
    );
}

Hope this helps


问:
Scrolling through two snap points at once in Chrome
I'm working on a website that uses scroll snapping for 3 viewport-sized
 elements implemented like this:

html, body {
  scroll-behavior: smooth;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vh);
  scroll-snap-type: y mandatory;
}

section {
  height: 100vh;
  scroll-snap-align: start;
}

section:nth-of-type(1) {
  background-color: red;
}

section:nth-of-type(2) {
  background-color: green;
}

section:nth-of-type(3) {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <main>
    <section></section>
    <section></section>
    <section></section>
  </main>
</body></code>```

It works perfectly in Firefox but whenever I scroll in a Chromium-based browser it scrolls straight from the first section to the third. Any ideas for why this could happen?

答:
Update: How does this work out for you?

* {
    box-sizing: border-box;
}
html {
    scroll-snap-type: mandatory;
    scroll-snap-points-y: repeat(100vh);
    scroll-snap-type: y mandatory;
}
section {
    border-bottom: 1px solid white;
    height: 100vh;
    scroll-snap-align: start;
    scroll-snap-stop: always;
}

section:nth-of-type(1) {
  background-color: red;
}

section:nth-of-type(2) {
  background-color: green;
}

section:nth-of-type(3) {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <main>
    <section></section>
    <section></section>
    <section></section>
  </main>
</body></code>```

Body:
I'm working on a website that uses scroll snapping for 3 viewport-sized
 elements implemented like this:

html, body {
  scroll-behavior: smooth;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vh);
  scroll-snap-type: y mandatory;
}

section {
  height: 100vh;
  scroll-snap-align: start;
}

section:nth-of-type(1) {
  background-color: red;
}

section:nth-of-type(2) {
  background-color: green;
}

section:nth-of-type(3) {
  background-color: blue;
}

It works perfectly in Firefox but whenever I scroll in a Chromium-based browser it scrolls straight from the first section to the third. Any ideas for why this could happen?

Body:
Update: How does this work out for you?

* {
    box-sizing: border-box;
}
html {
    scroll-snap-type: mandatory;
    scroll-snap-points-y: repeat(100vh);
    scroll-snap-type: y mandatory;
}
section {
    border-bottom: 1px solid white;
    height: 100vh;
    scroll-snap-align: start;
    scroll-snap-stop: always;
}

section:nth-of-type(1) {
  background-color: red;
}

section:nth-of-type(2) {
  background-color: green;
}

section:nth-of-type(3) {
  background-color: blue;
}

<body>
  <main>
    <section></section>
    <section></section>
    <section></section>
  </main>
</body>


问:
Quickly checking if set is superset of stored sets

The problem

I am given N arrays of C booleans. I want to organize these into a datastructure that allows me to do the following operation as fast as possible: Given a new array, return true if this array is a "superset" of any of the stored arrays. With superset I mean this: A is a superset of B if A[i] is true for every i where B[i] is true. If B[i] is false, then A[i] can be anything.

Or, in terms of sets instead of arrays:

Store N sets (each with C possible elements) into a datastructure so you can quickly look up if a given set is a superset of any of the stored sets.

Building the datastructure can take as long as possible, but the lookup should be as efficient as possible, and the datastructure can't take too much space.

Some context

I think this is an interesting problem on its own, but for the thing I'm really trying to solve, you can assume the following:

N = 10000

C = 1000

The stored arrays are sparse

The looked up arrays are random (so not sparse)

What I've come up with so far

For O(NC) lookup: Just iterate all the arrays. This is just too slow though.

For O(C) lookup: I had a long description here, but as Amit pointed out in the comments, it was basically a BDD. While this has great lookup speed, it has an exponential number of nodes. With N and C so large, this takes too much space.

I hope that in between this O(N*C) and O(C) solution, there's maybe a O(log(N)*C) solution that doesn't require an exponential amount of space.

EDIT: A new idea I've come up with

For O(sqrt(N)C) lookup: Store the arrays as a prefix trie. When looking up an array A, go to the appropriate subtree if A[i]=0, but visit both subtrees if A[i]=1.

My intuition tells me that this should make the (average) complexity of the lookup O(sqrt(N)C), if you assume that the stored arrays are random. But: 1. they're not, the arrays are sparse. And 2. it's only intuition, I can't prove it.

I will try out both this new idea and the BDD method, and see which of the 2 work out best.

But in the meantime, doesn't this problem occur more often? Doesn't it have a name? Hasn't there been previous research? It really feels like I'm reinventing the wheel here.

答:
Building on the trie solution and the paper mentioned by @mmihaltz, it is also possible to implement a method to find subsets by using already existing efficient trie implementations for python. Below I use the package datrie. The only downside is that the keys must be converted to strings, which can be done with "".join(chr(i) for i in myset). This, however, limits the range of elements to about 110000.

```<code>from datrie import BaseTrie, BaseState

def existsSubset(trie, setarr, trieState=None):

    if trieState is None:
        trieState = BaseState(trie)

    trieState2 = BaseState(trie)
    trieState.copy_to(trieState2)
    for i, elem in enumerate(setarr):
        if trieState2.walk(elem):
            if trieState2.is_terminal() or existsSubset(trie, setarr[i:], trieState2):
                return True
            trieState.copy_to(trieState2)
    return False

</code>```

The trie can be used like dictionary, but the range of possible elements has to be provided at the beginning:

```<code>alphabet = "".join(chr(i) for i in range(100))
trie = BaseTrie(alphabet)

for subset in sets:
   trie["".join(chr(i) for i in subset)] = 0 # the assigned value does not matter

</code>```

Note that the trie implementation above works only with keys larger than (and not equal to) 0. Otherwise, the integer to character mapping does not work properly. This problem can be solved with an index shift.

A cython implementation that also covers the conversion of elements can be found here.

ContentLicense: CC BY-SA 3.0

Body:
Building on the trie solution and the paper mentioned by @mmihaltz, it is also possible to implement a method to find subsets by using already existing efficient trie implementations for python. Below I use the package datrie. The only downside is that the keys must be converted to strings, which can be done with "".join(chr(i) for i in myset). This, however, limits the range of elements to about 110000.

from datrie import BaseTrie, BaseState

def existsSubset(trie, setarr, trieState=None):

    if trieState is None:
        trieState = BaseState(trie)

    trieState2 = BaseState(trie)
    trieState.copy_to(trieState2)
    for i, elem in enumerate(setarr):
        if trieState2.walk(elem):
            if trieState2.is_terminal() or existsSubset(trie, setarr[i:], trieState2):
                return True
            trieState.copy_to(trieState2)
    return False

The trie can be used like dictionary, but the range of possible elements has to be provided at the beginning:

alphabet = "".join(chr(i) for i in range(100))
trie = BaseTrie(alphabet)

for subset in sets:
   trie["".join(chr(i) for i in subset)] = 0 # the assigned value does not matter

Note that the trie implementation above works only with keys larger than (and not equal to) 0. Otherwise, the integer to character mapping does not work properly. This problem can be solved with an index shift.

A cython implementation that also covers the conversion of elements can be found here.


问:
Console shows me a ExpressionChangedAfterItHasBeenCheckedError in Angular 7
Working with my angular project, i`ve added a filter of date range (with a from date and to date) in a widget, when my system starts the filters must to have the first day of current month and the current date, it is working but the console shows me the following message.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'fromDate: undefined'. Current value: 'fromDate: Mon Jun 01 2020 21:17:17 GMT-0400 (hora estándar de Chile)'.

The line in my template of component is the following:

```<code> <div class="range-date"  *ngIf = "item?.id === this.widgetEnum.process">
                    <app-range-date [enableInitDate]="true" [(fromDate)]="item.fromDate" [(toDate)]="item.toDate" (dateChange)="changeDateProcess(item)"></app-range-date>
                  </div>
</code>```

please can you give me so kind of the idea regarding with it?

答:
You have two way binding on toDate and fromDate. This is fine, but you also have an input (dateChange) which I assume will also affect the toDate and fromDate variables in the component (not sure without component class code). You can only do one or the other. remove either (dateChange) or make it a one way binding

```<code><div class="range-date"  *ngIf = "item?.id === this.widgetEnum.process">
                <app-range-date [enableInitDate]="true" [(fromDate)]="item.fromDate" [(toDate)]="item.toDate"></app-range-date>
              </div>
</code>```

OR

```<code><div class="range-date"  *ngIf = "item?.id === this.widgetEnum.process">
                <app-range-date [enableInitDate]="true" [fromDate]="item.fromDate" [toDate]="item.toDate" (dateChange)="changeDateProcess(item)"></app-range-date>
              </div>
</code>```

Body:
Working with my angular project, i`ve added a filter of date range (with a from date and to date) in a widget, when my system starts the filters must to have the first day of current month and the current date, it is working but the console shows me the following message.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'fromDate: undefined'. Current value: 'fromDate: Mon Jun 01 2020 21:17:17 GMT-0400 (hora estándar de Chile)'.

The line in my template of component is the following:

                    <app-range-date [enableInitDate]="true" [(fromDate)]="item.fromDate" [(toDate)]="item.toDate" (dateChange)="changeDateProcess(item)"></app-range-date>

please can you give me so kind of the idea regarding with it?

Body:
You have two way binding on toDate and fromDate. This is fine, but you also have an input (dateChange) which I assume will also affect the toDate and fromDate variables in the component (not sure without component class code). You can only do one or the other. remove either (dateChange) or make it a one way binding

<div class="range-date"  *ngIf = "item?.id === this.widgetEnum.process">
                <app-range-date [enableInitDate]="true" [(fromDate)]="item.fromDate" [(toDate)]="item.toDate"></app-range-date>
              </div>

OR

<div class="range-date"  *ngIf = "item?.id === this.widgetEnum.process">
                <app-range-date [enableInitDate]="true" [fromDate]="item.fromDate" [toDate]="item.toDate" (dateChange)="changeDateProcess(item)"></app-range-date>
              </div>


问:
Blazor - Compare Previous and Next State
I have a table of students in Blazor, which is coming from an api, and I am also receiving a pushed data to update the students info which is basically the score upon a change in the database, the push is working fine and the score is being updated but I also want to change the background colour of the field that has been updated in the table upon a change in the score to red just the td tag for few sec, my code is as follow:

```<code>@foreach(var student in SS.GetStudents()){
     <tr>
          <td> student.name </>
          <td> student.section </>
          // trying to compare between the previous and next state
          var stud = SS.GetStuentsCopy().SingleOrDefault(s =>s.Id == student.Id);
          var color = "";
          if(stud.score != student.score){
            color = red;
           }
          <td class="@color"> student.score </>
     </tr>
  }

   @code{
         [Inject]
         public StudentsStates SS { get; set;}
         public StudentsResponse Students { get; set; }
         protected override async Task OnInitializedAsync()
         {
              // Subscribe to the StateChanged EventHandler
               SS.StateChanged +=
               SSAdvancedStateChanged;

          Students = await Service.GetStudents();
         // update the students and the copy together
          SS.UpdateStudents(Students)
          SS.UpdateStudentsCopy(Students)

       //upon receiving students updated score
                hubConnection = new HubConnectionBuilder()
        .WithUrl(NavigationManager.ToAbsoluteUri("/studhub"))
        .Build();

        hubConnection.On<StudentsResponse>("ReceiveMessage", s =>
        {
            // update the students after 3 sec update the copy
            SS.UpdateStudents(s);

           //Here the state is not being updated
           // unless there is a new push
           // or the issue might be in rendering
           // FYI without the sleep also I can see the changes in the color
            System.Threading.Thread.Sleep(3000);
            SS.UpdateStudentsCopy(s);

        }

      }}
</code>```

StudentsStates.cs

```<code>namespace Ctrl.Web.Data
{
    public class StudentsStates
    {

        public StudentsResponse Students { get; set; }
        public StudentsResponse StudentsCopy { get; set; }
        public StudentsResponse GetStudents(){return Students;}
        public StudentsResponse GetStudentsCopy(){return StudentsCopy;}
        public void UpdateStudents(Students students){ Students = students;}
        public void UpdateStudentsCopy(Students students){ StudentsCopy = students;}

}}
</code>```

As I said above everything is working fine except when there is a multiple push in a sec, the first pushed student score's background color is being changed too fast, sometimes u won't even notice it because of the pushed data and state is being updated, what I want is to slow down the background color without effecting the next pushed student score or if there is a better approach to this scenario, your answers are highly appreciated.

答:
I would suggest creating a component for the student row as follow:

```<code>@foreach(var student in SS.GetStudents())
{
      <StudentRow Student={student} />
}
</code>```

Then inside the StudentRow component u can create a new private student variable where u update it after a delay of 3sec and do the comparison there, Instead of saving the ids in a list or in another copy:

StudentRow.razor

```<code>  <tr>
      <td> Student.name </>
      <td> Student.section </>
      var color = "";
      if(StudentCopy.score != Student.score){
        color = red;
       }
      <td class="@color"> student.score </>
 </tr>
 @code{
         public StudentResponse StudentCopy { get; set; }
         [Parameter]
         public StudentResponse Student { get; set; }

         protected override async Task OnParametersSetAsync()
         {
          await Task.Delay(3000);
          StudentCopy = Student;

         }
      }
</code>```

OnParametersSetAsync method invoked when the component has received parameters from its parent in the render tree, and the incoming values have been assigned to properties. Read more here

Body:
I have a table of students in Blazor, which is coming from an api, and I am also receiving a pushed data to update the students info which is basically the score upon a change in the database, the push is working fine and the score is being updated but I also want to change the background colour of the field that has been updated in the table upon a change in the score to red just the td tag for few sec, my code is as follow:

@foreach(var student in SS.GetStudents()){

           student.name </>
           student.section </>
          // trying to compare between the previous and next state
          var stud = SS.GetStuentsCopy().SingleOrDefault(s =>s.Id == student.Id);
          var color = "";
          if(stud.score != student.score){
            color = red;
           }
           student.score </>

  }

   @code{
         [Inject]
         public StudentsStates SS { get; set;}
         public StudentsResponse Students { get; set; }
         protected override async Task OnInitializedAsync()
         {
              // Subscribe to the StateChanged EventHandler
               SS.StateChanged +=
               SSAdvancedStateChanged;

          Students = await Service.GetStudents();
         // update the students and the copy together
          SS.UpdateStudents(Students)
          SS.UpdateStudentsCopy(Students)

       //upon receiving students updated score
                hubConnection = new HubConnectionBuilder()
        .WithUrl(NavigationManager.ToAbsoluteUri("/studhub"))
        .Build();

        hubConnection.On<StudentsResponse>("ReceiveMessage", s =>
        {
            // update the students after 3 sec update the copy
            SS.UpdateStudents(s);

           //Here the state is not being updated
           // unless there is a new push
           // or the issue might be in rendering
           // FYI without the sleep also I can see the changes in the color
            System.Threading.Thread.Sleep(3000);
            SS.UpdateStudentsCopy(s);

        }

      }}

StudentsStates.cs

namespace Ctrl.Web.Data
{
    public class StudentsStates
    {

        public StudentsResponse Students { get; set; }
        public StudentsResponse StudentsCopy { get; set; }
        public StudentsResponse GetStudents(){return Students;}
        public StudentsResponse GetStudentsCopy(){return StudentsCopy;}
        public void UpdateStudents(Students students){ Students = students;}
        public void UpdateStudentsCopy(Students students){ StudentsCopy = students;}

}}

As I said above everything is working fine except when there is a multiple push in a sec, the first pushed student score's background color is being changed too fast, sometimes u won't even notice it because of the pushed data and state is being updated, what I want is to slow down the background color without effecting the next pushed student score or if there is a better approach to this scenario, your answers are highly appreciated.

Body:
I would suggest creating a component for the student row as follow:

@foreach(var student in SS.GetStudents())
{
      <StudentRow Student={student} />
}

Then inside the StudentRow component u can create a new private student variable where u update it after a delay of 3sec and do the comparison there, Instead of saving the ids in a list or in another copy:

StudentRow.razor

  <tr>
      <td> Student.name </>
      <td> Student.section </>
      var color = "";
      if(StudentCopy.score != Student.score){
        color = red;
       }
      <td class="@color"> student.score </>
 </tr>
 @code{
         public StudentResponse StudentCopy { get; set; }
         [Parameter]
         public StudentResponse Student { get; set; }

         protected override async Task OnParametersSetAsync()
         {
          await Task.Delay(3000);
          StudentCopy = Student;

         }
      }

OnParametersSetAsync method invoked when the component has received parameters from its parent in the render tree, and the incoming values have been assigned to properties. Read more here


问:
Kivy: how to set the focus on the next inputbox?
I want to create a login screen, but I have a problem to set the focus on the second inputbox. When I fill in the username and hit enter, the password field never get the focus, so I can’t fill in the password, never... I don’t see the problem..

Can anyone help me out?

This is my signin.kv file:

```<code><FlatButton@ButtonBehavior+Label>:
font_size: 16

<SigninWindow>:
    id: main_win
    orientation: "vertical"
    spacing: 10
    space_x: self.size[0]/3
    canvas.before:
    Color:
        rgba: (1,1,1, 1)
    Rectangle:
        size: self.size
        pos: self.pos

BoxLayout:
    size_hint_y: None
    height: 50
    canvas.before:
        Color:
            rgba: (.06, .45, .45, 1)
        Rectangle:
            size: self.size
            pos: self.pos
    Label:
        text: "Access Control"
        bold: True
        size_hint_x: .9
    FlatButton:
        text: "x"
        size_hint_x: .1
BoxLayout:
    orientation: 'vertical'
    padding: main_win.space_x, 10
    #spacing: 20
    BoxLayout:
        orientation: "vertical"
        spacing: 10
        size_hint_y: None
        height: 100
        Label:
            id: info
            text: ''
            markup: True
            size_hint_y: None
            height: 20
        TextInput:
            id: username_field
            hint_text: "Username"
            multiline: False
            focus: True
            on_text_validate: pwd_field.focus = True
        TextInput:
            id: pwd_field
            hint_text: "Password"
            multiline: False
            password: True
            on_text_validate: root.validate_user()
    Label:
        id: sp
        size_hint_y: None
        height: 40
    Button:
        text: "Sign In"
        size_hint_y: None
        height: 40
        background_color: (.06,.45,.45, 1)
        background_normal: ''
        on_release: root.validate_user()
    Label:
        id: sp2
</code>```

This is my signin.py file:

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class SigninWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def validate_user(self):
        user = self.ids.username_field
        pwd = self.ids.pwd_field
        info = self.ids.info

        uname = user.text
        passw = pwd.text

        if uname == '' or passw == '':
            info.text = '[color=#FF0000]username and/ or password required[/color]'
        else:
            if uname == 'admin' and passw == 'admin':
                info.text = '[color=#00FF00]Logged In successfully!!![/color]'
            else:
                info.text = '[color=#FF0000]Invalid Username and/or Password[/color]'
class SigninApp(App):
    def build(self):
        return SigninWindow()

if __name__=="__main__":
    sa = SigninApp()
    sa.run()
</code>```

答:
```<code>TextInput:
    id: username_field
    hint_text: "Username"
    multiline: False
    focus: True
    on_text_validate: password_field.focus = True
TextInput:
    id: password_field
    hint_text: "Password"
    multiline: False
    password: True
</code>```

Body:
I want to create a login screen, but I have a problem to set the focus on the second inputbox. When I fill in the username and hit enter, the password field never get the focus, so I can’t fill in the password, never... I don’t see the problem..

Can anyone help me out?

This is my signin.kv file:

<FlatButton@ButtonBehavior+Label>:
font_size: 16

<SigninWindow>:
    id: main_win
    orientation: "vertical"
    spacing: 10
    space_x: self.size[0]/3
    canvas.before:
    Color:
        rgba: (1,1,1, 1)
    Rectangle:
        size: self.size
        pos: self.pos

BoxLayout:
    size_hint_y: None
    height: 50
    canvas.before:
        Color:
            rgba: (.06, .45, .45, 1)
        Rectangle:
            size: self.size
            pos: self.pos
    Label:
        text: "Access Control"
        bold: True
        size_hint_x: .9
    FlatButton:
        text: "x"
        size_hint_x: .1
BoxLayout:
    orientation: 'vertical'
    padding: main_win.space_x, 10
    #spacing: 20
    BoxLayout:
        orientation: "vertical"
        spacing: 10
        size_hint_y: None
        height: 100
        Label:
            id: info
            text: ''
            markup: True
            size_hint_y: None
            height: 20
        TextInput:
            id: username_field
            hint_text: "Username"
            multiline: False
            focus: True
            on_text_validate: pwd_field.focus = True
        TextInput:
            id: pwd_field
            hint_text: "Password"
            multiline: False
            password: True
            on_text_validate: root.validate_user()
    Label:
        id: sp
        size_hint_y: None
        height: 40
    Button:
        text: "Sign In"
        size_hint_y: None
        height: 40
        background_color: (.06,.45,.45, 1)
        background_normal: ''
        on_release: root.validate_user()
    Label:
        id: sp2

This is my signin.py file:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class SigninWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def validate_user(self):
        user = self.ids.username_field
        pwd = self.ids.pwd_field
        info = self.ids.info

        uname = user.text
        passw = pwd.text

        if uname == '' or passw == '':
            info.text = '[color=#FF0000]username and/ or password required[/color]'
        else:
            if uname == 'admin' and passw == 'admin':
                info.text = '[color=#00FF00]Logged In successfully!!![/color]'
            else:
                info.text = '[color=#FF0000]Invalid Username and/or Password[/color]'
class SigninApp(App):
    def build(self):
        return SigninWindow()

if __name__=="__main__":
    sa = SigninApp()
    sa.run()


问:
Qr code scanner with webview
I have an app that scans qr code. The app returns the url in a string named value. I want to open the url in a webview. How can I call the WebViewActivity in CameraTestActivity the the WebViewActivity uses the url from the CameraTestActvity for loading the website. There are comments in the code for the things I want to do but I do not know how.  Can you please help me? I may be not able to graduate because of this problem? I've been doing this for days.

CameraTestActivity.java

```<code>import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
/* Import ZBar Class files */

@SuppressLint("SetJavaScriptEnabled")
public class CameraTestActivity extends Activity
{
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    TextView scanText;
    Button scanButton;
    Button exitButton;
    WebView web;

    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

        scanText = (TextView)findViewById(R.id.scanText);

        scanButton = (Button)findViewById(R.id.ScanButton);

        scanButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (barcodeScanned) {
                        barcodeScanned = false;
                        scanText.setText("Place code inside the square to scan");
                        mCamera.setPreviewCallback(previewCb);
                        mCamera.startPreview();
                        previewing = true;
                        mCamera.autoFocus(autoFocusCB);

                    }
                }
            });

        exitButton = (Button)findViewById(R.id.ExitButton);

        exitButton.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            System.exit(0);
        }
    });

    }

    public void onPause() {
            super.onPause();

            if (mCamera != null) {
                mCamera.setPreviewCallback(null);
                mPreview.getHolder().removeCallback(mPreview);   // you need this line
                releaseCamera();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Get the Camera instance as the activity achieves full user focus
        try {
            mCamera = Camera.open();
            mCamera.setPreviewCallback(null);
            mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
            FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
            preview.addView(mPreview);
            mCamera.startPreview();
        } catch (Exception e) {

        }

}

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);

                if (result != 0) {
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();

                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {

                      String value = new String(sym.getData()); //url scanned from the qr code
                      if(value.startsWith("http://192.168.1.6")){ //if the url starts with

                      scanText.setText("QR Code result: " + value);
                        barcodeScanned = true;
                        //intent for WebViewActivty.java
                        //The WebViewActivty.java should load the string value which contains the the url

                      }
                      else{
                          scanText.setText("QR Code result 2: " + value);
                          barcodeScanned = true;
                          }
                       TextView tv = (TextView) findViewById(R.id.scanText);
                        tv.setMovementMethod(LinkMovementMethod.getInstance());

                    }

                }

            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };

        private void releaseCamera(){
            if (mCamera != null){
                mCamera.release();        // release the camera for other applications
                mCamera = null;
            }
        }
}
</code>```

WebViewActivity.java

```<code>    package net.sourceforge.zbar.android.CameraTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity {

    private WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        webView = (WebView) findViewById(R.id.web_engine);
        webView.setWebViewClient(new MyWebClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://192.168.1.6/sp/products.php");//the link should be from the CameraTestActivity

    }
}
 class MyWebClient extends WebViewClient {
     @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            return false;

        }
 }
</code>```

答:
if you use ('me.dm7.barcodescanner:zxing:1.9') library. So just follow this. Hope it works for you also.

```<code>   Intent newWindow = new Intent(getApplicationContext(), Browser.class);
            newWindow.putExtra("scannedLink", myResult);
            startActivity(newWindow);
</code>```

Happy Coding

Title: Qr code scanner with webview

Body:
I have an app that scans qr code. The app returns the url in a string named value. I want to open the url in a webview. How can I call the WebViewActivity in CameraTestActivity the the WebViewActivity uses the url from the CameraTestActvity for loading the website. There are comments in the code for the things I want to do but I do not know how.  Can you please help me? I may be not able to graduate because of this problem? I've been doing this for days.

CameraTestActivity.java

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
/* Import ZBar Class files */

@SuppressLint("SetJavaScriptEnabled")
public class CameraTestActivity extends Activity
{
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    TextView scanText;
    Button scanButton;
    Button exitButton;
    WebView web;

    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

        scanText = (TextView)findViewById(R.id.scanText);

        scanButton = (Button)findViewById(R.id.ScanButton);

        scanButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (barcodeScanned) {
                        barcodeScanned = false;
                        scanText.setText("Place code inside the square to scan");
                        mCamera.setPreviewCallback(previewCb);
                        mCamera.startPreview();
                        previewing = true;
                        mCamera.autoFocus(autoFocusCB);

                    }
                }
            });

        exitButton = (Button)findViewById(R.id.ExitButton);

        exitButton.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            System.exit(0);
        }
    });

    }

    public void onPause() {
            super.onPause();

            if (mCamera != null) {
                mCamera.setPreviewCallback(null);
                mPreview.getHolder().removeCallback(mPreview);   // you need this line
                releaseCamera();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Get the Camera instance as the activity achieves full user focus
        try {
            mCamera = Camera.open();
            mCamera.setPreviewCallback(null);
            mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
            FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
            preview.addView(mPreview);
            mCamera.startPreview();
        } catch (Exception e) {

        }

}

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);

                if (result != 0) {
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();

                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {

                      String value = new String(sym.getData()); //url scanned from the qr code
                      if(value.startsWith("http://192.168.1.6")){ //if the url starts with

                      scanText.setText("QR Code result: " + value);
                        barcodeScanned = true;
                        //intent for WebViewActivty.java
                        //The WebViewActivty.java should load the string value which contains the the url

                      }
                      else{
                          scanText.setText("QR Code result 2: " + value);
                          barcodeScanned = true;
                          }
                       TextView tv = (TextView) findViewById(R.id.scanText);
                        tv.setMovementMethod(LinkMovementMethod.getInstance());

                    }

                }

            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };

        private void releaseCamera(){
            if (mCamera != null){
                mCamera.release();        // release the camera for other applications
                mCamera = null;
            }
        }
}

WebViewActivity.java

    package net.sourceforge.zbar.android.CameraTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity {

    private WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        webView = (WebView) findViewById(R.id.web_engine);
        webView.setWebViewClient(new MyWebClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://192.168.1.6/sp/products.php");//the link should be from the CameraTestActivity

    }
}
 class MyWebClient extends WebViewClient {
     @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            return false;

        }
 }

Body:
if you use ('me.dm7.barcodescanner:zxing:1.9') library. So just follow this. Hope it works for you also.

   Intent newWindow = new Intent(getApplicationContext(), Browser.class);
            newWindow.putExtra("scannedLink", myResult);
            startActivity(newWindow);

Happy Coding


问:
how to add a variable inside of a label in Tkinter?
In a normal print statement, I am able to put in a variable inside the statement like :

```<code>x=1
print("x is equal to" x)
</code>```

But how would I be able to write the same thing in tkinter?

```<code>x=2
label1 = Label(text="x is equal to " x)
</code>```

that's what my line of code looks like right now. any help will be appreciated, thanks

答:
You need to make x a str so as to avoid concatenation of str and int error.

```<code>x=2
label1 = Label(......,text="x is equal to "+ str(x))
</code>```

or you can make it a str in the first itself

```<code>x = '2'
label1 = Label(.....,text="x is equal to "+x)
</code>```

or you can also use formatted string (f'...') in python 3.x and use {} to dynamically enter values

```<code>x = 2
label1 = Label(.....,text=f"x is equal to {str(x)}")
</code>```

Body:
In a normal print statement, I am able to put in a variable inside the statement like :

x=1
print("x is equal to" x)

But how would I be able to write the same thing in tkinter?

x=2
label1 = Label(text="x is equal to " x)

that's what my line of code looks like right now. any help will be appreciated, thanks

Body:
You need to make x a str so as to avoid concatenation of str and int error.

x=2
label1 = Label(......,text="x is equal to "+ str(x))

or you can make it a str in the first itself

x = '2'
label1 = Label(.....,text="x is equal to "+x)

or you can also use formatted string (f'...') in python 3.x and use {} to dynamically enter values

x = 2
label1 = Label(.....,text=f"x is equal to {str(x)}")


问:
How to sort a list of strings?
What is the best way of creating an alphabetically sorted list in Python?</p>

答:
It is simple:
https://trinket.io/library/trinkets/5db81676e4

```<code>scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'
</code>```

scores = scores.split(',')
for x in sorted(scores):
  print(x)

OwnerDisplayName: ziobro

Title: How to sort a list of strings?

Body:
It is simple:
https://trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

scores = scores.split(',')
for x in sorted(scores):
  print(x)


问:
xpath expression to find either one type of element or another
I am trying to get either a parent li or tr from an element with specific text.

As it stands I am just trying different separate xpath expressions, but I am curious if I can just make one that goes something like this:

```<code>'//[tr | li]//*[contains(text(), "Some Text")]'
</code>```

or

```<code>'//*[contains(text(), "Some Text")]/[ancestor::tr | ancestor::li]'
</code>```

I have found that I can just string the statements together like so:

```<code>'//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]'
</code>```

but that isn't ideal either.

答:
Assuming the following XPath is your desired expression :

```<code>//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]
</code>```

You can do :

```<code>(//tr|//li)[.//*[contains(text(), "Some Text")]]
</code>```

Body:
I am trying to get either a parent li or tr from an element with specific text.

As it stands I am just trying different separate xpath expressions, but I am curious if I can just make one that goes something like this:

'//[tr | li]//*[contains(text(), "Some Text")]'

or

'//*[contains(text(), "Some Text")]/[ancestor::tr | ancestor::li]'

I have found that I can just string the statements together like so:

'//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]'

but that isn't ideal either.

Body:
Assuming the following XPath is your desired expression :

//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]

You can do :

(//tr|//li)[.//*[contains(text(), "Some Text")]]


问:
JS: detect a dom mutation of a watched div (or change-event-listener to innerHTML)
:)

I'm using the NicEdit WYSIWYG editor. The DIV is patched with a hidden textarea field.

The problem is that all changes are just synced onSubmit().

Now I need a way to listen for changes. For example to change backgound color of the field on changing content (inputs) (flagged as unsaved). But there is no addEventListener for changed InnerHTML, as far as I know.
So maybe it's possible to use a callback function like a domMutationObserver. But I have no ideas how to deal with that.

js code:

```<code>let domField = document.querySelector('.contents .subpage[data-pagename="Index"][data-culture="en-US"] .nicEdit-main');
</code>```

I can detect the selector of the editor div. So how to detect changes inside this element/node?

I read something about an "observer" to detect dom mutations. Maybe somebody can give me a simple and easy example.

Thx for everything. ;)

EDIT: And I hope we all agree that I won't set an interval (just to save browser performance). But yeah that could be a way. So watching for mutations or changing innerHTML of my DIV element.

pseudo code:

```<code>domElement.innerHTML.watch('change', elem => {
    elem.classList.add('changed'); //or unsaved
});
</code>```

答:
maybe Proxy could solve it.when some properties of style has changed,set will invoke.

    var app = document.getElementById('app')
    var handle = {
      get(target, property, value, receive) {
        return target[property]
      },
      set(target, property, value, receive) {
        // callback()
        Reflect.set(target, property, value)
      }
    }
    var a = new Proxy(app, handle)
    a.innerHTML = 2
    a.style.background = "red"
    a.style.height = "200px"
    a.style.width = "200px"
```

Body:
:)

I'm using the NicEdit WYSIWYG editor. The DIV is patched with a hidden textarea field.

The problem is that all changes are just synced onSubmit().

Now I need a way to listen for changes. For example to change backgound color of the field on changing content (inputs) (flagged as unsaved). But there is no addEventListener for changed InnerHTML, as far as I know.
So maybe it's possible to use a callback function like a domMutationObserver. But I have no ideas how to deal with that.

js code:

let domField = document.querySelector('.contents .subpage[data-pagename="Index"][data-culture="en-US"] .nicEdit-main');

I can detect the selector of the editor div. So how to detect changes inside this element/node?

I read something about an "observer" to detect dom mutations. Maybe somebody can give me a simple and easy example.

Thx for everything. ;)

EDIT: And I hope we all agree that I won't set an interval (just to save browser performance). But yeah that could be a way. So watching for mutations or changing innerHTML of my DIV element.

pseudo code:

domElement.innerHTML.watch('change', elem => {
    elem.classList.add('changed'); //or unsaved
});


问:
Sproutcore: Cannot call method 'get' of null
I thought it would be fun to check Sproutcore out, but I ran into an error which I cannot seem to figure out. I'm following the recent NetTuts+ tutorial on writing a microblog with the framework. My code is the following:

```<code>Microblog.mainPage = SC.Page.design({

mainPane: SC.MainPane.design({
    childViews: 'topView postView contentView'.w(),

    topView: SC.ToolbarView.design({
        childViews: 'appName'.w(),
        layout: { top: 0, left: 0, right: 0, height: 40 },
        anchorLocation: SC.ANCHOR_TOP,

        appName: SC.LabelView.design({
            layout: { top: 5, left: 5, width: 100 },
            displayValue: "MicroBlog App",
            layerId: "mb-logo" // html id attribute
        })
    }),

    postView: SC.View.design({
        childViews: 'form'.w(),
        layout: { top: 40, height: 75 },
        backgroundColor: 'white',

        form: SC.View.design({
            childViews: 'postContent post'.w(),
            layout: { left: 200, right: 200 },

            postContent: SC.TextFieldView.design({
                layout: { top: 10, left: 10, right: 10, height: 60 },
                isTextArea: YES,
                hint: "What's on your mind?"
            }),

            post: SC.ButtonView.design({
                layout: { top: 80, right: 10, width: 100 },
                title: "Post",
                isDefault: YES
            })
        })
    }),

    contentView: SC.ScrollView.design({
        hasHorizontalScroller: NO,
        layout: { top: 135, bottom: 0, left: 0, right: 0 },
        contentView: SC.ListView.design({

        })
    })
})
});
</code>```

However, for some reason it doesn't load the button and when I click on the page where either my buttonView or contentView goes, I get the following error in my console:

Uncaught TypeError: Cannot call method 'get' of null

I tried googling for it, but no luck. I'm using Sproutcore 1.6.

Thanks

答: You've already solved this problem, but: The error "Cannot call method 'get' of null" in SproutCore is pretty unhelpful on its face, but it usually means there's either a syntax error in the code, or something else is missing in the declaration of, the object you're trying to call get() on. In your case, I think adding the childViews attribute helped, and disambiguating the contentView label was also necessary.

Body:
I thought it would be fun to check Sproutcore out, but I ran into an error which I cannot seem to figure out. I'm following the recent NetTuts+ tutorial on writing a microblog with the framework. My code is the following:

Microblog.mainPage = SC.Page.design({

mainPane: SC.MainPane.design({
    childViews: 'topView postView contentView'.w(),

    topView: SC.ToolbarView.design({
        childViews: 'appName'.w(),
        layout: { top: 0, left: 0, right: 0, height: 40 },
        anchorLocation: SC.ANCHOR_TOP,

        appName: SC.LabelView.design({
            layout: { top: 5, left: 5, width: 100 },
            displayValue: "MicroBlog App",
            layerId: "mb-logo" // html id attribute
        })
    }),

    postView: SC.View.design({
        childViews: 'form'.w(),
        layout: { top: 40, height: 75 },
        backgroundColor: 'white',

        form: SC.View.design({
            childViews: 'postContent post'.w(),
            layout: { left: 200, right: 200 },

            postContent: SC.TextFieldView.design({
                layout: { top: 10, left: 10, right: 10, height: 60 },
                isTextArea: YES,
                hint: "What's on your mind?"
            }),

            post: SC.ButtonView.design({
                layout: { top: 80, right: 10, width: 100 },
                title: "Post",
                isDefault: YES
            })
        })
    }),

    contentView: SC.ScrollView.design({
        hasHorizontalScroller: NO,
        layout: { top: 135, bottom: 0, left: 0, right: 0 },
        contentView: SC.ListView.design({

        })
    })
})
});

However, for some reason it doesn't load the button and when I click on the page where either my buttonView or contentView goes, I get the following error in my console:

Uncaught TypeError: Cannot call method 'get' of null

I tried googling for it, but no luck. I'm using Sproutcore 1.6.

Thanks


问:
how to detect MacOS Sierra version in plain javascript
I need to detect MacOS Sierra and its version number using plain javascript. Please help me out with a code snippet.

答:
try running child process with your command as below:</p>

```<code>const { exec } = require("child_process");

 exec("system_profiler SPSoftwareDataType", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});
</code>```

Body:
try running child process with your command as below:

const { exec } = require("child_process");

 exec("system_profiler SPSoftwareDataType", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});


问:
Can I send a ctrl-C (SIGINT) to an application on Windows?
I have (in the past) written cross-platform (Windows/Unix) applications which, when started from the command line, handled a user-typed Ctrl-C combination in the same way (i.e. to terminate the application cleanly).

Is it possible on Windows to send a Ctrl-C/SIGINT/equivalent to a process from another (unrelated) process to request that it terminate cleanly (giving it an opportunity to tidy up resources etc.)?

答:
```<code>// Send [CTRL-C] to interrupt a batch file running in a Command Prompt window, even if the Command Prompt window is not visible,
// without bringing the Command Prompt window into focus.
// [CTRL-C] will have an effect on the batch file, but not on the Command Prompt  window itself -- in other words,
// [CTRL-C] will not have the same visible effect on a Command Prompt window that isn't running a batch file at the moment
// as bringing a Command Prompt window that isn't running a batch file into focus and pressing [CTRL-C] on the keyboard.
ulong ulProcessId = 0UL;
// hwC = Find Command Prompt window HWND
GetWindowThreadProcessId (hwC, (LPDWORD) &ulProcessId);
AttachConsole ((DWORD) ulProcessId);
SetConsoleCtrlHandler (NULL, TRUE);
GenerateConsoleCtrlEvent (CTRL_C_EVENT, 0UL);
SetConsoleCtrlHandler (NULL, FALSE);
FreeConsole ();
</code>```


问:
PayPal, IPNs for Xenforo and Buttons
I have to figure out what I need to do to sort out a couple of IPN problems I have created.
Here's what I have:
- One PayPal account
- PayPal Buttons that do not require IPNs
- 2 Xenforo forums which have paid user upgrades activated

I have activated IPN under Notifications for the Xenforo site that is active. The second site is not used much and with only one IPN, that means it gets an error. This is not my first concern right now.

My buttons get used, and also through IPN errors. I see I can override the notify_url in the advanced settings, but I don't have an url to use. I don't need an url notified for these purchases. Is there something I can put in there to overide the xenforo notify_url or simply cause the button to not notify any url?

How can I deal with two xenforo sites when I am only allowed one PayPal account?

Thanks for explaining my options

答:
Any transaction can specify its own notify_url at transaction setup/creation/redirect time , which will override any setting in the PayPal account.

The Notify URL in the PayPal account is just the default one that will be used if none is given at transaction time.

Ensure that any URL you give responds with an HTTP 200 OK/success status, since if it does not respond with a 2xx status, PayPal will consider the delivery failed and will keep retrying and will eventually deactivate the IPN delivery service for your account.

Title: PayPal, IPNs for Xenforo and Buttons


问:
How do I print a line in one file based on a corresponding value in a second file?
I have two files:
File1:

```<code>A
B
C
</code>```

File2:

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

I would like to print each line in file1 the number of times found on the corresponding line of file2, and then append each line to a separate file.

Desired output:

```<code>A
A
B
B
B
B
C
C
C
</code>```

Here is one of the approaches I have tried:

```<code>touch output.list
paste file1 file2 > test.dict
cat test.dict
</code>```

```<code>A       2
B       4
C       3
</code>```

```<code>while IFS="\t" read -r f1 f2
do
   yes "$f1" | head -n "$f2" >> output.list
done < test.dict
</code>```

For my output I get a bunch of lines that read:

```<code>head: : invalid number of lines
</code>```

Any guidance would be greatly appreciated. Thanks!

答:
You can do this with an awk 1-liner</p>

```<code>$ awk 'NR==FNR{a[++i]=$0;next}{for(j=0;j<$0;j++)print a[FNR]}' File1 File2
A
A
B
B
B
B
C
C
C
</code>```

Body:
I have two files:
File1:

A
B
C

File2:

2
4
3

I would like to print each line in file1 the number of times found on the corresponding line of file2, and then append each line to a separate file.

Desired output:

A
A
B
B
B
B
C
C
C

Here is one of the approaches I have tried:

touch output.list
paste file1 file2 > test.dict
cat test.dict

A       2
B       4
C       3

while IFS="\t" read -r f1 f2
do
   yes "$f1" | head -n "$f2" >> output.list
done < test.dict

For my output I get a bunch of lines that read:

head: : invalid number of lines

Any guidance would be greatly appreciated. Thanks!

Body:
You can do this with an awk 1-liner

$ awk 'NR==FNR{a[++i]=$0;next}{for(j=0;j<$0;j++)print a[FNR]}' File1 File2
A
A
B
B
B
B
C
C
C


问:
C How to capture closing a Terminal
Any idea on how to capture closing the terminal window that my program is running in?
While I'm at it, any way to capture when the computer is shutting down but the program is still running, or if the user logs off?</p>

答: From my tests... the signal that my program is receiving when closing terminal is 1 or SIGHUP</p>

Title: C How to capture closing a Terminal


问:
React Js Context Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
I am using React and request data from api, but it seems like my 'data' is getting error

My class as below:

```<code>class Login extends Component {
  constructor() {
    super();

this.state = {
  UserName: '',
  Password: '',
  var:'',
}
this.Login = this.Login.bind(this);

  }

  Login(event) {
    debugger;
    api.post('/api/login', {
      UserName: this.state.UserName,
      Password: this.state.Password,
    })
      .then((result) => {
        if (result.data.Status === 'Success') {
          this.setState({var: result.data.status});
          alert("User login Successfully");
        } else {
          alert('Invalid User');
        }
        debugger;
      })
  }
</code>```

I am trying to make a login.
After user make a request, I will get some data from api and setState my var

The error prompt that the my result.data.Success was error. I dig some research on stack overflow, it mentioned about the Arrow Function which I used. Or is it any snytax error?

答:
Looks like your api may result undefined as response.

So make a check on results

.then((result) => {
        if (result && result.data.Status === 'Success') {
```

Body:
I am using React and request data from api, but it seems like my 'data' is getting error

My class as below:

class Login extends Component {
  constructor() {
    super();

this.state = {
  UserName: '',
  Password: '',
  var:'',
}
this.Login = this.Login.bind(this);

  }

  Login(event) {
    debugger;
    api.post('/api/login', {
      UserName: this.state.UserName,
      Password: this.state.Password,
    })
      .then((result) => {
        if (result.data.Status === 'Success') {
          this.setState({var: result.data.status});
          alert("User login Successfully");
        } else {
          alert('Invalid User');
        }
        debugger;
      })
  }

I am trying to make a login.
After user make a request, I will get some data from api and setState my var

The error prompt that the my result.data.Success was error. I dig some research on stack overflow, it mentioned about the Arrow Function which I used. Or is it any snytax error?


问:
Pausing and Resuming a Thread in Android. Studio
I just want to create another thread, I need to have it to keep doing something until I click button A, then resume when I click on Button B, that's all.

Thread t = new Thread(new Runnable(){

@Override

public void run(){

while(bool) { .... }

}});

t.start();
```

This is the format that I'm trying to follow. I start at the onCreate, but how do I pause and resume a thread?

答:
Use wait() and notifyAll().

Sample code for you to understand:

```<code>class myRunnable implements somethingRunnable {
    private Object mPauseLock;
    private boolean mPaused;
    private boolean mFinish;

    public myRunnable() {
        mPauseLock = new Object();
        mPaused = false;
        mFinish = false;
    }

    public void run() {
        while (!mFinish) {
            // Do stuff here.

            synchronized (mPauseLock) {
                while (mPaused) {
                    try {
                        mPauseLock.wait();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }

    /**
    * Call this on pause.
    */
    public void onPause() {
        synchronized (mPauseLock) {
            mPaused = true;
        }
    }

    /**
    * Call this on resume.
    */
    public void onResume() {
        synchronized (mPauseLock) {
            mPaused = false;
            mPauseLock.notifyAll();
        }
    }

}
</code>```

Hope it helps :)

Body:
I just want to create another thread, I need to have it to keep doing something until I click button A, then resume when I click on Button B, that's all.

Thread t = new Thread(new Runnable(){

@Override

public void run(){

while(bool) { .... }

}});

t.start();

This is the format that I'm trying to follow. I start at the onCreate, but how do I pause and resume a thread?

Body:
Use wait() and notifyAll().

Sample code for you to understand:

class myRunnable implements somethingRunnable {
    private Object mPauseLock;
    private boolean mPaused;
    private boolean mFinish;

    public myRunnable() {
        mPauseLock = new Object();
        mPaused = false;
        mFinish = false;
    }

    public void run() {
        while (!mFinish) {
            // Do stuff here.

            synchronized (mPauseLock) {
                while (mPaused) {
                    try {
                        mPauseLock.wait();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }

    /**
    * Call this on pause.
    */
    public void onPause() {
        synchronized (mPauseLock) {
            mPaused = true;
        }
    }

    /**
    * Call this on resume.
    */
    public void onResume() {
        synchronized (mPauseLock) {
            mPaused = false;
            mPauseLock.notifyAll();
        }
    }

}

Hope it helps :)


问:
Xamarin.Forms Preview Screen Isn't Working
In my Xamarin.Forms project the preview screen stopped responding after I edited my .xaml file. It is giving java.lang.NullPointerException error, but it doesn't show any errors in the errors section in Visual Studio 2019. My final .xaml file is below:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:map="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
             mc:Ignorable="d"
             x:Class="x.MainPage">

    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <Grid.RowDefinitions>
            <RowDefinition Height="2.1*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="1" HeightRequest="160" ColumnSpacing="0" Margin="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.1*"/>
            </Grid.ColumnDefinitions>
            <Grid BackgroundColor="White">
                <StackLayout VerticalOptions="FillAndExpand" Orientation="Vertical">

                    <SearchBar Text="x" VerticalTextAlignment="Center" VerticalOptions="Fill" HorizontalTextAlignment="Start" IsEnabled="False" IsReadOnly="True" HorizontalOptions="Fill" Margin="5"/>

                    <Grid Grid.Row="1" HeightRequest="160" ColumnSpacing="0" Margin="0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Image Source="https://cdn1.iconfinder.com/data/icons/general-9/500/add-512.png" VerticalOptions="Center" HorizontalOptions="Center" Scale="0.5" Grid.Column="0" />
                        <Image Source="https://cdn1.iconfinder.com/data/icons/general-9/500/add-512.png" VerticalOptions="Center" HorizontalOptions="Center" Scale="0.5" Grid.Column="1" />
                        <Image Source="https://cdn1.iconfinder.com/data/icons/general-9/500/add-512.png" VerticalOptions="Center" HorizontalOptions="Center" Scale="0.5" Grid.Column="2" />
                        <Image Source="https://cdn1.iconfinder.com/data/icons/general-9/500/add-512.png" VerticalOptions="Center" HorizontalOptions="Center" Scale="0.5" Grid.Column="3" />
                        <Image Source="https://cdn1.iconfinder.com/data/icons/general-9/500/add-512.png" VerticalOptions="Center" HorizontalOptions="Center" Scale="0.5" Grid.Column="4" />
                    </Grid>

                </StackLayout>
            </Grid>
        </Grid>
        <Grid>
            <map:Map x:Name="Map" MapType="Street" HasZoomEnabled="True"/>
        </Grid>
    </Grid>

</ContentPage>
```

答:
Welcome to SO !

After checking code , there is a property of SearchBar can cause this error .

Modify IsEnabled="False" to IsEnabled="True" , or if want SearchBar not shows can set IsVisible="False" .

Effect as follow :

In addition , you defined only one row in the first Grid , however used setted the second one :

```<code><Grid Grid.Row="1" HeightRequest="160" ColumnSpacing="0" Margin="0">
</code>```

If changed to :

```<code><Grid Grid.Row="0" HeightRequest="160" ColumnSpacing="0" Margin="0">
</code>```

Preview Screen will show as follow :

The same wrong setted is in fourth Grid , you can check that .

Body:
Welcome to SO !

After checking code , there is a property of SearchBar can cause this error .

Modify IsEnabled="False" to IsEnabled="True" , or if want SearchBar not shows can set IsVisible="False" .

Effect as follow :

In addition , you defined only one row in the first Grid , however used setted the second one :

<Grid Grid.Row="1" HeightRequest="160" ColumnSpacing="0" Margin="0">

If changed to :

<Grid Grid.Row="0" HeightRequest="160" ColumnSpacing="0" Margin="0">

Preview Screen will show as follow :

The same wrong setted is in fourth Grid , you can check that .


问:
What kind of algorithm paradigm/algorithm design paradigm is A* (A star) pathfinding algorithm?
I'm not sure about what kind of design paradigm is A* (A star) pathfinding algorithm. According of the topics of the book "Introduction to the Design & Analysis of Algorithms" by Anany Levitin, I think the design paradigm is a greedy technique, because this algorithm is a combination of Dijktra's algorithm and greedy best first which are greedy techniques. But I'm not sure if that is a good reasoning.

Edit: According Emma comment, she gave me a link of Wikipedia where it says " Dijkstra and A* are special cases of dynamic programming. A* itself is a special case of a generalization of branch and bound." link.
But in this other Wikipedia link says "Dijkstra's algorithm and the related A* search algorithm are verifiably optimal greedy algorithms for graph search and shortest path finding."

答:
You have a good question!

Greedy is setteld!!!

I guess it would depend and I agree with "that's a bit of apples and oranges." in the question's comment.

The answer to your specific question might be here or here.

It is considered Greedy or Dynamic Programming (DP), according to some wikipedia pages.

However, templatetypedef also has a good point in the comment: "I would have pegged it as greedy given that it’s making a locally optimal decision at each point."

Greedy

Dijkstra's algorithm and the related A* search algorithm are
verifiably optimal greedy algorithms for graph search and shortest
path finding.

Dynamic Programming

What sets A* apart from a greedy best-first search algorithm is that
it takes the cost/distance already traveled, g(n), into account.

Some common variants of Dijkstra's algorithm can be viewed as a
special case of A* where the heuristic h(n) = 0 for all nodes; in
turn, both Dijkstra and A* are special cases of dynamic programming.
A* itself is a special case of a generalization of branch and bound.

Reference

A* search algorithm

Algorithmic paradigm


问:
Deserializing Java org.apache.kafka.common.serialization serialized objects with Python
I have a Java Kafka producer that uses org.apache.kafka.common.serialization.LongSerializer as the key serializer and I'm trying to consume messages from the topic using a Python Kafka consumer.

I thought that since LongSerializer is part of org.apache.kafka, an equivalent serializer and deserializer would be available in all official Kafka clients for other languages, to promote interoperability. However, I couldn't find it.

So, are people supposed to use org.apache.kafka.common.serialization only for projects which are pure JVM, or is there some other way to deserialize these objects using Python?

I feel like I'm missing something because I find it hard to believe Kafka provides serializers and deserializers out of the box which do not promote communication between processes written in different languages...

答:
If anyone still needs an answer a year after it was asked, you can just re-implement Java's LongSerializer in Python:

```<code>    def long_deserializer(data: bytes):
      if not data:
        return None
      if len(data) != 8:
        raise Exception(f"Size of data received by long_deserializer is not 8. Received {len(data)}")

      # 0xF...FFFFFFFF is always -1
      if data == b'\xff\xff\xff\xff\xff\xff\xff\xff':
        return -1

      value = 0
      for b in data:
        value <<= 8
        value |= b & 0xFF

      return value
</code>```

The example usage would be as follows:

Input:

b'\x00\x00\x00\x00\x00\x00\x04\xd2

decoding part:

x04\xd2

decoding to binary:

0x04=100, d=1010 , 2=0010

result:

10010100010

translate to int (the return value):

10010100010 = 1234

Also, if you want a more "pythonic" way, you can use builtin functions:

```<code>int('0x' + data.hex().lstrip('0'), 0)
</code>```

Body:
If anyone still needs an answer a year after it was asked, you can just re-implement Java's LongSerializer in Python:

    def long_deserializer(data: bytes):
      if not data:
        return None
      if len(data) != 8:
        raise Exception(f"Size of data received by long_deserializer is not 8. Received {len(data)}")

      # 0xF...FFFFFFFF is always -1
      if data == b'\xff\xff\xff\xff\xff\xff\xff\xff':
        return -1

      value = 0
      for b in data:
        value <<= 8
        value |= b & 0xFF

      return value

The example usage would be as follows:

Input:

b'\x00\x00\x00\x00\x00\x00\x04\xd2

decoding part:

x04\xd2

decoding to binary:

0x04=100, d=1010 , 2=0010

result:

10010100010

translate to int (the return value):

10010100010 = 1234

Also, if you want a more "pythonic" way, you can use builtin functions:

int('0x' + data.hex().lstrip('0'), 0)


问:
I get this JavaScriptSerializer.Deserialize Exception, how do I fix it?
System.Exception: There was an error reading the city list for CANANDA ---> System.ArgumentException: Unrecognized escape sequence. (1056):

```<code>{code: "CA",cities: [{name: "Abbotsford",lat: 49029998,lon: -122370002},{name: "Calgary",lat: 51119998,lon: -114019996},{name: "Edmonton",lat: 53299999,lon: -113580001},{name: "Halifax",lat: 44880001,lon: -63500000},{name: "Hamilton",lat: 43279998,lon: -79900001},{name: "Kanata",lat: 45319999,lon: -75669998},{name: "Kelowna",lat: 49970001,lon: -119379997},{name: "Kingston",lat: 44220001,lon: -76599998},{name: "London",lat: 43029998,lon: -81150001},{name: "Mississauga",lat: 43630001,lon: -79400001},{name: "Moncton",lat: 46119998,lon: -64680000},{name: "Montreal",lat: 45470001,lon: -73750000},{name: "Oshawa",lat: 43630001,lon: -79400001},{name: "Ottawa",lat:45319999,lon: -75669998},{name: "Peterborough",lat: 44229999,lon: -78370002},{name: "Prince George",lat: 53880001,lon: -122680000},{name: "Quebec",lat: 46799999,lon: -71379997},{name: "Regina",lat: 50430000,lon: -104669998},{name: "Saint John",lat: 45319999,lon: -65879997},{name: "Saskatoon",lat: 52169998,lon: -106680000},{name: "Sherbrooke",lat: 45430000,lon: -71680000},{name: "St John\x27s",lat: 47619998,lon: -52729999},{name: "Sydney",lat: 46169998,lon: -60049999},{name: "Thunder Bay",lat: 48369998,lon: -89319999},{name: "Toronto",lat: 43630001,lon: -79400001, selected: true},{name: "Trois-Rivieres",lat: 46349998,lon: -72519996},{name: "Vancouver",lat: 49180000,lon: -123169998},{name: "Victoria",lat: 48650001,lon: -123430000},{name: "Windsor",lat: 42270000,lon: -82970001},{name: "Winnipeg",lat: 49900001,lon: -97230003}]}
</code>```

I think it's the name "St John\x27s" that is causing the exception. Does that mean the System.Web.Extensions JavaScriptSerializer doesn't support Unicode?

Or is that actually invalid JSON?

How can I fix this problem?

答: \x27 is invalid JSON. Replace it with \u0027.</p>

OwnerDisplayName: CVertex

Body:
System.Exception: There was an error reading the city list for CANANDA ---> System.ArgumentException: Unrecognized escape sequence. (1056):

{code: "CA",cities: [{name: "Abbotsford",lat: 49029998,lon: -122370002},{name: "Calgary",lat: 51119998,lon: -114019996},{name: "Edmonton",lat: 53299999,lon: -113580001},{name: "Halifax",lat: 44880001,lon: -63500000},{name: "Hamilton",lat: 43279998,lon: -79900001},{name: "Kanata",lat: 45319999,lon: -75669998},{name: "Kelowna",lat: 49970001,lon: -119379997},{name: "Kingston",lat: 44220001,lon: -76599998},{name: "London",lat: 43029998,lon: -81150001},{name: "Mississauga",lat: 43630001,lon: -79400001},{name: "Moncton",lat: 46119998,lon: -64680000},{name: "Montreal",lat: 45470001,lon: -73750000},{name: "Oshawa",lat: 43630001,lon: -79400001},{name: "Ottawa",lat:45319999,lon: -75669998},{name: "Peterborough",lat: 44229999,lon: -78370002},{name: "Prince George",lat: 53880001,lon: -122680000},{name: "Quebec",lat: 46799999,lon: -71379997},{name: "Regina",lat: 50430000,lon: -104669998},{name: "Saint John",lat: 45319999,lon: -65879997},{name: "Saskatoon",lat: 52169998,lon: -106680000},{name: "Sherbrooke",lat: 45430000,lon: -71680000},{name: "St John\x27s",lat: 47619998,lon: -52729999},{name: "Sydney",lat: 46169998,lon: -60049999},{name: "Thunder Bay",lat: 48369998,lon: -89319999},{name: "Toronto",lat: 43630001,lon: -79400001, selected: true},{name: "Trois-Rivieres",lat: 46349998,lon: -72519996},{name: "Vancouver",lat: 49180000,lon: -123169998},{name: "Victoria",lat: 48650001,lon: -123430000},{name: "Windsor",lat: 42270000,lon: -82970001},{name: "Winnipeg",lat: 49900001,lon: -97230003}]}

I think it's the name "St John\x27s" that is causing the exception. Does that mean the System.Web.Extensions JavaScriptSerializer doesn't support Unicode?

Or is that actually invalid JSON?

How can I fix this problem?

OwnerDisplayName: darin

ContentLicense: CC BY-SA 2.5


问:
ORA-00984 column not allowed here
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

```<code>CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);
</code>```

Inserting values using a pro*c method

```<code>addCustomer(i, name,age, gender, address,contectNo);
</code>```

in Pro*C method I use following code to insert

```<code>EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);
</code>```

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.

答:
If im seeing correct you are trying to insert into the columns, the columns??

"EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (cust_id, cust_name, age, sex, addr, contact);"??

it would be more helpful if you post your procedure complete.

Regards

Title: ORA-00984 column not allowed here

Body:
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);

Inserting values using a pro*c method

addCustomer(i, name,age, gender, address,contectNo);

in Pro*C method I use following code to insert

EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.


问:
How do I replace a cell's contents when it matches a specific string?
I have this line working:

```<code>access$`Reading Score` <- gsub('NA', '', access$`Reading Score`)
</code>```

However, I'd like to apply the same thing to 20+ more columns. Without having to explicitly write out all 20 column changes, is there a way to do this when the cell's contents exactly match 'NA'? I have a few columns that are people names so they have the string NA but I obviously don't want to apply the changes to those names, just the 20 columns where the entire cell's contents is 'NA'

Also, what should the second statement be if I want to properly replace with a NULL value?

答:
An easier way may be to not let "NA" into the data in the first place.  E.g., you can call

```<code>library(readxl)
readxl::read_excel(path, na = "NA")
</code>```

and it will convert all the "NA" to NA.  read_delim, read_csv and related also have similar options.

Body:
I have this line working:

access$`Reading Score` <- gsub('NA', '', access$`Reading Score`)

However, I'd like to apply the same thing to 20+ more columns. Without having to explicitly write out all 20 column changes, is there a way to do this when the cell's contents exactly match 'NA'? I have a few columns that are people names so they have the string NA but I obviously don't want to apply the changes to those names, just the 20 columns where the entire cell's contents is 'NA'

Also, what should the second statement be if I want to properly replace with a NULL value?

Body:
An easier way may be to not let "NA" into the data in the first place.  E.g., you can call

library(readxl)
readxl::read_excel(path, na = "NA")

and it will convert all the "NA" to NA.  read_delim, read_csv and related also have similar options.


问:
Why is plotly() and enquo + !! in conflict?
I am writing a function that uses plot_ly for a pieplot. The tilde (~) within argument labels = ~ is in conflict with the unquote operator !!. Is there a solution for this problem?

```<code>pieplotr <- function (df, Property){

Property_Name <- enquo(Property)

Pie <- plot_ly(df,
              labels = ~!!Property_Name,
              type = "pie")

return(Pie)

}
</code>```

```<code>Toy_dataframe <- data.frame(
                 Sex = c("Male", "Female", "Female", "Male", "Male","NA"),
                 Height = c(12,11,7,3,9,NA),
                 Name = c("John", "Dora", "Dora","Dora", "Anna", "John"),
                 Last = c("Henry", "Paul", "House", "Houze", "Henry", "Bill"),
                 Location = c("Chicago", "Chicago", "Portland", "NYC", "NYC", "NYC"),
                 stringsAsFactors = TRUE)
</code>```

e.g.

```<code>pieplotr(df = Toy_dataframe,
          Property = Name)
</code>```

I expect to return a pieplot, but I am getting the following error message:

Error in as.list.environment(x, all.names = TRUE) :

   object 'Name' not found

答:
I was trying to find a way to use plot_ly inside a function, but also trying to avoid passing unquoted variable names. Turns out passing quoted column names, parsing, and then evaluating within the plot_ly call works nicely, and, at least for me, its easier to read and understand than some of the other solutions:

```<code>ply <- function(data, x, y) {

  name_x <- parse(text = x)
  name_y <- parse(text = y)

  plotly::plot_ly(data = data, x = ~eval(name_x), y = ~eval(name_y)) %>%
    plotly::add_trace(type = "scatter")
}

ply(faithful, "eruptions", "waiting")
</code>```

Body:
I am writing a function that uses plot_ly for a pieplot. The tilde (~) within argument labels = ~ is in conflict with the unquote operator !!. Is there a solution for this problem?

pieplotr <- function (df, Property){

Property_Name <- enquo(Property)

Pie <- plot_ly(df,
              labels = ~!!Property_Name,
              type = "pie")

return(Pie)

}

Toy_dataframe <- data.frame(
                 Sex = c("Male", "Female", "Female", "Male", "Male","NA"),
                 Height = c(12,11,7,3,9,NA),
                 Name = c("John", "Dora", "Dora","Dora", "Anna", "John"),
                 Last = c("Henry", "Paul", "House", "Houze", "Henry", "Bill"),
                 Location = c("Chicago", "Chicago", "Portland", "NYC", "NYC", "NYC"),
                 stringsAsFactors = TRUE)

e.g.

pieplotr(df = Toy_dataframe,
          Property = Name)

I expect to return a pieplot, but I am getting the following error message:

Error in as.list.environment(x, all.names = TRUE) :

   object 'Name' not found

Body:
I was trying to find a way to use plot_ly inside a function, but also trying to avoid passing unquoted variable names. Turns out passing quoted column names, parsing, and then evaluating within the plot_ly call works nicely, and, at least for me, its easier to read and understand than some of the other solutions:

ply <- function(data, x, y) {

  name_x <- parse(text = x)
  name_y <- parse(text = y)

  plotly::plot_ly(data = data, x = ~eval(name_x), y = ~eval(name_y)) %>%
    plotly::add_trace(type = "scatter")
}

ply(faithful, "eruptions", "waiting")


问:
Cannot open Visual Studio - throw error 'cannot run when setup is in progress'
I am trying to open Visual Studio, but it is giving an error:

cannot run when set up is in progress

It was running fine before when I restarted my machine. I have already installed this version from past one year.

答: Just restart the system,Its worked for me.</p>


问:
Database re-provisioning failed
Trying to create data sync between 2 databases one on my local computer and the other is on Azure cloud, after creating sync agent and sync group and adding the needed tables to be synced an error appears preventing the sync process.

Database re-provisioning failed with the exception "Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation. Inner exception: SqlException ID: 92d7c5bf-96c9-4c43-a578-0cb9b678b044, Error Code: -2146232060 - SqlError Number:468, Message: SQL error with code 468 For more information, provide tracing ID ‘954e4a9d-f025-4919-a9cc-5f32e9e620e6’ to customer support."

Any help how to solve this?

答:
How to change Collation by SSMS.

Choose your db, right click

find options, and select a collation from the Collation drop-down list

find SQL_Latin1_General_CP1_CI_AS, then click ok button.

The default collation value of Azure SQL DB is SQL_Latin1_General_CP1_CI_AS. You can change your local server's collation.

Title: Database re-provisioning failed


问:
Downloading a file from Adls gen1 using powershell is not working
I am trying a download a file from azure data lake store using powershell script. The code is triggered from a runbook in azure cloud. Looks like Export-AdlStoreItem is not working as expected.I dont get any error messages or compilation errors. In fact when this command is executed a zero byte file is generated in the destination.The name of that file is TemporaryFile2020-06-02_14-56-57.datc18371c2-d39c-4588-9af0-93aa3e136b01Segments
what is happening?.Please help!.

```<code>$LocalDwldPath = "T:\ICE_PROD_DATA_SOURCING\FILE_DOWNLOAD_PATH\TemporaryFile$($TimeinSec).dat"
    $SourcePath = "Dataproviders/Landing/GCW/HPIndirect/Orders/AMS/gcw_hp_indirect_orders_ams_745_20200601_04_34_01.dat"
    $PRODAdlsName = "itgdls01"
    Export-AdlStoreItem  -Account $PRODAdlsName -Path  $("/" + $SourcePath.Trim()) -Destination $LocalDwldPath -Force -ErrorAction Stop
    if( Test-Path $LocalDwldPath.Trim() )
    {
    Get-Content -Path $LocalDwldPath.Trim() -ReadCount 1000 |% { $FileCount += $_.Count }
        Remove-Item $LocalDwldPath.Trim()
        Set-Content -Path $cntCaptureFile -Value $FileCount
        $TimeinSec = TimeStamp2
        Add-Content -Value "$TimeinSec Log: Identified file for getting count is $($SourcePath.Trim()) and the count is $FileCount" -Path $logfile
    }
    else
    {
        $TimeinSec = TimeStamp2
        Add-Content -Value "$TimeinSec Error: Identified file for getting count is $($SourcePath.Trim()) and the count capture failed as local file is not found!" -Path $logfile
    }
</code>```

答:
According to my research, if you want to download a file from azure data lake with PowerShell, we can use the PowerShell command Export-AzDataLakeStoreItem.

For example

```<code>Export-AzDataLakeStoreItem -Account <> -Path '/test/test.csv' -Destination 'D:\myDirectory\test.csv'
</code>```

For more details, please refer to the document

Body:
I am trying a download a file from azure data lake store using powershell script. The code is triggered from a runbook in azure cloud. Looks like Export-AdlStoreItem is not working as expected.I dont get any error messages or compilation errors. In fact when this command is executed a zero byte file is generated in the destination.The name of that file is TemporaryFile2020-06-02_14-56-57.datc18371c2-d39c-4588-9af0-93aa3e136b01Segments
what is happening?.Please help!.

$LocalDwldPath = "T:\ICE_PROD_DATA_SOURCING\FILE_DOWNLOAD_PATH\TemporaryFile$($TimeinSec).dat"
    $SourcePath = "Dataproviders/Landing/GCW/HPIndirect/Orders/AMS/gcw_hp_indirect_orders_ams_745_20200601_04_34_01.dat"
    $PRODAdlsName = "itgdls01"
    Export-AdlStoreItem  -Account $PRODAdlsName -Path  $("/" + $SourcePath.Trim()) -Destination $LocalDwldPath -Force -ErrorAction Stop
    if( Test-Path $LocalDwldPath.Trim() )
    {
    Get-Content -Path $LocalDwldPath.Trim() -ReadCount 1000 |% { $FileCount += $_.Count }
        Remove-Item $LocalDwldPath.Trim()
        Set-Content -Path $cntCaptureFile -Value $FileCount
        $TimeinSec = TimeStamp2
        Add-Content -Value "$TimeinSec Log: Identified file for getting count is $($SourcePath.Trim()) and the count is $FileCount" -Path $logfile
    }
    else
    {
        $TimeinSec = TimeStamp2
        Add-Content -Value "$TimeinSec Error: Identified file for getting count is $($SourcePath.Trim()) and the count capture failed as local file is not found!" -Path $logfile
    }

Body:
According to my research, if you want to download a file from azure data lake with PowerShell, we can use the PowerShell command Export-AzDataLakeStoreItem.

For example

Export-AzDataLakeStoreItem -Account <> -Path '/test/test.csv' -Destination 'D:\myDirectory\test.csv'

For more details, please refer to the document