问:
Extensible Records and Higher Order Functions
I want to specify a type for records that have an id field whose type is a Uuid. So, I'm using extensible records. The type looks like this:

```<code>type alias WithId a = { a | id : Uuid }
</code>```

So far, so good. But then I went to create a Json.Encoder -- that is, a function of type WithId a -> Value -- for this type. I need a way to encode the underlying value, so I want to take a first argument of type a -> Value. Since I know a is a record, I can safely assume it is encoded to a JSON object, even though Elm doesn't expose the data types for Value.

However, when I create such a function, I get a compile error:

```<code>    The argument to function `encoder` is causing a mismatch.

27|             encoder a
                        ^
Function `encoder` is expecting the argument to be:

    a

But it is:

    WithId a

Hint: Your type annotation uses type variable `a` which means any type of value
can flow through. Your code is saying it CANNOT be anything though! Maybe change
your type annotation to be more specific? Maybe the code has a problem? More at:
<https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/type-annotations.md>

Detected errors in 1 module.
</code>```

I'm confused. Isn't something of type WithId a going to contain all the fields of a, and therefore shouldn't WithId a be an a through the type alias structural typing?

What am I missing? Why isn't the type alias of WithId a allowing me to use a WithId a as an instance of a, even though it is defined as {a|...}?

ADDENDUM

I've marked an answer below (which amounts to "You just can't do that, but here's what you're supposed to be doing."), but I'm still a bit unsatisfied. I guess I'm confused by the use of the term type alias. My understanding was that records were always a type alias, because they were explicitly specifying a subset of fields among all possible fields...but the underlying type was still the unifying record type (akin to a JS Object).

I guess I don't understand why we say:

```<code>type alias Foo = { bar : Int }
</code>```

instead of

```<code>type Foo = { bar : Int }
</code>```

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

ADDENDUM 2

My goal is not just to have a type WithId that specifies there is an .id on a field, but rather to have two types: Foo and WithId Foo where Foo has structure { bar:Int } and WithId Foo has structure { bar:Int, id:Uuid}.  I'd then like to also have a WithId Baz, WithId Quux, etc., etc., with a single encoder and single decoder function for WithId a.

The basic issue is that I have persisted and non-persisted data, which have the exact same structure, except that once something is persisted, I have an id. And want I type-level guarantees that records are persisted in certain cases, so Maybe doesn't work.

答:
The only thing we know about an instance of WithId ais that is has a .id field. If we encode a WithId a the best we can do is encode the .id value.

```<code>type alias Uuid =
    String

encodeUuid : Uuid -> Value
encodeUuid =
    Encode.string

type alias WithId a =
    { a | id : Uuid }

encode : WithId a -> Value
encode withId =
    encodeUuid withId.id
</code>```

Body:
I want to specify a type for records that have an id field whose type is a Uuid. So, I'm using extensible records. The type looks like this:

type alias WithId a = { a | id : Uuid }

So far, so good. But then I went to create a Json.Encoder -- that is, a function of type WithId a -> Value -- for this type. I need a way to encode the underlying value, so I want to take a first argument of type a -> Value. Since I know a is a record, I can safely assume it is encoded to a JSON object, even though Elm doesn't expose the data types for Value.

However, when I create such a function, I get a compile error:

    The argument to function `encoder` is causing a mismatch.

27|             encoder a
                        ^
Function `encoder` is expecting the argument to be:

    a

But it is:

    WithId a

Hint: Your type annotation uses type variable `a` which means any type of value
can flow through. Your code is saying it CANNOT be anything though! Maybe change
your type annotation to be more specific? Maybe the code has a problem? More at:
<https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/type-annotations.md>

Detected errors in 1 module.

I'm confused. Isn't something of type WithId a going to contain all the fields of a, and therefore shouldn't WithId a be an a through the type alias structural typing?

What am I missing? Why isn't the type alias of WithId a allowing me to use a WithId a as an instance of a, even though it is defined as {a|...}?

ADDENDUM

I've marked an answer below (which amounts to "You just can't do that, but here's what you're supposed to be doing."), but I'm still a bit unsatisfied. I guess I'm confused by the use of the term type alias. My understanding was that records were always a type alias, because they were explicitly specifying a subset of fields among all possible fields...but the underlying type was still the unifying record type (akin to a JS Object).

I guess I don't understand why we say:

type alias Foo = { bar : Int }

instead of

type Foo = { bar : Int }

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

ADDENDUM 2

My goal is not just to have a type WithId that specifies there is an .id on a field, but rather to have two types: Foo and WithId Foo where Foo has structure { bar:Int } and WithId Foo has structure { bar:Int, id:Uuid}.  I'd then like to also have a WithId Baz, WithId Quux, etc., etc., with a single encoder and single decoder function for WithId a.

The basic issue is that I have persisted and non-persisted data, which have the exact same structure, except that once something is persisted, I have an id. And want I type-level guarantees that records are persisted in certain cases, so Maybe doesn't work.

Body:
The only thing we know about an instance of WithId ais that is has a .id field. If we encode a WithId a the best we can do is encode the .id value.

type alias Uuid =
    String

encodeUuid : Uuid -> Value
encodeUuid =
    Encode.string

type alias WithId a =
    { a | id : Uuid }

encode : WithId a -> Value
encode withId =
    encodeUuid withId.id


来源: stackexchange

问:
How can I perform a generic cast to the correct subclass type?
Currently I have the following code for a method that I have created:

```<code>public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}
</code>```

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

```<code>return this.overlaps((collider.subclassType()) collider);
</code>```

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

```<code>BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}
</code>```

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?

答:
I think this sounds like a design problem.

Why don't you use an interface instead of a class?

```<code>public boolean overlaps(Collidable collider) {
    return collider.overlaps(this);
}
</code>```

You would need a new interface that would look something like this:

```<code>public interface Collidable {
    boolean overlaps(Collidable collider);
}
</code>```

You may use a "same class collider" or whatever you need:

```<code>public class SameClassCollider implements Collidable {
    @Override
    public boolean overlaps(Collidable collider) {
        return (collider instanceof this.getClass());
    }
}
</code>```

I mainly suggested to use a Strategy pattern. You may also would like to take a look at the Decorator pattern in case you may want to build more sofisticated collitions.

ContentLicense: CC BY-SA 3.0

Body:
Currently I have the following code for a method that I have created:

public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

return this.overlaps((collider.subclassType()) collider);

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?

Body:
I think this sounds like a design problem.

Why don't you use an interface instead of a class?

public boolean overlaps(Collidable collider) {
    return collider.overlaps(this);
}

You would need a new interface that would look something like this:

public interface Collidable {
    boolean overlaps(Collidable collider);
}

You may use a "same class collider" or whatever you need:

public class SameClassCollider implements Collidable {
    @Override
    public boolean overlaps(Collidable collider) {
        return (collider instanceof this.getClass());
    }
}

I mainly suggested to use a Strategy pattern. You may also would like to take a look at the Decorator pattern in case you may want to build more sofisticated collitions.


问:
Retrieving data from a form?
I am trying to enter data to a website using python, search for it and then extract the address, but not sure where to proceed after this. My code as of now looks like this:

```<code>import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")
for form in br.forms():
     print "Form name:", form.name
     print form
</code>```

This gives me the formname and the form. The form has multiple fields under drop down and I need to select Tax ID search and fetch the value '218N02W27C003' and then should display the result. Out of this result we just need to take the parcel address and display the output.

答:
As you already know the name of form, form name can be selected using

```<code>for form in br.forms():
        if form.attrs.get('name') == 'frmSearch':
            br.form = form
            break
</code>```

To select a option from drop down menu, pass the value of option as a list

br.form['ddlType']=["taxid"]

overall code:

```<code>import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")

for form in br.forms():
    if form.attrs.get('name') == 'frmSearch':
        br.form = form
        break

br.form['ddlType']=["taxid"]
br['txtParm']="abcdef"
req=br.submit().read()
print req
</code>```

for reference HTML code was something like this.

```<code><select name="ddlType" id="ddlType">
    <option value="owner">Owner Search</option>
    <option value="buyer">Buyer Search</option>
    <option value="address">Address Search</option>
    <option value="subdivision">Subdivision Search</option>
    <option value="subdivision2">Subdivision ID Search</option>
    <option value="taxid">Tax ID Search</option>
    <option value="parcel">Parcel ID Search</option>

</select>
</code>```

Title: Retrieving data from a form?

Body:
I am trying to enter data to a website using python, search for it and then extract the address, but not sure where to proceed after this. My code as of now looks like this:

import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")
for form in br.forms():
     print "Form name:", form.name
     print form

This gives me the formname and the form. The form has multiple fields under drop down and I need to select Tax ID search and fetch the value '218N02W27C003' and then should display the result. Out of this result we just need to take the parcel address and display the output.

