问:
Hibernate Envers doesn't save referenced column value in case of @OneToMany Relationship
Here's the code for 2 entities, machine and device.

```<code>@Audited
@Entity(name = "device")
@Table(name = "device")
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "machineCode", referencedColumnName = "machineCode")
    private Machine machine;

}

@Audited
@Entity(name = "machine")
@Table(name = "machine")
public class Machine {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String machineCode;

}
</code>```

Now, when i save the device entity. The machineCode column (in the auditing table of device) gets the value of id and not the corresponding machineCode from machine's domain object.
I am not sure if there is anything wrong with the code or not. Thanks in advance.

PS - there are other intermingled entities attached to machine entity as well. So, adding @OneToMany is not required or i should say, it would be an overhead.

Edit 1: this question is regarding the envers auditing framework if i didn't make it clear enough.

答:
You need to make sure, that the referenced entity(Machine) implements Serializable.

Check the below link for further clarifications:-

https://thorben-janssen.com/hibernate-tips-model-association-dont-reference-primary-key-columns/

Body:
Here's the code for 2 entities, machine and device.

@Audited
@Entity(name = "device")
@Table(name = "device")
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "machineCode", referencedColumnName = "machineCode")
    private Machine machine;

}

@Audited
@Entity(name = "machine")
@Table(name = "machine")
public class Machine {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String machineCode;

}

Now, when i save the device entity. The machineCode column (in the auditing table of device) gets the value of id and not the corresponding machineCode from machine's domain object.
I am not sure if there is anything wrong with the code or not. Thanks in advance.

PS - there are other intermingled entities attached to machine entity as well. So, adding @OneToMany is not required or i should say, it would be an overhead.

Edit 1: this question is regarding the envers auditing framework if i didn't make it clear enough.


来源: stackexchange

问:
Best option for modal screens in ASP.NET
I'm looking for the best way to implement a modal popup in ASP.NET of another ASP.NET page. I'm coding for Firefox 2.x+ and can use JQuery, but I'm not very familiar with it.

I see a lot of solutions that use "AJAX", but I'm not sure in what context, so I haven't gone down that route.

答:
I make my own, using DOM methods. I've found it to be a lot simpler than adapting any of these plugins to our CSS.

A modal is simply an absolutely positioned window with a background.
We make ours using a larger transparent container with floated contents.

I use a function that returns some html with the floated contents. The class used for the modal box should be absolutely positioned with a high z layer.

```<code>function create_modal(doc_id,css_class,append_to)
{
if(typeof append_to==='undefined'){append_to='content';}
var container=document.getElementById(append_to);
if(!container){return false;}
var modal_box=document.createElement('div');
container.appendChild(modal_box);
modal_box.id=doc_id;
modal_box.className=css_class;
return modal_box;
}

var modal_window=create_modal('modal_id','a_css_class');
if(!modal_window){return false;}
modal_window.innerHTML=function_or_var_providing_html();
</code>```

so, it's all nice and simple without some 10 or 15 k plugin!

OwnerDisplayName: Caveatrob

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mausch

Body:
I make my own, using DOM methods. I've found it to be a lot simpler than adapting any of these plugins to our CSS.

A modal is simply an absolutely positioned window with a background.
We make ours using a larger transparent container with floated contents.

I use a function that returns some html with the floated contents. The class used for the modal box should be absolutely positioned with a high z layer.

function create_modal(doc_id,css_class,append_to)
{
if(typeof append_to==='undefined'){append_to='content';}
var container=document.getElementById(append_to);
if(!container){return false;}
var modal_box=document.createElement('div');
container.appendChild(modal_box);
modal_box.id=doc_id;
modal_box.className=css_class;
return modal_box;
}

var modal_window=create_modal('modal_id','a_css_class');
if(!modal_window){return false;}
modal_window.innerHTML=function_or_var_providing_html();

so, it's all nice and simple without some 10 or 15 k plugin!

OwnerDisplayName: Code Duck


问:
Angular 8 prevent dropdown field scroll trigger the windows scroll event
I have a top nav bar and when scroll down the page need to do some css changes on the navbar.

So i using window.addEventListener in my shared header.component.ts to detect the scroll event. But if in other components have dropdown field will scrollbar will also trigger the changes navbar css function.

How do I limit the dropdown field do not trigger the changes navbar css function?

header.component.ts

```<code>ngOnInit() {
    window.addEventListener('scroll', this.scroll, true);
  }

  scroll = (event: any): void => {
    const number = event.srcElement.scrollTop;
    const element = document.querySelector('.navbar');
    if (number > 50) {
      element.classList.add('toolbar-scroll');
    } else {
      element.classList.remove('toolbar-scroll');
    }
  }
</code>```

答:
I manage to solve this by look through all the event one by one and find event.target.firstChild.nodeName has a unique variable which can be used to differentiate component with the drop-down field

```<code>if (event.target.firstChild.nodeName === 'ROUTER-OUTLET') {
      if (number > 50) {
        element.classList.add('toolbar-scroll');
      } else {
        element.classList.remove('toolbar-scroll');
      }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a top nav bar and when scroll down the page need to do some css changes on the navbar.

So i using window.addEventListener in my shared header.component.ts to detect the scroll event. But if in other components have dropdown field will scrollbar will also trigger the changes navbar css function.

How do I limit the dropdown field do not trigger the changes navbar css function?

header.component.ts

ngOnInit() {
    window.addEventListener('scroll', this.scroll, true);
  }

  scroll = (event: any): void => {
    const number = event.srcElement.scrollTop;
    const element = document.querySelector('.navbar');
    if (number > 50) {
      element.classList.add('toolbar-scroll');
    } else {
      element.classList.remove('toolbar-scroll');
    }
  }

Body:
I manage to solve this by look through all the event one by one and find event.target.firstChild.nodeName has a unique variable which can be used to differentiate component with the drop-down field

if (event.target.firstChild.nodeName === 'ROUTER-OUTLET') {
      if (number > 50) {
        element.classList.add('toolbar-scroll');
      } else {
        element.classList.remove('toolbar-scroll');
      }
    }


问:
Meteor Mongo aggregate returns BSON type
I have the below aggregate query

```<code>var pipeline=[ { $match: { Active:1, Duration:'monthly' } },{ $sample: { size: 3 } }]
Products.aggregate(pipeline).toArray((err, result) => {
  subscription.added('random-aggregate', 'random-order', { result: result });
});
</code>```

it returns the correct result but the ObjectId is in BSON type which makes it difficult to further process it. How can I get the correct Object id of the collection record?
Attached a screenshot how the id looks on console

Although when checking the MiniMongo Meteor screen the id looks normal and also in other queries I use among the project the id is in the correct format

答:
I'm sure you must have solved the issue by now, just in case anyone else runs into this...

save products in a variable, then clone the array like this,

JSON.parse(JSON.stringify(products))

Body:
I have the below aggregate query

var pipeline=[ { $match: { Active:1, Duration:'monthly' } },{ $sample: { size: 3 } }]
Products.aggregate(pipeline).toArray((err, result) => {
  subscription.added('random-aggregate', 'random-order', { result: result });
});

it returns the correct result but the ObjectId is in BSON type which makes it difficult to further process it. How can I get the correct Object id of the collection record?
Attached a screenshot how the id looks on console

Although when checking the MiniMongo Meteor screen the id looks normal and also in other queries I use among the project the id is in the correct format


问:
How do I sort by the last letter of a value in a dictionay in python?
given the following list of dictionaries, how do I sort by the last letter of the name?

```<code>    list_of_dicts = [
    {'name': 'Jadis', 'year_of_birth': 0, 'gender': 'Female'},
    {'name': 'Peter', 'year_of_birth': 1927, 'gender': 'Male'},
    {'name': 'Susan', 'year_of_birth': 1928, 'gender': 'Female'},
    {'name': 'Edmund', 'year_of_birth': 1930, 'gender': 'Male'},
    {'name': 'Lucy', 'year_of_birth': 1932, 'gender': 'Female'}]
