问:
How can I upload the image with ajax and save image address in mysql with pdo
How can I upload the image and save the image address in the mysql ?
1.I want to upload the image with AJAX
2.And the image address will be stored in the mysql with pdo
This is my code:

```<code>$(document).ready(function(){
    $("#usredit").click(function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var file = $("#file").val();
        var image = $("#image").val();
        var id = $("#id").val();
        var send = true;
        $.post("set-ajax.php",{name:name,email:email,file:file,image:image,id:id,send:send},function(data){
                    $("#editres").html(data);
        });
    });
});
</code>```

ajax.php

```<code>if(isset($_POST['send'])){
    if(empty($_POST['name']) || empty($_POST['email'])){
        echo '<div class="alert alert-warning">Fill empty fields</div>';
            }else{
                if(isset($_POST['file'])){
                    $file = $_POST['file'];
                    $tmp = $_FILES['file']["tmp_name"];
                    $name = $_FILES['file']['name'];
                    $type = $_FILES['file']['type'];
                    if (is_uploaded_file($tmp)){
                        $ext = array("image/jpg","image/png","image/jpeg");
                        if (in_array($type,$ext)){
                            $filename = md5($name.microtime()).substr($name,-5,5);
                        if(move_uploaded_file($tmp,"user/img".$filename)){
                            echo '<div class="alert alert-success">Upload done</div>';
                        }else{
                                echo '<div class="alert alert-warning">Upload failed</div>';
                            }
                        }else{
                            echo '<div class="alert alert-warning">Unrelated file</div>';
                        }
                    }
                }
                $name = $_POST['name'];
                $email = $_POST['email'];
                $image = $_POST['image'];
                $id = $_POST['id'];
                $resualt = $User->UpdateUserProfile($name,$email,$image,$id);
                if($resualt ){
                    echo '<div class="alert alert-success">Edit done</div>';
                }else{
                    echo '<div class="alert alert-warning">Edit failed</div>';
                }
            }
</code>```

答:
Assuming, you were able to upload image to user/img folder. Then, create a method which will update/insert details of uploaded image. And call that method by passing image name (since, folder path will be common for all )

```<code>      if(move_uploaded_file($tmp,"user/img".$filename)){
            // update/insert table with folder location.
            // call the method here
           echo '<div class="alert alert-success">Upload done</div>';
        }
</code>```

Body:
How can I upload the image and save the image address in the mysql ?
1.I want to upload the image with AJAX
2.And the image address will be stored in the mysql with pdo
This is my code:

$(document).ready(function(){
    $("#usredit").click(function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var file = $("#file").val();
        var image = $("#image").val();
        var id = $("#id").val();
        var send = true;
        $.post("set-ajax.php",{name:name,email:email,file:file,image:image,id:id,send:send},function(data){
                    $("#editres").html(data);
        });
    });
});

ajax.php

if(isset($_POST['send'])){
    if(empty($_POST['name']) || empty($_POST['email'])){
        echo '
Fill empty fields
';
            }else{
                if(isset($_POST['file'])){
                    $file = $_POST['file'];
                    $tmp = $_FILES['file']["tmp_name"];
                    $name = $_FILES['file']['name'];
                    $type = $_FILES['file']['type'];
                    if (is_uploaded_file($tmp)){
                        $ext = array("image/jpg","image/png","image/jpeg");
                        if (in_array($type,$ext)){
                            $filename = md5($name.microtime()).substr($name,-5,5);
                        if(move_uploaded_file($tmp,"user/img".$filename)){
                            echo '
Upload done
';
                        }else{
                                echo '
Upload failed
';
                            }
                        }else{
                            echo '
Unrelated file
';
                        }
                    }
                }
                $name = $_POST['name'];
                $email = $_POST['email'];
                $image = $_POST['image'];
                $id = $_POST['id'];
                $resualt = $User->UpdateUserProfile($name,$email,$image,$id);
                if($resualt ){
                    echo '
Edit done
';
                }else{
                    echo '
Edit failed
';
                }
            }

Body:
Assuming, you were able to upload image to user/img folder. Then, create a method which will update/insert details of uploaded image. And call that method by passing image name (since, folder path will be common for all )

      if(move_uploaded_file($tmp,"user/img".$filename)){
            // update/insert table with folder location.
            // call the method here
           echo '<div class="alert alert-success">Upload done</div>';
        }


来源: stackexchange

问:
problem with conditional switch
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

```<code><?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>
</code>```

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

答:
Lucky,

PHP switch is same as series of IF statements. The cases are evaluated as:

```<code>if($totaltime == ($totaltime < 1)) {
  echo "That was fast!";
  break;
}
if($totaltime == ($totaltime > 1)) {
  echo "Not fast!";
  break;
}
...
</code>```

Clearly 0 == false for 2nd IF is true and hence the result.

Thanks,
Vikas.

ContentLicense: CC BY-SA 2.5

Title: problem with conditional switch

Body:
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

<?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

Body:
Lucky,

PHP switch is same as series of IF statements. The cases are evaluated as:

if($totaltime == ($totaltime < 1)) {
  echo "That was fast!";
  break;
}
if($totaltime == ($totaltime > 1)) {
  echo "Not fast!";
  break;
}
...

Clearly 0 == false for 2nd IF is true and hence the result.

Thanks,
Vikas.


问:
C# - StreamReader ReadToEnd - WebException: The request was aborted: The request was canceled
My app produces the following error randomly. I havent been able to re-produce it on my machine, but on users who have installed it, it happens to them.

```<code>System.Net.WebException: The request was aborted: The request was canceled.
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadToEnd()
</code>```

Whats odd is, ReadToEnd() cant product a WebException error (Found out by hovering over it and seeing what type of exceptions it can cause), yet from this Crash Dump it is?, To make sure I even put a WebException try catch and it still happens.

I read online a tiny bit and see it might be caused by ServicePointManager.DefaultConnectionLimit so I added that in with 1000 int value, and now im not sure if it fixed it - I havent seen any reports, but that doesnt mean its not happening.

```<code>using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string s = "";
    try { s = sr.ReadToEnd(); }
    catch (IOException) { return "2"; }
    catch (WebException) { return "2"; }
}
</code>```

This is the code im using, if needed, I can provide r's values. Just know that I use quite a lot.

EDIT: I can confirm on the client's side that even with the ServicePointManager.DefaultConnectionLimit set to 1000 it still occurs.

答:
I had a similar problem to this some time ago.  Can you handle the WexException doing something like this:

```<code>public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
    try
    {
        return (HttpWebResponse) request.GetResponse();
    }
    catch (WebException ex)
    {
        if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError)
            throw;

        return (HttpWebResponse)ex.Response;
    }
}
</code>```

I borrowed the code above from the answerer here: HttpWebRequest.GetResponse throws WebException on HTTP 304

Then the first line of your code would do this:

```<code>using (HttpWebResponse resp = GetHttpResponse(r))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My app produces the following error randomly. I havent been able to re-produce it on my machine, but on users who have installed it, it happens to them.

System.Net.WebException: The request was aborted: The request was canceled.
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadToEnd()

Whats odd is, ReadToEnd() cant product a WebException error (Found out by hovering over it and seeing what type of exceptions it can cause), yet from this Crash Dump it is?, To make sure I even put a WebException try catch and it still happens.

I read online a tiny bit and see it might be caused by ServicePointManager.DefaultConnectionLimit so I added that in with 1000 int value, and now im not sure if it fixed it - I havent seen any reports, but that doesnt mean its not happening.

using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string s = "";
    try { s = sr.ReadToEnd(); }
    catch (IOException) { return "2"; }
    catch (WebException) { return "2"; }
}

This is the code im using, if needed, I can provide r's values. Just know that I use quite a lot.

EDIT: I can confirm on the client's side that even with the ServicePointManager.DefaultConnectionLimit set to 1000 it still occurs.

Body:
I had a similar problem to this some time ago.  Can you handle the WexException doing something like this:

public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
    try
    {
        return (HttpWebResponse) request.GetResponse();
    }
    catch (WebException ex)
    {
        if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError)
            throw;

        return (HttpWebResponse)ex.Response;
    }
}

I borrowed the code above from the answerer here: HttpWebRequest.GetResponse throws WebException on HTTP 304

Then the first line of your code would do this:

using (HttpWebResponse resp = GetHttpResponse(r))


问:
Remove [ ' ' ] from a string in Node.js
I know how to remove for example only [, but how can I do for remove multiple things?

I have to remove 3 things, the two ', the [ & ] and the space

The string when I print it's something like this: [ 'Chroma 2 Case' ]

Thank you so much!

答:
u can either use slice function i.e using

```<code>var s1 = "this is a test string.";
s1.slice(3, s1.length-3);
</code>```

or you can either replace the extra string ([, ], ', ......) using regex

```<code>s1.replace(^\[\s'(.*)'\s\]$/, '$1');
</code>```

Title: Remove [ ' ' ] from a string in Node.js

Body:
u can either use slice function i.e using

var s1 = "this is a test string.";
s1.slice(3, s1.length-3);

or you can either replace the extra string ([, ], ', ......) using regex

s1.replace(^\[\s'(.*)'\s\]$/, '$1');


问:
how to make an scale animation for decreasing view size(a bit)
here is my XML code:

```<code>   <?xml version="1.0" encoding="utf-8"?>
        <set xmlns:android="http://schemas.android.com/apk/res/android">
            <scale
                android:toXScale="99%"
                android:toYScale="99%"
         />
        </set>
</code>```

i want to add a touch effect by resizing view(i have some card views in layout).
but my code is wrong!

thanks in advance

答:
You can use this :

```<code>view.setOnTouchListener(new View.OnTouchListener(){

@Override
public boolean onTouch(View view,MotionEvent motionEvent){
    if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
    view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(200);
    }
    else if(motionEvent.getAction()==MotionEvent.ACTION_UP){
    view.animate().scaleX(1f).scaleY(1f).setDuration(200);
    }
    return false;
  }
});
</code>```

Hope this helps.

Body:
here is my XML code:

   <?xml version="1.0" encoding="utf-8"?>
        <set xmlns:android="http://schemas.android.com/apk/res/android">
            <scale
                android:toXScale="99%"
                android:toYScale="99%"
         />
        </set>

i want to add a touch effect by resizing view(i have some card views in layout).
but my code is wrong!

thanks in advance

Body:
You can use this :

view.setOnTouchListener(new View.OnTouchListener(){

@Override
public boolean onTouch(View view,MotionEvent motionEvent){
    if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
    view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(200);
    }
    else if(motionEvent.getAction()==MotionEvent.ACTION_UP){
    view.animate().scaleX(1f).scaleY(1f).setDuration(200);
    }
    return false;
  }
});

Hope this helps.


问:
How can I get the current date and time in UTC or GMT in Java?
When I create a new Date object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?

答:
```<code>SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
</code>```

OwnerDisplayName: Behrang


问:
How to pass an iterated ArrayList to another activity as a JSON Array, and make it show?
Hey Stackoverflow community, when I pass the JSON Array to another Activity, it just gives "null" back, could you give me a solution ?

EDIT it stops, after the onClick

First Activity:

```<code>eingabe = (TextView) findViewById(R.id.tv_dish_name);

    send.setOnClickListener(this);
    save.setOnClickListener(this);

    speicher = getApplicationContext().getSharedPreferences("jsondata", 0);
   zugreifen können (hier private --> 0)
    editor = speicher.edit();
}

