问:
Is there a way to pass a jquery variable on same page without any need of action like click etc?
Thank you for your time reading this. Ok, so I know how to pass a jquery variable to php with no action needed on the same page but now I need the opposite and I do not seem to find any documentation about it. Imagine the simpliest possible thing. I pass the name Jack to jquery like this:

```<code><?php
$my_name = "Jack Goodman";
?>
<script>
$(document).ready(function(){
var my_name = <?php echo json_encode($my_name); ?>;
alert(my_name);
});
</script>
</code>```

The question is how do I get the name from jquery back in php variable after?

```<code><?php
$my_name = ?
?>
</code>```

答:
You need to understand how pages are constructed. PHP is a server side language, that means that all the PHP is executed prior to being sent to the client (i.e. the persons browser). Your PHP is parsed and what is sent to the client is:

```<code><script>
    $(document).ready(function(){
        var my_name = 'Jack Goodman';
        alert(my_name);
    });
</script>
</code>```

That is then executed on the client's PC. The PHP has completely finished, there is no way for the client to change the value of the PHP variable, it doesn't exist any more. The only way to pass information from the client to the server is to open a new connection (e.g. a new page) and set the information you want to send to the server as a GET or POST variable.

Imagine going to a page on your website, you enter a URL in the browser such as http://www.mywebsite.com. We can include variable information by using GET variables, so if we wanted to pass the name in it would be something like http://www.mywebsite.com?name=My%20Name (%20 is a space). In your PHP you can then access this using the $_GET superglobal, e.g. $name = $_GET['name'] and use it as you need.

So if you have some information you need sending to the server, traditionally you would use a form:

```<code><form action="mypage.php" method="get" id="myform">
    <input type="text" name="name" id="myname" value="Jack Goodman">
    <button type="submit">Submit</button>
</form>
</code>```

However you can also send data asynchronously using AJAX. That means we don't have to open a new page, or submit a form to send data to the server. AJAX allows us to send some data to the server and read its response. So to send the name variable we can use jQuery's AJAX plugin.

```<code>// We intercept the submission of the form
$('#myform').submit(function () {
    $.ajax({
        url: 'mypage.php',
        type: 'GET',
        dataType: 'JSON',
        data: { name: $('#myname').val() }
    }).success(function (response) {
        alert(response);
    });

    return false; // This stops the form submitting so the page doesn't reload.
});
</code>```

response will contain whatever the PHP page outputs. So if your PHP page looked like this:

```<code><?php
$name = $_GET['name'];
// ... do something with $name
$response = ['result' => 'success', 'name' => $name];
echo json_encode($response);
</code>```

We're passing back a JSON string, so response will contain that JSON string. However because we know that it's a JSON string and we tell jQuery to expect a JSON string response (by using dataType: 'JSON') jQuery will automatically convert that to an object for us, so response contains an object with the properties result and name.

Body:
Thank you for your time reading this. Ok, so I know how to pass a jquery variable to php with no action needed on the same page but now I need the opposite and I do not seem to find any documentation about it. Imagine the simpliest possible thing. I pass the name Jack to jquery like this:

<?php
$my_name = "Jack Goodman";
?>

The question is how do I get the name from jquery back in php variable after?

<?php
$my_name = ?
?>

Body:
You need to understand how pages are constructed. PHP is a server side language, that means that all the PHP is executed prior to being sent to the client (i.e. the persons browser). Your PHP is parsed and what is sent to the client is:

<script>
    $(document).ready(function(){
        var my_name = 'Jack Goodman';
        alert(my_name);
    });
</script>

That is then executed on the client's PC. The PHP has completely finished, there is no way for the client to change the value of the PHP variable, it doesn't exist any more. The only way to pass information from the client to the server is to open a new connection (e.g. a new page) and set the information you want to send to the server as a GET or POST variable.

Imagine going to a page on your website, you enter a URL in the browser such as http://www.mywebsite.com. We can include variable information by using GET variables, so if we wanted to pass the name in it would be something like http://www.mywebsite.com?name=My%20Name (%20 is a space). In your PHP you can then access this using the $_GET superglobal, e.g. $name = $_GET['name'] and use it as you need.

So if you have some information you need sending to the server, traditionally you would use a form:

<form action="mypage.php" method="get" id="myform">
    <input type="text" name="name" id="myname" value="Jack Goodman">
    <button type="submit">Submit</button>
</form>

However you can also send data asynchronously using AJAX. That means we don't have to open a new page, or submit a form to send data to the server. AJAX allows us to send some data to the server and read its response. So to send the name variable we can use jQuery's AJAX plugin.

// We intercept the submission of the form
$('#myform').submit(function () {
    $.ajax({
        url: 'mypage.php',
        type: 'GET',
        dataType: 'JSON',
        data: { name: $('#myname').val() }
    }).success(function (response) {
        alert(response);
    });

    return false; // This stops the form submitting so the page doesn't reload.
});

response will contain whatever the PHP page outputs. So if your PHP page looked like this:

<?php
$name = $_GET['name'];
// ... do something with $name
$response = ['result' => 'success', 'name' => $name];
echo json_encode($response);

We're passing back a JSON string, so response will contain that JSON string. However because we know that it's a JSON string and we tell jQuery to expect a JSON string response (by using dataType: 'JSON') jQuery will automatically convert that to an object for us, so response contains an object with the properties result and name.


来源: stackexchange

问:
Compile/bundle tesseract into one binary
Is it possible to compile tesseract into one binary?

I use the following to compile a program, but how is it possible to compile tesseract shared libraries into one binary so the program is 100% portable and you dont need tesseract to be installed on the current system?

Its not necessary to compile leptonica into the binary

```<code>g++ -std=c++11 txtocr.cpp -o txtocr -llept -ltesseract
</code>```

答:
For that you need to use a Static Library, on unix systems they usually ends with the .a extension, and a Shared Library ends with .so

If you only have the .so (or .dylib on mac, .dll on windows) library of the tesseract, then you cannot compile it as a single binary.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to compile tesseract into one binary?

I use the following to compile a program, but how is it possible to compile tesseract shared libraries into one binary so the program is 100% portable and you dont need tesseract to be installed on the current system?

Its not necessary to compile leptonica into the binary

g++ -std=c++11 txtocr.cpp -o txtocr -llept -ltesseract


问:
Vector of pointer to union. How to access elements of the union correctly?
I have the following union:

```<code>union uval_t
{
   size_t   _size;
   void*    _pointer;
   uint32_t _tid[2];
};
</code>```

If I now do the following:

```<code>std::vector<uval_t*> uvalPointerVec;
uvalPointerVec.push_back((uval_t*)malloc(sizeof(uval_t) * 1000));
</code>```