</code>```

答:
In case, you want to sort the same list (in place), you can use ".sort" method on the list.

```<code>list_of_dicts.sort(key= lambda x: x.get('name')[-1]) # key accepts a function, and we are fetching the last letter of the name.
print (list_of_dicts)
</code>```

I hope this helps and counts.

Body:
given the following list of dictionaries, how do I sort by the last letter of the name?

    list_of_dicts = [
    {'name': 'Jadis', 'year_of_birth': 0, 'gender': 'Female'},
    {'name': 'Peter', 'year_of_birth': 1927, 'gender': 'Male'},
    {'name': 'Susan', 'year_of_birth': 1928, 'gender': 'Female'},
    {'name': 'Edmund', 'year_of_birth': 1930, 'gender': 'Male'},
    {'name': 'Lucy', 'year_of_birth': 1932, 'gender': 'Female'}]

Body:
In case, you want to sort the same list (in place), you can use ".sort" method on the list.

list_of_dicts.sort(key= lambda x: x.get('name')[-1]) # key accepts a function, and we are fetching the last letter of the name.
print (list_of_dicts)

I hope this helps and counts.


问:
call a php function from jquery
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

```<code>$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX
</code>```

PHP:

```<code><?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
</code>```

答:
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server.  This is because javascript executes client side and PHP executes server side.  Therefore, javascript does not have direct access to PHP functions.

You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.

Can you replicate the functionality of the PHP function with a JavaScript function?

Would this, or something similar, work for you:

```<code>$.ajax({
  type: "POST",
  url: post_url,
  success: function(groups) //we're calling the response json array 'tree'
  {
        for(group in groups){
            document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
        }
  }
}); //end AJAX
</code>```

ContentLicense: CC BY-SA 3.0

Title: call a php function from jquery

Body:
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX

PHP:

<?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>

Body:
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server.  This is because javascript executes client side and PHP executes server side.  Therefore, javascript does not have direct access to PHP functions.

You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.

Can you replicate the functionality of the PHP function with a JavaScript function?

Would this, or something similar, work for you:

$.ajax({
  type: "POST",
  url: post_url,
  success: function(groups) //we're calling the response json array 'tree'
  {
        for(group in groups){
            document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
        }
  }
}); //end AJAX


问:
why do i get the error as 'cannot find symbol'?
Inheritance.java file

```<code>
      package oops.Inheritance;

       public class Inheritance {

        public static void main(String[] args) {

        Teacher t=new Teacher("gopi");

        t.name="ravi";
        t.eat();
        t.walk();
        t.teach();
        Singer s=new Singer("rock");
        s.name="arjun";
        s.eat();
        s.walk();

        person p =new person("jack");
        //person p=t;//upcasting

        //Teacher t=(Teacher)p;//downcasting

        // boolean yo = t instanceof Teacher;//to fine whether t is is instance of teacher
        // System.out.println(t instanceof Teacher);//true
        // System.out.println(s instanceof Singer);//true
        // System.out.println(t instanceof person);//true
        // System.out.println(p instanceof Teacher);//flase

    }
}
</code>```

The error is

```<code>D:\study files\java files\oops\Inheritance>javac Inheritance.java
</code>```

Inheritance.java:5: error: cannot find symbol

```<code>        Teacher t=new Teacher("gopi");
        ^
</code>```

symbol:   class Teacher

location: class Inheritance

Inheritance.java:5: error: cannot find symbol

```<code>    Teacher t=new Teacher("gopi");
                  ^
</code>```

symbol:   class Teacher

location: class Inheritance

Inheritance.java:10: error: cannot find symbol

```<code>    Singer s=new Singer("rock");
    ^
</code>```

symbol:   class Singer

location: class Inheritance

Inheritance.java:10: error: cannot find symbol

```<code>    Singer s=new Singer("rock");
                 ^
</code>```

symbol:   class Singer

location: class Inheritance

Inheritance.java:15: error: cannot find symbol

```<code>    person p =new person("jack");
    ^
</code>```

symbol:   class person

location: class Inheritance

Inheritance.java:15: error: cannot find symbol

```<code>    person p =new person("jack");
                  ^
</code>```

symbol:   class person

location: class Inheritance

6 errors

person.java

```<code>
     package oops.Inheritance;

      public class person {

      protected String name;

        public person(String name){

        this.name=name;
        System.out.println("Inside person constructor");
      }

      public void walk(){
      System.out.println("person"+name+"person is walking");
    }
      public void eat(){
      System.out.println("person"+name+"person is eating");
     }
      public static void laughing(){
      System.out.println("person is laughing");
         }

      }
</code>```

Teacher.java

```<code>
      package oops.Inheritance;

      public class Teacher extends person{//inheriting from person

      public Teacher(String name){

      super(name);//calls the constructor in the parent class

      System.out.println("Inside teacher constructor");
      }

       public void teach(){
       System.out.println(name+"Teacher is teaching");
       }

       public void eat(){
       super.eat();//to access the parent class i.e, here person           class
       System.out.println("teacher"+name+"is eating");
         }
        }
       }
</code>```

singer.java

```<code>
       package oops.Inheritance;

       public class Singer extends person{//inheriting from person

       public Singer(String name){

        super(name);//calls the the constructor in parent class

        System.out.println("Inside singer constructor");

      }

        public void sing(){
        System.out.println("Singer is singing");
    }

        public void eat(){
        System.out.println("teacher"+name+"is eating");
    }
}