@Override
public void onClick(View v) {
    if (v == save) {
        FavDishes.add(eingabe);

        for (int i = 0; i < 4; i++) {
        }
            JSONArray jsArray = new JSONArray(FavDishes);

        editor.putString("jsondata", jsArray.toString());
        editor.commit();
</code>```

second Activity:

```<code>anzeige = (TextView)findViewById(R.id.anzeige);

SaveDish(anzeige.getText().toString());
speicher = getApplicationContext().getSharedPreferences("jsondata",0);
editor = speicher.edit();

private void SaveDish(String jsondata){

    String strJson = speicher.getString("jsondata","0");//second parameter is necessary ie.,Value to return if this preference does not exist.

    if(strJson != null) try {
        JSONObject jsonData = new JSONObject(strJson);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    editor.putString("jsondata",strJson);
    editor.commit();
    //"Data 1" als key für "Schublade Data1", value Inhalt (übergebener String)
   anzeige.setText(speicher.getString("jsondata", null));
}
anzeige = (TextView)findViewById(R.id.anzeige);
</code>```

Help would be appreciated, thanks for your time!

答:
You need to iterate over you array and for each element into you array you can parse it to JSON object then push to your json array.

Regards,

Body:
Hey Stackoverflow community, when I pass the JSON Array to another Activity, it just gives "null" back, could you give me a solution ?

EDIT it stops, after the onClick

First Activity:

eingabe = (TextView) findViewById(R.id.tv_dish_name);

    send.setOnClickListener(this);
    save.setOnClickListener(this);

    speicher = getApplicationContext().getSharedPreferences("jsondata", 0);
   zugreifen können (hier private --> 0)
    editor = speicher.edit();
}

@Override
public void onClick(View v) {
    if (v == save) {
        FavDishes.add(eingabe);

        for (int i = 0; i < 4; i++) {
        }
            JSONArray jsArray = new JSONArray(FavDishes);

        editor.putString("jsondata", jsArray.toString());
        editor.commit();

second Activity:

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

SaveDish(anzeige.getText().toString());
speicher = getApplicationContext().getSharedPreferences("jsondata",0);
editor = speicher.edit();

private void SaveDish(String jsondata){

    String strJson = speicher.getString("jsondata","0");//second parameter is necessary ie.,Value to return if this preference does not exist.

    if(strJson != null) try {
        JSONObject jsonData = new JSONObject(strJson);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    editor.putString("jsondata",strJson);
    editor.commit();
    //"Data 1" als key für "Schublade Data1", value Inhalt (übergebener String)
   anzeige.setText(speicher.getString("jsondata", null));
}
anzeige = (TextView)findViewById(R.id.anzeige);

Help would be appreciated, thanks for your time!


问:
Custom annotation for userlocation pin
Can seems to change the users location annotation image.
Maybe someone could see where i am mistaken if...</p>

```<code>-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        NSString* AnnotationIdentifier = @"Annotation";
        MKAnnotationView *annoationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
        [annoationView setImage:[UIImage imageNamed:@"melocation"] ];
        return annoationView;
    }
}
</code>```

答:
You forgot to initialize the annotation for the first time when it can't be dequeued:</p>

```<code>-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        static NSString* const kAnnotationIdentifier = @"Annotation";
        MKAnnotationView *annoationView = [mapView dequeueReusableAnnotationViewWithIdentifier:kAnnotationIdentifier];
        if (!annoationView) {
            annoationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kAnnotationIdentifier];
        }
        [annoationView setImage:[UIImage imageNamed:@"melocation"] ];
        return annoationView;
    }
    return nil;
}
</code>```

Title: Custom annotation for userlocation pin

Body:
Can seems to change the users location annotation image.
Maybe someone could see where i am mistaken if...

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        NSString* AnnotationIdentifier = @"Annotation";
        MKAnnotationView *annoationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
        [annoationView setImage:[UIImage imageNamed:@"melocation"] ];
        return annoationView;
    }
}

Body:
You forgot to initialize the annotation for the first time when it can't be dequeued:

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        static NSString* const kAnnotationIdentifier = @"Annotation";
        MKAnnotationView *annoationView = [mapView dequeueReusableAnnotationViewWithIdentifier:kAnnotationIdentifier];
        if (!annoationView) {
            annoationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kAnnotationIdentifier];
        }
        [annoationView setImage:[UIImage imageNamed:@"melocation"] ];
        return annoationView;
    }
    return nil;
}


问:
How to reliably count preceding rows in MySQL?
I would like to know how to count preceding number of rows of a given row, in a given order by clause, in MySQL.
Also the rows may be inserted randomly, so auto_increment is unreliable.

```
MyAgenda - List