How do I access the array in the union correctly? Let's say my first union value is of type size_t. I can do:

```<code>uvalPointerVec[0]->_size = 1000;
</code>```

But what are the best practices to do pointer arithmetic with the union pointer to access the elemets?

Example: Can I do the following to access the first union pointer in my vector and access the location after where my _size was was stored?

```<code>uvalPointerVec[0][1]->_tid[0]  = 42;
uvalPointerVec[0][1]->_tid[1]  = 24;
uvalPointerVec[0][2]->_pointer = somePointer;
</code>```

Do I get the following result with this?

```<code>| 1000 | 42 | 24 | 0x... |
^   ^
|   |_First union value
|_union pointer
</code>```

Edit: I think my question is answered (did not try it yet) but a little bit more context for all the confused. I implement the physical algebra of an database system. The Scan operator for example reads data stored in memory and saves all tuples in some kind of data structure. Currently the Scan operator is implemented as template and must work for different page layouts (row store [nsm=n-ary store model] vs column store[pax=partition attributes across]). The data structure which stores the retrieved tuples must work for both page layouts aswell. In NSM (e.g., row-stores) I can access a tuple by a single pointer to that tuple since all attributes are stored in a consecutive manner. For the other page layout I need two integers to exactly adress a tuple: a page number and a record number on that page (tid). Size is needed for some optimization reasons I dont want to discuss now. So if I now want to Scan a NSM page I can store pointer to tuples in my data structure, if i Scan a PAX-page I can reuse the same data structure and instead of storing pointers I store pairs of PageNo/TupleNo.

That is the short version of what I want to achieve

答:
The correct way would be like this:

```<code>vector[i][j].member = value;
</code>```

Where i is the index to your vector element and j being an index into the array element i.

This is irrelevant to the question but you're using a lot of C rather than C++, I'd suggest replacing your

```<code>(uval_t*)malloc(sizeof(uval_t) * 1000)
</code>```

With the more standard (but still not desireable):

```<code>new uval_t[1000]
</code>```

or an even better and more acceptable:

```<code>std::array<uval_t, 1000>() //fixed size
std::vector<uval_t>(1000) //resizable
</code>```

They are safer and way easier to pass around, they also free themselves when elements are replaced or erased. Array will have equivalent performance and vector coming in close if you make sure to allocate the amount you need beforehand.

Body:
I have the following union:

union uval_t
{
   size_t   _size;
   void*    _pointer;
   uint32_t _tid[2];
};

If I now do the following:

std::vector<uval_t*> uvalPointerVec;
uvalPointerVec.push_back((uval_t*)malloc(sizeof(uval_t) * 1000));

How do I access the array in the union correctly? Let's say my first union value is of type size_t. I can do:

uvalPointerVec[0]->_size = 1000;

But what are the best practices to do pointer arithmetic with the union pointer to access the elemets?

Example: Can I do the following to access the first union pointer in my vector and access the location after where my _size was was stored?

uvalPointerVec[0][1]->_tid[0]  = 42;
uvalPointerVec[0][1]->_tid[1]  = 24;
uvalPointerVec[0][2]->_pointer = somePointer;

Do I get the following result with this?

| 1000 | 42 | 24 | 0x... |
^   ^
|   |_First union value
|_union pointer

Edit: I think my question is answered (did not try it yet) but a little bit more context for all the confused. I implement the physical algebra of an database system. The Scan operator for example reads data stored in memory and saves all tuples in some kind of data structure. Currently the Scan operator is implemented as template and must work for different page layouts (row store [nsm=n-ary store model] vs column store[pax=partition attributes across]). The data structure which stores the retrieved tuples must work for both page layouts aswell. In NSM (e.g., row-stores) I can access a tuple by a single pointer to that tuple since all attributes are stored in a consecutive manner. For the other page layout I need two integers to exactly adress a tuple: a page number and a record number on that page (tid). Size is needed for some optimization reasons I dont want to discuss now. So if I now want to Scan a NSM page I can store pointer to tuples in my data structure, if i Scan a PAX-page I can reuse the same data structure and instead of storing pointers I store pairs of PageNo/TupleNo.

That is the short version of what I want to achieve

Body:
The correct way would be like this:

vector[i][j].member = value;

Where i is the index to your vector element and j being an index into the array element i.

This is irrelevant to the question but you're using a lot of C rather than C++, I'd suggest replacing your

(uval_t*)malloc(sizeof(uval_t) * 1000)

With the more standard (but still not desireable):

new uval_t[1000]

or an even better and more acceptable:

std::array<uval_t, 1000>() //fixed size
std::vector<uval_t>(1000) //resizable

They are safer and way easier to pass around, they also free themselves when elements are replaced or erased. Array will have equivalent performance and vector coming in close if you make sure to allocate the amount you need beforehand.


问:
Extract only pattern matched text
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

```<code>use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*
</code>```

Is my regular expression incorrect?

答:
I don't know how you output the match in perl but you can use below regex for output the full match in your regex, you might getting space appended with your result in your current regex.

```<code>\b[\d]{4}
</code>```

DEMO

Title: Extract only pattern matched text

Body:
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*

Is my regular expression incorrect?

Body:
I don't know how you output the match in perl but you can use below regex for output the full match in your regex, you might getting space appended with your result in your current regex.

\b[\d]{4}

DEMO


问:
Why is the examples link for nodejs examples returning a 404: https://github.com/api-ai/apiai-nodejs-client/blob/master/examples
This link is not working: https://github.com/api-ai/apiai-nodejs-client/blob/master/examples

Any other links for this purpose?

答:
Yes, try this link. It appears they renamed it to samples. :)

In future it's better to bookmark a link to the whole repo, not to a separate folder as it may change and GitHub doesn't do redirecting for that unlike for changing username or repo name.


问:
Can I use a PNG sequence as an animated material on a SceneKit object?
I'd like to programmatically change the material of an object rendered using SceneKit in iOS. But I would like to use animated image files. PNG sequences work great in iOS for stuff like UIImageViews -- how do I use them as a material in SceneKit?

Something like this doesn't work:

```<code>floor.firstMaterial.diffuse.contents = [UIImage animatedImageNamed:@"ANIMATION_" duration:6.0f];
</code>```

Thanks!

