问:
Wordpress Custom Post Type Archives
I have added the following to my functions.php file

```<code>register_post_type( 'news',
 array(
   'labels' => array(
     'name' => __( 'News' ),
     'singular_name' => __( 'News' ),
 'add_new' => __( 'Add New Article' ),
 'add_new_item' => __( 'Add Article' ),
 'edit_item' => __( 'Edit Article' ),
 'new_item' => __( 'New Article' ),
 'view_item' => __( 'View Article' ),
 'search_items' => __( 'Search Articles' ),
 'not_found' => __( 'No Articles Found' ),
 'not_found_in_trash' => __( 'No Articles Found In Trash' ),
 'rewrite' => array(
    'slug' => 'news',
    'with_front' => false
    ),
 'has_archive' => true,
   ),
   'public' => true,
 )
</code>```

);

But when i type in news after my site mysite/news/ I get a page not found when it should I gather be listing my archives for news with the has_archives option.

What am I doing wrong!!!

By the way I have an archives.php file

答: Solved its not actually been released yet, the feature. I had to download the beta version however this version of wordpress is due soon.</p>

Title: Wordpress Custom Post Type Archives

Body:
I have added the following to my functions.php file

register_post_type( 'news',
 array(
   'labels' => array(
     'name' => __( 'News' ),
     'singular_name' => __( 'News' ),
 'add_new' => __( 'Add New Article' ),
 'add_new_item' => __( 'Add Article' ),
 'edit_item' => __( 'Edit Article' ),
 'new_item' => __( 'New Article' ),
 'view_item' => __( 'View Article' ),
 'search_items' => __( 'Search Articles' ),
 'not_found' => __( 'No Articles Found' ),
 'not_found_in_trash' => __( 'No Articles Found In Trash' ),
 'rewrite' => array(
    'slug' => 'news',
    'with_front' => false
    ),
 'has_archive' => true,
   ),
   'public' => true,
 )

);

But when i type in news after my site mysite/news/ I get a page not found when it should I gather be listing my archives for news with the has_archives option.

What am I doing wrong!!!

By the way I have an archives.php file


来源: stackexchange

问:
Read Response body in retrofit2
I am accessing webservice API using retrofit2. The response from API is in JSON Format.

JSONResponseImage

In retrofit my client is making successful connection with API but I want to access "statusMessage": "Email Address already exists" which is sent by webservice. I have tried couple of things but no success.

```<code>public void onResponse(Call<User> call, Response<User> response) {
   if (response.isSuccessful()) {
      Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
   } else {
       switch(response.code()) {
          case 409:
             Log.e("TAG", "1: " +response.raw());
             Toast.makeText(MainActivity.this, "email already Registered",
                       Toast.LENGTH_SHORT).show();
             break;
       }
    }
}
</code>```

seeImageLog

答:
Add the following to your User class

```<code>private Integer statusCode;
private String statusMessage;

public Integer getStatusCode() {
return statusCode;
}

public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}

public String getStatusMessage() {
return statusMessage;
}

public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
</code>```

Now you can access getStatusMessage() like response.body().getStatusMessage();
NOTE : setters are not necessary, adding getters will do the job

ContentLicense: CC BY-SA 3.0

Title: Read Response body in retrofit2

Body:
I am accessing webservice API using retrofit2. The response from API is in JSON Format.

JSONResponseImage

In retrofit my client is making successful connection with API but I want to access "statusMessage": "Email Address already exists" which is sent by webservice. I have tried couple of things but no success.

public void onResponse(Call<User> call, Response<User> response) {
   if (response.isSuccessful()) {
      Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
   } else {
       switch(response.code()) {
          case 409:
             Log.e("TAG", "1: " +response.raw());
             Toast.makeText(MainActivity.this, "email already Registered",
                       Toast.LENGTH_SHORT).show();
             break;
       }
    }
}

seeImageLog

Body:
Add the following to your User class

private Integer statusCode;
private String statusMessage;

public Integer getStatusCode() {
return statusCode;
}

public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}

public String getStatusMessage() {
return statusMessage;
}

public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}

Now you can access getStatusMessage() like response.body().getStatusMessage();
NOTE : setters are not necessary, adding getters will do the job


问:
AND OR syntax inside strtotime/array
i develop a program that you cannot see the data if it is older or younger than 1 days, so you can only see the TODAY data, TOMORROW data, and YESTERDAY data.

i tried using or/and syntax inside my array and strtotime but it's not working.

I tried this:

```<code>   $date = date('Y-m-d');
    $date1 = date('Y-m-d',strtotime("-1 days"));
    $date2 = date('Y-m-d',strtotime("+1 days"));

    $query = $this->db->get_where('info',array(dates => $date2 or $date or $date1)

);
</code>```

I also tried this:

```<code>$date = date('Y-m-d');
$date1 = date('Y-m-d',strtotime("-1 days"));
$date2 = date('Y-m-d',strtotime("+1 days"));
$datefix = $date or $date1 or $date2;

$query = $this->db->get_where('info',array(dates => $datefix));
</code>```

both doesnot work. I searching for how to use OR and AND syntax inside ARRAY or STRTOTIME and i couldnot find it. Can anyone help me with this? Little help would be appreciated!

答:
Try This

```<code>$this->db->where('dates <=', $date1);
$this->db->where('dates >=', $date2);
$query = $this->db->get('info');
</code>```

OR

```<code>$this->db->where('dates', $date);
$this->db->where('dates', $date1);
$this->db->where('dates', $date2);
$query = $this->db->get('info');
</code>```

Title: AND OR syntax inside strtotime/array

Body:
i develop a program that you cannot see the data if it is older or younger than 1 days, so you can only see the TODAY data, TOMORROW data, and YESTERDAY data.

i tried using or/and syntax inside my array and strtotime but it's not working.

I tried this:

   $date = date('Y-m-d');
    $date1 = date('Y-m-d',strtotime("-1 days"));
    $date2 = date('Y-m-d',strtotime("+1 days"));

    $query = $this->db->get_where('info',array(dates => $date2 or $date or $date1)

);

I also tried this:

$date = date('Y-m-d');
$date1 = date('Y-m-d',strtotime("-1 days"));
$date2 = date('Y-m-d',strtotime("+1 days"));
$datefix = $date or $date1 or $date2;

$query = $this->db->get_where('info',array(dates => $datefix));

both doesnot work. I searching for how to use OR and AND syntax inside ARRAY or STRTOTIME and i couldnot find it. Can anyone help me with this? Little help would be appreciated!

Body:
Try This

$this->db->where('dates <=', $date1);
$this->db->where('dates >=', $date2);
$query = $this->db->get('info');

OR

$this->db->where('dates', $date);
$this->db->where('dates', $date1);
$this->db->where('dates', $date2);
$query = $this->db->get('info');


问:
PHP Sytax in html has unexpected output
I'm new to PHP, I wrote these code from a online courses. But when I open the PHP file in web browser, it was not what I expected.

```<code><!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php>
        echo 'My name is Chao';
        echo Hello World!<br>
    <?>
    <?php> echo 5+6+7 <?>
    </body>
</html>
</code>```

The result is:
echo 'My name is Chao'; echo Hello World!
echo 5+6+7;

I was expecting: echo My name is Chao echo Hello World!
18

Why this is happening? I'm using Microsoft Edge currently.

I'm looking forward for you reply.Thank you.

答:
You are making php syntax error here.

php starts with <?php

ends with ?>

Note: Hello world should be within a quote, echo must end with a semicolon.

Title: PHP Sytax in html has unexpected output

Body:
I'm new to PHP, I wrote these code from a online courses. But when I open the PHP file in web browser, it was not what I expected.

<!DOCTYPE>

        <title>untitled</title>

My Bio

    <?php>
        echo 'My name is Chao';
        echo Hello World!

    <?>
    <?php> echo 5+6+7 <?>

The result is:
echo 'My name is Chao'; echo Hello World!
echo 5+6+7;

I was expecting: echo My name is Chao echo Hello World!
18

Why this is happening? I'm using Microsoft Edge currently.

I'm looking forward for you reply.Thank you.


问:
Web-based Game Development: Flex Builder or Flash CS3?
I'm researching game development in Flash and Flex.  I've downloaded the Flex Builder trial and have worked with older versions of Flash.  I see that generally, Flex Builder is a developer's tool, and Flash is a designer's tool.  It's not clear to me whether one is better suited to game development than the other, or if it's necessary to have both to effectively design games.  To my mind, games are equal parts design/art and programming.  Which tool is more commonly, or more intensively, used for game development?</p>

答:
Flash CS3/4 is really helpful if you're creating frame-by-frame animation and for layout. If you're happy to do this stuff in code, then you won't need it. It's not the best tool for creating artwork anyway, you can use Paint.Net and Inkscape for that which are both free (or PhotoShop and Illustrator if you have the money).

You don't want to use the Flex framework, so if you're using Flexbuilder you'll want to do an ActionScript project not an MXML project, as someone else noted. Save yourself some money and just use Flashdevelop with the MXMLC compiler.

Here's a blog post I wrote about free software for making Flash games:

http://blog.iainlobb.com/2008/11/cool-free-and-open-source-software-for.html

OwnerDisplayName: Dave

OwnerDisplayName: Iain

ContentLicense: CC BY-SA 2.5


问:
Execute code just before onComplete() in RxJava 2?
I need to close socket connection in my observable before RxLifecycle dispose it. How can I do that?

答:
You could try using doFinally

Calls the specified action after this Observable signals onError or onCompleted or gets disposed by the downstream.

http://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html#doFinally-io.reactivex.functions.Action-