ID   FROM                  TO
32   2017-09-26 12:35:00   2017-09-26 13:35:00
33   2017-10-10 12:35:00   2017-10-10 13:35:00
32   2017-10-17 12:35:00   2017-10-17 13:35:00
32   2017-10-24 12:35:00   2017-10-24 13:35:00
```

Like in this case, The rows are sorted by the "From" column, but apparently row 34 is inserted before row 36, but after sorting 36 is above 34, and if another row 37 is inserted it maybe above or below any row, or even at the top. So how can I reliably count the preceding number of rows above a given row, in a given order by clause?

Tried the subquery method but it is O(n^2) and will be painfully slow when the number of rows is large.

答:
This counts records before record #36:</p>

```<code>select count(*)
from mytable
where from_date < (select from_date from mytable where id = 36);
</code>```

Body:
I would like to know how to count preceding number of rows of a given row, in a given order by clause, in MySQL.
Also the rows may be inserted randomly, so auto_increment is unreliable.

MyAgenda - List

ID   FROM                  TO
32   2017-09-26 12:35:00   2017-09-26 13:35:00
33   2017-10-10 12:35:00   2017-10-10 13:35:00
32   2017-10-17 12:35:00   2017-10-17 13:35:00
32   2017-10-24 12:35:00   2017-10-24 13:35:00

Like in this case, The rows are sorted by the "From" column, but apparently row 34 is inserted before row 36, but after sorting 36 is above 34, and if another row 37 is inserted it maybe above or below any row, or even at the top. So how can I reliably count the preceding number of rows above a given row, in a given order by clause?

Tried the subquery method but it is O(n^2) and will be painfully slow when the number of rows is large.

Body:
This counts records before record #36:

select count(*)
from mytable
where from_date < (select from_date from mytable where id = 36);


答:
Using the replace method on any string with regular expression. In your case:

```<code>let originalString = "[ 'Chroma 2 Case' ]";
let newString = originalString.replace(/[\[\]\'\s]/g, '');
</code>```

Usually you would use trim() on a string to just remove whitespace, however since you're already using a regex for [, ], and ', the \s in the matching regex takes care of any spaces, too.

Title: Remove [ ' ' ] from a string in Node.js

Body:
I know how to remove for example only [, but how can I do for remove multiple things?

I have to remove 3 things, the two ', the [ & ] and the space

The string when I print it's something like this: [ 'Chroma 2 Case' ]

Thank you so much!

Body:
Using the replace method on any string with regular expression. In your case:

let originalString = "[ 'Chroma 2 Case' ]";
let newString = originalString.replace(/[\[\]\'\s]/g, '');

Usually you would use trim() on a string to just remove whitespace, however since you're already using a regex for [, ], and ', the \s in the matching regex takes care of any spaces, too.


问:
Is this better approach of creating Objects in Java than this?
Approach of creating objects

At present,

I have the following
structure

```<code>Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}
</code>```

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?

答: Your design might violate the Liskov Substitution Principle. Consider using an interface for X(), and/or delegation instead of inheritance.</p>

Body:
Approach of creating objects

At present,

I have the following
structure

Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?


问:
Change method call font color Pycharm
I would like to change font color for methods call. For instance string.lower() or string.strip(). I would like to change the color of lower() or strip() in PyCharm. I have tweaked around quite some time and I can't find where to change it. I did change other code font color but can't find specifically for methods call. Does anyone know how to do this in PyCharm?

答:
Unfortunately, you can't highlight function calls in PyCharm yet.

See How-to-syntax-highlight-Python-function-calls

It's unfortunate they didn't implement such a basic feature in their font color editor. The post above is from 2014 (3 years ago at the time I'm writing these lines...)

Title: Change method call font color Pycharm


问:
Reading CSV in Python/Django - Weird Mapping for csvDict
I am trying to read a csv file line-by-line in my views.py file. The csv file is structured as follows:

xk, ab, cd

11, 20, 30

31, 27, 35

etc

```<code>if request.method == "POST":
    pdb.set_trace()
    form = FormName(request.POST, request.FILES)
    file = request.FILES['csv'].read()
    if form.is_valid():
        try:
            reader = csv.DictReader(file)
            for row in reader:
                xk = row['xk']
</code>```

Before executing the last line above, when I print 'row' in pdb, I get {'x': 'k'}. However, I should get "11, 20, 30" (or something similar with that data, since DictReader is supposed to automatically use the first line as a header. When I print the file in pdb I get:

'xk,ab,cd\n11,20,30\n31,27,35' etc. How can I properly read the csv file?

答:
Resolved in comments:

try the same without the .read() method, like in this post – PRMoureu

request.FILES['csv'] returns an UploadedFile object, that seems to fit your dictReader approach – PRMoureu

^^That worked. Thanks!! – user7518095

Body:
I am trying to read a csv file line-by-line in my views.py file. The csv file is structured as follows:

xk, ab, cd

11, 20, 30

31, 27, 35

etc

if request.method == "POST":
    pdb.set_trace()
    form = FormName(request.POST, request.FILES)
    file = request.FILES['csv'].read()
    if form.is_valid():
        try:
            reader = csv.DictReader(file)
            for row in reader:
                xk = row['xk']

Before executing the last line above, when I print 'row' in pdb, I get {'x': 'k'}. However, I should get "11, 20, 30" (or something similar with that data, since DictReader is supposed to automatically use the first line as a header. When I print the file in pdb I get:

'xk,ab,cd\n11,20,30\n31,27,35' etc. How can I properly read the csv file?


问:
Flushing footer to bottom of the page, twitter bootstrap
I am generally familiar with the technique of flushing a footer using css.

But I am having some trouble getting this approach to work for Twitter bootstrap, most likely due to the fact that Twitter bootstrap is responsive in nature. Using Twitter bootstrap I am not able to get the footer to flush to the bottom of the page using the approach described in the above blog post.

答:
Tested with Bootstrap 3.6.6.

HTML

```<code><div class="container footer navbar-fixed-bottom">
  <footer>
    <!-- your footer content here -->
  </footer>
</div>
</code>```

CSS

```<code>.footer {
  bottom: 0;
  position: absolute;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Tested with Bootstrap 3.6.6.

HTML

<div class="container footer navbar-fixed-bottom">
  <footer>
    <!-- your footer content here -->
  </footer>
</div>

CSS

.footer {
  bottom: 0;
  position: absolute;
}


问:
Could not find ildasm.exe
I recently upgraded to VS 2017 and uninstalled the previous VS 2015.

However when I try and build and compile my project I keep getting and error:

Microsoft.Build.Utilities.ToolLocationHelper could not find ildasm.exe

The project uses Unmanaged Exports for C# - https://www.nuget.org/packages/UnmanagedExports

I cannot understand why this message comes up and googling has showed nothing. I have made sure that the target framework is the same >> 4.5.2. But nothing will build!!

I could only find the following directories though:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools

Please help, thanks

答:
I had the exact same problem.

I installed the Unmanaged Exports again and the problem was solved.

Title: Could not find ildasm.exe


问:
Merge functions to run serveral lines of JS code on browser Console
i'm trying to batch download PDF files on a single page like this:

http://procweb.jfrj.jus.br/portal/consulta/resinfopecas2.asp?CodDoc=76359308&CodUsuWeb=

I need to click every item to open a page that redirects me to a PDF file. That's what the function "MostraPeca" does.

If I run this function on Chrome console it also works:

```<code>MostraPeca('75959255','406','','14/03/2017 16:35:21','3744','3','1','930853');
</code>```

And I already have a list like this:

```<code>MostraPeca('75959255','406','','14/03/2017 16:35:21','3744','3','1','930853');
MostraPeca('75959255','287','','31/01/2017 14:24:48','3358','1','1','513367');
MostraPeca('75959255','605','','06/04/2017 13:47:49','4061','1','1','929011');
MostraPeca('75959255','780','','12/05/2017 16:20:56','4706','1','1','350899');
MostraPeca('75959255','759','','08/05/2017 16:05:41','4657','13','2','825754');
MostraPeca('75959255','142','','19/12/2016 15:53:09','1884','1','1','589882');
</code>```

But when I paste it on console just the first line runs. I would like run all lines at the same time. How it would be posible?

EDIT:

I've checked in the website source code and the functions looks like this:

```<code>    function MostraPeca( P1, P2, P3, DTI, NPI, NPT, TI, NV) {
        var newWindow;
        var left = (screen.width - 600) / 2;
        var top = (screen.height - 450) / 2;
        if (left < 0) {left = 1;}
        if (top < 0) {top = 1;}
        var props = 'resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=600,height=450'+',top='+top+',left='+left;
        newWindow = window.open('mostraarquivo.asp?P1='+P1+'&P2='+P2+'&P3='+P3+'&DTI='+DTI+'&NPI='+NPI+'&NPT='+NPT+'&TI='+TI+'&NV='+NV, 'pdf'+NPI , props);
    }
</code>```

答:
Its chrome trying to protect you against malicious websites. You will notice that chrome brings up an alarm with a message like

If you select "Always allow pop-ups from (your url)" then these functions will not be blocked.
you can read more information here link

Body:
i'm trying to batch download PDF files on a single page like this:

http://procweb.jfrj.jus.br/portal/consulta/resinfopecas2.asp?CodDoc=76359308&CodUsuWeb=

I need to click every item to open a page that redirects me to a PDF file. That's what the function "MostraPeca" does.

If I run this function on Chrome console it also works:

MostraPeca('75959255','406','','14/03/2017 16:35:21','3744','3','1','930853');

And I already have a list like this:

MostraPeca('75959255','406','','14/03/2017 16:35:21','3744','3','1','930853');
MostraPeca('75959255','287','','31/01/2017 14:24:48','3358','1','1','513367');
MostraPeca('75959255','605','','06/04/2017 13:47:49','4061','1','1','929011');
MostraPeca('75959255','780','','12/05/2017 16:20:56','4706','1','1','350899');
MostraPeca('75959255','759','','08/05/2017 16:05:41','4657','13','2','825754');
MostraPeca('75959255','142','','19/12/2016 15:53:09','1884','1','1','589882');

But when I paste it on console just the first line runs. I would like run all lines at the same time. How it would be posible?

EDIT:

I've checked in the website source code and the functions looks like this:

    function MostraPeca( P1, P2, P3, DTI, NPI, NPT, TI, NV) {
        var newWindow;
        var left = (screen.width - 600) / 2;
        var top = (screen.height - 450) / 2;
        if (left < 0) {left = 1;}
        if (top < 0) {top = 1;}
        var props = 'resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=600,height=450'+',top='+top+',left='+left;
        newWindow = window.open('mostraarquivo.asp?P1='+P1+'&P2='+P2+'&P3='+P3+'&DTI='+DTI+'&NPI='+NPI+'&NPT='+NPT+'&TI='+TI+'&NV='+NV, 'pdf'+NPI , props);
    }


问:
resizing image function implementation inpage
resize.php

```<code><?php
function resizeImg($new_width, $new_height, $get_image, $quality){
    ini_set("allow_url_fopen", 1);
    list($old_width, $old_height) = getimagesize($get_image);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($get_image);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
    header('Content-Type: image/jpeg');
    imagejpeg($image_p, NULL, $quality);
}
$new_width = $_GET['w'];
$new_height = $_GET['h'];
$get_image = $_GET['img'];
$get_quality = $_GET['q'];
if($get_quality == NULL){$quality = "80";}
else{$quality = $get_quality;}
resizeImg($new_width, $new_height, $get_image, $quality);
?>
</code>```

Above is code which i use to resize any image (e.g http://example.com/resize.php?w=480&h=320&q=50&img=http://example.com/image.jpg)

But i'm resizing images on just single page in my website so i wanted to implement the code inside that page as a function and put the result of that function in an  tag.

答:
You can use a data-url for that:

```<code><img src="data:image/jpeg;base64,<?php echo resizeImg(...) ?>"/>
</code>```

Your resizeImg() would then need to echo out the image base64 encoded like this:

```<code>echo base64_encode(...);
</code>```

Body:
resize.php

<?php
function resizeImg($new_width, $new_height, $get_image, $quality){
    ini_set("allow_url_fopen", 1);
    list($old_width, $old_height) = getimagesize($get_image);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($get_image);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
    header('Content-Type: image/jpeg');
    imagejpeg($image_p, NULL, $quality);
}
$new_width = $_GET['w'];
$new_height = $_GET['h'];
$get_image = $_GET['img'];
$get_quality = $_GET['q'];
if($get_quality == NULL){$quality = "80";}
else{$quality = $get_quality;}
resizeImg($new_width, $new_height, $get_image, $quality);
?>

Above is code which i use to resize any image (e.g http://example.com/resize.php?w=480&h=320&q=50&img=http://example.com/image.jpg)

But i'm resizing images on just single page in my website so i wanted to implement the code inside that page as a function and put the result of that function in an  tag.

Body:
You can use a data-url for that:

<img src="data:image/jpeg;base64,<?php echo resizeImg(...) ?>"/>

Your resizeImg() would then need to echo out the image base64 encoded like this:

echo base64_encode(...);


问:
Mac : Launch command when device connected by bluetooth
I would like to launch a shell command when a specific external bluetooth device is connected to my Mac.

A nice way (without installing third party software) to do that is by adding a plist file in ~/Library/LaunchAgents

On this page, there is an example of launching an event when the wifi connects to a specific location. It is done by watching a specific file :

```<code><key>WatchPaths</key>
<array>
   <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
</array>
</code>```

Do you think it'd possible to do the same with bluetooth events ?

Thanks for your help !

答:
Create a file in ~/Library/LaunchAgents containing :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

    <key>Label</key>
    <string>Smartcard reader</string>

    <key>ProgramArguments</key>
    <array>
        <string>/Users/USERNAME/Library/Scripts/script.bash</string>
    </array>

    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/com.apple.Bluetooth.plist</string>
    </array>

</dict>
</plist>
</code>```

And in /Users/USERNAME/Library/Scripts/script.bash we can test if the connected device is the right one :

```<code>if [ $(system_profiler SPBluetoothDataType | grep "Smart Reader 2501" | wc -l) -eq 1 ] ; then
    echo "Smartcard connected"
fi
</code>```

Launch the service using

```<code>launchctl load ~/Library/LaunchAgents/yourscript
</code>```

Body:
I would like to launch a shell command when a specific external bluetooth device is connected to my Mac.

A nice way (without installing third party software) to do that is by adding a plist file in ~/Library/LaunchAgents

On this page, there is an example of launching an event when the wifi connects to a specific location. It is done by watching a specific file :

<key>WatchPaths</key>
<array>
   <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
</array>

Do you think it'd possible to do the same with bluetooth events ?

Thanks for your help !

Body:
Create a file in ~/Library/LaunchAgents containing :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

    <key>Label</key>
    <string>Smartcard reader</string>

    <key>ProgramArguments</key>
    <array>
        <string>/Users/USERNAME/Library/Scripts/script.bash</string>
    </array>

    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/com.apple.Bluetooth.plist</string>
    </array>

</dict>
</plist>

And in /Users/USERNAME/Library/Scripts/script.bash we can test if the connected device is the right one :

if [ $(system_profiler SPBluetoothDataType | grep "Smart Reader 2501" | wc -l) -eq 1 ] ; then
    echo "Smartcard connected"
fi

Launch the service using

launchctl load ~/Library/LaunchAgents/yourscript


问:
Gaps setting font-size in inline elements
I have problems setting font-size styles in inline elements. Some gaps comes up.
There are questions related to this issue but I've not found a solution to my case.

Given this code:

<!doctype html>

Big text

                    Small text

                    Small text

```

How could I remove the extra vertical gaps if the HTML markup can't be modified and new CSS can only be applied to the container div and its children?

I've tried setting vertical-aling:top and line-height:0 but I can't get it to work.

What I need is this:

What I'm getting is:

答:
Here you go! Just add .small {display: block} to your CSS and you're save.

<!doctype html>

Big text

                    Small text

                    Small text

```

working fiddle: https://jsfiddle.net/y7edz1tj/

Body:
I have problems setting font-size styles in inline elements. Some gaps comes up.
There are questions related to this issue but I've not found a solution to my case.

Given this code:

<!doctype html>

Big text

                    Small text

                    Small text

How could I remove the extra vertical gaps if the HTML markup can't be modified and new CSS can only be applied to the container div and its children?

I've tried setting vertical-aling:top and line-height:0 but I can't get it to work.

What I need is this:

What I'm getting is:

Body:
Here you go! Just add .small {display: block} to your CSS and you're save.

<!doctype html>
<html>
    <style>
        .container {
            font-size: 40px;
        }

        p {
            margin: 0;
        }

        .small {
            font-size: 16px;
            display: block;
        }
    </style>
    <body>
        <div class="container">
            <p>Big text</p>
            <p>
                <span class="small">
                    Small text
                </span>
            </p>
            <p>
                <span class="small">
                    Small text
                </span>
            </p>
        </div>
    </body>
</html>

working fiddle: https://jsfiddle.net/y7edz1tj/


问:
Sprint Boot and Elastic Search Connection issue
I'm creating an application using Spring Boot and also Elastic-Search. Spring application part is working. And also when I start Elastic server, it's also running well. No issues at all. I can test it via POSTMAN and also CURL. Adding and also searching works well.

But when I run the application, i'm getting following issues.
This is the issue i'm getting in the IDE. (which means from my java application)

org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{127.0.0.1}{127.0.0.1:9300}]

And this is the issue i'm getting from the Elasctic server on my local system.

java.lang.IllegalStateException: Received message from unsupported version: [2.0.0] minimal compatible version is: [5.0.0]

These are the libraries I'm using.

Spring Boot 1.5.1.RELEASE

Spring Boot Starter Data Elasticsearch 1.5.1.RELEASE

Spring Data Elasticsearch 2.10.RELEASE

Elastic Search 5.0

I think this is a issue with Elastic and above library version mismatch.
I'm new to Elastic and also Spring. The version issue is here.
https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix

And also here is my pom.xml. If I need to update any library, can anyone tell me what's that ? And also tell me how to update those libraries ? Can I update them without changing to my source code ?

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><artifactId>springboot-springdata-elasticsearch-example</artifactId>
<packaging>jar</packaging>
<url>https://www.mkyong.com</url>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Runtime, for Embedded Elasticsearch,
        comment this if connect to external elastic search server-->
    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <!-- Package as an executable jar/war -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

In this pom.xml , I can't find all the dependencies too.

答:
According to the versions matrix that you provided, the spring boot version that you're using is not compatible with ElasticSearch 5.x instances. So, i think you have 3 options:

If you really need to work with SpringBoot 1.5.1 using ElasticSearch 5.0, you should add the maven dependencies related to ElasticSearch 5.0 and implement your own DAO service.

You can try to downgrade your ElasticSearch version to 2.4 in order to make it compatible with your current spring boot version.

Maybe you can try to use the recent spring boot version (1.5.4) because arcording to the spring-data-elasticsearch project (https://github.com/spring-projects/spring-data-elasticsearch/), the last version supports ElasticSearch 5.x, so probably it could be the easiest way.

Please let me know if any of options above was useful for you.

Body:
I'm creating an application using Spring Boot and also Elastic-Search. Spring application part is working. And also when I start Elastic server, it's also running well. No issues at all. I can test it via POSTMAN and also CURL. Adding and also searching works well.

But when I run the application, i'm getting following issues.
This is the issue i'm getting in the IDE. (which means from my java application)

org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{127.0.0.1}{127.0.0.1:9300}]

And this is the issue i'm getting from the Elasctic server on my local system.

java.lang.IllegalStateException: Received message from unsupported version: [2.0.0] minimal compatible version is: [5.0.0]

These are the libraries I'm using.

Spring Boot 1.5.1.RELEASE

Spring Boot Starter Data Elasticsearch 1.5.1.RELEASE

Spring Data Elasticsearch 2.10.RELEASE

Elastic Search 5.0

I think this is a issue with Elastic and above library version mismatch.
I'm new to Elastic and also Spring. The version issue is here.
https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix

And also here is my pom.xml. If I need to update any library, can anyone tell me what's that ? And also tell me how to update those libraries ? Can I update them without changing to my source code ?

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<artifactId>springboot-springdata-elasticsearch-example</artifactId>
<packaging>jar</packaging>
<url>https://www.mkyong.com</url>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

In this pom.xml , I can't find all the dependencies too.


问:
Is there any way to simulate django collectstatic command during development?
I'm working on React App and after that I want to make a bundle.js file and place it in assets/bundles/ folder.

I'm using django-webpack-loader

Here's my settings.py file:

```<code>INSTALLED_APPS = (
 ...
 'webpack_loader',
)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

STATIC_URL = '/media/static/'

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}
</code>```

Here's my template.html:

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

{% load render_bundle from webpack_loader %}
{% render_bundle 'main' %}
</code>```

The error I get is:

GET example.com/media/static/bundles/bundle.js 404 (Not Found)

If I run

python manage.py collectstatic

It will move bundle.js from assets/bundles/ to media/static/bundles. But I don't want to run it every time I'm changing my bundle.

In the django-webpack-loader documentation collectstatic command is not run but the bundle.js still can be accessed as though it's in static folder. But actually it's located in assets.

答:
Is this what you are looking for?

```<code>./manage.py collectstatic --noinput
</code>```

If you have a lot of duplicates you can use --clear method

```<code>./manage.py collectstatic --clear
</code>```

If you struggle adding the package you can search for the Path to the JS like:

```<code>./manage.py findstatic js/bundle.js
</code>```

read more about the command here

Body:
I'm working on React App and after that I want to make a bundle.js file and place it in assets/bundles/ folder.

I'm using django-webpack-loader

Here's my settings.py file:

INSTALLED_APPS = (
 ...
 'webpack_loader',
)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

STATIC_URL = '/media/static/'

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}

Here's my template.html:

{% load render_bundle from webpack_loader %}
{% render_bundle 'main' %}

The error I get is:

GET example.com/media/static/bundles/bundle.js 404 (Not Found)

If I run

python manage.py collectstatic

It will move bundle.js from assets/bundles/ to media/static/bundles. But I don't want to run it every time I'm changing my bundle.

In the django-webpack-loader documentation collectstatic command is not run but the bundle.js still can be accessed as though it's in static folder. But actually it's located in assets.

Body:
Is this what you are looking for?

./manage.py collectstatic --noinput

If you have a lot of duplicates you can use --clear method

./manage.py collectstatic --clear

If you struggle adding the package you can search for the Path to the JS like:

./manage.py findstatic js/bundle.js

read more about the command here


问:
HTTPS Facebook Opengraph URL requested a HTTP redirect, but it could not be followed
I keep getting this warning in Facebook debug tool for my pages from my site i want to share. URL requested a HTTP redirect, but it could not be followed.

after i re crawl everything usually comes out fine, with description , picture, title etc.

the problem is when someone uses the Facebook share button on the site itself, its hit or miss , sometimes it works fine and shares the post properly, and other times, nothing gets shown, no title, no image, no discription , only url.

I think it has something to do with my site being https

heres an example url https://plugmatch.com/singlepost/312 and i'm getting errors on it, I know that if I rescrape, it'll probably fix it, but thats not the point, I need when users of my site share something, that it gets shared properly.

any ideas

答:
I've run into similar problems and can't say one will solve, but try the following:

use api v2.9.  (fb recently deprecated an earlier version. I think you are ok with 2.6)

change your meta property="og:url" to:

content="   https://plugmatch.com/"

(added 's' to 'http' and an
   '/' at the end of the url)

Check to make sure your og:url is something that people can access whether they are logged in or not.


问:
How to reboot kubernetes pod and keep the data
I'm now using kubernetes to run the Docker container.I just create the container and i use SSH connect to my pods.

I need to do some system config change so i need to reboot the container but when i`reboot the container it will lose all the data in the pod. kubernetes  will run a new pod just like the Docker image original.

So how can i reboot the pod and just keep the data in it?

The kubernetes  was offered my Bluemix

答:
You need to learn more about containers as your question suggests that you are not fully grasping the concepts.

Running SSH in a container is an anti-pattern, a container is not a virtual machine. So remove the SSH server from it.

the fact that you run SSH indicates that you may be running more than one process per container. This is usually bad practice. So remove that supervisor and call your main process directly in your entrypoint.

Setup your container image main process to use environment variables or configuration files for configuration at runtime.

The last item means that you can define environment variables in your Pod manifest or use Kubernetes configmaps to store configuration file. Your Pod will read those and your process in your container will get configured properly. If not your Pod will die or your process will not run properly and you can just edit the environment variable or config map.

My main suggestion here is to not use Kubernetes until you have your docker image properly written and your configuration thought through, you should not have to exec in the container to get your process running.

Finally, more generally, you should not keep state inside a container.


问:
Angular Material Components Not Displayed
I am new to Angular 2 and Angular Material I tried creating one example to check Angular Material but its not working. I am getting empty html page. My code is as follows.

App Component ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}
</code>```

App Module .ts

```<code>    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import {MdSidenavModule,MdMenuModule} from '@angular/material';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {NoopAnimationsModule} from '@angular/platform-browser/animations';
    import 'hammerjs';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MdSidenavModule,
    BrowserAnimationsModule,
    NoopAnimationsModule,
    MdMenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

App Component Html;

```<code><!--The whole content below can be removed with the new code.-->

 <link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
 <div>

 <md-sidenav-container>

   <md-sidenav opened="true">
    <button>
     Add
    </button>
   </md-sidenav>
 </md-sidenav-container>

 <md-menu>
  <button md-menu-item> Settings </button>
  <button md-menu-item> Help </button>
</md-menu>
</div>
</code>```

styles.css

```<code>@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";
</code>```

My Package.json

```<code>{
  "name": "asyncpipe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.6",
    "@angular/cdk": "^2.0.0-beta.8",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.8",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.2",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

My angular-cli.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "asyncpipe"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

I have included all dependencies as per mentioned on web. Please help me to resolve this.

答:
Remove import { MaterialModule } from '@angular/material'; and MaterialModule from imports: [] too. It's deprecated since beta.3 [Changelog].

Also, add NoopAnimationsModule

```<code>import {NoopAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [NoopAnimationsModule],
  ...
})
</code>```

I also found your error issue listed in Github. Seems like fallback to animations version 4.1.3 is the solution for now.

Try npm install '@angular/animations"@4.1.3' --save

Let me know if that helps!

UPDATE:

md-menu isn't showing up because it needs a mdMenuTriggerFor which can open the menu. Until then, it stays hidden. Also, for sidenav to work, everything needs to be within the md-sidenav-container tag. Sidenav doc, Menu doc.

Please change your html code with following:

```<code><md-sidenav-container style="height: 500px">

  <button md-icon-button [mdMenuTriggerFor]="menu">
    <md-icon>more_vert</md-icon>Menu
  </button>

  <md-sidenav opened="true" #sidenav
      style="background-color: skyblue">
    <button md-raised-button style="margin: 2px 0 0 6px">
     Add
    </button>
    <p>This is Sidenav</p>
   </md-sidenav>

   <md-menu #menu="mdMenu">
     <button md-menu-item (click)="sidenav.open()"> Sidenav </button>
    <button md-menu-item> Settings </button>
    <button md-menu-item> Help </button>
  </md-menu>

</md-sidenav-container>
</code>```

Demo

Body:
I am new to Angular 2 and Angular Material I tried creating one example to check Angular Material but its not working. I am getting empty html page. My code is as follows.

App Component ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

App Module .ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import {MdSidenavModule,MdMenuModule} from '@angular/material';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {NoopAnimationsModule} from '@angular/platform-browser/animations';
    import 'hammerjs';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MdSidenavModule,
    BrowserAnimationsModule,
    NoopAnimationsModule,
    MdMenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

App Component Html;

 <link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

 <md-sidenav-container>

   <md-sidenav opened="true">
    <button>
     Add
    </button>
   </md-sidenav>
 </md-sidenav-container>

 <md-menu>
  <button md-menu-item> Settings </button>
  <button md-menu-item> Help </button>
</md-menu>

styles.css

@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";

My Package.json

{
  "name": "asyncpipe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.6",
    "@angular/cdk": "^2.0.0-beta.8",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.8",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.2",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

My angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "asyncpipe"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

I have included all dependencies as per mentioned on web. Please help me to resolve this.

Body:
Remove import { MaterialModule } from '@angular/material'; and MaterialModule from imports: [] too. It's deprecated since beta.3 [Changelog].

Also, add NoopAnimationsModule

import {NoopAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [NoopAnimationsModule],
  ...
})

I also found your error issue listed in Github. Seems like fallback to animations version 4.1.3 is the solution for now.

Try npm install '@angular/animations"@4.1.3' --save

Let me know if that helps!

UPDATE:

md-menu isn't showing up because it needs a mdMenuTriggerFor which can open the menu. Until then, it stays hidden. Also, for sidenav to work, everything needs to be within the md-sidenav-container tag. Sidenav doc, Menu doc.

Please change your html code with following:

<md-sidenav-container style="height: 500px">

  <button md-icon-button [mdMenuTriggerFor]="menu">
    <md-icon>more_vert</md-icon>Menu
  </button>

  <md-sidenav opened="true" #sidenav
      style="background-color: skyblue">
    <button md-raised-button style="margin: 2px 0 0 6px">
     Add
    </button>
    <p>This is Sidenav</p>
   </md-sidenav>

   <md-menu #menu="mdMenu">
     <button md-menu-item (click)="sidenav.open()"> Sidenav </button>
    <button md-menu-item> Settings </button>
    <button md-menu-item> Help </button>
  </md-menu>

</md-sidenav-container>

Demo


问:
HOW TO Return value array on function php mysql
Hy I have code below,
I wanna return value array with function :

```<code>    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "<br>";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);

?>
</code>```

and the result :

```<code>script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )
</code>```

there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?

答:
Is the variable id_orders_temp
returning a correct value ??
and if its a column of DB then u have to

```<code>$row['id_orders_temp'];
</code>```

Body:
Hy I have code below,
I wanna return value array with function :

    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "
";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);

?>

and the result :

script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )

there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?

Body:
Is the variable id_orders_temp
returning a correct value ??
and if its a column of DB then u have to

$row['id_orders_temp'];


问:
How to show maximum same adjacent elements in an array in Java
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

```<code>int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);
</code>```

```<code> Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )
</code>```

My output is (directly from console)

1

[I@6d06d69c

答:
Here is your solution : </p>

```<code>package com.sujit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Test {
    public static int count = 0;
    public static void main(String[] args) {
        Integer[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array
        List<Integer> resultList =Arrays.asList(arr);
        List<Integer> maxOccurence = new ArrayList<Integer>();
        Set<Integer> set = new HashSet<>();

        for (Integer integer : resultList) {
            set.add(integer);
        }
        for (Integer integer : set) {
            int freq = Collections.frequency(resultList, integer);
            maxOccurence.add(freq);
            System.out.println("Element : "+integer+"  Occurences= "+freq);
        }
        System.out.println(Collections.max(maxOccurence));
    }
}
</code>```

Body:
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);

 Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )

My output is (directly from console)

1

[I@6d06d69c

Body:
Here is your solution :

package com.sujit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Test {
    public static int count = 0;
    public static void main(String[] args) {
        Integer[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array
        List<Integer> resultList =Arrays.asList(arr);
        List<Integer> maxOccurence = new ArrayList<Integer>();
        Set<Integer> set = new HashSet<>();

        for (Integer integer : resultList) {
            set.add(integer);
        }
        for (Integer integer : set) {
            int freq = Collections.frequency(resultList, integer);
            maxOccurence.add(freq);
            System.out.println("Element : "+integer+"  Occurences= "+freq);
        }
        System.out.println(Collections.max(maxOccurence));
    }
}


问:
Trying to shift left by EAX a variable
How can I use the command shl to shift 1 by a variable?

```<code>mov one, 1

shl one , eax
</code>```

Returns an error.

答:
You can shift only shift by cl, unless you use BMI2 shifts. So for example:

```<code>mov edx, 1
shl edx, cl
</code>```

Since you're shifting the value 1 to the left, there is an other applicable instruction: bts. bts can take any register as index.

```<code>xor edx, edx
bts edx, eax
</code>```

Be careful when using it with a memory destination, the index won't be reduced modulo 32, so you can use it to (accidentally) set a bit quite far away from the base address.

Title: Trying to shift left by EAX a variable

Body:
How can I use the command shl to shift 1 by a variable?

mov one, 1

shl one , eax

Returns an error.

Body:
You can shift only shift by cl, unless you use BMI2 shifts. So for example:

mov edx, 1
shl edx, cl

Since you're shifting the value 1 to the left, there is an other applicable instruction: bts. bts can take any register as index.

xor edx, edx
bts edx, eax

Be careful when using it with a memory destination, the index won't be reduced modulo 32, so you can use it to (accidentally) set a bit quite far away from the base address.


问:
Formatting mysqli output table with different functionalities
I am outputting newsletter email registrations.
How can I format them into tables and what edits can I do so that I can drop that row also.

My PHP code is :

```<code><?php include "navbar-datacheck.php" ?>
<?php
    include "../backend/db.php";
    $sql = "SELECT * from newsletter";
    $result = $mysqli->query($sql);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            print "id: " . $row["id"]. " - Email ID: " . $row["email"]."<br>";
        }
    } else {
        echo "0 results";
    }

    $mysqli->close();
?>
</code>```

答:
Construct your table comprising of all the newsletter details in the following manner,

```<code>// your code
if ($result->num_rows > 0) {
    // output data of each row
    ?>
    <table>
        <tr>
            <td>ID</td>
            <td>Email</td>
            <td>Action</td>
        </tr>
    <?php
    while($row = $result->fetch_assoc()) {
        ?>
        <tr>
            <td><?php echo $row["id"]; ?></td>
            <td><?php echo $row["email"]; ?></td>
            <td><a href="delete.php?id=<?php echo $row["id"] ?>">Delete</a></td>
        </tr>
        <?php
    }
    ?>
    </table>
    <?php
} else {
    echo "0 results";
}
// your code
</code>```

... what edits can I do so that I can drop that row also.

As you can see, I have added a third column Action in your table so that you could delete a row of your choice at any given time. So once the user clicks on Delete link, this is how you should process and delete the corresponding record in delete.php file.

```<code>if(isset($_GET['id']) && !empty($_GET['id'])){
    $id = $_GET['id'];
    // Now delete the corresponding record from the table
}
</code>```

Body:
I am outputting newsletter email registrations.
How can I format them into tables and what edits can I do so that I can drop that row also.

My PHP code is :

<?php include "navbar-datacheck.php" ?>
<?php
    include "../backend/db.php";
    $sql = "SELECT * from newsletter";
    $result = $mysqli->query($sql);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            print "id: " . $row["id"]. " - Email ID: " . $row["email"]."
";
        }
    } else {
        echo "0 results";
    }

    $mysqli->close();
?>

Body:
Construct your table comprising of all the newsletter details in the following manner,

// your code
if ($result->num_rows > 0) {
    // output data of each row
    ?>
    <table>
        <tr>
            <td>ID</td>
            <td>Email</td>
            <td>Action</td>
        </tr>
    <?php
    while($row = $result->fetch_assoc()) {
        ?>
        <tr>
            <td><?php echo $row["id"]; ?></td>
            <td><?php echo $row["email"]; ?></td>
            <td><a href="delete.php?id=<?php echo $row["id"] ?>">Delete</a></td>
        </tr>
        <?php
    }
    ?>
    </table>
    <?php
} else {
    echo "0 results";
}
// your code

... what edits can I do so that I can drop that row also.

As you can see, I have added a third column Action in your table so that you could delete a row of your choice at any given time. So once the user clicks on Delete link, this is how you should process and delete the corresponding record in delete.php file.

if(isset($_GET['id']) && !empty($_GET['id'])){
    $id = $_GET['id'];
    // Now delete the corresponding record from the table
}


问:
Agent JAR loaded but agent failed to initialize
I'm trying to "inject" a jar using Agents, now the Java version are both 1.8, and the tools are from my JDK lib folder so I don't think anything is wrong with that either

This is my loading class

```<code>public static void main(final String[] args) throws Exception {
    final File jarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
    System.out.println("Starting Lizard...");
    try {
        Class.forName("com.sun.tools.attach.VirtualMachine");
    }
    catch (ClassNotFoundException e2) {
        System.out.println("ERROR: Couldn't load VirtualMachine class, is tools.jar present?");
        return;
    }
    System.out.println("Loading attach library...");
    extractLibrary(jarFile);
    try {
        System.loadLibrary("attach");
    }
    catch (Exception e3) {
        System.out.println("ERROR: Couldn't load attach libary!");
        return;
    }

    System.out.println("Attach library loaded.");
    System.out.println("Searching for Minecraft JVM...");
    for (final VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        if (descriptor.displayName().startsWith("net.minecraft.launchwrapper.Launch")) {
            System.out.println("Minecraft found, attaching...");
            System.out.println(descriptor.id());
            final VirtualMachine vm = VirtualMachine.attach(descriptor.id());
            final String vmJavaVersion = vm.getSystemProperties().getProperty("java.version");
            final String clientJavaVersion = System.getProperty("java.version");
            System.out.println("vmJava: " + vmJavaVersion);
            System.out.println("ClientJava: " + clientJavaVersion);
            if (!vmJavaVersion.equals(clientJavaVersion)) {
                System.out.println("WARN: Lizard and Minecraft Java version do not match, agent might fail!");
            }
            System.out.println("Loading agent...");
            try {
                vm.loadAgent(jarFile.getAbsolutePath());
            }
            catch (Exception e) {
                System.out.println("ERROR: Agent failed to load (" + e.getMessage() + ")!");
                System.out.println("1: "+ e);
                e.printStackTrace();
                return;
            }
            System.out.println("Agent successfully loaded, detaching...");
            vm.detach();
            System.out.println("Lizard started successfully.");
            System.exit(0);
            return;
        }
    }
    System.out.println("Minecraft not found, exiting.");
    JOptionPane.showMessageDialog(null, "No Minecraft JVM found.", "Lizard", 0);
}
</code>```

And this is my agentmain

```<code>public static void agentmain(String args, Instrumentation instrumentation) {
    try {
        @SuppressWarnings("rawtypes")
        Class[] arrclass = instrumentation.getAllLoadedClasses();
        int n = arrclass.length;
        int n2 = 0;
        while (n2 < n) {
            Class<?> clazz = arrclass[n2];
            if (clazz.getName().equals("net.minecraft.client.Minecraft")) {
                LaunchClassLoader classLoader = (LaunchClassLoader)clazz.getClassLoader();
                classLoader.addURL(Agent.class.getProtectionDomain().getCodeSource().getLocation());
                Class<?> spookyNan = classLoader.loadClass(gorilla.Gorilla.class.getName());
                spookyNan.newInstance();
                return;
            }
            ++n2;
        }
    }

    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.toString());
        JOptionPane.showMessageDialog(null, e.getStackTrace());
    }
}
</code>```

now the stacktrace I get is:

```<code>com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize
    at sun.tools.attach.HotSpotVirtualMachine.loadAgent(HotSpotVirtualMachine.java:121)
    at com.sun.tools.attach.VirtualMachine.loadAgent(VirtualMachine.java:540)
    at gorilla.Main.main(Main.java:47)
</code>```

With Line47 being this line

```<code>vm.loadAgent(jarFile.getAbsolutePath());
</code>```

答:
AgentInitializationException: Agent JAR loaded but agent failed to initialize means that agentmain method has thrown an uncaught exception. Check the console or the logs of the target Java application (Minecraft) to see the cause.

Note: once you've loaded an agent into the target application, you won't be able to load the modified version of the same agent. This particularly means that if your agent has once failed with an exception, even after you has fixed the error and tried to load the correct class again, the agent will still fail with the same error.

In order to load the updated agent you'll have to rename the agent class and pack it to a different JAR file.

Body:
I'm trying to "inject" a jar using Agents, now the Java version are both 1.8, and the tools are from my JDK lib folder so I don't think anything is wrong with that either

This is my loading class

public static void main(final String[] args) throws Exception {
    final File jarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
    System.out.println("Starting Lizard...");
    try {
        Class.forName("com.sun.tools.attach.VirtualMachine");
    }
    catch (ClassNotFoundException e2) {
        System.out.println("ERROR: Couldn't load VirtualMachine class, is tools.jar present?");
        return;
    }
    System.out.println("Loading attach library...");
    extractLibrary(jarFile);
    try {
        System.loadLibrary("attach");
    }
    catch (Exception e3) {
        System.out.println("ERROR: Couldn't load attach libary!");
        return;
    }

    System.out.println("Attach library loaded.");
    System.out.println("Searching for Minecraft JVM...");
    for (final VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        if (descriptor.displayName().startsWith("net.minecraft.launchwrapper.Launch")) {
            System.out.println("Minecraft found, attaching...");
            System.out.println(descriptor.id());
            final VirtualMachine vm = VirtualMachine.attach(descriptor.id());
            final String vmJavaVersion = vm.getSystemProperties().getProperty("java.version");
            final String clientJavaVersion = System.getProperty("java.version");
            System.out.println("vmJava: " + vmJavaVersion);
            System.out.println("ClientJava: " + clientJavaVersion);
            if (!vmJavaVersion.equals(clientJavaVersion)) {
                System.out.println("WARN: Lizard and Minecraft Java version do not match, agent might fail!");
            }
            System.out.println("Loading agent...");
            try {
                vm.loadAgent(jarFile.getAbsolutePath());
            }
            catch (Exception e) {
                System.out.println("ERROR: Agent failed to load (" + e.getMessage() + ")!");
                System.out.println("1: "+ e);
                e.printStackTrace();
                return;
            }
            System.out.println("Agent successfully loaded, detaching...");
            vm.detach();
            System.out.println("Lizard started successfully.");
            System.exit(0);
            return;
        }
    }
    System.out.println("Minecraft not found, exiting.");
    JOptionPane.showMessageDialog(null, "No Minecraft JVM found.", "Lizard", 0);
}

And this is my agentmain

public static void agentmain(String args, Instrumentation instrumentation) {
    try {
        @SuppressWarnings("rawtypes")
        Class[] arrclass = instrumentation.getAllLoadedClasses();
        int n = arrclass.length;
        int n2 = 0;
        while (n2 < n) {
            Class<?> clazz = arrclass[n2];
            if (clazz.getName().equals("net.minecraft.client.Minecraft")) {
                LaunchClassLoader classLoader = (LaunchClassLoader)clazz.getClassLoader();
                classLoader.addURL(Agent.class.getProtectionDomain().getCodeSource().getLocation());
                Class<?> spookyNan = classLoader.loadClass(gorilla.Gorilla.class.getName());
                spookyNan.newInstance();
                return;
            }
            ++n2;
        }
    }

    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.toString());
        JOptionPane.showMessageDialog(null, e.getStackTrace());
    }
}