</code>```

I'm running this program in vscode the latest version.
every time it works but when I import the classes from the other package I get the above-mentioned error.

答:
The best thing you can do is to fix the setup in Eclipse so that that works. Once that problem is solved, you don't need to worry about how to compile anymore.

In any case, to answer the question you asked:

In order to compile your files from the command line, you need to be in the java files directory. This needs to be your working directory since it is the root directory containing your outermost package, oops.

Then you need to compile person first. You cannot compile Inheritance alone. The compiler will only recognize the classes used in Inheritance — person, Teacher and Singer — after each of them has been compiled. Use the relative path name to the file:

```<code>javac oops/Inheritance/person.java
</code>```

(use backslash instead of slash if on Windows). After person compile Teacher and Singer (in any order). Finally compile Inheritance.

Edit: This worked on my BSD Unix with bash:

```<code>$ ls oops/inheritance/
Inheritance.java  Singer.java
Person.java       Teacher.java
$ javac oops/inheritance/Person.java
$ javac oops/inheritance/Teacher.java oops/inheritance/Singer.java
$ javac oops/inheritance/Inheritance.java
$ ls oops/inheritance/
Inheritance.class Person.java     Teacher.class
Inheritance.java  Singer.class        Teacher.java
Person.class      Singer.java
$ java oops.inheritance.Inheritance
Inside Person constructor
Inside teacher constructor
Personraviperson is eating
teacherraviis eating
Personraviperson is walking
raviTeacher is teaching
Inside Person constructor
Inside singer constructor
teacherarjunis eating
Personarjunperson is walking
Inside Person constructor
$
</code>```

Compared to your code I have used small i in the package name inheritance and upper case P in the class Person, both in accordance with Java naming conventions. I have also corrected the number of closing curly braces and similar tiny details that aren’t relevant to the problem of compiling and running.

What went wrong for you when you tried my suggestion, I am sorry, I cannot guess.

Body:
Inheritance.java file

      package oops.Inheritance;

       public class Inheritance {

        public static void main(String[] args) {

        Teacher t=new Teacher("gopi");

        t.name="ravi";
        t.eat();
        t.walk();
        t.teach();
        Singer s=new Singer("rock");
        s.name="arjun";
        s.eat();
        s.walk();

        person p =new person("jack");
        //person p=t;//upcasting

        //Teacher t=(Teacher)p;//downcasting

        // boolean yo = t instanceof Teacher;//to fine whether t is is instance of teacher
        // System.out.println(t instanceof Teacher);//true
        // System.out.println(s instanceof Singer);//true
        // System.out.println(t instanceof person);//true
        // System.out.println(p instanceof Teacher);//flase

    }
}

The error is

D:\study files\java files\oops\Inheritance>javac Inheritance.java

Inheritance.java:5: error: cannot find symbol

        Teacher t=new Teacher("gopi");
        ^

symbol:   class Teacher

location: class Inheritance

Inheritance.java:5: error: cannot find symbol

    Teacher t=new Teacher("gopi");
                  ^

symbol:   class Teacher

location: class Inheritance

Inheritance.java:10: error: cannot find symbol

    Singer s=new Singer("rock");
    ^

symbol:   class Singer

location: class Inheritance

Inheritance.java:10: error: cannot find symbol

    Singer s=new Singer("rock");
                 ^

symbol:   class Singer

location: class Inheritance

Inheritance.java:15: error: cannot find symbol

    person p =new person("jack");
    ^

symbol:   class person

location: class Inheritance

Inheritance.java:15: error: cannot find symbol

    person p =new person("jack");
                  ^

symbol:   class person

location: class Inheritance

6 errors

person.java

     package oops.Inheritance;

      public class person {

      protected String name;

        public person(String name){

        this.name=name;
        System.out.println("Inside person constructor");
      }

      public void walk(){
      System.out.println("person"+name+"person is walking");
    }
      public void eat(){
      System.out.println("person"+name+"person is eating");
     }
      public static void laughing(){
      System.out.println("person is laughing");
         }

      }

Teacher.java

      package oops.Inheritance;

      public class Teacher extends person{//inheriting from person

      public Teacher(String name){

      super(name);//calls the constructor in the parent class

      System.out.println("Inside teacher constructor");
      }

       public void teach(){
       System.out.println(name+"Teacher is teaching");
       }

       public void eat(){
       super.eat();//to access the parent class i.e, here person           class
       System.out.println("teacher"+name+"is eating");
         }
        }
       }

singer.java

       package oops.Inheritance;

       public class Singer extends person{//inheriting from person

       public Singer(String name){

        super(name);//calls the the constructor in parent class

        System.out.println("Inside singer constructor");

      }

        public void sing(){
        System.out.println("Singer is singing");
    }

        public void eat(){
        System.out.println("teacher"+name+"is eating");
    }
}

I'm running this program in vscode the latest version.
every time it works but when I import the classes from the other package I get the above-mentioned error.

Body:
The best thing you can do is to fix the setup in Eclipse so that that works. Once that problem is solved, you don't need to worry about how to compile anymore.

In any case, to answer the question you asked:

In order to compile your files from the command line, you need to be in the java files directory. This needs to be your working directory since it is the root directory containing your outermost package, oops.

Then you need to compile person first. You cannot compile Inheritance alone. The compiler will only recognize the classes used in Inheritance — person, Teacher and Singer — after each of them has been compiled. Use the relative path name to the file:

javac oops/Inheritance/person.java

(use backslash instead of slash if on Windows). After person compile Teacher and Singer (in any order). Finally compile Inheritance.

Edit: This worked on my BSD Unix with bash:

$ ls oops/inheritance/
Inheritance.java  Singer.java
Person.java       Teacher.java
$ javac oops/inheritance/Person.java
$ javac oops/inheritance/Teacher.java oops/inheritance/Singer.java
$ javac oops/inheritance/Inheritance.java
$ ls oops/inheritance/
Inheritance.class Person.java     Teacher.class
Inheritance.java  Singer.class        Teacher.java
Person.class      Singer.java
$ java oops.inheritance.Inheritance
Inside Person constructor
Inside teacher constructor
Personraviperson is eating
teacherraviis eating
Personraviperson is walking
raviTeacher is teaching
Inside Person constructor
Inside singer constructor
teacherarjunis eating
Personarjunperson is walking
Inside Person constructor
$

Compared to your code I have used small i in the package name inheritance and upper case P in the class Person, both in accordance with Java naming conventions. I have also corrected the number of closing curly braces and similar tiny details that aren’t relevant to the problem of compiling and running.

What went wrong for you when you tried my suggestion, I am sorry, I cannot guess.


问:
How to Build the MySQL plugin for Qt Using MySQL Server 8.0?
I'm new to QT. I tried to Installing QMYSQL driver by using MySQL Server8.0. But I'm unable to build the MySQL plugin for Qt. I tried many ways and thats thing does not help to me.

I used this way

```<code>C:\Qt\5.14.2\Src\qtbase\src\plugins\sqldrivers>qmake -- MYSQL_INCDIR="C:/Program Files/MySQL/Connector C++ 8.0/include"MYSQL_LIBDIR="C:/Program Files/MySQL/Connector C++ 8.0/ib64"
</code>```

to build the MYSQL plugin to QT .

The results like this

答:
Error was my command.
C:\Qt\5.14.2\Src\qtbase\src\plugins\sqldrivers>qmake -- MYSQL_INCDIR="C:/Program Files/MySQL/Connector C++ 8.0/include"MYSQL_LIBDIR="C:/Program Files/MySQL/Connector C++ 8.0/ib64"
in here it should not be Connector C++/path/ should be the MySQL Server8.0/path/. It should be the path for mysql.h file and libmysql.lib/libmysql.dll.

Body:
I'm new to QT. I tried to Installing QMYSQL driver by using MySQL Server8.0. But I'm unable to build the MySQL plugin for Qt. I tried many ways and thats thing does not help to me.

I used this way

C:\Qt\5.14.2\Src\qtbase\src\plugins\sqldrivers>qmake -- MYSQL_INCDIR="C:/Program Files/MySQL/Connector C++ 8.0/include"MYSQL_LIBDIR="C:/Program Files/MySQL/Connector C++ 8.0/ib64"

to build the MYSQL plugin to QT .

The results like this


问:
Send SVG behing border div
I am making an infography, and I want to place a round circle with a border behind the border line of a div, as show in this picture:

As you can see in the image, the circle is behind the path in the layers. I have tried with z-index and I can not make it work. The result I have right now is perfect but for the fact that I can not place the circle behind:

.flex {
  display: flex !important;
}

.contenido {
  height: 180px;
}

.left {
  width: 33.33%;
}

.up {
  border-top: 5px solid;
  border-color: #5396C3;
}

.color {
  border-color: #5396C3;
}

.left-half {
  width: 16.667%;
}

.right-half {
  width: 16.667%;
}

.d {
  border-top-right-radius: 500px;
  border-bottom-right-radius: 500px;
  border-right: 5px solid;
  border-color: #5396C3;
  z-index: 8;
  position: relative;
}

.right {
  width: 33.33%;
}

.down {
  border-bottom: 5px solid;
  border-color: #5396C3;
}

/* This is the point that need to be behind */

.right-point {
  width: 40px;
  float: right;
  margin-top: 62px;
  margin-right: -23px;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex contenido">
  <div class="left up color">
  </div>
  <div class="left-half up color">
  </div>
  <div class="right-half up down d color">
    <img src="svg/work.svg" alt="" class="right-point">
  </div>
  <div class="right color">
  </div>
</div>
<div class="flex contenido">
  <div class="left ">
    <div class="flex" style="justify-content: flex-end;">
      <img src="img/vv.png" alt="" class="logo logo-left ">
    </div>
  </div>
  <div class="left-half up down c work" style="margin-top: -5px;">
    <img src="svg/work.svg" alt="" class="left-point">
  </div>
  <div class="right-half color">
  </div>
  <div class="right color">
  </div>
</div></code>```

Why is the circle not going behind the border?
In my case I am using an SVG as a circle, maybe it is a better idea to create the circle with CSS (does it even affect the fact that is an SVG?).

Thanks!

答:
remove the z-index and position relative from class .d and add position relative for the .right-point

.flex {
  display: flex !important;
}

.contenido {
  height: 180px;
}

.left {
  width: 33.33%;
}

.up {
  border-top: 5px solid;
  border-color: #5396C3;
}

.color {
  border-color: #5396C3;
}

.left-half {
  width: 16.667%;
}

.right-half {
  width: 16.667%;
}

.d {
  border-top-right-radius: 500px;
  border-bottom-right-radius: 500px;
  border-right: 5px solid;
  border-color: #5396C3;

}

.right {
  width: 33.33%;
}

.down {
  border-bottom: 5px solid;
  border-color: #5396C3;
}

/* This is the point that need to be behind */