答:
There is a much simpler solution (or at least I think it's simpler) though I can't attest to whether it's more efficient.  I've tested this on an iPad mini (1st gen) and it works fine.

Rather than place a texture that is a spritesheet into the material's contents (and fiddle with the shader), you can place an SKScene object there instead.

That way you can just use SKSpriteNode objects within the SKScene and animate them using SCNAction objects.  All of the animation can then be controlled easily and more powerfully without having to touch shader code.

```<code>    NSArray<SKTexture*> *cursorTextures =
    @[
      [SKTexture textureWithImageNamed:@"tilecursor1.png"],
      [SKTexture textureWithImageNamed:@"tilecursor2.png"],
      [SKTexture textureWithImageNamed:@"tilecursor3.png"],
      [SKTexture textureWithImageNamed:@"tilecursor4.png"],
      [SKTexture textureWithImageNamed:@"tilecursor5.png"]
      ];

    SKSpriteNode *cursorSprite = [SKSpriteNode spriteNodeWithTexture:cursorTextures[0]];
    cursorSprite.position = CGPointMake(cursorSprite.size.width/2.0, cursorSprite.size.height/2.0);
    [cursorSprite runAction:[SKAction repeatActionForever:[SKAction animateWithTextures:cursorTextures timePerFrame:0.1]]];

    SKScene *cursorScene = [SKScene sceneWithSize:cursorSprite.size];
    cursorScene.backgroundColor = [UIColor clearColor];
    [cursorScene addChild:cursorSprite];

    ...

    self.cursor.material.diffuse.contents = cursorScene;
</code>```

Body:
I'd like to programmatically change the material of an object rendered using SceneKit in iOS. But I would like to use animated image files. PNG sequences work great in iOS for stuff like UIImageViews -- how do I use them as a material in SceneKit?

Something like this doesn't work:

floor.firstMaterial.diffuse.contents = [UIImage animatedImageNamed:@"ANIMATION_" duration:6.0f];

Thanks!

Body:
There is a much simpler solution (or at least I think it's simpler) though I can't attest to whether it's more efficient.  I've tested this on an iPad mini (1st gen) and it works fine.

Rather than place a texture that is a spritesheet into the material's contents (and fiddle with the shader), you can place an SKScene object there instead.

That way you can just use SKSpriteNode objects within the SKScene and animate them using SCNAction objects.  All of the animation can then be controlled easily and more powerfully without having to touch shader code.

    NSArray<SKTexture*> *cursorTextures =
    @[
      [SKTexture textureWithImageNamed:@"tilecursor1.png"],
      [SKTexture textureWithImageNamed:@"tilecursor2.png"],
      [SKTexture textureWithImageNamed:@"tilecursor3.png"],
      [SKTexture textureWithImageNamed:@"tilecursor4.png"],
      [SKTexture textureWithImageNamed:@"tilecursor5.png"]
      ];

    SKSpriteNode *cursorSprite = [SKSpriteNode spriteNodeWithTexture:cursorTextures[0]];
    cursorSprite.position = CGPointMake(cursorSprite.size.width/2.0, cursorSprite.size.height/2.0);
    [cursorSprite runAction:[SKAction repeatActionForever:[SKAction animateWithTextures:cursorTextures timePerFrame:0.1]]];

    SKScene *cursorScene = [SKScene sceneWithSize:cursorSprite.size];
    cursorScene.backgroundColor = [UIColor clearColor];
    [cursorScene addChild:cursorSprite];

    ...

    self.cursor.material.diffuse.contents = cursorScene;


问:
PostgreSQL search criteria must output missing row
I have two postgreSQL tables, namely: employees and employee_cars.
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'.

I have tried below query:

```<code>SELECT DISTINCT a.employee_name, b.car_brand
FROM employees a
LEFT JOIN employee_cars b
ON a.employee_id = b.employee_id
WHERE b.car_brand IN ('BMW','MERC','VW')
AND b.car_brand NOT LIKE 'AUDI';
</code>```

OUTPUT below:

```<code>employee_name,car_brand
"Mary","BMW"
"Mary","MERC"
"Mary","VW"
"Paul","BMW"
"Paul","MERC"
"Paul","VW"
</code>```

Problem is that each vehicle that an employee owns is a row in the employee_cars tables. So for example; I have 'Mary' which owns: 'BMW','MERC','VW','AUDI'.
I have 'Paul' which only owns: 'BMW','MERC','VW'.
My query will display Both Mary and Paul, because they both own 'BMW','MERC','VW'.

I only want to see 'Paul' in my results, because he is missing the 'AUDI'.

Please note that I am not a DB expert, I will appreciate any help and assistance.
Thanks in advance.

答:
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'. If you need employees to be distinct, not employee + car brand pairs, you can do this with aggregation:

```<code>SELECT   e.employee_name, string_agg(c.car_brand, ', ')
FROM     employees e
JOIN     employee_cars c ON e.employee_id = c.employee_id
GROUP BY e.employee_id
HAVING   COUNT(1) FILTER (WHERE c.car_brand IN ('BMW', 'MERC', 'VW')) = 3
AND      COUNT(1) FILTER (WHERE c.car_brand = 'AUDI') = 0
</code>```

This will also filter out employees, who doesn't have either 'BMW', 'MERC' or 'VW' (like your question suggested).

http://rextester.com/MQL14836

Edit: for older PostgreSQL version use the CASE expression instead of FILTERing:

```<code>SELECT   e.employee_name, string_agg(c.car_brand, ', ')
FROM     employees e
JOIN     employee_cars c ON e.employee_id = c.employee_id
GROUP BY e.employee_id
HAVING   COUNT(CASE WHEN c.car_brand IN ('BMW', 'MERC', 'VW') THEN 1 END) = 3
AND      COUNT(CASE WHEN c.car_brand = 'AUDI' THEN 1 END) = 0
</code>```

http://rextester.com/KHMW56692

Body:
I have two postgreSQL tables, namely: employees and employee_cars.
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'.

I have tried below query:

SELECT DISTINCT a.employee_name, b.car_brand
FROM employees a
LEFT JOIN employee_cars b
ON a.employee_id = b.employee_id
WHERE b.car_brand IN ('BMW','MERC','VW')
AND b.car_brand NOT LIKE 'AUDI';

OUTPUT below:

employee_name,car_brand
"Mary","BMW"
"Mary","MERC"
"Mary","VW"
"Paul","BMW"
"Paul","MERC"
"Paul","VW"

Problem is that each vehicle that an employee owns is a row in the employee_cars tables. So for example; I have 'Mary' which owns: 'BMW','MERC','VW','AUDI'.
I have 'Paul' which only owns: 'BMW','MERC','VW'.
My query will display Both Mary and Paul, because they both own 'BMW','MERC','VW'.

I only want to see 'Paul' in my results, because he is missing the 'AUDI'.

Please note that I am not a DB expert, I will appreciate any help and assistance.
Thanks in advance.

Body:
I need to output all employees that own a 'BMW', 'MERC' AND 'VW', BUT NOT an 'AUDI'. If you need employees to be distinct, not employee + car brand pairs, you can do this with aggregation:

SELECT   e.employee_name, string_agg(c.car_brand, ', ')
FROM     employees e
JOIN     employee_cars c ON e.employee_id = c.employee_id
GROUP BY e.employee_id
HAVING   COUNT(1) FILTER (WHERE c.car_brand IN ('BMW', 'MERC', 'VW')) = 3
AND      COUNT(1) FILTER (WHERE c.car_brand = 'AUDI') = 0

This will also filter out employees, who doesn't have either 'BMW', 'MERC' or 'VW' (like your question suggested).

http://rextester.com/MQL14836

Edit: for older PostgreSQL version use the CASE expression instead of FILTERing:

SELECT   e.employee_name, string_agg(c.car_brand, ', ')
FROM     employees e
JOIN     employee_cars c ON e.employee_id = c.employee_id
GROUP BY e.employee_id
HAVING   COUNT(CASE WHEN c.car_brand IN ('BMW', 'MERC', 'VW') THEN 1 END) = 3
AND      COUNT(CASE WHEN c.car_brand = 'AUDI' THEN 1 END) = 0

http://rextester.com/KHMW56692


问:
How to show a thank you message after someone submits a form in Angular?
I have made this snippet in Angular: http://plnkr.co/edit/kQz0fiaXLv7T37N8fzJU?p=preview

```<code>$scope.loadEditForm = function () {
    $scope.checkItem = "yes";
    $modal.open({
        templateUrl: 'modal.html',
        controller: 'modalController',
        scope: $scope
    })
    .result.then(function() {
        alert('closed');
    });
};
</code>```

As you can see, I am prompting a "closed" pop-up, but I want to make this much more stylish and show a message IN the modal, instead of having to show an ugly pop-up screen that says "closed".

How could I do this in Angular? Is there some nifty trick?

答:
You can have a service and define the following bootstrap modal function. template="url where your modal is present". And display the message using the showThankYouCtrl</p>

```<code>          $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            template: template,
            size: 'md',
            controller: function ($uibModalInstance) {
              this.data = "Thank you!";
              this.cancel = function () {
                $uibModalInstance.dismiss('cancel');
              };
              this.ok = function () {
                $uibModalInstance.dismiss('cancel');
              };
            },
            controllerAs: '$showThankYouCtrl'
          });
</code>```

Body:
I have made this snippet in Angular: http://plnkr.co/edit/kQz0fiaXLv7T37N8fzJU?p=preview

$scope.loadEditForm = function () {
    $scope.checkItem = "yes";
    $modal.open({
        templateUrl: 'modal.html',
        controller: 'modalController',
        scope: $scope
    })
    .result.then(function() {
        alert('closed');
    });
};

As you can see, I am prompting a "closed" pop-up, but I want to make this much more stylish and show a message IN the modal, instead of having to show an ugly pop-up screen that says "closed".

How could I do this in Angular? Is there some nifty trick?

Body:
You can have a service and define the following bootstrap modal function. template="url where your modal is present". And display the message using the showThankYouCtrl

          $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            template: template,
            size: 'md',
            controller: function ($uibModalInstance) {
              this.data = "Thank you!";
              this.cancel = function () {
                $uibModalInstance.dismiss('cancel');
              };
              this.ok = function () {
                $uibModalInstance.dismiss('cancel');
              };
            },
            controllerAs: '$showThankYouCtrl'
          });