Body:
As you already know the name of form, form name can be selected using

for form in br.forms():
        if form.attrs.get('name') == 'frmSearch':
            br.form = form
            break

To select a option from drop down menu, pass the value of option as a list

br.form['ddlType']=["taxid"]

overall code:

import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")

for form in br.forms():
    if form.attrs.get('name') == 'frmSearch':
        br.form = form
        break

br.form['ddlType']=["taxid"]
br['txtParm']="abcdef"
req=br.submit().read()
print req

for reference HTML code was something like this.

<select name="ddlType" id="ddlType">
    <option value="owner">Owner Search</option>
    <option value="buyer">Buyer Search</option>
    <option value="address">Address Search</option>
    <option value="subdivision">Subdivision Search</option>
    <option value="subdivision2">Subdivision ID Search</option>
    <option value="taxid">Tax ID Search</option>
    <option value="parcel">Parcel ID Search</option>

</select>


问:
How to count duplicate items in XMLList and assign them into an ArrayCollection?
I've following XMLList ,

<party/>
<party/>
<party/>
<party>A</party>
<party>B</party>
<party>C</party>
<party>A</party>
<party>B</party>
<party>C</party>
<party>D</party>
<party>E</party>
<party>D</party>
<party>A</party>
<party/>
<party>C</party>

I would like eliminate blank node and to make an ArrayCollection like ( with count of individual party),

tArr = new ArrayCollection([ {Party:"A", Count:3},
                      {Party:"B", Count:2},
                      {Party:"C", Count:3},
                  {Party:"D", Count:2},
                  {Party:"E", Count:1},
                     ]);

Thanks in advance.

答:
If you have the list of possible parties it's just:</p>

```<code>var partiesObjs:ArrayCollection = new ArrayCollection();

var xml:XML = <root><party/><party/><party/><party>A</party><party>B</party><party>C</party><party>A</party><party>B</party><party>C</party><party>D</party><party>E</party><party>D</party><party>A</party><party/><party>C</party></root>;
var parties:Array = ["A","B","C","D"]

for each(var p:String in parties){
  var count:int = xml..party.(toString() == p).length()
  partiesObjs.addItem( {Party:p, Count:count} )
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you have the list of possible parties it's just:

var partiesObjs:ArrayCollection = new ArrayCollection();

var xml:XML = <root><party/><party/><party/><party>A</party><party>B</party><party>C</party><party>A</party><party>B</party><party>C</party><party>D</party><party>E</party><party>D</party><party>A</party><party/><party>C</party></root>;
var parties:Array = ["A","B","C","D"]

for each(var p:String in parties){
  var count:int = xml..party.(toString() == p).length()
  partiesObjs.addItem( {Party:p, Count:count} )
}


问:
How can I get the nearest points each other in a given list in python?
```<code>from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]
</code>```

<p>After this step I don't know how to do further.. </p>

答:
Try building a dictionary of (pair, dist) key-value tuples.

Then find the tuple with the minimum distance value.

```<code>import operator as op

pair_distances = {pair: dist(*pair) for pair in combinations(p, 2)}
min(pair_distances.items(), key=op.itemgetter(1))
#(((0, 0), (1, 1)), 1.4142135623730951)
</code>```

Body:
from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]

After this step I don't know how to do further..

Body:
Try building a dictionary of (pair, dist) key-value tuples.

Then find the tuple with the minimum distance value.

import operator as op

pair_distances = {pair: dist(*pair) for pair in combinations(p, 2)}
min(pair_distances.items(), key=op.itemgetter(1))
#(((0, 0), (1, 1)), 1.4142135623730951)


问:
Redirect to another controller after clicking on the button

Simple Problem:

I have a button and whenever the user will click on this button, I want to redirect him to another action in another controller. How could I do that?!

This code would be in the .html.erb file

```<code><%= form.submit "Create Request"%>
</code>```

Note: i don't want to use link_to! Additionally, I could not use redirect_to in the controller because i used render there.

答:
Using remote: true in the form , Ex:

```<code><% form_tag create_path(params_you_needed), remote: true do |form| %>
</code>```

add rails js for create method create.js.erb

```<code>$('#id').html('<%= j render(:partial => "file/location", :locals => {data}) %>');
</code>```

and in that you can render the file you need!

Body:
Simple Problem:

I have a button and whenever the user will click on this button, I want to redirect him to another action in another controller. How could I do that?!

This code would be in the .html.erb file

<%= form.submit "Create Request"%>

Note: i don't want to use link_to! Additionally, I could not use redirect_to in the controller because i used render there.

Body:
Using remote: true in the form , Ex:

<% form_tag create_path(params_you_needed), remote: true do |form| %>

add rails js for create method create.js.erb

$('#id').html('<%= j render(:partial => "file/location", :locals => {data}) %>');

and in that you can render the file you need!


问:
Chrome/Internet explorer browser refresh (F5, ctrl+R, refresh arrow etc.) not working using Angular (2+) project on remote server
I have a problem with a simple manual refresh (F5, ctrl+R, refresh arrow etc.) action for a deployed Angular (2+) project on a remote server.

Testing the project locally (development and build prod testet) works perfectly, even when deployed to our intern server, refresh works normally.

On the remote server, any refresh (F5, ctrl+R etc.) is ignored. I get no errors, no page not found, nothing - the browser just stays on the current page with no change or refresh.

In the network tab, it doesn't even send a request to the server.

I can see that the favicon blinks for a millisecond (so something is registered front-end).

The only way I can force the refresh is to change the URL manually.

PS. The only visible differnce is that the remote server runs on https:// protocol.

I have searched for hours on google without any help.

答:
Sounds like a bad router configuration on the angular side is causing a route loop. I would double check your app.module.ts routes. You can also add enableTracing to diagnose the routing:

{ enableTracing: true }

app.module.ts

```<code>const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- Add this to debug routes
    )
  ]
})
export class AppModule { }
</code>```

Body:
Sounds like a bad router configuration on the angular side is causing a route loop. I would double check your app.module.ts routes. You can also add enableTracing to diagnose the routing:

{ enableTracing: true }

app.module.ts

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- Add this to debug routes
    )
  ]
})
export class AppModule { }


问:
I need help understanding this iteration of two, two tuples in Python3
I need help trying to understand why this function returns forenames surnames instead of names. It's the first for loop that's got me confused I believe. For some background, the paths in the first for loop are just text files that list different names, one per line. Why are we returning forenames and surnames when each name from the files are being appended into the names variable? Please help, and let me know if more information is needed.

```<code>import random

def get_forenames_and_surnames():
    forenames = []
    surnames = []
    for names, filename in ((forenames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/forenames.txt"),
                        (surnames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/surnames.txt")):
        with open(filename, encoding="utf8") as file:
            for name in file:
                names.append(name.rstrip())
    return forenames, surnames

forenames, surnames = get_forenames_and_surnames()
with open("test-names1.txt", "w", encoding="utf8") as file:
    for i in range(100):
        line = "{0} {1}\n".format(random.choice(forenames),
                                  random.choice(surnames))
        file.write(line)
</code>```

The file for with list of forenames looks like:

```<code>Ailish
Cayden
Cohen
Maison
Becky
Dodou
Nickie
Zachary
Climate
</code>```

The file with a list of surnames is the same but with different names.

答:
what it is returning is essentially this:

```<code>(['Ailish', 'Cayden', 'Cohen', 'Maison', 'Becky', 'Dodou', 'Nickie', 'Zachary', 'Climate'],
['Ailish2', 'Cayden2', 'Cohen2', 'Maison2', 'Becky2', 'Dodou2', 'Nickie2', 'Zachary2',
'Climate2'])
</code>```

so you are getting a tuple with two objects in it, each object is a list of names the first list in the tuple being named forenames and the second named surnames.

The end part of that code you wrote is just taking a random name from the first list of names and matching it with a random name from the second list of names.

Body:
I need help trying to understand why this function returns forenames surnames instead of names. It's the first for loop that's got me confused I believe. For some background, the paths in the first for loop are just text files that list different names, one per line. Why are we returning forenames and surnames when each name from the files are being appended into the names variable? Please help, and let me know if more information is needed.

import random

def get_forenames_and_surnames():
    forenames = []
    surnames = []
    for names, filename in ((forenames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/forenames.txt"),
                        (surnames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/surnames.txt")):
        with open(filename, encoding="utf8") as file:
            for name in file:
                names.append(name.rstrip())
    return forenames, surnames

forenames, surnames = get_forenames_and_surnames()
with open("test-names1.txt", "w", encoding="utf8") as file:
    for i in range(100):
        line = "{0} {1}\n".format(random.choice(forenames),
                                  random.choice(surnames))
        file.write(line)

The file for with list of forenames looks like:

Ailish
Cayden
Cohen
Maison
Becky
Dodou
Nickie
Zachary
Climate

The file with a list of surnames is the same but with different names.

Body:
what it is returning is essentially this:

(['Ailish', 'Cayden', 'Cohen', 'Maison', 'Becky', 'Dodou', 'Nickie', 'Zachary', 'Climate'],
['Ailish2', 'Cayden2', 'Cohen2', 'Maison2', 'Becky2', 'Dodou2', 'Nickie2', 'Zachary2',
'Climate2'])

so you are getting a tuple with two objects in it, each object is a list of names the first list in the tuple being named forenames and the second named surnames.

The end part of that code you wrote is just taking a random name from the first list of names and matching it with a random name from the second list of names.


问:
Call PHP function in ajax, Synchronous XMLHttpRequest deprecarted
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

```<code>[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
</code>```

My index.php relevant data, the error is on the xmlhttp.open line.

```<code>disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);
</code>```

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

```<code>$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");
</code>```

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

```<code><div id ="disp_data"></div>

<script src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">

(function() {
  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);

    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  sendXHR("GET", "update.php?status=disp", null, function(response) {
    document.getElementById("disp_data").innerHTML=newXHR.responseText;
  });

})();

</script>

</body>
</code>```

my full update.php file

```<code>$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "<table>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>";   echo $row["id"]; echo "</td>";
echo "<td>";  echo $row["name"];  echo "</td>";
echo "<td>";  echo $row["city"];  echo "</td>";

echo "</tr>";
}
echo "</table>";
}
</code>```

答:
try this way

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "update.php?status=disp",false);
xmlhttp.send();
</code>```