.right-point {
  width: 40px;
  float: right;
  margin-top: 62px;
  margin-right: -23px;
  z-index: -1;
   position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex contenido">
  <div class="left up color">
  </div>
  <div class="left-half up color">
  </div>
  <div class="right-half up down d color">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/17/Yin_yang.svg/1024px-Yin_yang.svg.png" alt="" class="right-point">
  </div>
  <div class="right color">
  </div>
</div>
<div class="flex contenido">
  <div class="left ">
    <div class="flex" style="justify-content: flex-end;">
      <img src="img/vv.png" alt="" class="logo logo-left ">
    </div>
  </div>
  <div class="left-half up down c work" style="margin-top: -5px;">
    <img src="svg/work.svg" alt="" class="left-point">
  </div>
  <div class="right-half color">
  </div>
  <div class="right color">
  </div>
</div></code>```

Title: Send SVG behing border div

Body:
I am making an infography, and I want to place a round circle with a border behind the border line of a div, as show in this picture:

As you can see in the image, the circle is behind the path in the layers. I have tried with z-index and I can not make it work. The result I have right now is perfect but for the fact that I can not place the circle behind:

.flex {
  display: flex !important;
}

.contenido {
  height: 180px;
}

.left {
  width: 33.33%;
}

.up {
  border-top: 5px solid;
  border-color: #5396C3;
}

.color {
  border-color: #5396C3;
}

.left-half {
  width: 16.667%;
}

.right-half {
  width: 16.667%;
}

.d {
  border-top-right-radius: 500px;
  border-bottom-right-radius: 500px;
  border-right: 5px solid;
  border-color: #5396C3;
  z-index: 8;
  position: relative;
}

.right {
  width: 33.33%;
}

.down {
  border-bottom: 5px solid;
  border-color: #5396C3;
}

/* This is the point that need to be behind */

.right-point {
  width: 40px;
  float: right;
  margin-top: 62px;
  margin-right: -23px;
  z-index: -1;
}

Why is the circle not going behind the border?
In my case I am using an SVG as a circle, maybe it is a better idea to create the circle with CSS (does it even affect the fact that is an SVG?).

Thanks!

Body:
remove the z-index and position relative from class .d and add position relative for the .right-point

.flex {
  display: flex !important;
}

.contenido {
  height: 180px;
}

.left {
  width: 33.33%;
}

.up {
  border-top: 5px solid;
  border-color: #5396C3;
}

.color {
  border-color: #5396C3;
}

.left-half {
  width: 16.667%;
}

.right-half {
  width: 16.667%;
}

.d {
  border-top-right-radius: 500px;
  border-bottom-right-radius: 500px;
  border-right: 5px solid;
  border-color: #5396C3;

}

.right {
  width: 33.33%;
}

.down {
  border-bottom: 5px solid;
  border-color: #5396C3;
}

/* This is the point that need to be behind */

.right-point {
  width: 40px;
  float: right;
  margin-top: 62px;
  margin-right: -23px;
  z-index: -1;
   position: relative;
}

<div class="flex contenido">
  <div class="left up color">
  </div>
  <div class="left-half up color">
  </div>
  <div class="right-half up down d color">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/17/Yin_yang.svg/1024px-Yin_yang.svg.png" alt="" class="right-point">
  </div>
  <div class="right color">
  </div>
</div>
<div class="flex contenido">
  <div class="left ">
    <div class="flex" style="justify-content: flex-end;">
      <img src="img/vv.png" alt="" class="logo logo-left ">
    </div>
  </div>
  <div class="left-half up down c work" style="margin-top: -5px;">
    <img src="svg/work.svg" alt="" class="left-point">
  </div>
  <div class="right-half color">
  </div>
  <div class="right color">
  </div>
</div>


问:
Share viewmodel between multiple fragments in Bottom Navigation with Android Navigation Component
I have app, where i'm using fragment with navHost and connected navigation graph to it. This fragment, let's call it main fragment needs to download some data, that will be used by each of the tabs in bottom navigation. This looks like perfect usage of Shared ViewModel.

But there is no obvious way of using it with bottom navigation. There is a method navGraphViewModels() used with kotlin delegate:

```<code>val parentViewModel: CourtDetailRootVM by navGraphViewModels(R.id.court_detail)
</code>```

but that produces Exception:

```<code> java.lang.IllegalArgumentException: No destination with ID 2131296449 is on the NavController's back stack
</code>```

because according to documentation this method is looking for a viewModel that is on the current backstack, which is not the case with bottom navigation!

There are some other ways of getting parent viewModel but all of them requires reusage of ViewModelFactory. I can not use that, because my factory has constructor with some arguments, that need to be passed, and I don't have access to this arguments on child fragments.

So, I'm stuck and can't see any possible solution for this rather trivial issue

答:
I had the same problem twice.

The 1st issue was that I was created a new navigation file and used . This should technically work, but I was getting the same error.
So I fixed it by selecting all the fragments that need to be grouped together inside the nav graph and right-click->move to nested graph->new graph

which will create something like this:

```<code><navigation
    android:id="@+id/checkout_graph"
    app:startDestination="@id/cartFragment">

    <fragment android:id="@+id/orderSummaryFragment".../>
    <fragment android:id="@+id/addressFragment" .../>
    <fragment android:id="@+id/paymentFragment" .../>
    <fragment android:id="@+id/cartFragment" .../>

</navigation>
</code>```

Now, inside the fragments when you initialize the ViewModel do this

```<code>val viewModel: CheckoutViewModel by navGraphViewModels(R.id.checkout_graph)
</code>```

If you need to pass the viewmodel factory(may be for injecting the viewmodel) you can do it like this:

```<code>val viewModel: CheckoutViewModel by navGraphViewModels(R.id.checkout_graph) { viewModelFactory }
</code>```

The 2nd issue was a mistake of the Id that I was using while initializing the ViewModel. So make sure you are using the navGraph that is currently being used to initialize your ViewModel.

Body:
I have app, where i'm using fragment with navHost and connected navigation graph to it. This fragment, let's call it main fragment needs to download some data, that will be used by each of the tabs in bottom navigation. This looks like perfect usage of Shared ViewModel.

But there is no obvious way of using it with bottom navigation. There is a method navGraphViewModels() used with kotlin delegate:

val parentViewModel: CourtDetailRootVM by navGraphViewModels(R.id.court_detail)

but that produces Exception:

 java.lang.IllegalArgumentException: No destination with ID 2131296449 is on the NavController's back stack

because according to documentation this method is looking for a viewModel that is on the current backstack, which is not the case with bottom navigation!

There are some other ways of getting parent viewModel but all of them requires reusage of ViewModelFactory. I can not use that, because my factory has constructor with some arguments, that need to be passed, and I don't have access to this arguments on child fragments.

So, I'm stuck and can't see any possible solution for this rather trivial issue

Body:
I had the same problem twice.

The 1st issue was that I was created a new navigation file and used . This should technically work, but I was getting the same error.
So I fixed it by selecting all the fragments that need to be grouped together inside the nav graph and right-click->move to nested graph->new graph

which will create something like this:

<navigation
    android:id="@+id/checkout_graph"
    app:startDestination="@id/cartFragment">

    <fragment android:id="@+id/orderSummaryFragment".../>
    <fragment android:id="@+id/addressFragment" .../>
    <fragment android:id="@+id/paymentFragment" .../>
    <fragment android:id="@+id/cartFragment" .../>

</navigation>

Now, inside the fragments when you initialize the ViewModel do this

val viewModel: CheckoutViewModel by navGraphViewModels(R.id.checkout_graph)

If you need to pass the viewmodel factory(may be for injecting the viewmodel) you can do it like this:

val viewModel: CheckoutViewModel by navGraphViewModels(R.id.checkout_graph) { viewModelFactory }

The 2nd issue was a mistake of the Id that I was using while initializing the ViewModel. So make sure you are using the navGraph that is currently being used to initialize your ViewModel.


问:
How `pandas.Series.str` works when values are `list`?
How this works? If it's converting each item into string i should get first character like "[1,2]"[0] ----> '[' but instead it treating as list, How?

>>> df = pd.DataFrame({'a':[[1,2],[2,3]]})
>>> df.a.str[0]
0    1
1    2
Name: a, dtype: int64
```

答:
It working, because strings and lists are iterables. It means .str[0] return first value of string, first value of lists, first value of iterable.

What is iterable:

As stated by Raymond Hettinger:

An ITERABLE is:

anything that can be looped over (i.e. you can loop over a string or file) or

anything that can appear on the right-side of a for-loop:   for x in iterable: ... or

anything you can call with iter() that will return an ITERATOR:  iter(obj) or

an object that defines __iter__ that returns a fresh ITERATOR,
or it may have a __getitem__ method suitable for indexed lookup.


问:
How to get a list of the arguments a method is called with
How do I get a list of the arguments passed to a method, preferably one that I can iterate through?

For example something like

```<code>def foo(a,b,c)
  puts args.inspect
end

foo(1,2,3)
=> [1,2,3]
</code>```

?
Thanks!

答:
You can always define a method that takes an arbitrary number of arguments:

```<code>def foo(*args)
  puts args.inspect
end
</code>```

This does exactly what you want, but only works on methods defined in such a manner.

The *args notation means "zero or more arguments" in this context. The opposite of this is the splat operator which expands them back into a list, useful for calling other methods.

As a note, the *-optional arguments must come last in the list of arguments.

Body:
How do I get a list of the arguments passed to a method, preferably one that I can iterate through?

For example something like

def foo(a,b,c)
  puts args.inspect
end

foo(1,2,3)
=> [1,2,3]

?
Thanks!

Body:
You can always define a method that takes an arbitrary number of arguments:

def foo(*args)
  puts args.inspect
end

This does exactly what you want, but only works on methods defined in such a manner.

The *args notation means "zero or more arguments" in this context. The opposite of this is the splat operator which expands them back into a list, useful for calling other methods.

As a note, the *-optional arguments must come last in the list of arguments.


问:
How to fetch a parameter value from parsed String (Json Request)
I have json request which I have parsed as a String and I need to fetch a param value of "sitename" that is "SIT-SITE-2219" from the long json request using Java.Please help .

"siteCounty":"UC",
         "alocCounty":"test2",
         "alocLat":"39.98",
         "siteName":"SIT-SITE-2219",
         "requestedBy":"UnitTester",
         "msc":"test",
```

答:
You can use untyped map to read the json, and then do a kv lookup. Something like the following:

```<code>        String jsonString = "{\"siteCounty\":\"UC\",\n" +
                "         \"alocCounty\":\"test2\",\n" +
                "         \"alocLat\":\"39.98\",\n" +
                "         \"siteName\":\"SIT-SITE-2219\",\n" +
                "         \"requestedBy\":\"UnitTester\",\n" +
                "         \"msc\":\"test\"}";

        ObjectMapper mapper = new ObjectMapper();

        TypeReference<HashMap<String, String>> typeRef
                = new TypeReference<HashMap<String, String>>() {};
        Map<String, String> map = null;
        try {
           map =  mapper.readValue(jsonString, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map.get("siteName"));
</code>```

Example uses the following dependencies on Java:8

```<code>   compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.11.0'
   compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
</code>```

Body:
You can use untyped map to read the json, and then do a kv lookup. Something like the following:

        String jsonString = "{\"siteCounty\":\"UC\",\n" +
                "         \"alocCounty\":\"test2\",\n" +
                "         \"alocLat\":\"39.98\",\n" +
                "         \"siteName\":\"SIT-SITE-2219\",\n" +
                "         \"requestedBy\":\"UnitTester\",\n" +
                "         \"msc\":\"test\"}";

        ObjectMapper mapper = new ObjectMapper();

        TypeReference<HashMap<String, String>> typeRef
                = new TypeReference<HashMap<String, String>>() {};
        Map<String, String> map = null;
        try {
           map =  mapper.readValue(jsonString, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map.get("siteName"));

Example uses the following dependencies on Java:8

   compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.11.0'
   compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'


问:
Simple prime number generator in Python
Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway.  I just want a very simple prime generator (nothing fancy). </p>

```<code>import math

def main():
    count = 3
    one = 1
    while one == 1:
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0:
                continue
            if count % x != 0:
                print count

        count += 1
</code>```

答:
Just studied the topic, look for the examples in the thread and try to make my version:

```<code>from collections import defaultdict
# from pprint import pprint

import re

def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1

def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num

def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])