问:
django jquery comment form posting too many times
I have modified my comments/form.html and comments/posted.html to work in a similar way to facebook, ie you post a comment, the data posted is then reloaded and appended to a certain div with a given ID.

The problem I have is that it seems to post all the data for the amount of forms.

So the scenario is, I have 5 forms, one with data in it, if I then hit comment, it submits the data, 1 successful but 4 return empty.

```<code><div id="commentload"></div>
<div class="comments">
    <form action="{% comment_form_target %}" method="post" class="comment-form">
    {% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
    {% for field in form %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}
        {% if field.errors %}{{ field.errors }}{% endif %}
            <p
            {% if field.errors %} class="error"{% endif %}
            {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}>
            </p>
        {% endif %}
    {% endfor %}
    <textarea id="id_comment" rows="1" cols="60" name="comment" class='id_comment'></textarea>
    <p class="submit">
        <input type="submit" name="post" class="submit-post blue comment_submit" value="{% trans "Comment" %}" id="button" style="float:right;margin-top:-6px;margin-bottom:4px;"/>
    </p>
    <div class="clearfix"></div>
    </form>

</div>
</code>```

And then my jQuery looks as follows

```<code><script type="text/javascript">
    $(document).ready(function(){
        // Here it runs a simple each statement to apply a unique ID to each comment-form
        $('.comment-form').each(function(){
            var element = $(this).find('#id_object_pk').val();
            $('#commentload').attr('id','commentload'+element);
            $(this).attr('name', element);
            $(this).attr('id', element);
            $(this).find('#button').attr('id', element);
            $(this).find('#id_content_type').attr('id', 'id_content_type' + element);
            $(this).find('#id_timestamp').attr('id', 'id_timestamp' + element);
            $(this).find('#id_security_hash').attr('id', 'id_security_hash' + element);
            $(this).find('#id_comment').attr('id', 'id_comment' + element);
        });

        $(".comment_submit").live("click",function() {
            var ID = $(this).attr('id');

            var content_type = $('#id_content_type'+ID).val();
            var timestamp = $('#id_timestamp'+ID).val();
            var security_hash = $('#id_security_hash'+ID).val();
            var comment = $('#id_comment'+ID).val();
            var dataString = 'content_type='+ content_type +'&timestamp='+ timestamp +'&security_hash=' + security_hash + '&comment=' + comment + '&object_pk=' + ID;

            if (comment=='') {
                alert('Please enter a comment');
            } else {
                $('#id_comment'+ID).val('').addClass("greyout");
                $.ajax({
                    type: "POST",
                    url: "{% comment_form_target %}",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        $("#commentload"+ID).append(html);
                        $('#id_comment'+ID).val('').removeClass("greyout").focus();
                    }
                });
            }
            return false;
        });
    });
</script>
</code>```

HTML OUTPUT the difference between the forms obviously the ID for each one

```<code><div id="wall-comments">
    <div class="comments">
    <form action="/comments/post/" method="post" class="comment-form" id="114">
        <input type="hidden" name="content_type" value="wall.post" id="id_content_type114">
        <input type="hidden" name="object_pk" value="114" id="id_object_pk">
        <input type="hidden" name="timestamp" value="1291370494" id="id_timestamp114">
        <input type="hidden" name="security_hash" value="2d208d05d725528dfef940d8a5b520362faa3317" id="id_security_hash114">
        <textarea id="id_comment114" rows="1" cols="60" name="comment" class="id_comment" style="height: 24px; overflow-x: hidden; overflow-y: hidden; "></textarea>
        <p class="submit">
            <input type="submit" name="post" class="submit-post blue comment_submit" value="Comment" id="114" style="float:right;margin-top:-6px;margin-bottom:4px;">
        </p>
        <div class="clearfix"></div>
    </form>
    </div>
</div>
</code>```