use xmlhttp .send(); method for send a request to athore page

To avoid this warning, do not use false in perameter:

```<code>async: false
</code>```

Body:
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

My index.php relevant data, the error is on the xmlhttp.open line.

disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

my full update.php file

$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "
";
while($row = mysqli_fetch_array($res))
{
echo "
";
echo "";   echo $row["id"]; echo "	";
echo "";  echo $row["name"];  echo "	";
echo "";  echo $row["city"];  echo "	";

echo "
";
}
echo "
";
}

Body:
try this way

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "update.php?status=disp",false);
xmlhttp.send();

use xmlhttp .send(); method for send a request to athore page

To avoid this warning, do not use false in perameter:

async: false


问:
How to make an async event run continuously?
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

```<code>static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}
</code>```

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

```<code>    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }
</code>```

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?

答: Your task is outside the five second loop, so of course it only fires once.</p>

Body:
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?


问:
Core Data Query, most recent car per year?
In my model I have a Car entity.

Car
 year
 createDate
 name

I want to run a fetch that returns all most recent cars per year where name is not nil (name can be nil).

So, if I have 3 cars with year 2000 and 5 cars with year 2010, I want to get a total of 2 cars out of the fetch request (the most recent for year 2000 and the most recent for year 2010).

I am not sure how to write the proper predicate to achieve this. I looked in the returnsDistinctResults option, but I am not sure that is the right path go go down and it also said that it only works with NSDictionaryResultType which does not work for me.

What would be the proper query/predicate to get this done?

答:
You can achieve this, if say you're passing an array of years into an algorithm, and expecting a result in the form of a dictionary, with each year you passed in as a key for an object that corresponds to the most recent car of that year.

ie:

```<code>let years : [Int] = [2000, 2005]

//The ideal method:

func mostRecentFor<T>(years: [Int]) -> [String:T]
</code>```

Assuming you only use a small number of search years, and that your database has a small number of cars, you shouldn't have to worry about threading. Otherwise, for this approach you'd have to use concurrency, or a dedicated thread for the fetching to avoid blocking the main thread. For testing purposes you shouldn't need to.

To accomplish this, you would use a method that goes along the following line.

First, a number predicate should be used on the year like other answers have suggested.
For this you would use the date format for NSPredicate:

```<code>NSPredicate(format: "date == %@", year)
</code>```

Your model should, therefore, have the year as a parameter and the actual nsdate as another. You would then use a fecthLimit parameter set to 1, and a sortDescriptor applied to the nsDate key parameter. The combination of the later two will ensure that only the youngest or oldest value is returned for the given year.

```<code>func mostRecentFor(years: [Int]) -> [String:Car] {
        let result : [String:Car] = [:]
        for year in years {
           let request: NSFetchRequest<CarModel> = CarModel.fetchRequest()
           request.predicate = NSPredicate(format: "date == %@ AND name != nil", year)
           request.fetchLimit = 1
           let NSDateDescriptor: let sectionSortDescriptor = NSSortDescriptor(key: "nsDate", ascending: true)
           let descriptors = [NSDateDescriptor]
           fetchRequest.sortDescriptors = descriptors
           do {
                let fetched = try self.managedObjectContext.fetch(request) as
                [CarModel]
                guard !fetched.isEmpty, fetched.count == 1 else {
                    print("No Car For year: \(year)")
                    return
                }
                result["\(year)"] = new[0].resultingCarStruct //custom parameter here.. see bellow
            } catch let err {
                print("Error for Year: \(year), \(err.localizedDescription)")
            }
        }
        return result
}
</code>```

We use ascending set to true here, because we want the first value, the one actually returned due to the fetchLimit value of 1, to be the earliest car of the said year, or the one with the smallest timestamp for it's nsDate key.

This Should give you a simple fetch query for small datastores and testing. Also, creating a method or parameter to interpret CarModel into it's Car struct  counterpart could make it simpler to go from CD to your memory objects.

So you'd search for your cars like so:

```<code>let years = [1985, 1999, 2005]
let cars = mostRecentFor(years: years)

// cars = ["1985": Car<year: 1985, name: "Chevrolet", nsDate: "April 5th 1985">, "1999" : Car<year: 1999, name: "Toyota Corolla", nsDate: "February 5th 1999">]
// This examples suggests that no cars were found for 2005
</code>```

Body:
You can achieve this, if say you're passing an array of years into an algorithm, and expecting a result in the form of a dictionary, with each year you passed in as a key for an object that corresponds to the most recent car of that year.

ie:

let years : [Int] = [2000, 2005]

//The ideal method:

func mostRecentFor<T>(years: [Int]) -> [String:T]

Assuming you only use a small number of search years, and that your database has a small number of cars, you shouldn't have to worry about threading. Otherwise, for this approach you'd have to use concurrency, or a dedicated thread for the fetching to avoid blocking the main thread. For testing purposes you shouldn't need to.

To accomplish this, you would use a method that goes along the following line.

First, a number predicate should be used on the year like other answers have suggested.
For this you would use the date format for NSPredicate:

NSPredicate(format: "date == %@", year)

Your model should, therefore, have the year as a parameter and the actual nsdate as another. You would then use a fecthLimit parameter set to 1, and a sortDescriptor applied to the nsDate key parameter. The combination of the later two will ensure that only the youngest or oldest value is returned for the given year.

func mostRecentFor(years: [Int]) -> [String:Car] {
        let result : [String:Car] = [:]
        for year in years {
           let request: NSFetchRequest<CarModel> = CarModel.fetchRequest()
           request.predicate = NSPredicate(format: "date == %@ AND name != nil", year)
           request.fetchLimit = 1
           let NSDateDescriptor: let sectionSortDescriptor = NSSortDescriptor(key: "nsDate", ascending: true)
           let descriptors = [NSDateDescriptor]
           fetchRequest.sortDescriptors = descriptors
           do {
                let fetched = try self.managedObjectContext.fetch(request) as
                [CarModel]
                guard !fetched.isEmpty, fetched.count == 1 else {
                    print("No Car For year: \(year)")
                    return
                }
                result["\(year)"] = new[0].resultingCarStruct //custom parameter here.. see bellow
            } catch let err {
                print("Error for Year: \(year), \(err.localizedDescription)")
            }
        }
        return result
}

We use ascending set to true here, because we want the first value, the one actually returned due to the fetchLimit value of 1, to be the earliest car of the said year, or the one with the smallest timestamp for it's nsDate key.

This Should give you a simple fetch query for small datastores and testing. Also, creating a method or parameter to interpret CarModel into it's Car struct  counterpart could make it simpler to go from CD to your memory objects.

So you'd search for your cars like so:

let years = [1985, 1999, 2005]
let cars = mostRecentFor(years: years)

// cars = ["1985": Car<year: 1985, name: "Chevrolet", nsDate: "April 5th 1985">, "1999" : Car<year: 1999, name: "Toyota Corolla", nsDate: "February 5th 1999">]
// This examples suggests that no cars were found for 2005


问:
what is the difference between digital signature and digital certificate?
i've been google'ing the difference between digital signature and digital certificate (asymmetric encryption)
seems like they are the same. I would like to clarify if they are the same or not? many thanks!!!</p>