def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None

def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1

def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1

if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )
</code>```

The result of running this code show interesting results:

```<code>$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096
</code>```

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.

OwnerDisplayName: marc lincoln

Title: Simple prime number generator in Python

Body:
Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway.  I just want a very simple prime generator (nothing fancy).

import math

def main():
    count = 3
    one = 1
    while one == 1:
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0:
                continue
            if count % x != 0:
                print count

        count += 1

LastEditorDisplayName: marc lincoln

Body:
Just studied the topic, look for the examples in the thread and try to make my version:

from collections import defaultdict
# from pprint import pprint

import re

def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1

def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num

def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])

def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None

def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1

def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1

if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )

The result of running this code show interesting results:

$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.


问:
How to create a PHP page that loads dynamic/different content depending on which link is clicked?
I have an HTML page with a list of  links. Each link will link to the same PHP page. I want the PHP page to dynamically load a different  link depending on which link id is clicked on the previous HTML page.

HTML Page ↓

```<code><a id="link1" href="test.php">Download</a>
<a id="link2" href="test.php">Download</a>
<a id="link3" href="test.php">Download</a>
...
</code>```

PHP page will print out a specific link depending on which a id was clicked on the previous HTML page ↓

```<code><a id="link1" href="thisisaspecificlink.com">Link here</a>
</code>```

I'm a total noob at PHP and would greatly appreciate assistance of any kind.

答:
You can do it by this way:
Here suppose you want redirect page to about-us.php page you can directly put in

```<code><a href="about-us.php">
</code>```

or try this

This is your html page

```<code><a id="link1" href="test.php?link=aboutuspage">link</a>
</code>```

On test.php page need to get this link
    now check link is equal to about-us page or another page

```<code>if($_GET['link']=="aboutuspage"){
 //redirect to aboutus page
 header("Location:about-us.php");
}
</code>```

Note: This is untested code

Body:
I have an HTML page with a list of  links. Each link will link to the same PHP page. I want the PHP page to dynamically load a different  link depending on which link id is clicked on the previous HTML page.

HTML Page ↓

Download
Download
Download
...

PHP page will print out a specific link depending on which a id was clicked on the previous HTML page ↓

Link here

I'm a total noob at PHP and would greatly appreciate assistance of any kind.

Body:
You can do it by this way:
Here suppose you want redirect page to about-us.php page you can directly put in

<a href="about-us.php">

or try this

This is your html page

<a id="link1" href="test.php?link=aboutuspage">link</a>

On test.php page need to get this link
    now check link is equal to about-us page or another page

if($_GET['link']=="aboutuspage"){
 //redirect to aboutus page
 header("Location:about-us.php");
}

Note: This is untested code


问:
JSON to XML conversion in Node JS service (using xml2js)
I need some help/advice with JSON to XML conversion in Node js.
I have a service that gets a JSON object in request body that needs to convert to XML. I am able to achieve this using node-xml2js for json inputs with maximum one level of nested objects. But, it gets way more complicated with nested objects having attribute values. Attributes should be identified first, prefixed with $ sign and enclosed in curly braces before parsing through xml2js to get correct xml.
Is there a better way of doing this where this complicated layer of reformatting the json input can be simplified?
xml2js can converts this:

```<code>{
    "Level1":{  "$":{   "attribute":"value" },
                "Level2": {"$":{"attribute1":"05/29/2020",
                            "attribute2":"10","attribute3":"Pizza"}}
}
</code>```

to this:(which is correct):

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
</code>```

But actual json input is this:

```<code>{
    "Level1":{"attribute":"value",
              "Level2": {"attribute1":"05/29/2020",
                         "attribute2":"10","attribute3":"Pizza"} }
}
</code>```

Expected same result:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
</code>```

Please let me know if you have worked on similar requirements. Appreciate any help.
Thank you.

答:
This would be a way to change the object back to the format expected in the library, although it assumes that all non object keys are supposed to be attributes (is that a valid assumption for your application?)

function groupChildren(obj) {
  for(prop in obj) { // consider filtering for own properties (vs from prototype: for(prop of Object.keys(obj)) {
    if (typeof obj[prop] === 'object') {
      groupChildren(obj[prop]);
    } else {
      obj['$'] = obj['$'] || {};
      obj['$'][prop] = obj[prop];
      delete obj[prop];
    }
  }

  return obj;
}
```
<p>and then used like so:</p>
<pre class="lang-js prettyprint-override"><code>var xml2js = require('xml2js');
var obj = {
  Level1: {
    attribute: 'value',
    Level2: {
      attribute1: '05/29/2020',
      attribute2: '10',
      attribute3: 'Pizza'
    }
  }
};

var builder = new xml2js.Builder();
var xml = builder.buildObject(groupChildren(obj));
</code>```

which prints out:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
```

Body:
I need some help/advice with JSON to XML conversion in Node js.
I have a service that gets a JSON object in request body that needs to convert to XML. I am able to achieve this using node-xml2js for json inputs with maximum one level of nested objects. But, it gets way more complicated with nested objects having attribute values. Attributes should be identified first, prefixed with $ sign and enclosed in curly braces before parsing through xml2js to get correct xml.
Is there a better way of doing this where this complicated layer of reformatting the json input can be simplified?
xml2js can converts this:

{
    "Level1":{  "$":{   "attribute":"value" },
                "Level2": {"$":{"attribute1":"05/29/2020",
                            "attribute2":"10","attribute3":"Pizza"}}
}

to this:(which is correct):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>

But actual json input is this:

{
    "Level1":{"attribute":"value",
              "Level2": {"attribute1":"05/29/2020",
                         "attribute2":"10","attribute3":"Pizza"} }
}

Expected same result:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>

Please let me know if you have worked on similar requirements. Appreciate any help.
Thank you.

Body:
This would be a way to change the object back to the format expected in the library, although it assumes that all non object keys are supposed to be attributes (is that a valid assumption for your application?)

function groupChildren(obj) {
  for(prop in obj) { // consider filtering for own properties (vs from prototype: for(prop of Object.keys(obj)) {
    if (typeof obj[prop] === 'object') {
      groupChildren(obj[prop]);
    } else {
      obj['$'] = obj['$'] || {};
      obj['$'][prop] = obj[prop];
      delete obj[prop];
    }
  }

  return obj;
}

and then used like so:

var xml2js = require('xml2js');
var obj = {
  Level1: {
    attribute: 'value',
    Level2: {
      attribute1: '05/29/2020',
      attribute2: '10',
      attribute3: 'Pizza'
    }
  }
};

var builder = new xml2js.Builder();
var xml = builder.buildObject(groupChildren(obj));

which prints out:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>


问:
angular8 how to send allow Cors to the Web Api
This is the open api and I am trying to fetch data using the URL. But I am getting this error. I can't set the backend to allow localhost. What is my option to make it work ?

Error

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

what I have tried

```<code>let header = new HttpHeaders();
header.set("Access-Control-Allow-Origin", "*");
const URL =
    "url here ";
return this.http.get(URL, { headers: header })
.pipe(map(res => res));

</code>```

答:
Basically you want to access a server that is configured to deny requests from different origin clients.

You have two options IMO.

Ask the API developer to allow you to request. In this, the API would be changed to allow requests from your app. The server-side implementation differs from platform to platform. For e.g. .Net Core refer this article.

If the above option does not exist for you (The API developer refuses to do so) then use JSONP to bypass the CORS.

For e.g. below is a sample code from Kunal Tandon's blog.

```<code><head>

<script>
    var myFunc = function(data) {
        console.log(data);
    }
</script>
<script src="xyz.com?wrap=myFunc"></script>
</code>```

Refer Understanding JSON, JSONP, CORS, and bypassing CORS with JSONP for more information.

I would strongly suggest you change API because that is the correct way. The JSONP is just a workaround.

Body:
This is the open api and I am trying to fetch data using the URL. But I am getting this error. I can't set the backend to allow localhost. What is my option to make it work ?

Error

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

what I have tried

let header = new HttpHeaders();
header.set("Access-Control-Allow-Origin", "*");
const URL =
    "url here ";
return this.http.get(URL, { headers: header })
.pipe(map(res => res));

Body:
Basically you want to access a server that is configured to deny requests from different origin clients.

You have two options IMO.

Ask the API developer to allow you to request. In this, the API would be changed to allow requests from your app. The server-side implementation differs from platform to platform. For e.g. .Net Core refer this article.

If the above option does not exist for you (The API developer refuses to do so) then use JSONP to bypass the CORS.

For e.g. below is a sample code from Kunal Tandon's blog.

<head>

<script>
    var myFunc = function(data) {
        console.log(data);
    }
</script>
<script src="xyz.com?wrap=myFunc"></script>

Refer Understanding JSON, JSONP, CORS, and bypassing CORS with JSONP for more information.

I would strongly suggest you change API because that is the correct way. The JSONP is just a workaround.


问:
How to get value in nested field using Kibana scripted field?
I'm new to Elastic Stack.
Here, I'm trying to get the value for "pressure" and then convert it to numeric value(string⇒numeric) using Kibana scripted field.
I tried scripted field, but it didn't work for me.

Any idea? I really appreciate your support in advance.
One of my data records is as below.

{
  "_index": "production",
  "_type": "_doc",
  "_id": "4570df7a0d4ec1b0e624e868a5861a0f1a9a7f6c35fdsssafafsa734fb152f4bed",
  "_version": 1,
  "_score": null,
  "_source": {
    "factorycode": "AM-NY",
    "productcode": "STR",
    "lastupdatetime": "2020-05-28T04:16:17.590Z",
    "@timestamp": "2020-05-28T04:14:48.000Z",
    "massproduction": {
      "errorcode": null,
      "equipment": "P17470110",
      "operatorldap": null,
      "machinetime": null,
      "quantity": "1",
      "externalfilename": null,
      "errorcomment": null,
      "datas": {
        "data": [
          {
            "value": "45.4",
            "id": "001",
            "name": "pressure"
          },
          {
            "value": "0.45",
            "id": "002",
            "name": "current"
          }
        ]
      },
      "ladderver": null,
      "eid": null,
      "setupid": null,
      "model": "0",
      "identificationtagid": null,
      "workid": "GD606546sf0B002020040800198",
      "reuse": {
        "num": "0"
      },
      "registrydate": "2020-05-28T13:14:48",
      "product": "GD604564550B00",
      "line": "STRS001",
      "judge": "1",
      "cycletime": null,
      "processcode": "OP335",
      "registryutcdate": "2020-04-28T04:14:48",
      "name": "massproduction"
    }
  },
  "fields": {
    "massproduction.registrydate": [
      "2020-05-28T13:14:48.000Z"
    ],
    "@timestamp": [
      "2020-05-28T04:14:48.000Z"
    ],
    "lastupdatetime": [
      "2020-05-28T04:16:17.590Z"
    ],
    "registrydate": [
      "2020-05-28T13:14:48.000Z"
    ],
    "massproduction.registryutcdate": [
      "2020-05-28T04:14:48.000Z"
    ],
    "registryutcdate": [
      "2020-05-28T04:14:48.000Z"
    ]
  },
  "sort": [
    158806546548000
  ]
}```
</div>
</div>
</p>

<p>This is my "painless" scripted field in Kibana.</p>

```for(item in params._source.massproduction.datas.data)
{
    if(item.name=='pressure'){
      return item.value;
   }
}
return 0;
```

答:
You can use Float.parseFloat(value) to convert string to float</p>

```<code>if(params._source.massproduction!=null && params._source.massproduction.datas!=null &&params._source.massproduction.datas.data.size()>0)
  {
    def data = params._source.massproduction.datas.data;
     if(data instanceof ArrayList)
     {
       for(item in data)
        {
          if(item.name=='pressure')
          {
            return  Float.parseFloat(item.value);
          }
        }
     }else
     {
        if(data.name=='pressure')
        {
          return  Float.parseFloat(data.value);
        }
     }
  }
  return 0;
</code>```

Body:
I'm new to Elastic Stack.
Here, I'm trying to get the value for "pressure" and then convert it to numeric value(string⇒numeric) using Kibana scripted field.
I tried scripted field, but it didn't work for me.

Any idea? I really appreciate your support in advance.
One of my data records is as below.

{
  "_index": "production",
  "_type": "_doc",
  "_id": "4570df7a0d4ec1b0e624e868a5861a0f1a9a7f6c35fdsssafafsa734fb152f4bed",
  "_version": 1,
  "_score": null,
  "_source": {
    "factorycode": "AM-NY",
    "productcode": "STR",
    "lastupdatetime": "2020-05-28T04:16:17.590Z",
    "@timestamp": "2020-05-28T04:14:48.000Z",
    "massproduction": {
      "errorcode": null,
      "equipment": "P17470110",
      "operatorldap": null,
      "machinetime": null,
      "quantity": "1",
      "externalfilename": null,
      "errorcomment": null,
      "datas": {
        "data": [
          {
            "value": "45.4",
            "id": "001",
            "name": "pressure"
          },
          {
            "value": "0.45",
            "id": "002",
            "name": "current"
          }
        ]
      },
      "ladderver": null,
      "eid": null,
      "setupid": null,
      "model": "0",
      "identificationtagid": null,
      "workid": "GD606546sf0B002020040800198",
      "reuse": {
        "num": "0"
      },
      "registrydate": "2020-05-28T13:14:48",
      "product": "GD604564550B00",
      "line": "STRS001",
      "judge": "1",
      "cycletime": null,
      "processcode": "OP335",
      "registryutcdate": "2020-04-28T04:14:48",
      "name": "massproduction"
    }
  },
  "fields": {
    "massproduction.registrydate": [
      "2020-05-28T13:14:48.000Z"
    ],
    "@timestamp": [
      "2020-05-28T04:14:48.000Z"
    ],
    "lastupdatetime": [
      "2020-05-28T04:16:17.590Z"
    ],
    "registrydate": [
      "2020-05-28T13:14:48.000Z"
    ],
    "massproduction.registryutcdate": [
      "2020-05-28T04:14:48.000Z"
    ],
    "registryutcdate": [
      "2020-05-28T04:14:48.000Z"
    ]
  },
  "sort": [
    158806546548000
  ]
}

This is my "painless" scripted field in Kibana.

for(item in params._source.massproduction.datas.data)
{
    if(item.name=='pressure'){
      return item.value;
   }
}
return 0;

Body:
You can use Float.parseFloat(value) to convert string to float

if(params._source.massproduction!=null && params._source.massproduction.datas!=null &&params._source.massproduction.datas.data.size()>0)
  {
    def data = params._source.massproduction.datas.data;
     if(data instanceof ArrayList)
     {
       for(item in data)
        {
          if(item.name=='pressure')
          {
            return  Float.parseFloat(item.value);
          }
        }
     }else
     {
        if(data.name=='pressure')
        {
          return  Float.parseFloat(data.value);
        }
     }
  }
  return 0;


问:
Should i use gRPC in android (client) and node js (server) to make a video call?
I'm learning gRPC with android java is client and Node js is server side.
Now i want create a video call application.
Should i use gRPC or other framework for this task ?
If not Could you give me another suggest ?
Thank you </p>

答:
TL;DR;

If i were you, i would go for gRPC.

I do not know if it will help you or not but i build video streaming applications with websockets. But with HTTP/2 i did look at gRPC and i like it a lot from a developer stand point. It is fast and i think it will become the standard over time. You can look at this sources if you like to read:

https://www.infoq.com/articles/websocket-and-http2-coexist/

https://www.stevejgordon.co.uk/server-streaming-with-grpc-in-asp-dotnet-core

https://medium.com/@EdgePress/is-grpc-the-future-of-client-server-communication-b112acf9f365


问:
Sending a message on a user join event - discord.py
I've been programming a bot that welcomes a user when they join but it doesn't seem to be working.</p>

```<code>async def on_member_join(member):
    channel = member.channel
    await channel.send(f'{member} has arrived')
</code>```

答:
```<code>@client.event
async def on_member_join(member):
    for channel in member.guild.channels:
        if str(channel) == "member-log":
            await channel.send(f"""Welcome {member.mention}!""")
</code>```

This might help too. Here, we are checking if the channel name is member-log and then sending a welcome message to that channel.

Body:
I've been programming a bot that welcomes a user when they join but it doesn't seem to be working.

async def on_member_join(member):
    channel = member.channel
    await channel.send(f'{member} has arrived')

Body:
@client.event
async def on_member_join(member):
    for channel in member.guild.channels:
        if str(channel) == "member-log":
            await channel.send(f"""Welcome {member.mention}!""")

This might help too. Here, we are checking if the channel name is member-log and then sending a welcome message to that channel.


问:
How do I reference a textarea value in another table cell?
I want to reference the content of a text area, but I keep getting undefined:

```<code>$(".send-comment").click(function(e) {
    e.preventDefault();
    var data = $(this).siblings(".comment-text").val();
    alert(data);
});

<tr>
    <td>#textAreaTag(label=false, name="comment[text]", class="comment-text")#</td>
    <td>#submitTag(value="Send", class="send-comment")#</td>
</tr>
</code>```

I suspect it might be because the send button has no siblings (it's alone in a td)... but surely, there has to be a better way to get the value than using this.parent().sibling().child()...

I'm using classes because I have several comment forms on the same page that belong to different posts.

FYI, the generated source from my framework is as expected...

答: you could use $(this).closest('tr').find('.comment-text') for example

Body:
I want to reference the content of a text area, but I keep getting undefined:

$(".send-comment").click(function(e) {
    e.preventDefault();
    var data = $(this).siblings(".comment-text").val();
    alert(data);
});

    #textAreaTag(label=false, name="comment[text]", class="comment-text")#
    #submitTag(value="Send", class="send-comment")#

I suspect it might be because the send button has no siblings (it's alone in a td)... but surely, there has to be a better way to get the value than using this.parent().sibling().child()...

I'm using classes because I have several comment forms on the same page that belong to different posts.

FYI, the generated source from my framework is as expected...


问:
In Python: How can i get my code to print out all the possible words I can spell based on my input?
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!</p>

```<code>Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))
</code>```

答:
First off, you are confusing things by having the name of your variable StoredLetters also being the name of one of the arguments to your all_words function.

Second, you are actually passing in StoredLetters, which is art, as the 2nd argument to the function, so it is wordSet in the function, not StoredLetters!

You should really keep things more clear by using different variable names, and making it obvious what are you using for which argument. words isn't really words, it's a dictionary with letters as keys, and how many times they appear as the values! Making code clear and understandable goes a long way to making it easy to debug. You have word, StoredLetters, wordSet, another StoredLetters argument, words = characters(word) which doesn't do what is expected. This could all use a good cleanup.

As for the functionality, with art, each letter only appears once, so for tart, which has t twice, if wordSet.count(key) != words[key] will evaluate as True, and flag will be set to 0, and the word will not be printed.

Hope that helps, and happy coding!

Body:
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!

Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))


问:
Android Room : LiveData callback of update insert?
I have a Simple DAO including CRUD function

FeedEntryDAO.java

```<code>@Dao
public interface FeedEntryDAO {