now the stacktrace I get is:

com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize
    at sun.tools.attach.HotSpotVirtualMachine.loadAgent(HotSpotVirtualMachine.java:121)
    at com.sun.tools.attach.VirtualMachine.loadAgent(VirtualMachine.java:540)
    at gorilla.Main.main(Main.java:47)

With Line47 being this line

vm.loadAgent(jarFile.getAbsolutePath());


问:
TabControl winform c#
Does anyone know why my tabcontrol will not display on this form? Have a feeling it maybe something simple but at the moment i just get a blank form.

Thanks

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

namespace test_project_3
{
    public partial class TabTest : Form
    {
        public TabTest()
        {
            InitializeComponent();

            WebBrowser WB = new WebBrowser();
            WB.Navigate("www.google.com");

            TabControl tc = new TabControl();
            tc.Dock = DockStyle.Fill;
            tc.Show();

            TabPage tp = new TabPage();
            tp.Text = "test";
            tp.Show();
            tp.Controls.Add(WB);

            tc.TabPages.Add(tp);
        }
    }
}
</code>```

答:
You need to add the TabControl to the Controls collection:

```<code>this.Controls.Add(tc);
</code>```

Title: TabControl winform c#

Body:
Does anyone know why my tabcontrol will not display on this form? Have a feeling it maybe something simple but at the moment i just get a blank form.

Thanks

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

namespace test_project_3
{
    public partial class TabTest : Form
    {
        public TabTest()
        {
            InitializeComponent();

            WebBrowser WB = new WebBrowser();
            WB.Navigate("www.google.com");

            TabControl tc = new TabControl();
            tc.Dock = DockStyle.Fill;
            tc.Show();

            TabPage tp = new TabPage();
            tp.Text = "test";
            tp.Show();
            tp.Controls.Add(WB);

            tc.TabPages.Add(tp);
        }
    }
}

Body:
You need to add the TabControl to the Controls collection:

this.Controls.Add(tc);


问:
Is there a way to dynamically define the query fields?
Inspired by this great answer (How to simplify `case` iteraction when the code is almost the same) I though that there might be a way of doing something similar to this query to dynamically manipulate these fields:

u.date, u.title, u.text - u.date_pt, u.title_pt, u.text_pt - u.date_es, u.title_es, u.text_es -...
in this query:

```<code>    def search(query, search_term, locale) do
        language =
          case locale do
            "pt" ->
              "Portuguese"
            "es" ->
              "Spanish"
            "fr" ->
              "Spanish"
            "de" ->
              "German"
            _ ->
              "English"
          end
        f = if locale in ~w(en pt es fr de), do: :"u.date_#{locale}, u.title_#{locale}, u.text_#{locale}", else: :u.date, u.title, u.text # This is WRONG, just to illustrate what's intended
        (from u in query,
        where: fragment("(to_tsvector(?, unaccent(?)) || to_tsvector(?, unaccent(?)) || to_tsvector(coalesce(?, unaccent(?)))) @@ plainto_tsquery(?, unaccent(?))",
                         ^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term),
        order_by: fragment("ts_rank((to_tsvector(?, ?) || to_tsvector(?, ?) || to_tsvector(coalesce(?, ?))), plainto_tsquery(?, ?)) DESC",
                        ^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term))
        |> Repo.all()
      end