问:
Background color is stuck after changing it to transparent
So I am using a plugin (https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview) or (https://ionicframework.com/docs/native/camera-preview/) and for it to be shown, I have to set the background color to transparent like so in camera.scss:

    page-camera {

}
html, body, ion-app, ion-content, ion-page, .nav-decor{
   background-color: transparent !important;
}```

But an issue I have is that when I close the cameraPreview and pop the view, my background is stuck as transparent.

How can I get my background to only be transparent when I am using the camera plugin?

Here are some screenshots:

Background is white in this image ^^ correct

Background is transparent in this image ^^ correct

Background is transparent now ^^ incorrect

I have no other css being used in the app, so how can I change the background-color only on the one camera screen?

Thanks

答:
Why don't you use your transparent part inside the page-camera?

```<code>page-camera {
  html, body, ion-app, ion-content, ion-page, .nav-decor{
      background-color: transparent !important;
  }
}
</code>```

So it only effects to that page only. Or you have to set the background-color:initial in your home.component(If there is any).

Body:
So I am using a plugin (https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview) or (https://ionicframework.com/docs/native/camera-preview/) and for it to be shown, I have to set the background color to transparent like so in camera.scss:

    page-camera {

}
html, body, ion-app, ion-content, ion-page, .nav-decor{
   background-color: transparent !important;
}

But an issue I have is that when I close the cameraPreview and pop the view, my background is stuck as transparent.

How can I get my background to only be transparent when I am using the camera plugin?

Here are some screenshots:

Background is white in this image ^^ correct

Background is transparent in this image ^^ correct

Background is transparent now ^^ incorrect

I have no other css being used in the app, so how can I change the background-color only on the one camera screen?

Thanks

Body:
Why don't you use your transparent part inside the page-camera?

page-camera {
  html, body, ion-app, ion-content, ion-page, .nav-decor{
      background-color: transparent !important;
  }
}

So it only effects to that page only. Or you have to set the background-color:initial in your home.component(If there is any).


问:
Howto inject code using libclang (in C++)
I would like to know how to insert an argument to a function call using libclang? I have to following code that just prints the arguments:

```<code>class CASTVisitor : public RecursiveASTVisitor<CASTVisitor>
{
public:
    CASTVisitor(Rewriter &R) : rewriter(R)
    {
    }

    virtual bool VisitCallExpr(CallExpr *call)
    {
        for(int i = 0, j = call->getNumArgs(); i < j; ++ i)
        {
            errs() << "argType: " << call->getArg(i)->getType().getAsString() << "\n";
        }

        errs() << "** Added parameter to function call\n";

        return true;
    }
...
};
</code>```

Edit:

And although I can read and set the arguments, I don't see any way to insert one at the beginning of the parmVarDcl() matcher.

The same goes with adding member variables to base classes and compound statements. It would seem you can change existing text but you cannot insert new object easily. Am I right?

答:
The only solution I found so far is by getting a file pointer from a cursor and injecting code manually:

https://github.com/burnflare/libclang-experiments

```<code>CXFile file;
unsigned line;
unsigned offset;

clang_getSpellingLocation(clang_getCursorLocation(cursors[i+1]),
                          &file,
                          &line,
                          NULL,
                          &offset);

const char* filename = clang_getCString(clang_getFileName(file));
printf("\n\nMethod found in %s in line %d, offset %d\n", clang_getCString(clang_getFileName(file)), line, offset);

// File reader
FILE *fr = fopen(filename, "r");
fseek(fr, 0, SEEK_END);
long fsize = ftell(fr);
fseek(fr, 0, SEEK_SET);

// Reading file to string
char *input = malloc(fsize);
fread(input, fsize, 1, fr);
fclose(fr);

// Making an output that is input(start till offset) + code injection + input(offset till end)
FILE *fw = fopen(filename, "w");
char *output = malloc(fsize);
strncpy(output, input, offset);
strcat(output, injectCode);
strcat(output, input+offset);

// Rewrite the whole file with output string
fwrite(output, fsize, sizeof(output), fw);
fclose(fw);
</code>```

If anybody has a better idea then please let me know!

Body:
I would like to know how to insert an argument to a function call using libclang? I have to following code that just prints the arguments:

class CASTVisitor : public RecursiveASTVisitor<CASTVisitor>
{
public:
    CASTVisitor(Rewriter &R) : rewriter(R)
    {
    }

    virtual bool VisitCallExpr(CallExpr *call)
    {
        for(int i = 0, j = call->getNumArgs(); i < j; ++ i)
        {
            errs() << "argType: " << call->getArg(i)->getType().getAsString() << "\n";
        }

        errs() << "** Added parameter to function call\n";

        return true;
    }
...
};

Edit:

And although I can read and set the arguments, I don't see any way to insert one at the beginning of the parmVarDcl() matcher.

The same goes with adding member variables to base classes and compound statements. It would seem you can change existing text but you cannot insert new object easily. Am I right?

Body:
The only solution I found so far is by getting a file pointer from a cursor and injecting code manually:

https://github.com/burnflare/libclang-experiments

CXFile file;
unsigned line;
unsigned offset;

clang_getSpellingLocation(clang_getCursorLocation(cursors[i+1]),
                          &file,
                          &line,
                          NULL,
                          &offset);

const char* filename = clang_getCString(clang_getFileName(file));
printf("\n\nMethod found in %s in line %d, offset %d\n", clang_getCString(clang_getFileName(file)), line, offset);

// File reader
FILE *fr = fopen(filename, "r");
fseek(fr, 0, SEEK_END);
long fsize = ftell(fr);
fseek(fr, 0, SEEK_SET);

// Reading file to string
char *input = malloc(fsize);
fread(input, fsize, 1, fr);
fclose(fr);

// Making an output that is input(start till offset) + code injection + input(offset till end)
FILE *fw = fopen(filename, "w");
char *output = malloc(fsize);
strncpy(output, input, offset);
strcat(output, injectCode);
strcat(output, input+offset);

// Rewrite the whole file with output string
fwrite(output, fsize, sizeof(output), fw);
fclose(fw);

If anybody has a better idea then please let me know!


问:
jQueryValidate - check if a control is required without triggering validation
I'm trying to show asterisks for controls which are required. The code was working fine with required class but now I have two fields, company and name. Only one of them is required based on other elements value. Is it possible to check if an input is required without validating the control or the form?

Example html structure:

```<code><div class="form-group">
    <label class="control-label" for="CompanyName">Company Name</label>
    <div>
        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">
    </div>
</div>
</code>```

JS:

```<code>validationOptions: {
    ignore: ":disabled,:hidden",

    rules: {
        CompanyName: {
            required: function () {
                return ($("#ContactName").val().length === 0);
            }
        },
        ContactName: {
            required: function () {
                return ($("#CompanyName").val().length === 0);
            }
        }
    },

    onkeyup: function (element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).valid()) {
            $parent.removeClass("invalid");
        } else {
            $parent.addClass("invalid");
        }
    },

    onfocusout: function () {
        if ($("form").valid()) {
            $("form.error").removeClass("error");
            $("form .invalid").removeClass("invalid");
        }
    },

    errorPlacement: function (error, element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).hasClass("error")) {
            $parent.addClass("invalid");
        } else {
            $parent.removeClass("invalid");
        }
    },

    invalidHandler: function (event, validator) {
        $.each(validator.successList, function (index, item) {
            $(item).parents(".form-group").removeClass("invalid");
        });
        const errors = validator.numberOfInvalids();
        if (errors) {
            $.each(validator.errorList, function (index, item) {
                $(item.element).parents(".form-group").addClass("invalid");
            });
        }
    }
}
</code>```

Of course I can have my code inside required callbacks above but that wouldn't be a generic solution.

I want to be able to call following function many times to update (bootstrap) asterisks on the form based on required state of the fields.

```<code>appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control.required");

    $controls.each(function () {
        const $label = $(this).parents(".form-group").find(">.control-label");

        $label.html($label.html() + " <span class='text-danger'>*</span>");
    });
},
</code>```

Trying to accomplish something like:

```<code>appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        if ($(this).isRequired()) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " <span class='text-danger'>*</span>");
        }
    });
},
</code>```

答:
Below code sample should do the trick for you.

```<code>appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        // if ($(this).isRequired()) {
        if ($(this).rules().required) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " <span class='text-danger'>*</span>");
        }
    });
},
</code>```

If you don't have .form-control class on each element, then you can get the elements array from plugin's .elements() method and loop them with checking their .rules() method.

```<code>const elements = $("#signupform").validate().elements();
for (let i=0; i<elements.length; i++) {
    const $el = $(elements[i]);
    if ($el.rules().required) {
        $el.parents(".form-group").find(">.control-label").append(" <span class='text-danger'>*</span>");
    }
}
</code>```

Edit:

JSBin Demo added.

Body:
I'm trying to show asterisks for controls which are required. The code was working fine with required class but now I have two fields, company and name. Only one of them is required based on other elements value. Is it possible to check if an input is required without validating the control or the form?

Example html structure:

    Company Name

        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">

JS:

validationOptions: {
    ignore: ":disabled,:hidden",

    rules: {
        CompanyName: {
            required: function () {
                return ($("#ContactName").val().length === 0);
            }
        },
        ContactName: {
            required: function () {
                return ($("#CompanyName").val().length === 0);
            }
        }
    },

    onkeyup: function (element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).valid()) {
            $parent.removeClass("invalid");
        } else {
            $parent.addClass("invalid");
        }
    },

    onfocusout: function () {
        if ($("form").valid()) {
            $("form.error").removeClass("error");
            $("form .invalid").removeClass("invalid");
        }
    },

    errorPlacement: function (error, element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).hasClass("error")) {
            $parent.addClass("invalid");
        } else {
            $parent.removeClass("invalid");
        }
    },

    invalidHandler: function (event, validator) {
        $.each(validator.successList, function (index, item) {
            $(item).parents(".form-group").removeClass("invalid");
        });
        const errors = validator.numberOfInvalids();
        if (errors) {
            $.each(validator.errorList, function (index, item) {
                $(item.element).parents(".form-group").addClass("invalid");
            });
        }
    }
}

Of course I can have my code inside required callbacks above but that wouldn't be a generic solution.

I want to be able to call following function many times to update (bootstrap) asterisks on the form based on required state of the fields.

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control.required");

    $controls.each(function () {
        const $label = $(this).parents(".form-group").find(">.control-label");

        $label.html($label.html() + " *");
    });
},

Trying to accomplish something like:

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        if ($(this).isRequired()) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " *");
        }
    });
},

Body:
Below code sample should do the trick for you.

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        // if ($(this).isRequired()) {
        if ($(this).rules().required) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " <span class='text-danger'>*</span>");
        }
    });
},

If you don't have .form-control class on each element, then you can get the elements array from plugin's .elements() method and loop them with checking their .rules() method.

const elements = $("#signupform").validate().elements();
for (let i=0; i<elements.length; i++) {
    const $el = $(elements[i]);
    if ($el.rules().required) {
        $el.parents(".form-group").find(">.control-label").append(" <span class='text-danger'>*</span>");
    }
}

Edit:

JSBin Demo added.


问:
Form value creates a url with target blank and rel nofollow noopener noreferrer
I found this solution here Form value creates a url to make text input form a URL on submit.

Is it possible to add rel="nofollow noopener noreferrer" and target="_blank" to the the URL?

thanks

```<code><script>
function process()
{
var url="http://name.com/" + document.getElementById("url").value;
location.href=url;
return false;
}
</script>
<form onSubmit="return process();">
URL: <input type="text" name="url" id="url"> <input type="submit" value="go">
</form>
</code>```

答:
There are two approaches to get the submission response page/action page to open in a new window:

change your location.href call to a window.open call; refer to https://developer.mozilla.org/en-US/docs/Web/API/Window/open for documentation on using window.open

OR...

instead of loading the url in your javascript, set the form action attribute in the  tag and also set a target of _blank in the same  tag. Use your javascript function to return true to submit the form to the action url or return false to prevent submission.

Then, too set a nofollow behavior for the new page that the form action directs too, you can either disallow its indexing in robots.txt or add a metatag, as noted in the answer here:  https://webmasters.stackexchange.com/questions/13837/nofollow-in-a-form-action

Body:
I found this solution here Form value creates a url to make text input form a URL on submit.

Is it possible to add rel="nofollow noopener noreferrer" and target="_blank" to the the URL?

thanks

<form onSubmit="return process();">
URL: <input type="text" name="url" id="url"> <input type="submit" value="go">
</form>


问:
How can I trigger an segue action on button in a UITableViewCell created from a nib?
Right now I am creating a table view cell from a nib file. I have a button in this nib file. I want this button to trigger a segue to a specific view controller on the storyboard.

Seems pretty straight forward, except this nib file is being used in many different tables on different view controllers throughout my app, and I want the button to link to the same destination view controller in every single instance. Furthermore, the destination view controller also contains a table with this nib file as a cell, meaning it will also need to link to itself.

For these reasons, I would love if there was a solution that contained this code to the UITableViewCell subclass for said nib file. (however I doubt this is possible.)

A good example of the functionality I want is Instagram. Think about how several different tabs on Instagram have tables with cells that look like this:

and no matter what tab you are in, clicking the username on the top left of this cell transitions you to the user view controller, even if you are already in the user view controller:

答:
here you can do as :

1) no need of tags to provide
2) get button location and perform task according to that
3) ProductStarImage //is my button name

Step 1:

```<code> //IBOutlets
    @IBOutlet weak var CategoriesTableView: UITableView!

 //TableCell identifier
    let cellReuseIdentifier = "Cell"
    var cell = CustomTableCellClass()