答:
Digital signature explained: </p>

```<code>Sender   : Encrypt(hash(message), priv_key) = dig_sign
Receiver : Decrypt(dig_sign, pub_key) => hash_of_message == hash(message)
</code>```

Body:
Digital signature explained:

Sender   : Encrypt(hash(message), priv_key) = dig_sign
Receiver : Decrypt(dig_sign, pub_key) => hash_of_message == hash(message)


问:
ideal aws instance type for neo4j database
neo4j 3.2 version is installed aws Linux ec2 instance. I am checking for the ideal instance type.

There are different projects persisted in the neo4j graph and each project can have around 50k nodes, a million relationships, and around 100k properties. A single save operation can have up to 25k nodes, 75k relations, and 10k properties. i tried out i2,d2,r largest instance type. everything is taking almost a minute or more for every "save" operation. In my windows operating system, max time it takes is 20 seconds.
what would be the ideal instance type in this scenario?

and i also doubt whether it has something to do with the neo4j.conf file. there are so many jvm paramaters mentioned in neo4j.conf in Linux aws. none of them are specified in my windows system.

```<code>#*****************************************************************
# Neo4j configuration
#
# For more details and a complete list of settings, please see
# https://neo4j.com/docs/operations-manual/current/reference/configuration-settings/
#*****************************************************************

# The name of the database to mount
#dbms.active_database=graph.db

# Paths of directories in the installation.
dbms.directories.data=/var/lib/neo4j/data
dbms.directories.plugins=/var/lib/neo4j/plugins
dbms.directories.certificates=/var/lib/neo4j/certificates
dbms.directories.logs=/var/log/neo4j
dbms.directories.lib=/usr/share/neo4j/lib
dbms.directories.run=/var/run/neo4j

# This setting constrains all `LOAD CSV` import files to be under the `import` directory. Remove or comment it out to
# allow files to be loaded from anywhere in the filesystem; this introduces possible security problems. See the
# `LOAD CSV` section of the manual for details.
dbms.directories.import=/var/lib/neo4j/import

# Whether requests to Neo4j are authenticated.
# To disable authentication, uncomment this line
#dbms.security.auth_enabled=false

# Enable this to be able to upgrade a store from an older version.
#dbms.allow_upgrade=true

# Java Heap Size: by default the Java heap size is dynamically
# calculated based on available system resources.
# Uncomment these lines to set specific initial and maximum
# heap size.
# dbms.memory.heap.initial_size=512m
#dbms.memory.heap.max_size=512m

# The amount of memory to use for mapping the store files, in bytes (or
# kilobytes with the 'k' suffix, megabytes with 'm' and gigabytes with 'g').
# If Neo4j is running on a dedicated server, then it is generally recommended
# to leave about 2-4 gigabytes for the operating system, give the JVM enough
# heap to hold all your transaction state and query context, and then leave the
# rest for the page cache.
# The default page cache memory assumes the machine is dedicated to running
# Neo4j, and is heuristically set to 50% of RAM minus the max Java heap size.
#dbms.memory.pagecache.size=10g

#*****************************************************************
# Network connector configuration
#*****************************************************************

# With default configuration Neo4j only accepts local connections.
# To accept non-local connections, uncomment this line:
dbms.connectors.default_listen_address=0.0.0.0

# You can also choose a specific network interface, and configure a non-default
# port for each connector, by setting their individual listen_address.

# The address at which this server can be reached by its clients. This may be the server's IP address or DNS name, or
# it may be the address of a reverse proxy which sits in front of the server. This setting may be overridden for
# individual connectors below.
#dbms.connectors.default_advertised_address=localhost

# You can also choose a specific advertised hostname or IP address, and
# configure an advertised port for each connector, by setting their
# individual advertised_address.

# Bolt connector
dbms.connector.bolt.enabled=true
#dbms.connector.bolt.tls_level=OPTIONAL
#dbms.connector.bolt.listen_address=:7687

# HTTP Connector. There must be exactly one HTTP connector.
dbms.connector.http.enabled=true
#dbms.connector.http.listen_address=:7474

# HTTPS Connector. There can be zero or one HTTPS connectors.
dbms.connector.https.enabled=true
#dbms.connector.https.listen_address=:7473

# Number of Neo4j worker threads.
#dbms.threads.worker_count=

#*****************************************************************
# SSL system configuration
#*****************************************************************

# Names of the SSL policies to be used for the respective components.

# The legacy policy is a special policy which is not defined in
# the policy configuration section, but rather derives from
# dbms.directories.certificates and associated files
# (by default: neo4j.key and neo4j.cert). Its use will be deprecated.

# The policies to be used for connectors.
#
# N.B: Note that a connector must be configured to support/require
#      SSL/TLS for the policy to actually be utilized.
#
# see: dbms.connector.*.tls_level

#bolt.ssl_policy=legacy
#https.ssl_policy=legacy

#*****************************************************************
# SSL policy configuration
#*****************************************************************

# Each policy is configured under a separate namespace, e.g.
#    dbms.ssl.policy.<policyname>.*
#
# The example settings below are for a new policy named 'default'.

# The base directory for cryptographic objects. Each policy will by
# default look for its associated objects (keys, certificates, ...)
# under the base directory.
#
# Every such setting can be overriden using a full path to
# the respective object, but every policy will by default look
# for cryptographic objects in its base location.
#
# Mandatory setting

#dbms.ssl.policy.default.base_directory=certificates/default

# Allows the generation of a fresh private key and a self-signed
# certificate if none are found in the expected locations. It is
# recommended to turn this off again after keys have been generated.
#
# Keys should in general be generated and distributed offline
# by a trusted certificate authority (CA) and not by utilizing
# this mode.

#dbms.ssl.policy.default.allow_key_generation=false

# Enabling this makes it so that this policy ignores the contents
# of the trusted_dir and simply resorts to trusting everything.
#
# Use of this mode is discouraged. It would offer encryption but no security.

#dbms.ssl.policy.default.trust_all=false

# The private key for the default SSL policy. By default a file
# named private.key is expected under the base directory of the policy.
# It is mandatory that a key can be found or generated.

#dbms.ssl.policy.default.private_key=

# The private key for the default SSL policy. By default a file
# named public.crt is expected under the base directory of the policy.
# It is mandatory that a certificate can be found or generated.

#dbms.ssl.policy.default.public_certificate=

# The certificates of trusted parties. By default a directory named
# 'trusted' is expected under the base directory of the policy. It is
# mandatory to create the directory so that it exists, because it cannot
# be auto-created (for security purposes).
#
# To enforce client authentication client_auth must be set to 'require'!

#dbms.ssl.policy.default.trusted_dir=

# Client authentication setting. Values: none, optional, require
# The default is to require client authentication.
#
# Servers are always authenticated unless explicitly overridden
# using the trust_all setting. In a mutual authentication setup this
# should be kept at the default of require and trusted certificates
# must be installed in the trusted_dir.

#dbms.ssl.policy.default.client_auth=require

# A comma-separated list of allowed TLS versions.
# By default TLSv1, TLSv1.1 and TLSv1.2 are allowed.

#dbms.ssl.policy.default.tls_versions=

# A comma-separated list of allowed ciphers.
# The default ciphers are the defaults of the JVM platform.

#dbms.ssl.policy.default.ciphers=

#*****************************************************************
# Logging configuration
#*****************************************************************

# To enable HTTP logging, uncomment this line
#dbms.logs.http.enabled=true

# Number of HTTP logs to keep.
#dbms.logs.http.rotation.keep_number=5

# Size of each HTTP log that is kept.
#dbms.logs.http.rotation.size=20m

# To enable GC Logging, uncomment this line
#dbms.logs.gc.enabled=true

# GC Logging Options
# see http://docs.oracle.com/cd/E19957-01/819-0084-10/pt_tuningjava.html#wp57013 for more information.
#dbms.logs.gc.options=-XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintPromotionFailure -XX:+PrintTenuringDistribution

# Number of GC logs to keep.
#dbms.logs.gc.rotation.keep_number=5

# Size of each GC log that is kept.
#dbms.logs.gc.rotation.size=20m

# Size threshold for rotation of the debug log. If set to zero then no rotation will occur. Accepts a binary suffix "k",
# "m" or "g".
#dbms.logs.debug.rotation.size=20m

# Maximum number of history files for the internal log.
#dbms.logs.debug.rotation.keep_number=7

#*****************************************************************
# Miscellaneous configuration
#*****************************************************************

# Enable this to specify a parser other than the default one.
#cypher.default_language_version=3.0

# Determines if Cypher will allow using file URLs when loading data using
# `LOAD CSV`. Setting this value to `false` will cause Neo4j to fail `LOAD CSV`
# clauses that load data from the file system.
#dbms.security.allow_csv_import_from_file_urls=true

# Retention policy for transaction logs needed to perform recovery and backups.
dbms.tx_log.rotation.retention_policy=1 days

# Enable a remote shell server which Neo4j Shell clients can log in to.
#dbms.shell.enabled=true
# The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
#dbms.shell.host=127.0.0.1
# The port the shell will listen on, default is 1337.
#dbms.shell.port=1337

# Only allow read operations from this Neo4j instance. This mode still requires
# write access to the directory for lock purposes.
#dbms.read_only=false

# Comma separated list of JAX-RS packages containing JAX-RS resources, one
# package name for each mountpoint. The listed package names will be loaded
# under the mountpoints specified. Uncomment this line to mount the
# org.neo4j.examples.server.unmanaged.HelloWorldResource.java from
# neo4j-server-examples under /examples/unmanaged, resulting in a final URL of
# http://localhost:7474/examples/unmanaged/helloworld/{nodeId}
#dbms.unmanaged_extension_classes=org.neo4j.examples.server.unmanaged=/examples/unmanaged

#********************************************************************
# JVM Parameters
#********************************************************************

# G1GC generally strikes a good balance between throughput and tail
# latency, without too much tuning.
dbms.jvm.additional=-XX:+UseG1GC

# Have common exceptions keep producing stack traces, so they can be
# debugged regardless of how often logs are rotated.
#dbms.jvm.additional=-XX:-OmitStackTraceInFastThrow

# Make sure that `initmemory` is not only allocated, but committed to
# the process, before starting the database. This reduces memory
# fragmentation, increasing the effectiveness of transparent huge
# pages. It also reduces the possibility of seeing performance drop
# due to heap-growing GC events, where a decrease in available page
# cache leads to an increase in mean IO response time.
# Try reducing the heap memory, if this flag degrades performance.
dbms.jvm.additional=-XX:+AlwaysPreTouch

# Trust that non-static final fields are really final.
# This allows more optimizations and improves overall performance.
# NOTE: Disable this if you use embedded mode, or have extensions or dependencies that may use reflection or
# serialization to change the value of final fields!
dbms.jvm.additional=-XX:+UnlockExperimentalVMOptions
dbms.jvm.additional=-XX:+TrustFinalNonStaticFields

# Disable explicit garbage collection, which is occasionally invoked by the JDK itself.
dbms.jvm.additional=-XX:+DisableExplicitGC

# Remote JMX monitoring, uncomment and adjust the following lines as needed. Absolute paths to jmx.access and
# jmx.password files are required.
# Also make sure to update the jmx.access and jmx.password files with appropriate permission roles and passwords,
# the shipped configuration contains only a read only role called 'monitor' with password 'Neo4j'.
# For more details, see: http://download.oracle.com/javase/8/docs/technotes/guides/management/agent.html
# On Unix based systems the jmx.password file needs to be owned by the user that will run the server,
# and have permissions set to 0600.
# For details on setting these file permissions on Windows see:
#     http://docs.oracle.com/javase/8/docs/technotes/guides/management/security-windows.html
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.port=3637
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.authenticate=true
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.ssl=false
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.password.file=/absolute/path/to/conf/jmx.password
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.access.file=/absolute/path/to/conf/jmx.access

# Some systems cannot discover host name automatically, and need this line configured:
#dbms.jvm.additional=-Djava.rmi.server.hostname=$THE_NEO4J_SERVER_HOSTNAME

# Expand Diffie Hellman (DH) key size from default 1024 to 2048 for DH-RSA cipher suites used in server TLS handshakes.
# This is to protect the server from any potential passive eavesdropping.
dbms.jvm.additional=-Djdk.tls.ephemeralDHKeySize=2048

#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.

# Name of the service
dbms.windows_service_name=neo4j

#********************************************************************
# Other Neo4j system properties
#********************************************************************
dbms.jvm.additional=-Dunsupported.dbms.udc.source=rpm
</code>```