答:
You are binding the click function too many times. You only should call .live("click", function() {}); Once per page load. Or else you should use die() to unbind the functions before calling live() again.

I still think this is the answer. Change the click .live call to be:

```<code>$(".comment_submit").die("click").live("click",function() {
    var ID = $(this).attr('id');

    var content_type = $('#id_content_type'+ID).val();
    var timestamp = $('#id_timestamp'+ID).val();
    var security_hash = $('#id_security_hash'+ID).val();
    var comment = $('#id_comment'+ID).val();
    var dataString = 'content_type='+ content_type +'&timestamp='+ timestamp +'&security_hash=' + security_hash + '&comment=' + comment + '&object_pk=' + ID;

    if (comment=='') {
        alert('Please enter a comment');
    } else {
        $('#id_comment'+ID).val('').addClass("greyout");
        $.ajax({
            type: "POST",
            url: "{% comment_form_target %}",
            data: dataString,
            cache: false,
            success: function(html){
                $("#commentload"+ID).append(html);
                $('#id_comment'+ID).val('').removeClass("greyout").focus();
            }
        });
    }
    return false;
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have modified my comments/form.html and comments/posted.html to work in a similar way to facebook, ie you post a comment, the data posted is then reloaded and appended to a certain div with a given ID.

The problem I have is that it seems to post all the data for the amount of forms.

So the scenario is, I have 5 forms, one with data in it, if I then hit comment, it submits the data, 1 successful but 4 return empty.

    <form action="{% comment_form_target %}" method="post" class="comment-form">
    {% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
    {% for field in form %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}
        {% if field.errors %}{{ field.errors }}{% endif %}

        {% endif %}
    {% endfor %}
    <textarea id="id_comment" rows="1" cols="60" name="comment" class='id_comment'></textarea>

        <input type="submit" name="post" class="submit-post blue comment_submit" value="{% trans "Comment" %}" id="button" style="float:right;margin-top:-6px;margin-bottom:4px;"/>

    </form>

And then my jQuery looks as follows

HTML OUTPUT the difference between the forms obviously the ID for each one

    <form action="/comments/post/" method="post" class="comment-form" id="114">
        <input type="hidden" name="content_type" value="wall.post" id="id_content_type114">
        <input type="hidden" name="object_pk" value="114" id="id_object_pk">
        <input type="hidden" name="timestamp" value="1291370494" id="id_timestamp114">
        <input type="hidden" name="security_hash" value="2d208d05d725528dfef940d8a5b520362faa3317" id="id_security_hash114">
        <textarea id="id_comment114" rows="1" cols="60" name="comment" class="id_comment" style="height: 24px; overflow-x: hidden; overflow-y: hidden; "></textarea>

            <input type="submit" name="post" class="submit-post blue comment_submit" value="Comment" id="114" style="float:right;margin-top:-6px;margin-bottom:4px;">

    </form>

Body:
You are binding the click function too many times. You only should call .live("click", function() {}); Once per page load. Or else you should use die() to unbind the functions before calling live() again.

I still think this is the answer. Change the click .live call to be:

$(".comment_submit").die("click").live("click",function() {
    var ID = $(this).attr('id');

    var content_type = $('#id_content_type'+ID).val();
    var timestamp = $('#id_timestamp'+ID).val();
    var security_hash = $('#id_security_hash'+ID).val();
    var comment = $('#id_comment'+ID).val();
    var dataString = 'content_type='+ content_type +'&timestamp='+ timestamp +'&security_hash=' + security_hash + '&comment=' + comment + '&object_pk=' + ID;

    if (comment=='') {
        alert('Please enter a comment');
    } else {
        $('#id_comment'+ID).val('').addClass("greyout");
        $.ajax({
            type: "POST",
            url: "{% comment_form_target %}",
            data: dataString,
            cache: false,
            success: function(html){
                $("#commentload"+ID).append(html);
                $('#id_comment'+ID).val('').removeClass("greyout").focus();
            }
        });
    }
    return false;
});


问:
Using threads to apply UI changes in android
I ran into a problem and need some help. I want to remove some user's files after a button click and also show the files removing progress (in progressbar) and also show some Fancy UI. First i changed the layout after button click and hide some elements and visible the others. after that i called methods to remove files. The problem is that i can not see any UI changes and system hangs until all user file removed and after that based on my scenario it go to another activity. I've google around and found that i should use thread or UI thread but exactly don't know how. Here is my code :

```<code>new Thread() {
    public void run() {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressBar spinner;
                    spinner = (ProgressBar) findViewById(R.id.progressBar);
                    listview.setVisibility(View.GONE);
                    spinner.setVisibility(View.VISIBLE);
                    preresult.setVisibility(View.VISIBLE);
                    resulttxt.setVisibility(View.VISIBLE);
                    wv.setVisibility(View.VISIBLE);
                    btnClear.setVisibility(View.GONE);
                    wv.loadUrl("file:///android_asset/rocket.gif");
                    resulttxt.setText("");
                }
            });
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}.start();