</code>```

Step 2: in cellForRowAt of TableView

```<code>  //setting cell data
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.CategoriesTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomTableCellClass

    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowRadius = 2

    //add a action to button
    cell.ProductStarImage.addTarget(self, action: #selector(CategoriesVC.FavouriteButtonHandler(sender:)), for: .touchUpInside)

    return cell
}
</code>```

Step 2 : Button handler

```<code>//Favourite button Action Handler
    @objc func FavouriteButtonHandler (sender: UIButton) {

        //assign current cell to global cell declared //dequeue
        cell = self.CategoriesTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomTableCellClass
        //get CGPoint of button selected
        let buttonPosition : CGPoint = sender.convert(CGPoint.zero, to: self.CategoriesTableView)
        //get indexPath from CGPoint of Button
        let indexPath : IndexPath = self.CategoriesTableView.indexPathForRow(at: buttonPosition)!
        //Now assign selected cell indexPath to Cell declared globally
        cell = self.CategoriesTableView.cellForRow(at: indexPath)! as! CustomTableCellClass

    //here perform action required
    like - cell.ProductStarImage //any action

    self.CategoriesTableView.reloadRows(at: [indexPath], with: .none)
}
</code>```

Body:
here you can do as :

1) no need of tags to provide
2) get button location and perform task according to that
3) ProductStarImage //is my button name

Step 1:

 //IBOutlets
    @IBOutlet weak var CategoriesTableView: UITableView!

 //TableCell identifier
    let cellReuseIdentifier = "Cell"
    var cell = CustomTableCellClass()

Step 2: in cellForRowAt of TableView

  //setting cell data
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.CategoriesTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomTableCellClass

    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowRadius = 2

    //add a action to button
    cell.ProductStarImage.addTarget(self, action: #selector(CategoriesVC.FavouriteButtonHandler(sender:)), for: .touchUpInside)

    return cell
}

Step 2 : Button handler

//Favourite button Action Handler
    @objc func FavouriteButtonHandler (sender: UIButton) {

        //assign current cell to global cell declared //dequeue
        cell = self.CategoriesTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomTableCellClass
        //get CGPoint of button selected
        let buttonPosition : CGPoint = sender.convert(CGPoint.zero, to: self.CategoriesTableView)
        //get indexPath from CGPoint of Button
        let indexPath : IndexPath = self.CategoriesTableView.indexPathForRow(at: buttonPosition)!
        //Now assign selected cell indexPath to Cell declared globally
        cell = self.CategoriesTableView.cellForRow(at: indexPath)! as! CustomTableCellClass

    //here perform action required
    like - cell.ProductStarImage //any action

    self.CategoriesTableView.reloadRows(at: [indexPath], with: .none)
}


问:
Chrome gets hung randomly - Python Selenium Windows
We are running a Python Selenium script in Windows Chrome, and are now faced with an issue which we cannot resolve.

The script (medium sized) runs to completion only say 1 in 3 times.
Other times, it freezes in the middle, maybe after 10 steps, or 15 steps- after that there is no response whatsoever.

The only clue we got was that there is an error printed out (usually after 10 minutes of waiting) access denied.

After this hanging the only option is to

Kill the browser or

Kill the process

We tried --disable-extensions, and having an user-dir etc, but to no avail.

There is an anti-virus (Symantec) running in the machine, which cannot be disabled (enterprise level security settings).

Has anyone faced this issue?
Is there any solution? Please let me know.

答: Found that the issue was due to AV. Stopped the anti virus for some time and it is running properly now.</p>


问:
Unity/C# Stopwatch If Time Has Elapsed statement (timer > 0)
Searched the interwebs for a while and got something that pointed me in the right direction so I could get the answer. Thought I'd share it for somebody in the future:

How to write an if statement in C# for a Stopwatch to check if time as elapsed

答:
```<code>public Stopwatch timer = new Stopwatch();

if(timer.Elapsed.TotalSeconds == 0) {
    // if timer hasn't started
}
</code>```

or

```<code>if(timer.Elapsed.TotalSeconds > 0) {
    // if timer has started
}
</code>```

Body:
public Stopwatch timer = new Stopwatch();

if(timer.Elapsed.TotalSeconds == 0) {
    // if timer hasn't started
}

or

if(timer.Elapsed.TotalSeconds > 0) {
    // if timer has started
}


问:
My dynamic design doesn't appear. Why?
My design doesnt appear in my screen. The method addHeaderAttendance() contains the header while the addSchedule(ArrayList mysched) contains the populating of table of my data.

ScheduleProf.java:

```<code>public class ScheduleProf extends Activity{
    String data = "";
    TableLayout tl;
    TableRow tr;
    TextView label;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedprof);
        tl = (TableLayout) findViewById(R.id.maintable);
        final BackgroundWorker bw = new BackgroundWorker(ScheduleProf.this,"ScheduleProf");
        Bundle get=getIntent().getExtras();

        final int profid=get.getInt("id"); //kunin ni schedpof from fragment
        new Thread(new Runnable() {
            public void run() {
                data = bw.getProfSched(profid);
                System.out.println(data);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        addHeaderAttendance();
                        ArrayList<Properties> mysched = parseSchedule(data);
                        addSchedule(mysched);
                    }

                });
            }
        }).start();
    }