答:
According to your specified configurations and the give recommended system requirements in documentation  at the official neo4j site I would suggest these instances:

1) If your application is burstable in nature, I would recommend Burstable Performance Instances like t2.xlarge(16 GB RAM, Intel Xeon family processor, moderate Networking Performance) or t2.2xlarge (32 GB RAM, Intel Xeon family processor, moderate Networking Performance).

2) If your application is general purpose and requires high configuration I would recommend:

If cost is a concern- m3.xlarge(4 vCPU, 15 GB RAM, Intel Xeon E5-2670 v2, High Networking Performance, 2 x 40 SSD), m3.2xlarge(8 vCPU, 30 GB RAM, Intel Xeon E5-2670 v2, High Networking Performance, 2 x 80 SSD)

or

If you want the best and the latest generation of General Purpose Instances-  m4.xlarge(4 vCPU, 16 GB RAM, Intel Xeon E5-2676 v3, High Networking Performance, EBS Only storage), m4.2xlarge(8 vCPU, 32 GB RAM, Intel Xeon E5-2676 v3, High Networking Performance, EBS Only storage).

For more information on instance types you can refer here.

Body:
neo4j 3.2 version is installed aws Linux ec2 instance. I am checking for the ideal instance type.

There are different projects persisted in the neo4j graph and each project can have around 50k nodes, a million relationships, and around 100k properties. A single save operation can have up to 25k nodes, 75k relations, and 10k properties. i tried out i2,d2,r largest instance type. everything is taking almost a minute or more for every "save" operation. In my windows operating system, max time it takes is 20 seconds.
what would be the ideal instance type in this scenario?

and i also doubt whether it has something to do with the neo4j.conf file. there are so many jvm paramaters mentioned in neo4j.conf in Linux aws. none of them are specified in my windows system.

#*****************************************************************
# Neo4j configuration
#
# For more details and a complete list of settings, please see
# https://neo4j.com/docs/operations-manual/current/reference/configuration-settings/
#*****************************************************************

# The name of the database to mount
#dbms.active_database=graph.db

# Paths of directories in the installation.
dbms.directories.data=/var/lib/neo4j/data
dbms.directories.plugins=/var/lib/neo4j/plugins
dbms.directories.certificates=/var/lib/neo4j/certificates
dbms.directories.logs=/var/log/neo4j
dbms.directories.lib=/usr/share/neo4j/lib
dbms.directories.run=/var/run/neo4j

# This setting constrains all `LOAD CSV` import files to be under the `import` directory. Remove or comment it out to
# allow files to be loaded from anywhere in the filesystem; this introduces possible security problems. See the
# `LOAD CSV` section of the manual for details.
dbms.directories.import=/var/lib/neo4j/import

# Whether requests to Neo4j are authenticated.
# To disable authentication, uncomment this line
#dbms.security.auth_enabled=false

# Enable this to be able to upgrade a store from an older version.
#dbms.allow_upgrade=true

# Java Heap Size: by default the Java heap size is dynamically
# calculated based on available system resources.
# Uncomment these lines to set specific initial and maximum
# heap size.
# dbms.memory.heap.initial_size=512m
#dbms.memory.heap.max_size=512m

# The amount of memory to use for mapping the store files, in bytes (or
# kilobytes with the 'k' suffix, megabytes with 'm' and gigabytes with 'g').
# If Neo4j is running on a dedicated server, then it is generally recommended
# to leave about 2-4 gigabytes for the operating system, give the JVM enough
# heap to hold all your transaction state and query context, and then leave the
# rest for the page cache.
# The default page cache memory assumes the machine is dedicated to running
# Neo4j, and is heuristically set to 50% of RAM minus the max Java heap size.
#dbms.memory.pagecache.size=10g

#*****************************************************************
# Network connector configuration
#*****************************************************************

# With default configuration Neo4j only accepts local connections.
# To accept non-local connections, uncomment this line:
dbms.connectors.default_listen_address=0.0.0.0

# You can also choose a specific network interface, and configure a non-default
# port for each connector, by setting their individual listen_address.

# The address at which this server can be reached by its clients. This may be the server's IP address or DNS name, or
# it may be the address of a reverse proxy which sits in front of the server. This setting may be overridden for
# individual connectors below.
#dbms.connectors.default_advertised_address=localhost

# You can also choose a specific advertised hostname or IP address, and
# configure an advertised port for each connector, by setting their
# individual advertised_address.

# Bolt connector
dbms.connector.bolt.enabled=true
#dbms.connector.bolt.tls_level=OPTIONAL
#dbms.connector.bolt.listen_address=:7687

# HTTP Connector. There must be exactly one HTTP connector.
dbms.connector.http.enabled=true
#dbms.connector.http.listen_address=:7474

# HTTPS Connector. There can be zero or one HTTPS connectors.
dbms.connector.https.enabled=true
#dbms.connector.https.listen_address=:7473