Thread b = new Thread() {
    @Override
    public void run() {
        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
                                           }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }
};
b.start();
</code>```

What is wrong with my code. Is there any better method to do that?

答:
Try</p>

```<code>new AsyncTask<String, String, String> () {

    @Override
    protected void onPreExecute() {
        //show loader if requried
    }

    @Override
    protected String doInBackground(String... params) {

        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
        }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }

    @Override
    protected void onPostExecute(String result){

        ProgressBar spinner;
        spinner = (ProgressBar) findViewById(R.id.progressBar);
        listview.setVisibility(View.GONE);
        spinner.setVisibility(View.VISIBLE);
        preresult.setVisibility(View.VISIBLE);
        resulttxt.setVisibility(View.VISIBLE);
        wv.setVisibility(View.VISIBLE);
        btnClear.setVisibility(View.GONE);
        wv.loadUrl("file:///android_asset/rocket.gif");
        resulttxt.setText("");
    }

}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTER);
</code>```

Body:
I ran into a problem and need some help. I want to remove some user's files after a button click and also show the files removing progress (in progressbar) and also show some Fancy UI. First i changed the layout after button click and hide some elements and visible the others. after that i called methods to remove files. The problem is that i can not see any UI changes and system hangs until all user file removed and after that based on my scenario it go to another activity. I've google around and found that i should use thread or UI thread but exactly don't know how. Here is my code :

new Thread() {
    public void run() {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressBar spinner;
                    spinner = (ProgressBar) findViewById(R.id.progressBar);
                    listview.setVisibility(View.GONE);
                    spinner.setVisibility(View.VISIBLE);
                    preresult.setVisibility(View.VISIBLE);
                    resulttxt.setVisibility(View.VISIBLE);
                    wv.setVisibility(View.VISIBLE);
                    btnClear.setVisibility(View.GONE);
                    wv.loadUrl("file:///android_asset/rocket.gif");
                    resulttxt.setText("");
                }
            });
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}.start();

Thread b = new Thread() {
    @Override
    public void run() {
        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
                                           }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }
};
b.start();

What is wrong with my code. Is there any better method to do that?

Body:
Try

new AsyncTask<String, String, String> () {

    @Override
    protected void onPreExecute() {
        //show loader if requried
    }

    @Override
    protected String doInBackground(String... params) {

        Long TotalJunk = 0L;
        for (Apps social : checkedSocial) {
            if (social.getName() == "Telegram") {
                preresult.setText("Calculating Files :");
                resulttxt.setText("Telegram");
                preresult.setText("Removing Files...");
                clearMediashistory(social.path);
                TotalJunk = TotalJunk + social.junksize;
            }
        }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("FreeUp", formatSize(TotalJunk));
        //commits your edits
        editor.commit();
    }

    @Override
    protected void onPostExecute(String result){

        ProgressBar spinner;
        spinner = (ProgressBar) findViewById(R.id.progressBar);
        listview.setVisibility(View.GONE);
        spinner.setVisibility(View.VISIBLE);
        preresult.setVisibility(View.VISIBLE);
        resulttxt.setVisibility(View.VISIBLE);
        wv.setVisibility(View.VISIBLE);
        btnClear.setVisibility(View.GONE);
        wv.loadUrl("file:///android_asset/rocket.gif");
        resulttxt.setText("");
    }

}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTER);


问:
Go Plugin variable initialization
This is a general question about Go Plugin initialization.

I want to make a certain package in a Go program to a Go Plugin.

The package (say mypackage) has a variable which is initialized with a function call from a certain package in the executable. (E.g. a variable of type interface Logger which is to be initialized by a logger.CreateLogger function.)

In order to make mypackage a plugin, I need to create a main package, embed mypackage inside main, and export an api Init in package main which accepts a function which can get me a logger.

I want to do this so as to reduce the dependencies of my plugin. The mypackage plugin should depend on the interface Logger rather than Logger's implementation.

Now the problem is the initialization, in the case of executable, the initialization could have happened as below:

```<code>package mypackage

var dlog = logger.CreateLogger("mypackage")
</code>```

And the logger can be used in any func init() function of mypackage.

After converting to a plugin, it can't be initialized like this. It has to be initialized at a later point after the main.Init is invoked.

The func init is invoked when the plugin is Opened, so it cannot be used to initialize variables.

Only solution seems to be a creating a function per package, and invoke it from an exported function in main package.

```<code>package mypackage

var dlog Logger

func Init(f createLoggerType){
   dlog = f()
   yetanotherpackage.Init(f)
}

package main

func Init(f createLoogerType) {
    mypackage.Init(f)
    anotherpackage.Init(f)
}
</code>```

Is there a better way to initialize? I tried checking github.com/facebookgo/inject but couldn't figure out how it can be used in case of plugins.

答:
There is nothing wrong with your solution, but if you want to be able to use it in variable declarations and package init() functions, this is how you can do it. I also think it's easier to use the plugin this way, but this requires a common, shared package between your main app and the plugin.

One option would be to create a "store" package, which could store factory functions or pre-created loggers.

Let's say the Logger interface definition is in mylogger:

```<code>package mylogger

type Logger interface { Log(string) }
</code>```

The store for example:

```<code>package store

import "mylogger"

var LoggerFactory func(string) mylogger.Logger
</code>```

And in your main app initialize it before you load / open the mypackage plugin:

```<code>package main

import "store"

func main() {
    store.LoggerFactory = logger.CreateLogger

    // Now proceed to load / open mypackage plugin
}
</code>```

Then the mypackage plugin may look like this:

```<code>package mypackage

import "store"

var dlog = store.LoggerFactory("mypackage")
</code>```

Title: Go Plugin variable initialization

Body:
This is a general question about Go Plugin initialization.

I want to make a certain package in a Go program to a Go Plugin.

The package (say mypackage) has a variable which is initialized with a function call from a certain package in the executable. (E.g. a variable of type interface Logger which is to be initialized by a logger.CreateLogger function.)

In order to make mypackage a plugin, I need to create a main package, embed mypackage inside main, and export an api Init in package main which accepts a function which can get me a logger.

I want to do this so as to reduce the dependencies of my plugin. The mypackage plugin should depend on the interface Logger rather than Logger's implementation.

Now the problem is the initialization, in the case of executable, the initialization could have happened as below:

package mypackage

var dlog = logger.CreateLogger("mypackage")

And the logger can be used in any func init() function of mypackage.

After converting to a plugin, it can't be initialized like this. It has to be initialized at a later point after the main.Init is invoked.

The func init is invoked when the plugin is Opened, so it cannot be used to initialize variables.

Only solution seems to be a creating a function per package, and invoke it from an exported function in main package.

package mypackage

var dlog Logger

func Init(f createLoggerType){
   dlog = f()
   yetanotherpackage.Init(f)
}

package main

func Init(f createLoogerType) {
    mypackage.Init(f)
    anotherpackage.Init(f)
}

Is there a better way to initialize? I tried checking github.com/facebookgo/inject but couldn't figure out how it can be used in case of plugins.

Body:
There is nothing wrong with your solution, but if you want to be able to use it in variable declarations and package init() functions, this is how you can do it. I also think it's easier to use the plugin this way, but this requires a common, shared package between your main app and the plugin.

One option would be to create a "store" package, which could store factory functions or pre-created loggers.

Let's say the Logger interface definition is in mylogger:

package mylogger

type Logger interface { Log(string) }

The store for example:

package store

import "mylogger"

var LoggerFactory func(string) mylogger.Logger

And in your main app initialize it before you load / open the mypackage plugin:

package main

import "store"

func main() {
    store.LoggerFactory = logger.CreateLogger

    // Now proceed to load / open mypackage plugin
}

Then the mypackage plugin may look like this:

package mypackage

import "store"

var dlog = store.LoggerFactory("mypackage")


问:
SerializationException when setting instance of one class to another
I'm trying to pass an instance of a class between two separate classes, like the following.

```<code>//classes
public class A
{
  public string name;
  public string data;
}

public class B : MarshalByRefObject
{
  public A _a;
}

public class C : MarshalByRefObject
{
  public A _a;
}