</code>```

Is it?

答:
Yes, you can use field/2 in the Ecto query for this. I'd do it like this:

```<code>suffix = if locale in ~w(pt es fr de), do: "_#{locale}", else: ""
</code>```

Then, in the query, instead of

```<code>u.date
</code>```

do:

```<code>field(u, ^:"date#{suffix}")
</code>```

Similarly, u.title becomes field(u, ^:"title#{suffix}"), and so on.

Body:
Inspired by this great answer (How to simplify `case` iteraction when the code is almost the same) I though that there might be a way of doing something similar to this query to dynamically manipulate these fields:

u.date, u.title, u.text - u.date_pt, u.title_pt, u.text_pt - u.date_es, u.title_es, u.text_es -...
in this query:

    def search(query, search_term, locale) do
        language =
          case locale do
            "pt" ->
              "Portuguese"
            "es" ->
              "Spanish"
            "fr" ->
              "Spanish"
            "de" ->
              "German"
            _ ->
              "English"
          end
        f = if locale in ~w(en pt es fr de), do: :"u.date_#{locale}, u.title_#{locale}, u.text_#{locale}", else: :u.date, u.title, u.text # This is WRONG, just to illustrate what's intended
        (from u in query,
        where: fragment("(to_tsvector(?, unaccent(?)) || to_tsvector(?, unaccent(?)) || to_tsvector(coalesce(?, unaccent(?)))) @@ plainto_tsquery(?, unaccent(?))",
                         ^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term),
        order_by: fragment("ts_rank((to_tsvector(?, ?) || to_tsvector(?, ?) || to_tsvector(coalesce(?, ?))), plainto_tsquery(?, ?)) DESC",
                        ^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term))
        |> Repo.all()
      end

Is it?

Body:
Yes, you can use field/2 in the Ecto query for this. I'd do it like this:

suffix = if locale in ~w(pt es fr de), do: "_#{locale}", else: ""

Then, in the query, instead of

u.date

do:

field(u, ^:"date#{suffix}")

Similarly, u.title becomes field(u, ^:"title#{suffix}"), and so on.


问:
How can I access a control in WPF from another class or window
I want to access my controls like button or textbox in mainWindow in WPF, but I can't do this.

In Windows Form application it's so easy, you can set modifier of that control to True and you can reach that control from an instance of that mainWindow, but in WPF I can't declare a public control. How can I do this?

答:
```<code>var targetWindow = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is principal) as principal;
targetWindow .BssAcesso.Background = Brushes.Transparent;
</code>```

just call any control of it from your current window:

```<code>targetWindow.ABUTTON.Background = Brushes.Transparent;
</code>```

How can I access one window's control (richtextbox) from another window in wpf?

Body:
var targetWindow = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is principal) as principal;
targetWindow .BssAcesso.Background = Brushes.Transparent;

just call any control of it from your current window:

targetWindow.ABUTTON.Background = Brushes.Transparent;

How can I access one window's control (richtextbox) from another window in wpf?


答:
The only way to shift by a variable amount is to put the shift count in the CL register (which is the low 8 bits of the 32-bit ECX register). This is the only encoding available for any of the shift instructions that takes a register source operand.

So you would need to do:

```<code>mov DWORD PTR [one], 1      ; initialize variable 'one'
mov ecx, eax                ; copy shift count from EAX into ECX
shl DWORD PTR [one], cl     ; one << cl
</code>```

Note that only the low 8 bits of ECX are used here, but that's perfectly sufficient, since you can't shift a DWORD sized value by anything more than 32 bits anyway! In fact, on everything but the 8088/8086, the shift count will be masked to 5 bits anyway (i.e., modulo 32), limiting it to the range 0–31, inclusive.

Also, I should mention that while you can use a memory operand as the source for arithmetic instructions like shift, you probably shouldn't because it is slower than using a register. So, since you've got to clobber a register anyway, you could do:

```<code>mov  ecx, eax
mov  eax, 1
shl  eax, cl
mov  DWORD PTR [one], eax
</code>```

Title: Trying to shift left by EAX a variable

Body:
The only way to shift by a variable amount is to put the shift count in the CL register (which is the low 8 bits of the 32-bit ECX register). This is the only encoding available for any of the shift instructions that takes a register source operand.

So you would need to do:

mov DWORD PTR [one], 1      ; initialize variable 'one'
mov ecx, eax                ; copy shift count from EAX into ECX
shl DWORD PTR [one], cl     ; one << cl

Note that only the low 8 bits of ECX are used here, but that's perfectly sufficient, since you can't shift a DWORD sized value by anything more than 32 bits anyway! In fact, on everything but the 8088/8086, the shift count will be masked to 5 bits anyway (i.e., modulo 32), limiting it to the range 0–31, inclusive.

Also, I should mention that while you can use a memory operand as the source for arithmetic instructions like shift, you probably shouldn't because it is slower than using a register. So, since you've got to clobber a register anyway, you could do:

mov  ecx, eax
mov  eax, 1
shl  eax, cl
mov  DWORD PTR [one], eax


答:
You have to assign the array as a global array because of the scoping inside the array, so replace the first line inside the function with one below:
    $array1 = global $array;</p>

Title: HOW TO Return value array on function php mysql


问:
How to set value in array form with Angular
I want to set value in array like this:

this.form.controls[name].setValue('name')
```
<p>but I am working with array forms, and this is not working, even if I pass an array index explicitly</p>
<p>for example, this is my form array and I want to do is to set value in a function</p>
<pre class="lang-js prettyprint-override"><code>user: FormGroup;
users: FormGroup;