  @Query("SELECT * FROM feedEntrys")
  LiveData<List<FeedEntry>> getAll();

  @Query("SELECT * FROM feedEntrys WHERE uid = :uid LIMIT 1")
  LiveData<FeedEntry> findByUid(int uid);

  @Insert
  void insertAll(FeedEntry... feedEntries);

  @Delete
  void delete(FeedEntry feedEntry);

  @Update
  int update(FeedEntry feedEntry);

}
</code>```

For the select , it is okay to return the LiveData type.

Inside the Activity the code is pretty for the selection

```<code>viewModel.getFeedEntrys().observe(this,entries -> {...});
</code>```

However, when I try to insert, update , delete the data. The code seems a little bit ugly and also create a asynctask every time.

```<code>new AsyncTask<FeedEntry, Void, Void>() {
                @Override
                protected Void doInBackground(FeedEntry... feedEntries) {
                  viewModel.update(feedEntries[0]);
                  return null;
                }
}.execute(feedEntry);
</code>```

I have 2 question about it:

Can I use LiveData to wrap the delete, insert , update function ?

Better way to maintain such asynctask class for delete, insert , update?

Appreciate any suggestions and advices. Thank you.

答:
To Address your 2nd Question:

Google has posted an Android Room Codelab here which has laid out a concise MVVM architecture for implementing Room in Android:

(source: google.com)

Here the recommendation is to have database operations handled by a public static ExecutorService within the Database class. The location of the ExecutorService class can vary, just remember the idea is in MVVM your view does not care about how data are actually CURD'ed, that's the responsibility of the ViewModel, not View.

github repository for this code lab

In short, to apply a similar idea to your code, it would be something like this:

```<code>class YourRepository {
    private FeedEntryDAO mFeedEntryDAO;

    YourRepository(Application application) {
        YourDatabase db = YourDatabase.getDatabase(application);
        mFeedEntryDAO = db.feedEntryDAO();
        mAllWords = mWordDao.getAlphabetizedWords();
    }

    void update(FeedEntry feedEntry) {
        Database.databaseExecutor.execute(() - > {
            mFeedEntryDAO.update(feedEntry);
        });
    }
}