# Number of Neo4j worker threads.
#dbms.threads.worker_count=

#*****************************************************************
# SSL system configuration
#*****************************************************************

# Names of the SSL policies to be used for the respective components.

# The legacy policy is a special policy which is not defined in
# the policy configuration section, but rather derives from
# dbms.directories.certificates and associated files
# (by default: neo4j.key and neo4j.cert). Its use will be deprecated.

# The policies to be used for connectors.
#
# N.B: Note that a connector must be configured to support/require
#      SSL/TLS for the policy to actually be utilized.
#
# see: dbms.connector.*.tls_level

#bolt.ssl_policy=legacy
#https.ssl_policy=legacy

#*****************************************************************
# SSL policy configuration
#*****************************************************************

# Each policy is configured under a separate namespace, e.g.
#    dbms.ssl.policy.<policyname>.*
#
# The example settings below are for a new policy named 'default'.

# The base directory for cryptographic objects. Each policy will by
# default look for its associated objects (keys, certificates, ...)
# under the base directory.
#
# Every such setting can be overriden using a full path to
# the respective object, but every policy will by default look
# for cryptographic objects in its base location.
#
# Mandatory setting

#dbms.ssl.policy.default.base_directory=certificates/default

# Allows the generation of a fresh private key and a self-signed
# certificate if none are found in the expected locations. It is
# recommended to turn this off again after keys have been generated.
#
# Keys should in general be generated and distributed offline
# by a trusted certificate authority (CA) and not by utilizing
# this mode.

#dbms.ssl.policy.default.allow_key_generation=false

# Enabling this makes it so that this policy ignores the contents
# of the trusted_dir and simply resorts to trusting everything.
#
# Use of this mode is discouraged. It would offer encryption but no security.

#dbms.ssl.policy.default.trust_all=false

# The private key for the default SSL policy. By default a file
# named private.key is expected under the base directory of the policy.
# It is mandatory that a key can be found or generated.

#dbms.ssl.policy.default.private_key=

# The private key for the default SSL policy. By default a file
# named public.crt is expected under the base directory of the policy.
# It is mandatory that a certificate can be found or generated.

#dbms.ssl.policy.default.public_certificate=

# The certificates of trusted parties. By default a directory named
# 'trusted' is expected under the base directory of the policy. It is
# mandatory to create the directory so that it exists, because it cannot
# be auto-created (for security purposes).
#
# To enforce client authentication client_auth must be set to 'require'!

#dbms.ssl.policy.default.trusted_dir=

# Client authentication setting. Values: none, optional, require
# The default is to require client authentication.
#
# Servers are always authenticated unless explicitly overridden
# using the trust_all setting. In a mutual authentication setup this
# should be kept at the default of require and trusted certificates
# must be installed in the trusted_dir.

#dbms.ssl.policy.default.client_auth=require

# A comma-separated list of allowed TLS versions.
# By default TLSv1, TLSv1.1 and TLSv1.2 are allowed.

#dbms.ssl.policy.default.tls_versions=

# A comma-separated list of allowed ciphers.
# The default ciphers are the defaults of the JVM platform.

#dbms.ssl.policy.default.ciphers=

#*****************************************************************
# Logging configuration
#*****************************************************************

# To enable HTTP logging, uncomment this line
#dbms.logs.http.enabled=true

# Number of HTTP logs to keep.
#dbms.logs.http.rotation.keep_number=5

# Size of each HTTP log that is kept.
#dbms.logs.http.rotation.size=20m

# To enable GC Logging, uncomment this line
#dbms.logs.gc.enabled=true

# GC Logging Options
# see http://docs.oracle.com/cd/E19957-01/819-0084-10/pt_tuningjava.html#wp57013 for more information.
#dbms.logs.gc.options=-XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintPromotionFailure -XX:+PrintTenuringDistribution

# Number of GC logs to keep.
#dbms.logs.gc.rotation.keep_number=5

# Size of each GC log that is kept.
#dbms.logs.gc.rotation.size=20m

# Size threshold for rotation of the debug log. If set to zero then no rotation will occur. Accepts a binary suffix "k",
# "m" or "g".
#dbms.logs.debug.rotation.size=20m

# Maximum number of history files for the internal log.
#dbms.logs.debug.rotation.keep_number=7

#*****************************************************************
# Miscellaneous configuration
#*****************************************************************

# Enable this to specify a parser other than the default one.
#cypher.default_language_version=3.0

# Determines if Cypher will allow using file URLs when loading data using
# `LOAD CSV`. Setting this value to `false` will cause Neo4j to fail `LOAD CSV`
# clauses that load data from the file system.
#dbms.security.allow_csv_import_from_file_urls=true

# Retention policy for transaction logs needed to perform recovery and backups.
dbms.tx_log.rotation.retention_policy=1 days

# Enable a remote shell server which Neo4j Shell clients can log in to.
#dbms.shell.enabled=true
# The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
#dbms.shell.host=127.0.0.1
# The port the shell will listen on, default is 1337.
#dbms.shell.port=1337

# Only allow read operations from this Neo4j instance. This mode still requires
# write access to the directory for lock purposes.
#dbms.read_only=false

# Comma separated list of JAX-RS packages containing JAX-RS resources, one
# package name for each mountpoint. The listed package names will be loaded
# under the mountpoints specified. Uncomment this line to mount the
# org.neo4j.examples.server.unmanaged.HelloWorldResource.java from
# neo4j-server-examples under /examples/unmanaged, resulting in a final URL of
# http://localhost:7474/examples/unmanaged/helloworld/{nodeId}
#dbms.unmanaged_extension_classes=org.neo4j.examples.server.unmanaged=/examples/unmanaged

#********************************************************************
# JVM Parameters
#********************************************************************

# G1GC generally strikes a good balance between throughput and tail
# latency, without too much tuning.
dbms.jvm.additional=-XX:+UseG1GC

# Have common exceptions keep producing stack traces, so they can be
# debugged regardless of how often logs are rotated.
#dbms.jvm.additional=-XX:-OmitStackTraceInFastThrow

# Make sure that `initmemory` is not only allocated, but committed to
# the process, before starting the database. This reduces memory
# fragmentation, increasing the effectiveness of transparent huge
# pages. It also reduces the possibility of seeing performance drop
# due to heap-growing GC events, where a decrease in available page
# cache leads to an increase in mean IO response time.
# Try reducing the heap memory, if this flag degrades performance.
dbms.jvm.additional=-XX:+AlwaysPreTouch

# Trust that non-static final fields are really final.
# This allows more optimizations and improves overall performance.
# NOTE: Disable this if you use embedded mode, or have extensions or dependencies that may use reflection or
# serialization to change the value of final fields!
dbms.jvm.additional=-XX:+UnlockExperimentalVMOptions
dbms.jvm.additional=-XX:+TrustFinalNonStaticFields

# Disable explicit garbage collection, which is occasionally invoked by the JDK itself.
dbms.jvm.additional=-XX:+DisableExplicitGC

# Remote JMX monitoring, uncomment and adjust the following lines as needed. Absolute paths to jmx.access and
# jmx.password files are required.
# Also make sure to update the jmx.access and jmx.password files with appropriate permission roles and passwords,
# the shipped configuration contains only a read only role called 'monitor' with password 'Neo4j'.
# For more details, see: http://download.oracle.com/javase/8/docs/technotes/guides/management/agent.html
# On Unix based systems the jmx.password file needs to be owned by the user that will run the server,
# and have permissions set to 0600.
# For details on setting these file permissions on Windows see:
#     http://docs.oracle.com/javase/8/docs/technotes/guides/management/security-windows.html
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.port=3637
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.authenticate=true
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.ssl=false
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.password.file=/absolute/path/to/conf/jmx.password
#dbms.jvm.additional=-Dcom.sun.management.jmxremote.access.file=/absolute/path/to/conf/jmx.access

# Some systems cannot discover host name automatically, and need this line configured:
#dbms.jvm.additional=-Djava.rmi.server.hostname=$THE_NEO4J_SERVER_HOSTNAME

# Expand Diffie Hellman (DH) key size from default 1024 to 2048 for DH-RSA cipher suites used in server TLS handshakes.
# This is to protect the server from any potential passive eavesdropping.
dbms.jvm.additional=-Djdk.tls.ephemeralDHKeySize=2048

#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.

# Name of the service
dbms.windows_service_name=neo4j

#********************************************************************
# Other Neo4j system properties
#********************************************************************
dbms.jvm.additional=-Dunsupported.dbms.udc.source=rpm


问:
Android Float To Int
Why is this so hard to find out?

```<code>public boolean onTouch(View v, MotionEvent event)
</code>```

I need to convert float event.getY() to an int.

Is this possible?

event.getY().intValue() will not work at all.

Any ideas?