public ArrayList<Properties> parseSchedule(String result) {

        ArrayList<Properties> mysched = new ArrayList<Properties>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Properties user = new Properties();
                user.setRoom(json_data.getString("rooms_id"));
                user.setCourse(json_data.getString("course_id"));
                user.setSection(json_data.getString("sections_id"));

                DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String formatstart_time=json_data.getString("start_time");
                String formatend_time=json_data.getString("end_time");

                try {
                    Time startValue = new Time(formatter.parse(formatstart_time).getTime());
                     Time endValue = new Time(formatter.parse(formatend_time).getTime());
                     user.setStartTime(startValue);//error
                        user.setStartTime(endValue);//error
                        user.setDay("day");
                        mysched.add(user);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return mysched;
    }
@SuppressWarnings({ "rawtypes" })
public void addSchedule(ArrayList<Properties> mysched) {

    addHeaderAttendance();

    for (Iterator i = mysched.iterator(); i.hasNext();) {

        Properties p = (Properties) i.next();

        /** Create a TableRow dynamically **/
        tr = new TableRow(this);

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText(p.getStartTime() +"-"+p.getEndTime()+"<html><br></html>"+p.getDay());

        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(10, 10, 10, 10);
        label.setBackgroundColor(Color.YELLOW);
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(label,params);
        tr.addView((View)Ll); // Adding textView to tablerow.

        TextView stats = new TextView(this);
        stats.setText(p.getCourseId()+" "+p.getSection()+" "+p.getRoom());
        stats.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        stats.setPadding(10, 10, 10, 10);
        stats.setBackgroundColor(Color.GREEN);
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(stats,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

         // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }
}

void addHeaderAttendance(){

    /** Create a TableRow dynamically **/
    tr = new TableRow(this);
    /** Creating a TextView to add to the row **/
    label = new TextView(this);
    label.setText("Time and Day");
    label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    label.setPadding(10, 10, 10, 10);
    label.setBackgroundColor(Color.parseColor("#FFD700"));
    LinearLayout Ll = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(label,params);
    tr.addView((View)Ll); // Adding textView to tablerow.

    /** Creating Qty Button **/
    TextView place = new TextView(this);
    place.setText("Course/Section/Room");
    place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    place.setPadding(10, 10, 10, 10);
    place.setBackgroundColor(Color.parseColor("#008000"));
    Ll = new LinearLayout(this);
    params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(place,params);
    tr.addView((View)Ll); // Adding textview to tablerow.

     // Add the TableRow to the TableLayout
    tl.addView(tr, new TableLayout.LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
}
}
</code>```

This is my activity_schedprof.xml containing the maintable for dynamic population of data from my java class:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
        <TableLayout
            android:id="@+id/maintable"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:stretchColumns="1,1,1" >
        </TableLayout>
</RelativeLayout>
</code>```

答: try to add Tablelayout height like match_parent or some fixed size...</p>

Title: My dynamic design doesn't appear. Why?

Body:
My design doesnt appear in my screen. The method addHeaderAttendance() contains the header while the addSchedule(ArrayList mysched) contains the populating of table of my data.

ScheduleProf.java:

public class ScheduleProf extends Activity{
    String data = "";
    TableLayout tl;
    TableRow tr;
    TextView label;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedprof);
        tl = (TableLayout) findViewById(R.id.maintable);
        final BackgroundWorker bw = new BackgroundWorker(ScheduleProf.this,"ScheduleProf");
        Bundle get=getIntent().getExtras();

        final int profid=get.getInt("id"); //kunin ni schedpof from fragment
        new Thread(new Runnable() {
            public void run() {
                data = bw.getProfSched(profid);
                System.out.println(data);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        addHeaderAttendance();
                        ArrayList<Properties> mysched = parseSchedule(data);
                        addSchedule(mysched);
                    }

                });
            }
        }).start();
    }