class YourViewModel extends ViewModel {
    private YourRepository mRepository;
    void update(FeedEntry feedEntry) {
        mRepository.update(feedEntry)
    }
}
</code>```

By doing this, your View can directly call viewModel.update(feedEntries[0]).

One important thing to mention is the mFeedEntryDAO.update(feedEntry) will automatically trigger the onChanged callback of your observer on the getFeedEntrys LiveData.

This is quite handy in your case. You can read more about how the trigger happens here.

Body:
I have a Simple DAO including CRUD function

FeedEntryDAO.java

@Dao
public interface FeedEntryDAO {

  @Query("SELECT * FROM feedEntrys")
  LiveData<List<FeedEntry>> getAll();

  @Query("SELECT * FROM feedEntrys WHERE uid = :uid LIMIT 1")
  LiveData<FeedEntry> findByUid(int uid);

  @Insert
  void insertAll(FeedEntry... feedEntries);

  @Delete
  void delete(FeedEntry feedEntry);

  @Update
  int update(FeedEntry feedEntry);

}

For the select , it is okay to return the LiveData type.

Inside the Activity the code is pretty for the selection

viewModel.getFeedEntrys().observe(this,entries -> {...});

However, when I try to insert, update , delete the data. The code seems a little bit ugly and also create a asynctask every time.

new AsyncTask<FeedEntry, Void, Void>() {
                @Override
                protected Void doInBackground(FeedEntry... feedEntries) {
                  viewModel.update(feedEntries[0]);
                  return null;
                }
}.execute(feedEntry);

I have 2 question about it:

Can I use LiveData to wrap the delete, insert , update function ?

Better way to maintain such asynctask class for delete, insert , update?

Appreciate any suggestions and advices. Thank you.

Body:
To Address your 2nd Question:

Google has posted an Android Room Codelab here which has laid out a concise MVVM architecture for implementing Room in Android:

(source: google.com)

Here the recommendation is to have database operations handled by a public static ExecutorService within the Database class. The location of the ExecutorService class can vary, just remember the idea is in MVVM your view does not care about how data are actually CURD'ed, that's the responsibility of the ViewModel, not View.

github repository for this code lab

In short, to apply a similar idea to your code, it would be something like this:

class YourRepository {
    private FeedEntryDAO mFeedEntryDAO;

    YourRepository(Application application) {
        YourDatabase db = YourDatabase.getDatabase(application);
        mFeedEntryDAO = db.feedEntryDAO();
        mAllWords = mWordDao.getAlphabetizedWords();
    }

    void update(FeedEntry feedEntry) {
        Database.databaseExecutor.execute(() - > {
            mFeedEntryDAO.update(feedEntry);
        });
    }
}

class YourViewModel extends ViewModel {
    private YourRepository mRepository;
    void update(FeedEntry feedEntry) {
        mRepository.update(feedEntry)
    }
}

By doing this, your View can directly call viewModel.update(feedEntries[0]).

One important thing to mention is the mFeedEntryDAO.update(feedEntry) will automatically trigger the onChanged callback of your observer on the getFeedEntrys LiveData.

This is quite handy in your case. You can read more about how the trigger happens here.


问:
Laravel, get all orders of the stores in one group if the stores have the same group id
I'm stuck in a very complex problem, I have stores, groups, and orders table
I want to show all orders of all stores that have the same group id
I tried but what I get is group of stores individually
please check the screenshot you will understand my issue

For grouped stores I think should show both the group and the store

thank you in advance

```<code>// show the last 7 days report
public function getSalesStores()
{
    $weekStart = Carbon::parse('last Sunday')->subdays(7);
    $weekEnd = $weekStart->copy()->adddays(7);

    $allusers = User::getAllUsers();
    $allgroups = storeGroup::getAllGroups();

    $allstores = Storeinfo::select('id', 'store_name', 'site_percent', 'fee_type', 'store_group_id')
        ->whereHas('userorders', function ($query) use ($weekStart, $weekEnd) {
            $query->whereBetween('order_date', [$weekStart, $weekEnd]);
        })
        ->with(['userorders' => function ($query) use ($weekStart, $weekEnd) {
            $query
                ->whereBetween('order_date', [$weekStart, $weekEnd])
                ->whereNotIn('confirmed', ['c', 'a', 'r'])
                ->groupBy('userorders.order_number');
        }])
        ->orderBy('storeinfos.store_name')
        ->get();

        $groupedStores = $allstores->where('store_group_id', '!=', null);

return view('managedashboard.cservicedashboard.sales_orders_bystore.archive', compact('allusers', 'allstores','allgroups','groupedStores'));
}
</code>```

Blade:

```<code>   <table class="table table-striped table-bordered table-hover" id="postTable">
    <p class="tabletitle">Sales Report</p>
    <thead>
    <tr>
        <th class="textcenter">Store</th>
        <th class="textcenter">Total</th>
        <th class="textcenter">our fee</th>
        <th class="textcenter">Pay to store</th>
        <th class="textcenter">Order number</th>
        <th class="textcenter">Date</th>
        <th class="textcenter">Store Name</th>
        <th class="textcenter">Customer Name</th>
    </tr>