答: Math.round() will round the float to the nearest integer.</p>

Title: Android Float To Int

Body:
Why is this so hard to find out?

public boolean onTouch(View v, MotionEvent event)

I need to convert float event.getY() to an int.

Is this possible?

event.getY().intValue() will not work at all.

Any ideas?


问:
Error:java: javacTask: source release 8 requires target release 1.8
Using IntelliJ IDE can't compile any projects. Screenshots of settings below:

Used JDK:

Project SDK and Language level:

Language Level:

Anybody have any ideas?

答: You need to go to the /.idea/compiler.xml and change target to required jdk level.

ContentLicense: CC BY-SA 4.0


问:
Graph serialization
I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?</p>

答:
If the graph contains cycles, how can there exist allowed execution orders for your files?
It seems to me that if the graph contains cycles, then you have no solution, and this
is reported correctly by the above algorithm.</p>

Title: Graph serialization

LastEditorDisplayName: Blair Conrad

OwnerDisplayName: Giorgio


问:
Redis, CouchDB or Cassandra?
What are the strengths and weaknesses of the various NoSQL databases available?

In particular, it seems like Redis is weak when it comes to distributing write load over multiple servers. Is that the case? Is it a big problem? How big does a service have to grow before that could be a significant problem?

答: Take a look at http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis He does a good job summing up why you would use one over the other.</p>

Title: Redis, CouchDB or Cassandra?


问:
How to detect Ctrl+V, Ctrl+C using JavaScript?
How to detect Ctrl+V, Ctrl+C using JavaScript?

I need to restrict pasting in my textareas, end user should not copy and paste the content, user should only type text in textarea.

How can I achieve this?

答:
Another approach (no plugin needed) it to just use ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

```<code>$(document).keypress("c",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});
</code>```

See also jquery: keypress, ctrl+c (or some combo like that).

Body:
Another approach (no plugin needed) it to just use ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

$(document).keypress("c",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});

See also jquery: keypress, ctrl+c (or some combo like that).


问:
Testing user input is mirrored from one input to another with Selenium + Python
I am trying to write a test in Selenium that ensures text entered into one input is mirrored in another input. I keep getting this error below.

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]"}
</code>```

This is the code I'm using currently:

```<code>class inputMirror(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://foo.bar")

def test_mirror_input(self):
#Ensures text from the first input is mirrored into the second input box
    driver = self.driver
    userInput = "Howdy"
    inputBoxOneXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]')
    inputBoxTwoXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[2]')
    inputBoxOneXpath.clear()
    inputBoxOneXpath.send_keys(userInput)
    driver.implicitly_wait(10)
    assert inputBoxTwoXpath.text == userInput
    driver.close()
</code>```

HTML code:

<input type="text" placeholder="Enter text here..." value="">
<input class="textbox" placeholder="Enter text here..." value="" maxlength="80" required="true">```

答:
The error says it all NoSuchElementException: Message: no such element which is because the xpath you constructed is unable to identify the intended element. Here is the code block for your reference :

```<code>driver = self.driver
userInput = "Howdy"
inputBoxOneXpath = driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']")
inputBoxOneXpath.clear()
inputBoxOneXpath.send_keys(userInput)
driver.implicitly_wait(10)
inputBoxTwoXpath = driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']")
assert inputBoxTwoXpath.get_attribute("value") in userInput
driver.close()
</code>```

Body:
I am trying to write a test in Selenium that ensures text entered into one input is mirrored in another input. I keep getting this error below.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]"}

This is the code I'm using currently:

class inputMirror(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://foo.bar")

def test_mirror_input(self):
#Ensures text from the first input is mirrored into the second input box
    driver = self.driver
    userInput = "Howdy"
    inputBoxOneXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]')
    inputBoxTwoXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[2]')
    inputBoxOneXpath.clear()
    inputBoxOneXpath.send_keys(userInput)
    driver.implicitly_wait(10)
    assert inputBoxTwoXpath.text == userInput
    driver.close()

HTML code:

<input type="text" placeholder="Enter text here..." value="">
<input class="textbox" placeholder="Enter text here..." value="" maxlength="80" required="true">

Body:
The error says it all NoSuchElementException: Message: no such element which is because the xpath you constructed is unable to identify the intended element. Here is the code block for your reference :

driver = self.driver
userInput = "Howdy"
inputBoxOneXpath = driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']")
inputBoxOneXpath.clear()
inputBoxOneXpath.send_keys(userInput)
driver.implicitly_wait(10)
inputBoxTwoXpath = driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']")
assert inputBoxTwoXpath.get_attribute("value") in userInput
driver.close()


问:
My loop creating another parent array rather than appending it to where I have pointed?
I need to loop through my database and be able to group between day, time, class, and students. I have been able to use a bunch of if(!isset()) statements to achieve what I am after with this code.

```<code>foreach ($sqlEx as $rows) {
    if(!isset($day) || $day !== $rows['DAY']) {
        $day = $rows['DAY'];
        $scheduleJSON['DAY'] = $day;
    }
    if(!isset($time) || $time !== $rows['CLASSTIME']) {
        $time = $rows['CLASSTIME'];
        $scheduleJSON[$time]= [];
        $scheduleJSON[NULL] = $scheduleJSON[$time];
        unset($scheduleJSON[NULL]);
    }
    if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
        $instructor = $rows['INSTRUCTOR'];
        $classlevel = $rows['CLASSLEVEL'];
        $maxstudent = $rows['MAXSTUDENT'];
        $scheduleJSON[$time]['CLASSES'][]['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];
    } else {
        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];
    }
}
</code>```

I am looking at getting my array to have this structure:

```<code>$scheduleJSON = [
    'DAY' => NULL, 'TIME' => [
        'CLASSES' => [
            'CLASS' => [
                'INSTRUCTOR' => NULL, 'CLASS LEVEL' => NULL, 'MAX STUDENTS' => NULL, 'STUDENTS' => [
                    'STUDENT' => [
                        'FIRST NAME' => NULL, 'LAST NAME' => NULL, 'DATE OF BIRTH' => NULL, 'PARENT FIRST NAME' => NULL, 'PARENT LAST NAME' => NULL
                    ]
                ]
            ]
        ]
    ]
];
</code>```

However, when I print to JSON encode, my problem, I think, is within my else statement. Instead of appending the STUDENTS as another key => value in the class after MAX STUDENTS, it's creating another CLASS array.

```<code>"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "0": {
            "CLASS": {
                "INSTRUCTOR": "Teacher",
                "CLASS LEVEL": "JUNIOR",
                "MAX STUDENTS": "8"
            }
        },
        "CLASS": {
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "Student",
                        "LAST NAME": ""
                    }
                },
</code>```

Any help at this point would be greatly appreciated - I have been searching the problem and answer for days.

-- EDIT
Array from $sqlEx. Please note that I have removed the name data that did come out with it for privacy.

```<code>array(20) {
  ["DAY"]=>
  string(8) "THURSDAY"
  [0]=>
  string(8) "THURSDAY"
  ["CLASSTIME"]=>
  string(3) "530"
  [1]=>
  string(3) "530"
  ["CLASSLEVEL"]=>
  string(6) "JUNIOR"
  [2]=>
  string(6) "JUNIOR"
  ["MAXSTUDENT"]=>
  string(1) "8"
  [3]=>
  string(1) "8"
  ["INSTRUCTOR"]=>
  string(4) "TEACHER"
  [4]=>
  string(4) "TEACHER"
  ["STUDENTFIRST"]=>
  string(5) "First Name"
  [5]=>
  string(5) "First Name"
  ["STUDENTLAST"]=>
  string(0) ""
  [6]=>
  string(0) ""
  ["STUDENTDOB"]=>
  string(10) "2007-04-28"
  [7]=>
  string(10) "2007-04-28"
  ["PARENTFIRST"]=>
  string(12) "Parent First Name"
  [8]=>
  string(12) "Parent First Name"
  ["PARENTLAST"]=>
  string(6) "Parent Last Name"
  [9]=>
  string(6) "Parent Last Name"
}
</code>```

答:
First, when adding INSTRUCTOR key, you have to remove the [] between ['CLASSES'] and ['CLASS']

```<code>$scheduleJSON[$time]['CLASSES']['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];
</code>```

Next, move everything inside the else condition outside. Basically removing the else condition.

```<code>if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
    // instructor codes
} // else is removed
$studentfirst = $rows['STUDENTFIRST'];
$studentlast = $rows['STUDENTLAST'];
$scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];
</code>```

This will work effeciently assuming each data for STUDENTFIRST up to PARENTLAST are unique. No duplicate student info. Otherwise, you need to have something to check if student already exist.

Note: I suggested removing else condition because it will not cover the first loop. Thus, the student's info for the first row won't be added to the $scheduledJSON.
If you need the else condition, you have to add the STUDENT's info on the $instructor's IF condition