//main program
static void Main(string[] args)
{
  B _b = new B();
  C _c = new C();

  _b._a = new A();

  _c._a = _b._a;
}
</code>```

A exists in both classes B and C and I want to make the instance of class A that is in C equal to that instance of class A that is in B.  I basically want to make sure that both B and C have the same exact copy of A.

When I try to run this, however, I get a SerializationException saying that class A is not marked as Serializable.  I know I've done stuff like this before and it's never wanted it to be serialized.  Why would it need this anyways?  I thought that was for xml serialization.

I did try adding the [Serializable] attribute to class A, and the exception obviously went away.  But after doing that, making changes to A inside of class B wouldn't then propagate to the instance of A inside of C... like they are now completely separate copies.

Any ideas?

Edit:  Didn't realize that this would matter before, but after some looking around I think it does.  Classes B and C inherit from the MarshalByRefObject class.  Maybe this will help figure it out.  I've updated the classes above.

答: I get no such exception on the code above running in Visual Studio.  I don't see any serialization occuring at all, you're simply point references at different objects.</p>

OwnerDisplayName: Adam Haile

Body:
I'm trying to pass an instance of a class between two separate classes, like the following.

//classes
public class A
{
  public string name;
  public string data;
}

public class B : MarshalByRefObject
{
  public A _a;
}

public class C : MarshalByRefObject
{
  public A _a;
}

//main program
static void Main(string[] args)
{
  B _b = new B();
  C _c = new C();

  _b._a = new A();

  _c._a = _b._a;
}

A exists in both classes B and C and I want to make the instance of class A that is in C equal to that instance of class A that is in B.  I basically want to make sure that both B and C have the same exact copy of A.

When I try to run this, however, I get a SerializationException saying that class A is not marked as Serializable.  I know I've done stuff like this before and it's never wanted it to be serialized.  Why would it need this anyways?  I thought that was for xml serialization.

I did try adding the [Serializable] attribute to class A, and the exception obviously went away.  But after doing that, making changes to A inside of class B wouldn't then propagate to the instance of A inside of C... like they are now completely separate copies.

Any ideas?

Edit:  Didn't realize that this would matter before, but after some looking around I think it does.  Classes B and C inherit from the MarshalByRefObject class.  Maybe this will help figure it out.  I've updated the classes above.

LastEditorDisplayName: Adam Haile

OwnerDisplayName: Ray Booysen


问:
Why does this code produce an indent/syntax error
I am trying to have the user enter an 8 digit barcode. If the code is not 8 digits long, it prints an error message. If it is 8 digits long, it raises an error.</p>

```<code>def get_user_input():
    global total_price
    """ get input from user """
while len(str(GTIN))!=8:
    try:
        GTIN = int(input("input your gtin-8 number:"))
        if len(str(GTIN))!=8:
            print("make sure the length of the barcode is 8")
        else:
            print("make sure you enter a valid number")
        return GTIN
</code>```

答:
There actually several errors going on here:

Your indentation was being processed as the while loop being outside the function. Witespace in Python matters.

It is required to have an except with every try statement.

Additionally, GTIN was never initially defined, I fixed that.

Your new code:

```<code>def get_user_input():
    global total_price
    """ get input from user """
    GTIN = ""
    while True:
        try:
            GTIN = int(input("input your gtin-8 number:"))
            if len(str(GTIN)) == 8:
                break
            else:
                print("make sure the length of the barcode is 8")
        except:
            pass
    return GTIN
get_user_input()
</code>```

Body:
I am trying to have the user enter an 8 digit barcode. If the code is not 8 digits long, it prints an error message. If it is 8 digits long, it raises an error.

def get_user_input():
    global total_price
    """ get input from user """
while len(str(GTIN))!=8:
    try:
        GTIN = int(input("input your gtin-8 number:"))
        if len(str(GTIN))!=8:
            print("make sure the length of the barcode is 8")
        else:
            print("make sure you enter a valid number")
        return GTIN

Body:
There actually several errors going on here:

Your indentation was being processed as the while loop being outside the function. Witespace in Python matters.

It is required to have an except with every try statement.

Additionally, GTIN was never initially defined, I fixed that.

Your new code:

def get_user_input():
    global total_price
    """ get input from user """
    GTIN = ""
    while True:
        try:
            GTIN = int(input("input your gtin-8 number:"))
            if len(str(GTIN)) == 8:
                break
            else:
                print("make sure the length of the barcode is 8")
        except:
            pass
    return GTIN
get_user_input()


问:
Edit code of page on Wordpress
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

```<code><div class="authorimage">
   <a href="https://www.codesyntax.com/eu/bloga/author/lfernandez">
       <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
       <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
   </a>

</div>
</code>```

But in the published page the following appears:

```<code> <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
 <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
</code>```

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.

答:
Use the "text" mode in the text editor (instead of "visual mode") when you use the text editor to create a new page. There you can write HTML code.

Or, in "visual mode", just use select the part of the text on which you want to put the link and clock on the link symbol (the chain icon) above the text editor.

Title: Edit code of page on Wordpress

Body:
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

But in the published page the following appears:

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.


问:
How to create htaccess redirect
When a user is typing below urls

```<code>http://www.oldwebsite.de/schnitz_krippen.php
http://www.oldwebsite/holzrohlinge.php
http://www.oldwebsite/neuheiten.php
http://www.oldwebsite/impressum.php
</code>```

I need these url redirect in to

```<code>http://www.newwebsite.de/impressum.php
</code>```

How it's possible with htaccess? I don't need to redirect the whole website. because some links of old website need to show. eg:http://www.oldwebsite/main.php

```<code>RewriteEngine on
RewriteOptions inherit
RewriteBase /