</thead>
<tbody>
    @foreach($groupedStores as $key => $store)

        @php
            $class = $key % 2 === 0 ? 'even' : 'odd';
            $fee=0;
        @endphp
    <tr class="{{$class}}">
        <td class="storename" rowspan="{{ $store->userorders->count() + 1 }}">
                  @foreach($allgroups as $allgroup)
                        @if(($store->store_group_id)==$allgroup->id)
                            {{$allgroup->name}}
                          @endif
                   @endforeach
        </td>
    </tr>
     @foreach($store->userorders as $userorder)

            <tr>
                <td class="textcenter">
                    {{number_format($userorder->totalpayment, 2, '.', ',')}}
                </td>

                <td class="textcenter">

                    @if($store->fee_type=='total')
                        {{number_format(($userorder->totalpayment * ($store->site_percent / 100)), 2, '.', ',')}}
                        @else
                        {{number_format(($userorder->order_subtotal * ($store->site_percent / 100)), 2, '.', ',')}}

                    @endif

                    @php
                            if($store->fee_type=='total') {
                            $fee = $fee + number_format(($userorder->totalpayment * ($store->site_percent/100)), 2, '.', ',');
                                                 }
                        else {
                               $fee = $fee + number_format(($userorder->order_subtotal *
                               ($store->site_percent/100)), 2, '.', ',');
                              }
                    @endphp
                </td>

                <td class="textcenter">
                    <!-- Pay to Store -->
                    @if($store->fee_type=='total')
                        {{number_format(($userorder->totalpayment - ($userorder->totalpayment * ($store->site_percent/100))), 2, '.', ',')}}

                        @else
                            {{number_format(($userorder->totalpayment -
                            ($userorder->order_subtotal * ($store->site_percent/100))), 2, '.', ',')}}
                    @endif
                </td>

                <td class="textcenter">
                    {{$userorder->order_number}}
                </td>

                <td class="textcenter">
                    {{date('D d M, Y', strtotime($userorder->order_date))}}
                </td>

                <!--  Store Name  -->
                <td class="textcenter">
                    @foreach($allusers as $alluser)
                        @if(($userorder->user_id)==$alluser->id)
                            {{$alluser->fname}}
                        @endif
                    @endforeach
                </td>

                <!--  Customer Name  -->
                <td class="textcenter">
                    @foreach($allusers as $alluser)
                        @if(($userorder->user_id)==$alluser->id)
                            {{$alluser->fname}}
                        @endif
                    @endforeach
                </td>
            </tr>

            @endforeach <!-- end orders loop -->

    <tr>
        <td class="totalstyle">TOTAL</td>
        <td class="totalstyle">
            {{number_format($store->userorders->sum('totalpayment'), 2, '.', ',')}}
        </td>

        <td class="totalstyle">
            {{$fee}}
        </td>

        <td class="totalstyle">
            {{number_format($store->userorders->sum('totalpayment')-($fee), 2, '.', ',')}}
        </td>
    </tr>

    @endforeach <!-- end main store loop -->
</code>```

答:
All you need is to grab the query the data and reformat it accordingly. Then you can simply display the data in view using foreach loop. For the models StoreGroup, Store and Order, you can do something like given below. That would give u data in the format specified in "result" section of the attachment.</p>

```<code>$storeGroupNames = StoreGroup::query()
    ->pluck('name', 'id');
$data = Order::query()
    ->with('store')
    ->get()
    ->groupBy(function (Order $order) {
        return $order->store->store_group_id;
    })
    ->mapWithKeys(function (Collection $orders, $storeGroupId) use ($storeGroupNames) {
        $storeGroupName = $storeGroupNames->get($storeGroupId);

        return [$storeGroupName => $orders];
    });
dd($data);
</code>```

Body:
I'm stuck in a very complex problem, I have stores, groups, and orders table
I want to show all orders of all stores that have the same group id
I tried but what I get is group of stores individually
please check the screenshot you will understand my issue

For grouped stores I think should show both the group and the store

thank you in advance

// show the last 7 days report
public function getSalesStores()
{
    $weekStart = Carbon::parse('last Sunday')->subdays(7);
    $weekEnd = $weekStart->copy()->adddays(7);

    $allusers = User::getAllUsers();
    $allgroups = storeGroup::getAllGroups();

    $allstores = Storeinfo::select('id', 'store_name', 'site_percent', 'fee_type', 'store_group_id')
        ->whereHas('userorders', function ($query) use ($weekStart, $weekEnd) {
            $query->whereBetween('order_date', [$weekStart, $weekEnd]);
        })
        ->with(['userorders' => function ($query) use ($weekStart, $weekEnd) {
            $query
                ->whereBetween('order_date', [$weekStart, $weekEnd])
                ->whereNotIn('confirmed', ['c', 'a', 'r'])
                ->groupBy('userorders.order_number');
        }])
        ->orderBy('storeinfos.store_name')
        ->get();

        $groupedStores = $allstores->where('store_group_id', '!=', null);

return view('managedashboard.cservicedashboard.sales_orders_bystore.archive', compact('allusers', 'allstores','allgroups','groupedStores'));
}

Blade:

Sales Report

        Store
        Total
        our fee
        Pay to store
        Order number
        Date
        Store Name
        Customer Name

    @foreach($groupedStores as $key => $store)

        @php
            $class = $key % 2 === 0 ? 'even' : 'odd';
            $fee=0;
        @endphp

        userorders->count() + 1 }}">
                  @foreach($allgroups as $allgroup)
                        @if(($store->store_group_id)==$allgroup->id)
                            {{$allgroup->name}}
                          @endif
                   @endforeach

     @foreach($store->userorders as $userorder)

                    {{number_format($userorder->totalpayment, 2, '.', ',')}}

                    @if($store->fee_type=='total')
                        {{number_format(($userorder->totalpayment * ($store->site_percent / 100)), 2, '.', ',')}}
                        @else
                        {{number_format(($userorder->order_subtotal * ($store->site_percent / 100)), 2, '.', ',')}}

                    @endif

                    @php
                            if($store->fee_type=='total') {
                            $fee = $fee + number_format(($userorder->totalpayment * ($store->site_percent/100)), 2, '.', ',');
                                                 }
                        else {
                               $fee = $fee + number_format(($userorder->order_subtotal *
                               ($store->site_percent/100)), 2, '.', ',');
                              }
                    @endphp

                    @if($store->fee_type=='total')
                        {{number_format(($userorder->totalpayment - ($userorder->totalpayment * ($store->site_percent/100))), 2, '.', ',')}}

                        @else
                            {{number_format(($userorder->totalpayment -
                            ($userorder->order_subtotal * ($store->site_percent/100))), 2, '.', ',')}}
                    @endif

                    {{$userorder->order_number}}

                    {{date('D d M, Y', strtotime($userorder->order_date))}}

                    @foreach($allusers as $alluser)
                        @if(($userorder->user_id)==$alluser->id)
                            {{$alluser->fname}}
                        @endif
                    @endforeach

                    @foreach($allusers as $alluser)
                        @if(($userorder->user_id)==$alluser->id)
                            {{$alluser->fname}}
                        @endif
                    @endforeach

            @endforeach

        TOTAL

            {{number_format($store->userorders->sum('totalpayment'), 2, '.', ',')}}

            {{$fee}}

            {{number_format($store->userorders->sum('totalpayment')-($fee), 2, '.', ',')}}

    @endforeach

Body:
All you need is to grab the query the data and reformat it accordingly. Then you can simply display the data in view using foreach loop. For the models StoreGroup, Store and Order, you can do something like given below. That would give u data in the format specified in "result" section of the attachment.

$storeGroupNames = StoreGroup::query()
    ->pluck('name', 'id');
$data = Order::query()
    ->with('store')
    ->get()
    ->groupBy(function (Order $order) {
        return $order->store->store_group_id;
    })
    ->mapWithKeys(function (Collection $orders, $storeGroupId) use ($storeGroupNames) {
        $storeGroupName = $storeGroupNames->get($storeGroupId);

        return [$storeGroupName => $orders];
    });
dd($data);


问:
JS intervals and timeouts unexpectedly stop in webkit
Does anyone meet the problem when all the timeouts and intervals are stopped without any reason?

It seems that it happens in WebKit browsers, including QtWebKit custom app. Especially when minimized, but not every time.

I've never seen the problem at my PC, but several customers report the symptoms that point on it, and in logs I see that their client stops pinging the server.

The project uses ExtJS, Google Maps and some other open-source libraries.

答: Chrome/webkit suspend timeouts/intervals when the tab is moved to the background. That may be the issue here (you customers may have switched tabs whilst your intervals/timeouts where running). Check my SO-question for more information, or see the suspension in action </p>