Body:
I need to loop through my database and be able to group between day, time, class, and students. I have been able to use a bunch of if(!isset()) statements to achieve what I am after with this code.

foreach ($sqlEx as $rows) {
    if(!isset($day) || $day !== $rows['DAY']) {
        $day = $rows['DAY'];
        $scheduleJSON['DAY'] = $day;
    }
    if(!isset($time) || $time !== $rows['CLASSTIME']) {
        $time = $rows['CLASSTIME'];
        $scheduleJSON[$time]= [];
        $scheduleJSON[NULL] = $scheduleJSON[$time];
        unset($scheduleJSON[NULL]);
    }
    if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
        $instructor = $rows['INSTRUCTOR'];
        $classlevel = $rows['CLASSLEVEL'];
        $maxstudent = $rows['MAXSTUDENT'];
        $scheduleJSON[$time]['CLASSES'][]['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];
    } else {
        $studentfirst = $rows['STUDENTFIRST'];
        $studentlast = $rows['STUDENTLAST'];
        $scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];
    }
}

I am looking at getting my array to have this structure:

$scheduleJSON = [
    'DAY' => NULL, 'TIME' => [
        'CLASSES' => [
            'CLASS' => [
                'INSTRUCTOR' => NULL, 'CLASS LEVEL' => NULL, 'MAX STUDENTS' => NULL, 'STUDENTS' => [
                    'STUDENT' => [
                        'FIRST NAME' => NULL, 'LAST NAME' => NULL, 'DATE OF BIRTH' => NULL, 'PARENT FIRST NAME' => NULL, 'PARENT LAST NAME' => NULL
                    ]
                ]
            ]
        ]
    ]
];

However, when I print to JSON encode, my problem, I think, is within my else statement. Instead of appending the STUDENTS as another key => value in the class after MAX STUDENTS, it's creating another CLASS array.

"DAY": "THURSDAY",
"530": {
    "CLASSES": {
        "0": {
            "CLASS": {
                "INSTRUCTOR": "Teacher",
                "CLASS LEVEL": "JUNIOR",
                "MAX STUDENTS": "8"
            }
        },
        "CLASS": {
            "STUDENTS": [
                {
                    "STUDENT": {
                        "FIRST NAME": "Student",
                        "LAST NAME": ""
                    }
                },

Any help at this point would be greatly appreciated - I have been searching the problem and answer for days.

-- EDIT
Array from $sqlEx. Please note that I have removed the name data that did come out with it for privacy.

array(20) {
  ["DAY"]=>
  string(8) "THURSDAY"
  [0]=>
  string(8) "THURSDAY"
  ["CLASSTIME"]=>
  string(3) "530"
  [1]=>
  string(3) "530"
  ["CLASSLEVEL"]=>
  string(6) "JUNIOR"
  [2]=>
  string(6) "JUNIOR"
  ["MAXSTUDENT"]=>
  string(1) "8"
  [3]=>
  string(1) "8"
  ["INSTRUCTOR"]=>
  string(4) "TEACHER"
  [4]=>
  string(4) "TEACHER"
  ["STUDENTFIRST"]=>
  string(5) "First Name"
  [5]=>
  string(5) "First Name"
  ["STUDENTLAST"]=>
  string(0) ""
  [6]=>
  string(0) ""
  ["STUDENTDOB"]=>
  string(10) "2007-04-28"
  [7]=>
  string(10) "2007-04-28"
  ["PARENTFIRST"]=>
  string(12) "Parent First Name"
  [8]=>
  string(12) "Parent First Name"
  ["PARENTLAST"]=>
  string(6) "Parent Last Name"
  [9]=>
  string(6) "Parent Last Name"
}

Body:
First, when adding INSTRUCTOR key, you have to remove the [] between ['CLASSES'] and ['CLASS']

$scheduleJSON[$time]['CLASSES']['CLASS'] = ['INSTRUCTOR' => $instructor, 'CLASS LEVEL' => $classlevel, 'MAX STUDENTS' => $maxstudent];

Next, move everything inside the else condition outside. Basically removing the else condition.

if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
    // instructor codes
} // else is removed
$studentfirst = $rows['STUDENTFIRST'];
$studentlast = $rows['STUDENTLAST'];
$scheduleJSON[$time]['CLASSES']['CLASS']['STUDENTS'][] = ['STUDENT' => ['FIRST NAME' => $studentfirst, 'LAST NAME' => $studentlast]];

This will work effeciently assuming each data for STUDENTFIRST up to PARENTLAST are unique. No duplicate student info. Otherwise, you need to have something to check if student already exist.

Note: I suggested removing else condition because it will not cover the first loop. Thus, the student's info for the first row won't be added to the $scheduledJSON.
If you need the else condition, you have to add the STUDENT's info on the $instructor's IF condition


问:
How to determine if stdin is empty
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

```<code>int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}
</code>```

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

答:
How to determine if stdin is empty(?)

Read 1 character with  getchar().

```<code>int ch = getchar();
if (ch == EOF) {
  if (feof(stdin)) puts("stdin empty");
  else             puts("stdin error"); // very rare
} else {
  ungetc(ch, stdin); // put back
  puts("stdin not empty");
}
</code>```

Title: How to determine if stdin is empty

Body:
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

Body:
How to determine if stdin is empty(?)

Read 1 character with  getchar().

int ch = getchar();
if (ch == EOF) {
  if (feof(stdin)) puts("stdin empty");
  else             puts("stdin error"); // very rare
} else {
  ungetc(ch, stdin); // put back
  puts("stdin not empty");
}


问:
Import to PostgreSQL from partly csv, partly JSON
I'm running PostgreSQL 9.6, and I've got a table consisting of lots of columns.
I've got a csv-file containing the following format:

```<code>id, insert_time, JSON-object
</code>```

The JSON-object has the following format:

```<code>{ column_nameY: valueX, column_nameY: valueY, ... }
</code>```

The column_names in the JSON-object matches the columns in my PostgreSQL-table.

Is there a dynamic way to import such file, so I'll get the id, insert_time, and the remaining column values from the JSON object?

The order of columns in the JSON object might not match the order of the columns in the PostgreSQL table.

答:
I am assuming you know how to get that csv file imported into postgresql and that you know the fields inside that json object field.

first we create a table to store the contents of the csv file. Notice the datatype of that JSON field is jsonb.

```<code>create table test11 (id int, insert_time timestamp, json_object jsonb )
</code>```

Know you import the csv file. but for illustration purposes, i will insert sample data into this Table.

```<code>insert into test11 (id, insert_time, json_object) values (1, '2017-11-14'::timestamp, '{ "column_nameX": "3", "column_nameY": "4" }'::jsonb);
insert into test11 (id, insert_time, json_object) values (1, '2017-11-14'::timestamp, '{ "column_nameX": "13", "column_nameY": "14" }'::jsonb);
</code>```

we now select from that table;

```<code>Select id, insert_time,  json_object->>'column_nameY' as Column_NameY, json_object->>'column_nameX' as Column_NameX  from test11
</code>```

your results should look like this...

```<code>id  |insert_time    |column_namey   |column_namex
1   |11/14/2017     |4              |3
1   |11/14/2017     |14             |13
</code>```

-HTH

Body:
I'm running PostgreSQL 9.6, and I've got a table consisting of lots of columns.
I've got a csv-file containing the following format:

id, insert_time, JSON-object

The JSON-object has the following format:

{ column_nameY: valueX, column_nameY: valueY, ... }

The column_names in the JSON-object matches the columns in my PostgreSQL-table.

Is there a dynamic way to import such file, so I'll get the id, insert_time, and the remaining column values from the JSON object?

The order of columns in the JSON object might not match the order of the columns in the PostgreSQL table.

Body:
I am assuming you know how to get that csv file imported into postgresql and that you know the fields inside that json object field.

first we create a table to store the contents of the csv file. Notice the datatype of that JSON field is jsonb.

create table test11 (id int, insert_time timestamp, json_object jsonb )

Know you import the csv file. but for illustration purposes, i will insert sample data into this Table.

insert into test11 (id, insert_time, json_object) values (1, '2017-11-14'::timestamp, '{ "column_nameX": "3", "column_nameY": "4" }'::jsonb);
insert into test11 (id, insert_time, json_object) values (1, '2017-11-14'::timestamp, '{ "column_nameX": "13", "column_nameY": "14" }'::jsonb);

we now select from that table;

Select id, insert_time,  json_object->>'column_nameY' as Column_NameY, json_object->>'column_nameX' as Column_NameX  from test11

your results should look like this...

id  |insert_time    |column_namey   |column_namex
1   |11/14/2017     |4              |3
1   |11/14/2017     |14             |13

-HTH