RewriteCond %{HTTP_HOST} ^www.oldwebsite.com$ [NC]
RewriteRule ^(.*)$ http://www.newwebsite.com/impressum.php [L]
</code>```

答:
I think this will help you</p>

```<code>RewriteEngine on
# Redirect to another domain: www.newwebsite.de.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)?newwebsite\.de$ [NC]
RewriteRule .* http://www.newwebsite.de%{REQUEST_URI} [R=301,L]
</code>```

Title: How to create htaccess redirect

Body:
When a user is typing below urls

http://www.oldwebsite.de/schnitz_krippen.php
http://www.oldwebsite/holzrohlinge.php
http://www.oldwebsite/neuheiten.php
http://www.oldwebsite/impressum.php

I need these url redirect in to

http://www.newwebsite.de/impressum.php

How it's possible with htaccess? I don't need to redirect the whole website. because some links of old website need to show. eg:http://www.oldwebsite/main.php

RewriteEngine on
RewriteOptions inherit
RewriteBase /

RewriteCond %{HTTP_HOST} ^www.oldwebsite.com$ [NC]
RewriteRule ^(.*)$ http://www.newwebsite.com/impressum.php [L]

Body:
I think this will help you

RewriteEngine on
# Redirect to another domain: www.newwebsite.de.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)?newwebsite\.de$ [NC]
RewriteRule .* http://www.newwebsite.de%{REQUEST_URI} [R=301,L]


问:
What is the best solution with high accuracy for location based mobile app
I need to implement an app that is need to watch location updates.
I have to solutions in my options:

use native app with java and access the GPS data

use JavaScript with location services to get location data

I'm not sure witch one is more reliable and precise.

P.S: I need the location data in each 10 sec.

答: In Android you can call function onLocationChanged more here : https://developer.android.com/reference/android/location/LocationListener.html Then build timer. Also instead of GPS you can use NETWORK_PROVIDER you will get location too but less accurate</p>


问:
How to get the total sum
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

```<code>enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}
</code>```

答:
Did you add them together? </p>

```<code>public void getTotalPower()
{
int sum=0;
   for (BigGun oneGun : gun)
   {
       sum+=oneGun.getNumberPower();
   }
  System.out.println(sum);
}
</code>```

Title: How to get the total sum

Body:
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}

Body:
Did you add them together?

public void getTotalPower()
{
int sum=0;
   for (BigGun oneGun : gun)
   {
       sum+=oneGun.getNumberPower();
   }
  System.out.println(sum);
}


问:
Write with js-xlsx gives "_fs is undefined" error
I'm trying to use https://github.com/SheetJS/js-xlsx to export some array data to a file.

I took an example and put up a jsfiddle here: https://jsfiddle.net/connyake/y8a9nb7r/

Is it even possible to do this without requirejs? If it is, how?

HTML:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.core.min.js"></script>
<button onclick="arrayToXlsx()">Export</button>
</code>```

JS:

```<code>function arrayToXlsx() {
    /* original data */
    var data = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar","0.3"], ["baz", null, "qux"]];
    var ws_name = "SheetJS";

    /* set up workbook objects -- some of these will not be required in the future */
    var wb = {};
    wb.Sheets = {};
    wb.Props = {};
    wb.SSF = {};
    wb.SheetNames = [];

    /* create worksheet: */
    var ws = {};

    /* the range object is used to keep track of the range of the sheet */
    var range = {s: {c:0, r:0}, e: {c:0, r:0 }};

    /* Iterate through each element in the structure */
    for(var R = 0; R !== data.length; ++R) {
      if(range.e.r < R) range.e.r = R;
      for(var C = 0; C !== data[R].length; ++C) {
        if(range.e.c < C) range.e.c = C;

        /* create cell object: .v is the actual data */
        var cell = { v: data[R][C] };
        if(cell.v === null) continue;

        /* create the correct cell reference */
        var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

        /* determine the cell type */
        if(typeof cell.v === 'number') cell.t = 'n';
        else if(typeof cell.v === 'boolean') cell.t = 'b';
        else cell.t = 's';

        /* add to structure */
        ws[cell_ref] = cell;
      }
    }
    ws['!ref'] = XLSX.utils.encode_range(range);

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    /* write file */
    XLSX.writeFile(wb, 'test.xlsx');
};
</code>```

答:
The xlsx library has two functions for writing to files write and writeFile. The writeFile equation implements the node fs module and is therefor intended to be used within the node environment. Alternatively write is implemented using client side javascript and might therefor be of greater use in your circumstance. i.e:

write(wb, {bookType: 'xlsx' , bookSST: false, type: 'binary'});

Body:
I'm trying to use https://github.com/SheetJS/js-xlsx to export some array data to a file.

I took an example and put up a jsfiddle here: https://jsfiddle.net/connyake/y8a9nb7r/

Is it even possible to do this without requirejs? If it is, how?

HTML:

<button onclick="arrayToXlsx()">Export</button>

JS:

function arrayToXlsx() {
    /* original data */
    var data = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar","0.3"], ["baz", null, "qux"]];
    var ws_name = "SheetJS";

    /* set up workbook objects -- some of these will not be required in the future */
    var wb = {};
    wb.Sheets = {};
    wb.Props = {};
    wb.SSF = {};
    wb.SheetNames = [];

    /* create worksheet: */
    var ws = {};

    /* the range object is used to keep track of the range of the sheet */
    var range = {s: {c:0, r:0}, e: {c:0, r:0 }};

    /* Iterate through each element in the structure */
    for(var R = 0; R !== data.length; ++R) {
      if(range.e.r < R) range.e.r = R;
      for(var C = 0; C !== data[R].length; ++C) {
        if(range.e.c < C) range.e.c = C;

        /* create cell object: .v is the actual data */
        var cell = { v: data[R][C] };
        if(cell.v === null) continue;

        /* create the correct cell reference */
        var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

        /* determine the cell type */
        if(typeof cell.v === 'number') cell.t = 'n';
        else if(typeof cell.v === 'boolean') cell.t = 'b';
        else cell.t = 's';

        /* add to structure */
        ws[cell_ref] = cell;
      }
    }
    ws['!ref'] = XLSX.utils.encode_range(range);

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    /* write file */
    XLSX.writeFile(wb, 'test.xlsx');
};


问:
Where does google cloud platform install wordpress when using template?
I have a google cloud compute engine instance with wordpress installed from their template. Where exactly do they install wordpress?</p>

答: Google Cloud Launcher installs Wordpress within var/www/html you can access this by SSH'ing onto your server.


问:
How to hint use of UIView subclass for compiler
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

```<code>- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}
</code>```

This is fine until I call a method of UIWebView's. For example...

```<code>[self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...leads to a compiler warning...

```<code>warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'
</code>```

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

```<code>[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

```<code>warning: property 'view' type does not match super class 'UIViewController' property type
</code>```

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

答:
As has been mentioned, while it is possible to do this, it may or may not be wise.

You could declare a category on UIView itself, suggesting that it may respond to the selectors you're trying to call. This could be done in the implementation file of your custom view controller.  It would look something like this:

```<code>@interface UIView (WebViewFakery)

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

@end
</code>```

You'd have to add all the UIWebView methods you're trying to call on view. Maybe not the most elegant solution, but another one to consider.

Body:
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}

This is fine until I call a method of UIWebView's. For example...

[self.view loadHTMLString:HTMLString baseURL:baseURL];

...leads to a compiler warning...

warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

warning: property 'view' type does not match super class 'UIViewController' property type

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

Body:
As has been mentioned, while it is possible to do this, it may or may not be wise.

You could declare a category on UIView itself, suggesting that it may respond to the selectors you're trying to call. This could be done in the implementation file of your custom view controller.  It would look something like this:

@interface UIView (WebViewFakery)

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

@end

You'd have to add all the UIWebView methods you're trying to call on view. Maybe not the most elegant solution, but another one to consider.