constructor(private fb: FormBuilder) {}
ngOnInit() {
  this.user = this.buildGroup();
  this.users = this.fb.group({
    data: this.fb.array([this.user])
  });
}
get fData() {
  return this.users.get('data') as FormArray;
}
buildGroup() {
  return this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    account: this.fb.group({
      email: ['', Validators.required],
      confirm: ['', Validators.required]
    })
  });
}
setValue(index) {
  // This doesn't work
  this.fData[index].controls[name].setValue('name')
}
onSubmit() {
  this.fData.push(this.buildGroup());
  const {valid, value} = this.fData;
  console.log(valid, value);
}
</code>```

答:
For arrays, you need to use setControl. Something like this:

```<code>    this.productForm = this.fb.group({
        productName: ['', [Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(50)]],
        productCode: ['', Validators.required],
        starRating: ['', NumberValidators.range(1, 5)],
        tags: this.fb.array([]),
        description: ''
    });

    ...

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
</code>```

Body:
I want to set value in array like this:

this.form.controls[name].setValue('name')

but I am working with array forms, and this is not working, even if I pass an array index explicitly

for example, this is my form array and I want to do is to set value in a function

user: FormGroup;
users: FormGroup;

constructor(private fb: FormBuilder) {}
ngOnInit() {
  this.user = this.buildGroup();
  this.users = this.fb.group({
    data: this.fb.array([this.user])
  });
}
get fData() {
  return this.users.get('data') as FormArray;
}
buildGroup() {
  return this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    account: this.fb.group({
      email: ['', Validators.required],
      confirm: ['', Validators.required]
    })
  });
}
setValue(index) {
  // This doesn't work
  this.fData[index].controls[name].setValue('name')
}
onSubmit() {
  this.fData.push(this.buildGroup());
  const {valid, value} = this.fData;
  console.log(valid, value);
}

Body:
For arrays, you need to use setControl. Something like this:

    this.productForm = this.fb.group({
        productName: ['', [Validators.required,
                           Validators.minLength(3),
                           Validators.maxLength(50)]],
        productCode: ['', Validators.required],
        starRating: ['', NumberValidators.range(1, 5)],
        tags: this.fb.array([]),
        description: ''
    });

    ...

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));