public ArrayList<Properties> parseSchedule(String result) {

        ArrayList<Properties> mysched = new ArrayList<Properties>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Properties user = new Properties();
                user.setRoom(json_data.getString("rooms_id"));
                user.setCourse(json_data.getString("course_id"));
                user.setSection(json_data.getString("sections_id"));

                DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String formatstart_time=json_data.getString("start_time");
                String formatend_time=json_data.getString("end_time");

                try {
                    Time startValue = new Time(formatter.parse(formatstart_time).getTime());
                     Time endValue = new Time(formatter.parse(formatend_time).getTime());
                     user.setStartTime(startValue);//error
                        user.setStartTime(endValue);//error
                        user.setDay("day");
                        mysched.add(user);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return mysched;
    }
@SuppressWarnings({ "rawtypes" })
public void addSchedule(ArrayList<Properties> mysched) {

    addHeaderAttendance();

    for (Iterator i = mysched.iterator(); i.hasNext();) {

        Properties p = (Properties) i.next();

        /** Create a TableRow dynamically **/
        tr = new TableRow(this);

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText(p.getStartTime() +"-"+p.getEndTime()+"
"+p.getDay());

        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(10, 10, 10, 10);
        label.setBackgroundColor(Color.YELLOW);
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(label,params);
        tr.addView((View)Ll); // Adding textView to tablerow.

        TextView stats = new TextView(this);
        stats.setText(p.getCourseId()+" "+p.getSection()+" "+p.getRoom());
        stats.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        stats.setPadding(10, 10, 10, 10);
        stats.setBackgroundColor(Color.GREEN);
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 2, 2, 2);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(stats,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

         // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }
}

void addHeaderAttendance(){

    /** Create a TableRow dynamically **/
    tr = new TableRow(this);
    /** Creating a TextView to add to the row **/
    label = new TextView(this);
    label.setText("Time and Day");
    label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    label.setPadding(10, 10, 10, 10);
    label.setBackgroundColor(Color.parseColor("#FFD700"));
    LinearLayout Ll = new LinearLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(label,params);
    tr.addView((View)Ll); // Adding textView to tablerow.

    /** Creating Qty Button **/
    TextView place = new TextView(this);
    place.setText("Course/Section/Room");
    place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    place.setPadding(10, 10, 10, 10);
    place.setBackgroundColor(Color.parseColor("#008000"));
    Ll = new LinearLayout(this);
    params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.setMargins(5, 5, 5, 5);
    //Ll.setPadding(10, 5, 5, 5);
    Ll.addView(place,params);
    tr.addView((View)Ll); // Adding textview to tablerow.

     // Add the TableRow to the TableLayout
    tl.addView(tr, new TableLayout.LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
}
}

This is my activity_schedprof.xml containing the maintable for dynamic population of data from my java class:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
        <TableLayout
            android:id="@+id/maintable"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:stretchColumns="1,1,1" >
        </TableLayout>
</RelativeLayout>


问:
jQuery slider not working on d3 multiples, but not returning error either
I'm trying to add a jQuery range slider to the main chart on a page that contains small multiples of area charts, but the slider does not slide, and the charts do not transition. I'm using the code from this block as a guide for how to implement such a slider.

Here's a link to my (semi-working) Plunker: https://plnkr.co/edit/zwCBQ1wR3iBlGYCMYqFe?p=preview

I thought this should be simple, since I've already set up the means for dynamically configuring the x-axis, depending on the data, with the following code:

```<code>var startDate = d3.time.month.offset(new Date(), -108);
var endDate = new Date ();
var dates = createDatesArr(startDate, endDate);
...
var area = d3.svg.area()
.x(function(d) {
return xScale(d.x);
...
xScale.domain([
    d3.min(dates, function(d) {
        return d;
    }),
    d3.max(dates, function(d) {
            return d;
        })
    ]);

    var totals = [];

    for (i = 0; i < dates.length; i++) {
        totals[i] = 0;
        for (j = 0; j < dataset.length; j++) {
            totals[i] += dataset[j].values[i].y;
        }
    }
</code>```

The code that seems to be problematic with the jQuery slider I've added is this:

```<code>  function zoom(begin, end) {
    xScale.domain([begin, end - 1]);
    yScale.domain([begin, end - 1]);

    var t = state.transition().duration(0);

    var size = end - begin;
    var step = size / 10;

    t.select('.path').attr("d", function(d) {
                return area(d.values);
            });
  }
...
  $(function() {
        $( "#slider-range" ).slider({
            range: true,
            min: 0,
            max: dataset.length-1,
            values: [ 0, dataset.length-1 ],
            slide: function( event, ui ) {
              var begin = d3.min([ui.values[0], dataset.length]);
              var end = d3.max([ui.values[1], 0]);
              console.log("begin:", begin, "end:", end);

              zoom(begin, end);
            }
        });
    });
</code>```

Here, again, is a link to a (semi-working) Plunker: https://plnkr.co/edit/zwCBQ1wR3iBlGYCMYqFe?p=preview

From reading similar questions about sliders, it seems the general recommendation is to use brush/zoom to implement focus + context, as in this block, but doing so is beyond my abilities at this point. (Though I'd love to see it demonstrated.)

What I'm trying to do is implement some means of graphically (e.g. by means of a slider or brush) adjusting the x-axis/date range of the main chart, and its small multiples, such that they are zoomed or redrawn when the slider is moved. As it stands, the slider doesn't slide, the charts do not zoom or redraw, and the browser returns no error messages. Can you demonstrate a solution?

答:
Here you go buddy! Plunker

Made a lot of changes to the code. Here is a diff-check of our codes:

Code Difference

Relevant changes:

```<code>function rerenderAreaChart(selectedState, dataset, svgHook, size, begin, end) {
  var totalTicksX = Math.round(size.w / 60),
    totalTicksY = Math.round(size.h / 40);

  xAxis.ticks(totalTicksX);
  yAxis.ticks(totalTicksY);

  yScale.range([padding.top, size.h - padding.bottom]);

  xScale.domain([begin, end]);

  var filtered_indices = [];
  dataset[0].values.forEach(function(k, i) {
    if (k.x >= begin && k.x <= end) {
      filtered_indices.push(i);
    }
  });
  var max = d3.max(filtered_indices, function(idx) {
    return d3.sum(dataset, function(d) {
      return d.values[idx].y;
    })
  });
  yScale.domain([max, 0]);

  d3.select(svgHook).select('svg.state.' + selectedState).select('.x.axis')
    .transition().duration(50).call(xAxis).selectAll(".tick text")
    .call(wrap, 0);

  d3.select(svgHook).select('svg.state.' + selectedState).select('.y.axis')
    .transition().duration(50).call(yAxis);

  dataset.forEach(function(d) {
    d.values.forEach(function(v, idx) {
      v.hidden = filtered_indices.indexOf(idx) === -1;
    })
  });
  stack(dataset);

  d3.select(svgHook).select('svg.state.' + selectedState).select('g.paths').selectAll("path")
    .attr("clip-path", "url(#clip)")
    .attr('d', function(d) {
      return area(d.values.filter(function(k) {
        return k.x >= begin && k.x <= end;
      }));
    });
}
</code>```

Take a look at the jQuery slider too. I've missed commenting the code which I'll do soon and update the link. Please go through the code and let me know if find any bugs or anything that isn't understandable.

And I'm sorry for the delay as I lost all the code once (didn't save it), had to rewrite it today.

One thing I would like you to make note of is it's better to use "style" instead of "attr" (attribute) for stylings such as "fill", "stroke" etc. I've changed those too.

Hope this helps. :)

Body:
I'm trying to add a jQuery range slider to the main chart on a page that contains small multiples of area charts, but the slider does not slide, and the charts do not transition. I'm using the code from this block as a guide for how to implement such a slider.

Here's a link to my (semi-working) Plunker: https://plnkr.co/edit/zwCBQ1wR3iBlGYCMYqFe?p=preview

I thought this should be simple, since I've already set up the means for dynamically configuring the x-axis, depending on the data, with the following code:

var startDate = d3.time.month.offset(new Date(), -108);
var endDate = new Date ();
var dates = createDatesArr(startDate, endDate);
...
var area = d3.svg.area()
.x(function(d) {
return xScale(d.x);
...
xScale.domain([
    d3.min(dates, function(d) {
        return d;
    }),
    d3.max(dates, function(d) {
            return d;
        })
    ]);

    var totals = [];

    for (i = 0; i < dates.length; i++) {
        totals[i] = 0;
        for (j = 0; j < dataset.length; j++) {
            totals[i] += dataset[j].values[i].y;
        }
    }

The code that seems to be problematic with the jQuery slider I've added is this:

  function zoom(begin, end) {
    xScale.domain([begin, end - 1]);
    yScale.domain([begin, end - 1]);

    var t = state.transition().duration(0);

    var size = end - begin;
    var step = size / 10;

    t.select('.path').attr("d", function(d) {
                return area(d.values);
            });
  }
...
  $(function() {
        $( "#slider-range" ).slider({
            range: true,
            min: 0,
            max: dataset.length-1,
            values: [ 0, dataset.length-1 ],
            slide: function( event, ui ) {
              var begin = d3.min([ui.values[0], dataset.length]);
              var end = d3.max([ui.values[1], 0]);
              console.log("begin:", begin, "end:", end);

              zoom(begin, end);
            }
        });
    });

Here, again, is a link to a (semi-working) Plunker: https://plnkr.co/edit/zwCBQ1wR3iBlGYCMYqFe?p=preview

From reading similar questions about sliders, it seems the general recommendation is to use brush/zoom to implement focus + context, as in this block, but doing so is beyond my abilities at this point. (Though I'd love to see it demonstrated.)

What I'm trying to do is implement some means of graphically (e.g. by means of a slider or brush) adjusting the x-axis/date range of the main chart, and its small multiples, such that they are zoomed or redrawn when the slider is moved. As it stands, the slider doesn't slide, the charts do not zoom or redraw, and the browser returns no error messages. Can you demonstrate a solution?

Body:
Here you go buddy! Plunker

Made a lot of changes to the code. Here is a diff-check of our codes:

Code Difference

Relevant changes:

function rerenderAreaChart(selectedState, dataset, svgHook, size, begin, end) {
  var totalTicksX = Math.round(size.w / 60),
    totalTicksY = Math.round(size.h / 40);

  xAxis.ticks(totalTicksX);
  yAxis.ticks(totalTicksY);

  yScale.range([padding.top, size.h - padding.bottom]);

  xScale.domain([begin, end]);

  var filtered_indices = [];
  dataset[0].values.forEach(function(k, i) {
    if (k.x >= begin && k.x <= end) {
      filtered_indices.push(i);
    }
  });
  var max = d3.max(filtered_indices, function(idx) {
    return d3.sum(dataset, function(d) {
      return d.values[idx].y;
    })
  });
  yScale.domain([max, 0]);

  d3.select(svgHook).select('svg.state.' + selectedState).select('.x.axis')
    .transition().duration(50).call(xAxis).selectAll(".tick text")
    .call(wrap, 0);

  d3.select(svgHook).select('svg.state.' + selectedState).select('.y.axis')
    .transition().duration(50).call(yAxis);

  dataset.forEach(function(d) {
    d.values.forEach(function(v, idx) {
      v.hidden = filtered_indices.indexOf(idx) === -1;
    })
  });
  stack(dataset);

  d3.select(svgHook).select('svg.state.' + selectedState).select('g.paths').selectAll("path")
    .attr("clip-path", "url(#clip)")
    .attr('d', function(d) {
      return area(d.values.filter(function(k) {
        return k.x >= begin && k.x <= end;
      }));
    });
}

Take a look at the jQuery slider too. I've missed commenting the code which I'll do soon and update the link. Please go through the code and let me know if find any bugs or anything that isn't understandable.

And I'm sorry for the delay as I lost all the code once (didn't save it), had to rewrite it today.

One thing I would like you to make note of is it's better to use "style" instead of "attr" (attribute) for stylings such as "fill", "stroke" etc. I've changed those too.

Hope this helps. :)


问:
calculate the mean of one row according it's label
calculate the mean of the values in one row according it's label:

```<code>A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])
</code>```

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

答:
Firstly, it sounds like you want to label the index:

```<code>In [11]: Result = pd.DataFrame(data=[A, B], index=['A', 'B'])

In [12]: Result
Out[12]:
   0  1  2  3  4  5  6  7  8   9
A  1  2  3  4  5  6  7  8  9  10
B  0  0  0  0  0  1  1  1  1   1
</code>```

If the index was unique you wouldn't have to do any groupby, just take the mean of each row (that's the axis=1):

```<code>In [13]: Result.mean(axis=1)
Out[13]:
A    5.5
B    0.5
dtype: float64
</code>```

However, if you had multiple rows with the same label, then you'd need to groupby:

```<code>In [21]: Result2 = pd.DataFrame(data=[A, A, B], index=['A', 'A', 'B'])

In [22]: Result2.mean(axis=1)
Out[22]:
A    5.5
A    5.5
B    0.5
dtype: float64
</code>```

Note: the duplicate rows (that happen to have the same mean as I lazily used the same row contents), in general we'd want to take the mean of those means:

```<code>In [23]: Result2.mean(axis=1).groupby(level=0).mean()
Out[23]:
A    5.5
B    0.5
dtype: float64
</code>```

Note: .groupby(level=0) groups the rows which have the same index label.

Body:
calculate the mean of the values in one row according it's label:

A = [1,2,3,4,5,6,7,8,9,10]
B = [0,0,0,0,0,1,1,1,1, 1]

Result = pd.DataFrame(data=[A, B])

I want the output is: 0->3; 1-> 7.8

pandas has the groupby function, but I don't know how to implement this. Thanks

Body:
Firstly, it sounds like you want to label the index:

In [11]: Result = pd.DataFrame(data=[A, B], index=['A', 'B'])

In [12]: Result
Out[12]:
   0  1  2  3  4  5  6  7  8   9
A  1  2  3  4  5  6  7  8  9  10
B  0  0  0  0  0  1  1  1  1   1

If the index was unique you wouldn't have to do any groupby, just take the mean of each row (that's the axis=1):

In [13]: Result.mean(axis=1)
Out[13]:
A    5.5
B    0.5
dtype: float64

However, if you had multiple rows with the same label, then you'd need to groupby:

In [21]: Result2 = pd.DataFrame(data=[A, A, B], index=['A', 'A', 'B'])

In [22]: Result2.mean(axis=1)
Out[22]:
A    5.5
A    5.5
B    0.5
dtype: float64

Note: the duplicate rows (that happen to have the same mean as I lazily used the same row contents), in general we'd want to take the mean of those means:

In [23]: Result2.mean(axis=1).groupby(level=0).mean()
Out[23]:
A    5.5
B    0.5
dtype: float64

Note: .groupby(level=0) groups the rows which have the same index label.


问:
doing math on files
I am writing a program in C for file compression. The method i am trying to use involves doing math on the file as if it were one long number. Can anyone recommend a bignum library that would not try to do all of that in ram, but rather let me do math with file pointers. any help would be appreciated, thanks in advance.</p>

答: I doubt such a library exists. You could try mmap()ing the files in memory and see if you can do it that way.</p>

Title: doing math on files


答:
Php code has following syntax. Make sure you file has .php extension.
Also your expected result should be "My name is Chao Hello World! 18" and not "echo My name is Chao echo Hello World! 18", since echo is command to print those string.

```<code><?php /* php code here */ ?>
</code>```

Change your code this way.

```<code><!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php
        echo 'My name is Chao';
        echo 'Hello World!<br>' ;//note the quotes
        echo 5+6+7 ;
    ?>
    </body>
</html>
</code>```

Title: PHP Sytax in html has unexpected output

Body:
Php code has following syntax. Make sure you file has .php extension.
Also your expected result should be "My name is Chao Hello World! 18" and not "echo My name is Chao echo Hello World! 18", since echo is command to print those string.

<?php /* php code here */ ?>

Change your code this way.

<!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php
        echo 'My name is Chao';
        echo 'Hello World!<br>' ;//note the quotes
        echo 5+6+7 ;
    ?>
    </body>
</html>


问:
SQL Query Error SQL Syntax
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

```<code>create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/
</code>```

looking forward for your help. thanks

答:
use semicolon ; at end of each statement.

```<code>create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/
</code>```

Title: SQL Query Error SQL Syntax

Body:
here I have some problem during make database on mysql :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'use android_api

create table users(    id int(11) primary key auto_increme' at line 3

here my code :

create database android_api /** Creating Database **/

use android_api /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/

looking forward for your help. thanks

Body:
use semicolon ; at end of each statement.

create database android_api; /** Creating Database **/

use android_api; /** Selecting Database **/

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/


问:
Android 6.0+ java.io.FileNotFoundException: (Permission denied)
Recently， I have met a really strange problem about permission issue, it confused me a few days, I hope someone will help me figure out what is going on. Thanks!

Here is the problem:
For some reason, I need to apply the storage permission for save some photos, and I had added the permission to the AndroidManifestival.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

Off course, I knew I have to apply for storage permission in code after Android 6.0, and here is my code for apply for permission:

```<code>public static boolean isGrantExternalRW(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (context.checkSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

        ((Activity)context).requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, Constants.PERMISSION_REQUEST_CODE);

        return false;
    }

    return true;
}
</code>```

I had use this method before I saved photo, and the permission dialog had shown up and I had checked it. And I had checked the app permission in the app setting, it's ok.

And here is the method I used to save the bitmap to the file:

```<code>public static String savePhotoToSDCard(Bitmap bitmap, String photoName) {
    String absolutePath = "";

    String state = Environment.getExternalStorageState();
    Log.e("file", "---------------------" + state);
    File newsDir =  new File(Environment.getExternalStorageDirectory().toString()
            + File.separator + "photo");

    if (!newsDir.exists()) {
        newsDir.mkdirs();
    }

    File picFile = new File(newsDir, photoName + ".png");
    absolutePath = picFile.getAbsolutePath();

    if (picFile.exists()) {
        picFile.delete();
    }

    if (photoName.equals("avatar")) {
        int ratio = 2;
        Bitmap result = Bitmap.createBitmap(bitmap.getWidth() / ratio, bitmap.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bitmap.getWidth() / ratio, bitmap.getHeight() / ratio);
        canvas.drawBitmap(bitmap, null, rect, null);
    }

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(picFile);
        if (bitmap != null) {

            if (bitmap.compress(Bitmap.CompressFormat.PNG, 30, fileOutputStream)) {
                fileOutputStream.flush();
                Log.d("Photo", "---------------------------fileOutputStream.flush");
                fileOutputStream.close();
            }
        }
    } catch (FileNotFoundException e) {
        Log.e("File", "----------------------------" + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return absolutePath;
}
</code>```

When I ran the app, it went wrong, here is the log：

java.io.FileNotFoundException: /storage/emulated/photo/avatar.png(permission denied)

But the most strange thing was that when I add the storage permission twice to AndroidManifestival.xml,  it worked!

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

So, what's the problem? Please help.

答:
Luckily, I solved my problem finally. Here was the reason:
The storage permission conflicts with the dependency below:

```<code>compile 'com.github.vungle:vungle-android-sdk:5.3.0'
</code>```

When I added the dependency, system cannot recognized the storage permission which I have apply for(while I added twice in AndroidManifest.xml, it worked), but when I removed it, everything was ok ! This dependency was used to add ad into app, but now I have to abandon it.

Body:
Recently， I have met a really strange problem about permission issue, it confused me a few days, I hope someone will help me figure out what is going on. Thanks!

Here is the problem:
For some reason, I need to apply the storage permission for save some photos, and I had added the permission to the AndroidManifestival.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Off course, I knew I have to apply for storage permission in code after Android 6.0, and here is my code for apply for permission:

public static boolean isGrantExternalRW(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (context.checkSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

        ((Activity)context).requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, Constants.PERMISSION_REQUEST_CODE);

        return false;
    }

    return true;
}

I had use this method before I saved photo, and the permission dialog had shown up and I had checked it. And I had checked the app permission in the app setting, it's ok.

And here is the method I used to save the bitmap to the file:

public static String savePhotoToSDCard(Bitmap bitmap, String photoName) {
    String absolutePath = "";

    String state = Environment.getExternalStorageState();
    Log.e("file", "---------------------" + state);
    File newsDir =  new File(Environment.getExternalStorageDirectory().toString()
            + File.separator + "photo");

    if (!newsDir.exists()) {
        newsDir.mkdirs();
    }

    File picFile = new File(newsDir, photoName + ".png");
    absolutePath = picFile.getAbsolutePath();

    if (picFile.exists()) {
        picFile.delete();
    }

    if (photoName.equals("avatar")) {
        int ratio = 2;
        Bitmap result = Bitmap.createBitmap(bitmap.getWidth() / ratio, bitmap.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bitmap.getWidth() / ratio, bitmap.getHeight() / ratio);
        canvas.drawBitmap(bitmap, null, rect, null);
    }

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(picFile);
        if (bitmap != null) {

            if (bitmap.compress(Bitmap.CompressFormat.PNG, 30, fileOutputStream)) {
                fileOutputStream.flush();
                Log.d("Photo", "---------------------------fileOutputStream.flush");
                fileOutputStream.close();
            }
        }
    } catch (FileNotFoundException e) {
        Log.e("File", "----------------------------" + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return absolutePath;
}

When I ran the app, it went wrong, here is the log：

java.io.FileNotFoundException: /storage/emulated/photo/avatar.png(permission denied)

But the most strange thing was that when I add the storage permission twice to AndroidManifestival.xml,  it worked!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

So, what's the problem? Please help.

Body:
Luckily, I solved my problem finally. Here was the reason:
The storage permission conflicts with the dependency below:

compile 'com.github.vungle:vungle-android-sdk:5.3.0'

When I added the dependency, system cannot recognized the storage permission which I have apply for(while I added twice in AndroidManifest.xml, it worked), but when I removed it, everything was ok ! This dependency was used to add ad into app, but now I have to abandon it.


答: php is server side programming , it start with <?php and close with ?> and it can't run on html file , so if you will programming use php language use php file

Title: PHP Sytax in html has unexpected output

Body:
I'm new to PHP, I wrote these code from a online courses. But when I open the PHP file in web browser, it was not what I expected.

<!DOCTYPE>

        <title>untitled</title>

My Bio

    <?php>
        echo 'My name is Chao';
        echo Hello World!

    <?>
    <?php> echo 5+6+7 <?>

The result is:
echo 'My name is Chao'; echo Hello World!
echo 5+6+7;

I was expecting: echo My name is Chao echo Hello World!
18

Why this is happening? I'm using Microsoft Edge currently.

I'm looking forward for you reply.Thank you.


答:
Try</p>

```<code><?php
    echo 'My name is Chao<br>';
    echo 'Hello World!<br>';

    echo 5+6+7;
?>
</code>```

Title: PHP Sytax in html has unexpected output

Body:
Try

<?php
    echo 'My name is Chao<br>';
    echo 'Hello World!<br>';

    echo 5+6+7;
?>


问:
Twitter Bootstrap Modal Event Not Fired When Modal is Shown
According to the docs:

http://getbootstrap.com/javascript/#modals

It should fire the methods "show.bs.dropdown" and "shown.bs.dropdown". But it doesn't:

http://jsfiddle.net/mQunq/3/

HTML:

```<code><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">Hello world</div>
    </div>
</div>
</code>```

jQuery:

```<code>// show.bs.modal doesn't work either

$('#myModal')
    .modal('show')
    .on('show.bs.modal', function() {

        alert('shown baby!');

    });
</code>```

答:
I found a solution that works with .fade transitions:

```<code>$(document).on($.support.transition.end, '.modal.fade.in', function(e) {
  var $target = $(e.target);
  if ($(e.target).is(".modal-dialog")) {
    console.log("Modal Shown")
  }
});

$(document).on($.support.transition.end, '.modal.fade', function(e) {
  var $target = $(e.target);
  if (!$target.is(".modal.fade.in") && !$target.is(".modal-dialog")) {
    console.log("Modal Hidden")
  }
});
</code>```

Body:
According to the docs:

http://getbootstrap.com/javascript/#modals

It should fire the methods "show.bs.dropdown" and "shown.bs.dropdown". But it doesn't:

http://jsfiddle.net/mQunq/3/

HTML:

Hello world

jQuery:

// show.bs.modal doesn't work either

$('#myModal')
    .modal('show')
    .on('show.bs.modal', function() {

        alert('shown baby!');

    });

Body:
I found a solution that works with .fade transitions:

$(document).on($.support.transition.end, '.modal.fade.in', function(e) {
  var $target = $(e.target);
  if ($(e.target).is(".modal-dialog")) {
    console.log("Modal Shown")
  }
});

$(document).on($.support.transition.end, '.modal.fade', function(e) {
  var $target = $(e.target);
  if (!$target.is(".modal.fade.in") && !$target.is(".modal-dialog")) {
    console.log("Modal Hidden")
  }
});


问:
Selenium Webdriver java : unable to click on OK button (span tag in button tag)
HTML code:

```<code><div id="sieb-ui-popup-mvg-selected" class="AppletStylePopup">
    <form onsubmit="return false;" action="/ecom_enu/start.swe" method="post" name="SWEForm4_0">
        <div class="siebui-popup-btm siebui-mvg-btn-modifier">
            <span class="siebui-popup-button">
                <button id="s_4_1_79_0_Ctrl" class="siebui-ctrl-btn siebui-icon-closeapplet s_4_1_79_0 appletButton" aria-label="Responsibilities:OK" title="Responsibilities:OK" tabindex="0" data-display="OK" name="s_4_1_79_0" type="button">
                    <span>OK</span>
                </button>
            </span>
        </div>
    </form>
</div>
</code>```

I want to click on the OK button. Please help, Thanks!

I have tried with the below, but it does not work.

```<code>driver.findElement(By.cssSelector(".siebui-ctrl-btn.siebui-icon-closeapplet.appletButton")).click();
</code>```

Also tried likethis, it does not work.

```<code>driver.findElement(By.xpath(".//*button[@title='Responsibilities:OK']/span[contains(text(),'OK]")).click();
</code>```

Also tried the below, it does not work.

```<code>driver.findElement(By.xpath("//button[contains(span/text(), 'OK')]")).click();
</code>```

Also tried the below, it does not work. Timeout error occurred

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//span[contains(text(), 'OK')]")));
el.click();
driver.switchTo().defaultContent();
</code>```

答:
Please check with the below code, may be this should work,

```<code>driver.findElement(By.xpath(".//*[contains(@class,'siebui-popup')]//span[text()='OK']")).click();
</code>```

Try using Firepath in Mozilla, so that you can get the correct path by checking with different combinations of CSS and XPATH. It will give you the correct idea of using the selectors for identifying an element.

Body:
HTML code:

    <form onsubmit="return false;" action="/ecom_enu/start.swe" method="post" name="SWEForm4_0">

                <button id="s_4_1_79_0_Ctrl" class="siebui-ctrl-btn siebui-icon-closeapplet s_4_1_79_0 appletButton" aria-label="Responsibilities:OK" title="Responsibilities:OK" tabindex="0" data-display="OK" name="s_4_1_79_0" type="button">
                    OK
                </button>

    </form>

I want to click on the OK button. Please help, Thanks!

I have tried with the below, but it does not work.

driver.findElement(By.cssSelector(".siebui-ctrl-btn.siebui-icon-closeapplet.appletButton")).click();

Also tried likethis, it does not work.

driver.findElement(By.xpath(".//*button[@title='Responsibilities:OK']/span[contains(text(),'OK]")).click();

Also tried the below, it does not work.

driver.findElement(By.xpath("//button[contains(span/text(), 'OK')]")).click();

Also tried the below, it does not work. Timeout error occurred

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//span[contains(text(), 'OK')]")));
el.click();
driver.switchTo().defaultContent();

Body:
Please check with the below code, may be this should work,

driver.findElement(By.xpath(".//*[contains(@class,'siebui-popup')]//span[text()='OK']")).click();

Try using Firepath in Mozilla, so that you can get the correct path by checking with different combinations of CSS and XPATH. It will give you the correct idea of using the selectors for identifying an element.


问:
PHP Sytax in html has unexpected output
I'm new to PHP, I wrote these code from a online courses. But when I open the PHP file in web browser, it was not what I expected.

```<code><!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php>
        echo 'My name is Chao';
        echo Hello World!<br>
    <?>
    <?php> echo 5+6+7 <?>
    </body>
</html>
</code>```

The result is:
echo 'My name is Chao'; echo Hello World!
echo 5+6+7;

I was expecting: echo My name is Chao echo Hello World!
18

Why this is happening? I'm using Microsoft Edge currently.

I'm looking forward for you reply.Thank you.

答:
Use this updated code
Errors in your code explained in the comments.</p>

```<code><!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php //php code start with `<?php`
        echo 'My name is Chao';
        echo 'Hello World!<br>';   // a string must within a ' or ".
    //php code end with `?>`
?>
        <?php echo (5+6+7); ?>
        </body>
    </html>
</code>```

Title: PHP Sytax in html has unexpected output

Body:
Use this updated code
Errors in your code explained in the comments.

<!DOCTYPE>
<html>
    <head>
        <title>untitled</title>
    </head>
    <body>
    <h1>My Bio</h1>
    <?php //php code start with `<?php`
        echo 'My name is Chao';
        echo 'Hello World!<br>';   // a string must within a ' or ".
    //php code end with `?>`
?>
        <?php echo (5+6+7); ?>
        </body>
    </html>


问:
Calculate hash when writing to stream
I am currently creating an encrypted file format that needs to be signed.
For this I need to calculate the hash code of the content I have written to a stream.

In the .net framework there is numerous hash algorithms that can be used, and it works fine, but it requires me to process the stream three times.

```<code>byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

using (Stream fileStream = File.Open("myfile.bin", FileMode.Create))
{
    //Write content
    fileStream.Write(content, 0, content.Length);
}

byte[] hashValue = null;
using (Stream fileStream = File.Open("myfile.bin", FileMode.Open))
{
    HashAlgorithm hash = SHA256.Create();
    hashValue = hash.ComputeHash(fileStream);
}

using (Stream fileStream = File.Open("myfile.bin", FileMode.Append))
{
    fileStream.Write(hashValue, 0, hashValue.Length);
}
</code>```

This is okay if it is encrypted to a file, but if it is encrypted to a network destination, the bytes are no longer available.

So basically I need to only process the data once. On CodeProject there is an article that has implemented CRC32 as a Stream that calculates the CRC32 code every time there is written data to it.

Something like:

```<code>byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

using (FileStream fileStream = File.Create("myfile.bin"))
using (Stream crcStream = new CRCStream(fileStream)) //Takes a base stream
{
    //Write content
    crcStream.Write(content, 0, content.Length);

    //Write checksum
    fileStream.Write(crcStream.WriteCRC, 0, 4);
}

</code>```

Obviously CRC32 is not a hash alogorithm, but it would be nice to have something like a HashStream that takes a HashAlgorithm. The HashStream would update the hash value every time write/read is called.

Something like:

```<code>byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

HashAlgorithm hashAlgo = SHA256.Create();

using (FileStream fileStream = File.Create("myfile.bin"))
using (HashStream hashStream = new HashStream(hashAlgo, fileStream))
{
    //Write content to HashStream
    hashStream.Write(content, 0, content.Length);

    //Write checksum
    fileStream.Write(hashStream.HashValue, 0, hashAlgo.HashSize / 8);
}</code>```

Reading the files should work in a similar way, so when you have read the file (not including the hash), the hash of the read content has already been calculated.

Is it possible to construct something like this using the .net frameworks existing components?

Edit:

Thanks Peter! I did not know CryptoStream could take a HashAlgorithm. So for encrypting and hashing at the same time, I could do something like this:

```<code>byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

SymmetricAlgorithm cryptoSymetric = Aes.Create();
HashAlgorithm cryptoHash = SHA256.Create();

using (FileStream file = new FileStream("Crypto.bin", FileMode.Create, FileAccess.Write))
using (CryptoStream hashStream = new CryptoStream(file, cryptoHash, CryptoStreamMode.Write))
using (CryptoStream cryptStream = new CryptoStream(hashStream, cryptoSymetric.CreateEncryptor(), CryptoStreamMode.Write))
{
    cryptStream.Write(content, 0, content.Length);
    cryptStream.FlushFinalBlock();

    byte[] hashValue = cryptoHash.Hash;

    file.Write(hashValue, 0, hashValue.Length);
}</code>```

答:
It's done for you by CryptoStream.

SHA256 hashAlg = new SHA256Managed();
CryptoStream cs = new CryptoStream(_out, hashAlg, CryptoStreamMode.Write);
// Write data here
cs.FlushFinalBlock();
byte[] hash = hashAlg.Hash;
```

Title: Calculate hash when writing to stream

Body:
I am currently creating an encrypted file format that needs to be signed.
For this I need to calculate the hash code of the content I have written to a stream.

In the .net framework there is numerous hash algorithms that can be used, and it works fine, but it requires me to process the stream three times.

byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

using (Stream fileStream = File.Open("myfile.bin", FileMode.Create))
{
    //Write content
    fileStream.Write(content, 0, content.Length);
}

byte[] hashValue = null;
using (Stream fileStream = File.Open("myfile.bin", FileMode.Open))
{
    HashAlgorithm hash = SHA256.Create();
    hashValue = hash.ComputeHash(fileStream);
}

using (Stream fileStream = File.Open("myfile.bin", FileMode.Append))
{
    fileStream.Write(hashValue, 0, hashValue.Length);
}

This is okay if it is encrypted to a file, but if it is encrypted to a network destination, the bytes are no longer available.

So basically I need to only process the data once. On CodeProject there is an article that has implemented CRC32 as a Stream that calculates the CRC32 code every time there is written data to it.

Something like:

byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

using (FileStream fileStream = File.Create("myfile.bin"))
using (Stream crcStream = new CRCStream(fileStream)) //Takes a base stream
{
    //Write content
    crcStream.Write(content, 0, content.Length);

    //Write checksum
    fileStream.Write(crcStream.WriteCRC, 0, 4);
}

Obviously CRC32 is not a hash alogorithm, but it would be nice to have something like a HashStream that takes a HashAlgorithm. The HashStream would update the hash value every time write/read is called.

Something like:

byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

HashAlgorithm hashAlgo = SHA256.Create();

using (FileStream fileStream = File.Create("myfile.bin"))
using (HashStream hashStream = new HashStream(hashAlgo, fileStream))
{
    //Write content to HashStream
    hashStream.Write(content, 0, content.Length);

    //Write checksum
    fileStream.Write(hashStream.HashValue, 0, hashAlgo.HashSize / 8);
}

Reading the files should work in a similar way, so when you have read the file (not including the hash), the hash of the read content has already been calculated.

Is it possible to construct something like this using the .net frameworks existing components?

Edit:

Thanks Peter! I did not know CryptoStream could take a HashAlgorithm. So for encrypting and hashing at the same time, I could do something like this:

byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };

SymmetricAlgorithm cryptoSymetric = Aes.Create();
HashAlgorithm cryptoHash = SHA256.Create();

using (FileStream file = new FileStream("Crypto.bin", FileMode.Create, FileAccess.Write))
using (CryptoStream hashStream = new CryptoStream(file, cryptoHash, CryptoStreamMode.Write))
using (CryptoStream cryptStream = new CryptoStream(hashStream, cryptoSymetric.CreateEncryptor(), CryptoStreamMode.Write))
{
    cryptStream.Write(content, 0, content.Length);
    cryptStream.FlushFinalBlock();

    byte[] hashValue = cryptoHash.Hash;

    file.Write(hashValue, 0, hashValue.Length);
}


问:
C# - How to detect if SQLite DB is locked?
I'm working on a multithreaded C# program that uses SQLite. I'm having a problem that sometimes running SQLiteCommand.ExecuteNonQuery() to update some rows complains "SQLite error (5): database is locked". I'm aware that this happens because the database gets locked while an insert or update is going on, so if another query to modify the DB comes along the second query will have this database is locked error. So I'm trying to implement workarounds to it, but I'm not sure how I should do it.

I was trying to make it so that if the database locked error is thrown then the program waits a bit and tries again until it works. But somehow no exception gets caught and the code just exits the try-catch block even though the database locked message still gets printed in the debug output. I'm not entirely sure whether the SQL query gets rejected or accepted.

I also tried using TransactionScope and I haven't had the database is locked thing since then, but because of the random nature of the problem I can't be 100% sure if TransactionScope actually solves the problem, or if it only does to an extent, or if it doesn't and I was just lucky so far.

```<code>SQLiteConnection connection = new SQLiteConnection("Data Source=DB.db;Version=3;");
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.commandText = inputQuery;
try
{
  command.executeNonQuery();
}
catch (SQLiteException sqle)
{
  Debug.WriteLine("Database error: " + e.Message);
  return false;
}
catch (Exception e)
{
  Debug.WriteLine("Database error: " + e.Message);
  return false;
}
finally
{
  connection.Close();
}
</code>```

So I'd really like someone to help me find out 1) how to eliminate the database is locked problem or 2) how to detect if the DB is locked error happens. Thanks in advance.

答:
If you're receiving error code 5 (busy) you can limit this by using an immediate transaction. If you're able to begin an immediate transaction, SQLite guarantees that you won't receive a busy error until you commit.

Also note that SQLite doesn't have row-level locking. The entire database is locked. Using a WAL journal, you can one writer and multiple readers. With other journaling methods, you can have either one writer, or multiple readers, but not both simultaneously.

SQLite Documentation on 'SQLITE_BUSY'

Body:
I'm working on a multithreaded C# program that uses SQLite. I'm having a problem that sometimes running SQLiteCommand.ExecuteNonQuery() to update some rows complains "SQLite error (5): database is locked". I'm aware that this happens because the database gets locked while an insert or update is going on, so if another query to modify the DB comes along the second query will have this database is locked error. So I'm trying to implement workarounds to it, but I'm not sure how I should do it.

I was trying to make it so that if the database locked error is thrown then the program waits a bit and tries again until it works. But somehow no exception gets caught and the code just exits the try-catch block even though the database locked message still gets printed in the debug output. I'm not entirely sure whether the SQL query gets rejected or accepted.

I also tried using TransactionScope and I haven't had the database is locked thing since then, but because of the random nature of the problem I can't be 100% sure if TransactionScope actually solves the problem, or if it only does to an extent, or if it doesn't and I was just lucky so far.

SQLiteConnection connection = new SQLiteConnection("Data Source=DB.db;Version=3;");
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.commandText = inputQuery;
try
{
  command.executeNonQuery();
}
catch (SQLiteException sqle)
{
  Debug.WriteLine("Database error: " + e.Message);
  return false;
}
catch (Exception e)
{
  Debug.WriteLine("Database error: " + e.Message);
  return false;
}
finally
{
  connection.Close();
}

So I'd really like someone to help me find out 1) how to eliminate the database is locked problem or 2) how to detect if the DB is locked error happens. Thanks in advance.


问:
How to use the http post method on ionic 2 and Angular 2?
I am now creating the Ionic 2 app to register and authenticate to Stormpath. When I registered the user I used the http post method.
Following function is in provider there.

register(username: string, email: string, password: string, givenname: string, surname: string){
    var headers = new Headers();
    headers.append('content-type', 'application/json;charset=UTF-8');
    headers.append('Access-Control-Allow-Origin','*');
    let options= new RequestOptions({headers: headers});

    var url = 'https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts';

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
 }```
</div>
</div>
</p>

<p>And using this function code is as following.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>signup(form){

    console.log('Pressed Signup button.')

    let username = form.value.username,
      email = form.value.email,
      password = form.value.password,
      givenName = form.value.givenName,
      surname = form.value.surname;

    this.stormpathService.register(username, email, password, givenName, surname);

    this.navCtrl.pop();
  }</code>```

The HTML file is :

<ion-content padding>
  <form #signupForm="ngForm" (ngSubmit)="signup(signupForm)">
    <ion-list style="margin-bottom: 25%;">
      <ion-item>
        <ion-label floating>GivenName</ion-label>
        <ion-input [(ngModel)]="givenName" name="givenName" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>SurName</ion-label>
        <ion-input [(ngModel)]="surname" name="surname" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input [(ngModel)]="username" name="username" type="text" required=""></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Email</ion-label>
        <ion-input [(ngModel)]="email" name="email" type="text" ></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input [(ngModel)]="password" name="password" type="password" required=""></ion-input>
      </ion-item>
    </ion-list>

      <button ion-button type="submit" color="light" full > Sign up </button>

  </form>
</ion-content>```

Error screen is :

Why I don't get response from stormpath server?

答:
In the Ionic latest versions if you are using ionic serve commnad then  you must have to use Proxies to prevent Preflight and CORS Issues,

First add API path and URL in ionic.config.json file like

```<code>{
  "name": "APP-NAME",
  "app_id": "",
  "proxies": [
    {
      "path": "/accounts",
      "proxyUrl": "https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts"
    }
  ]
}
</code>```

Now, while calling your API from http use the /accounts URL instead of the https://api.stormpath.com/v1... like,

```<code>....
    var url = '/accounts'; // use the Proxy Path here instead of Stormpath API URL

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
....
</code>```

After making the above changes you must rerun command ionic serve.

Still, if you are getting issues then refer Handling CORS Issues In Ionic

Body:
I am now creating the Ionic 2 app to register and authenticate to Stormpath. When I registered the user I used the http post method.
Following function is in provider there.

register(username: string, email: string, password: string, givenname: string, surname: string){
    var headers = new Headers();
    headers.append('content-type', 'application/json;charset=UTF-8');
    headers.append('Access-Control-Allow-Origin','*');
    let options= new RequestOptions({headers: headers});

    var url = 'https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts';

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
 }

And using this function code is as following.

signup(form){

    console.log('Pressed Signup button.')

    let username = form.value.username,
      email = form.value.email,
      password = form.value.password,
      givenName = form.value.givenName,
      surname = form.value.surname;

    this.stormpathService.register(username, email, password, givenName, surname);

    this.navCtrl.pop();
  }

The HTML file is :

<ion-content padding>
  <form #signupForm="ngForm" (ngSubmit)="signup(signupForm)">
    <ion-list style="margin-bottom: 25%;">
      <ion-item>
        <ion-label floating>GivenName</ion-label>
        <ion-input [(ngModel)]="givenName" name="givenName" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>SurName</ion-label>
        <ion-input [(ngModel)]="surname" name="surname" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input [(ngModel)]="username" name="username" type="text" required=""></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Email</ion-label>
        <ion-input [(ngModel)]="email" name="email" type="text" ></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input [(ngModel)]="password" name="password" type="password" required=""></ion-input>
      </ion-item>
    </ion-list>

      <button ion-button type="submit" color="light" full > Sign up </button>

  </form>
</ion-content>

Error screen is :

Why I don't get response from stormpath server?

Body:
In the Ionic latest versions if you are using ionic serve commnad then  you must have to use Proxies to prevent Preflight and CORS Issues,

First add API path and URL in ionic.config.json file like

{
  "name": "APP-NAME",
  "app_id": "",
  "proxies": [
    {
      "path": "/accounts",
      "proxyUrl": "https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts"
    }
  ]
}

Now, while calling your API from http use the /accounts URL instead of the https://api.stormpath.com/v1... like,

....
    var url = '/accounts'; // use the Proxy Path here instead of Stormpath API URL

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
....

After making the above changes you must rerun command ionic serve.

Still, if you are getting issues then refer Handling CORS Issues In Ionic