问:
SKStoreReviewController requestReview doesn't prompt for review
I want to use the new feature added in 10.3 to ask users for reviews. In the docs, apple states that when this method is called "a rating/review request view is displayed".

I am getting the rating view( where you can select how many stars to rate), but I am not able to write a review. I have to mention that I only tested in simulator.

Is this the correct behaviour?

答: In development mode the “Submit” button is disabled. Once your app is in the App Store, this button becomes active and the user is given the option to write a review after they hit “Submit”.</p>


来源: stackexchange

问:
The expected Ejabberd filter_packet function not being called
The ejabberd module I'm using, mod_pottymouth is not filtering messages as expected.  After adding logging I see a generic handler method being called instead of the one that does the actual filtering. Problem is, I am not able to parse the ejabberd message to ensure the proper function is called. Can anyone help?

```<code>on_filter_packet({_From, _To, {xmlel, <<"message">>, _Attrs, Els} = _Packet} = _Msg) ->
  %This is what should be called to filter messages, but is never called
  FilteredEls = filterMessageBodyElements(Els, []),
  {_From, _To, {xmlel, <<"message">>, _Attrs, FilteredEls}};
on_filter_packet(Msg) ->
 % This is what actually gets called
 Msg.
</code>```

This is using ejabberd 17.01

答: Have you tried using xmlel as record instead of tuple ?</p>

ContentLicense: CC BY-SA 3.0

Body:
The ejabberd module I'm using, mod_pottymouth is not filtering messages as expected.  After adding logging I see a generic handler method being called instead of the one that does the actual filtering. Problem is, I am not able to parse the ejabberd message to ensure the proper function is called. Can anyone help?

on_filter_packet({_From, _To, {xmlel, <<"message">>, _Attrs, Els} = _Packet} = _Msg) ->
  %This is what should be called to filter messages, but is never called
  FilteredEls = filterMessageBodyElements(Els, []),
  {_From, _To, {xmlel, <<"message">>, _Attrs, FilteredEls}};
on_filter_packet(Msg) ->
 % This is what actually gets called
 Msg.

This is using ejabberd 17.01


问:
Partial human detection in OpenCV 3
I am working on a human detection program using OpenCV using Python. I saw this very good example and I ran it on the samples it had. It can detect people regardless where they are facing and has decent overlap detection as well as blurred motion as well.

However, when I was running it on some images I had (mostly knee up, waist up, and chest up photos of people), I found out that the software doesn't quite detect people.

You can get the photos from this link.  This is the code I am using:

```<code>    # import the necessary packages
    from __future__ import print_function
    from imutils.object_detection import non_max_suppression
    from imutils import paths
    import numpy as np
    import argparse
    import imutils
    import cv2

    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--images", required=True, help="path to images directory")
    args = vars(ap.parse_args())

    # initialize the HOG descriptor/person detector
    hog = cv2.HOGDescriptor()
    hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

    # loop over the image paths
    imagePaths = list(paths.list_images(args["images"]))
    for imagePath in imagePaths:
            # load the image and resize it to (1) reduce detection time
            # and (2) improve detection accuracy
            image = cv2.imread(imagePath)
            image = imutils.resize(image, width=min(400, image.shape[1]))
            orig = image.copy()

            # detect people in the image
            (rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
                    padding=(8, 8), scale=1.05)

            # draw the original bounding boxes
            for (x, y, w, h) in rects:
                    cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)

            # apply non-maxima suppression to the bounding boxes using a
            # fairly large overlap threshold to try to maintain overlapping
            # boxes that are still people
            rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
            pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)

            # draw the final bounding boxes
            for (xA, yA, xB, yB) in pick:
                    cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)

            # show some information on the number of bounding boxes
            filename = imagePath[imagePath.rfind("/") + 1:]
            print("[INFO] {}: {} original boxes, {} after suppression".format(
                    filename, len(rects), len(pick)))

            # show the output images
            cv2.imshow("Before NMS", orig)
            cv2.imshow("After NMS", image)
            cv2.waitKey(0)
</code>```

It is pretty straightforward. It goes through the images, finds the people in it, then draws bounding rectangles. If rectangles overlap, they are joined together to prevent false positives and detecting more than 1 person in a single person.

However, as I mentioned above, the code fails to recognize people if parts of their feet aren't present.

Is there a way to make OpenCV recognize people who may only have partial of their body (knee up, waist up, chest up) present in a video? In my use case scenarios, I don't think it will be critical to look for arms and legs, as long as the torso and head is present, I should be able to see it.

答:
I found the haar upper body cascade. Though it may not work always (I'll post a new question regarding this), it's a good start.

Here's the code:

```<code>import numpy as np
import cv2

img = cv2.imread('path/to/img.jpg',0)

upperBody_cascade = cv2.CascadeClassifier('../path/to/haarcascade_upperbody.xml')

arrUpperBody = upperBody_cascade.detectMultiScale(img)
if arrUpperBody != ():
        for (x,y,w,h) in arrUpperBody:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        print 'body found'

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

But it's not as refined as the solution I lifted off of pyimagesearch.

ContentLicense: CC BY-SA 4.0

Title: Partial human detection in OpenCV 3

Body:
I am working on a human detection program using OpenCV using Python. I saw this very good example and I ran it on the samples it had. It can detect people regardless where they are facing and has decent overlap detection as well as blurred motion as well.

However, when I was running it on some images I had (mostly knee up, waist up, and chest up photos of people), I found out that the software doesn't quite detect people.

You can get the photos from this link.  This is the code I am using:

    # import the necessary packages
    from __future__ import print_function
    from imutils.object_detection import non_max_suppression
    from imutils import paths
    import numpy as np
    import argparse
    import imutils
    import cv2

    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--images", required=True, help="path to images directory")
    args = vars(ap.parse_args())

    # initialize the HOG descriptor/person detector
    hog = cv2.HOGDescriptor()
    hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

    # loop over the image paths
    imagePaths = list(paths.list_images(args["images"]))
    for imagePath in imagePaths:
            # load the image and resize it to (1) reduce detection time
            # and (2) improve detection accuracy
            image = cv2.imread(imagePath)
            image = imutils.resize(image, width=min(400, image.shape[1]))
            orig = image.copy()

            # detect people in the image
            (rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
                    padding=(8, 8), scale=1.05)

            # draw the original bounding boxes
            for (x, y, w, h) in rects:
                    cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)

            # apply non-maxima suppression to the bounding boxes using a
            # fairly large overlap threshold to try to maintain overlapping
            # boxes that are still people
            rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
            pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)

            # draw the final bounding boxes
            for (xA, yA, xB, yB) in pick:
                    cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)

            # show some information on the number of bounding boxes
            filename = imagePath[imagePath.rfind("/") + 1:]
            print("[INFO] {}: {} original boxes, {} after suppression".format(
                    filename, len(rects), len(pick)))

            # show the output images
            cv2.imshow("Before NMS", orig)
            cv2.imshow("After NMS", image)
            cv2.waitKey(0)

It is pretty straightforward. It goes through the images, finds the people in it, then draws bounding rectangles. If rectangles overlap, they are joined together to prevent false positives and detecting more than 1 person in a single person.

However, as I mentioned above, the code fails to recognize people if parts of their feet aren't present.

Is there a way to make OpenCV recognize people who may only have partial of their body (knee up, waist up, chest up) present in a video? In my use case scenarios, I don't think it will be critical to look for arms and legs, as long as the torso and head is present, I should be able to see it.

Body:
I found the haar upper body cascade. Though it may not work always (I'll post a new question regarding this), it's a good start.

Here's the code:

import numpy as np
import cv2

img = cv2.imread('path/to/img.jpg',0)

upperBody_cascade = cv2.CascadeClassifier('../path/to/haarcascade_upperbody.xml')

arrUpperBody = upperBody_cascade.detectMultiScale(img)
if arrUpperBody != ():
        for (x,y,w,h) in arrUpperBody:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        print 'body found'

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

But it's not as refined as the solution I lifted off of pyimagesearch.


问:
How can this Java code compile without error?
Can someone explain why does this Java code compile?</p>

```<code>public class Main {
     public static void main(String []args){
        System.out.println(foo(true));
        System.out.println(foo(false));
     }

     public static boolean foo(boolean value) {
         // this should make the compiler say something, at least complain a bit...
         return value ? true : null;
     }
}
</code>```

答:
What kind of conditional expression do we have (JLS 15.25)?

Clearly not a numeric conditional expression.

A boolean conditional expressions would require two operands of type boolean, which is violated by the 3rd operand being null

Ergo we have a reference conditional expression

For reference conditional expressions Table 15.25-E specifies that a combination of boolean (2nd) and null (3rd) determines the full expression to have type lub(Boolean,null)

For runtime evaluation this sentence provides the desired clarity:

At run time, the first operand expression of the conditional expression is evaluated first. If necessary, unboxing conversion is performed on the result.

Depending on the first operand, one of the following happens:

true is autoboxed to Boolean, or

null is taken, which is already compatible to Boolean (based on JLS-4.1) (this is not autoboxing as claimed by the other answer)

The resulting Boolean will be autounboxed, which in the second case will throw NullPointerException.

Body:
Can someone explain why does this Java code compile?

public class Main {
     public static void main(String []args){
        System.out.println(foo(true));
        System.out.println(foo(false));
     }

     public static boolean foo(boolean value) {
         // this should make the compiler say something, at least complain a bit...
         return value ? true : null;
     }
}


问:
Creating/Using Files with Python 3.6
I am trying to make something that would generate several random files and based on those files it determines the outcome of what happens (text based adventure game) and yes I want to use files due to the fact the game is supposed to be 'hack-able/mod-able.' For some reason trying to create the files in another directory gives me the error

FileNotFoundError: [Errno 2] No such file or directory: 'file0599265.txt'

```<code>import os
import os.path
import random as rand
os.chdir("C:\Program Files (x86)\File Stuff")
f = open('file' + str(rand.randint(1,1000000)) + '.txt', 'w')
f.write('Test')
f.close
</code>```

What must I do so that it will create that file? I really cannot nail the who change directory thing to make it where I want, but I will stick for this for now (The "C:\Program Files (x86)\File Stuff" was only made for testing purposes).

答:
Try to write the file where you are sure to have write permission, such as in a subfolder of your home: C:\Users\YOUR_USERNAME.

I had no problem running your code, outside of C:\Program Files (x86)\

Title: Creating/Using Files with Python 3.6

Body:
I am trying to make something that would generate several random files and based on those files it determines the outcome of what happens (text based adventure game) and yes I want to use files due to the fact the game is supposed to be 'hack-able/mod-able.' For some reason trying to create the files in another directory gives me the error

FileNotFoundError: [Errno 2] No such file or directory: 'file0599265.txt'

import os
import os.path
import random as rand
os.chdir("C:\Program Files (x86)\File Stuff")
f = open('file' + str(rand.randint(1,1000000)) + '.txt', 'w')
f.write('Test')
f.close

What must I do so that it will create that file? I really cannot nail the who change directory thing to make it where I want, but I will stick for this for now (The "C:\Program Files (x86)\File Stuff" was only made for testing purposes).


问:
How to pass the search parameters in the link to print
How to pass the search parameters in the link to print.

I have a method #index controller #TicketsController

```<code>def index
  @search = current_account.searches.find_by(id: params[:search_id])

  @q = policy_scope(Ticket).ransack(params[:q])

  if params[:q].blank? && params[:advanced_search].blank? || params[:q]&.to_unsafe_h&.length == 1 && params[:q][:s].present?
    @q.add_default_condition('status', 'in', 'open')
    session[:last_ticket_search] = nil
  else
    session[:last_ticket_search] = {q: params[:q]}
    if params[:advanced_search].present?
      session[:last_ticket_search].merge!(advanced_search: 't', selected_columns: params[:selected_columns])
      session[:last_ticket_search].merge!(params[:search_id].present? ? {search_id: params[:search_id]} : {commit: 'Apply'})
    end
  end

  @selected_columns = selected_columns
  @tickets = @q.result.select('tickets.*')
                      .includes(:account, :ticket_responses, :assignee, :tags)
                      .order('tickets.created_at DESC')
                      .paginate(page: params[:page], per_page: per_page('tickets'))
end
</code>```

I need to make a page for printing all objects.
For this I made the link Print in `tickets/index.html.erb

```<code><a class="btn btn-primary print-button" href="<%= tickets_path(variant: :print) %>" target="_blank" title="Print ticket" data-tooltip data-placement="bottom">
  <i class="fa fa-print"></i>
</a>
</code>```

The point is that if you click on it will open the whole list of objects here, all is well. But if I use search, I will generate the list of all objects. I need a list of objects I defined in the search. So how do I pass a  search parameter in the controller to generate the print page?

I tried that.

```<code><%= tickets_path(q: params[:q], advanced_search: params[:advanced_search], variant: :print) %>
</code>```

But the controller does not share parameters and accepts a string.

need: "utf8"=>"✓", "q"=><ActionController::Parameters {"assignee_id_eq"=>"", "status_in"=>"closed", "ticket_type_eq"=>"", "simple_search"=>""}

I get: {"q"=>"assignee_id_eq=&simple_search=&status_in=closed&ticket_type_eq=", "variant"=>"print", "controller"=>"tickets", "action"=>"index"}

答:
Just create an instance variable with your required parameters parsed into a hash which will be available in the view:

```<code>def new
  @search_params = Rack::Utils.parse_nested_query params[:q]
  ...
end
</code>```

and in the view:

```<code><%= tickets_path(q: @search_params[:q], advanced_search: params[:advanced_search], variant: :print) %>
</code>```

Body:
How to pass the search parameters in the link to print.

I have a method #index controller #TicketsController

def index
  @search = current_account.searches.find_by(id: params[:search_id])

  @q = policy_scope(Ticket).ransack(params[:q])

  if params[:q].blank? && params[:advanced_search].blank? || params[:q]&.to_unsafe_h&.length == 1 && params[:q][:s].present?
    @q.add_default_condition('status', 'in', 'open')
    session[:last_ticket_search] = nil
  else
    session[:last_ticket_search] = {q: params[:q]}
    if params[:advanced_search].present?
      session[:last_ticket_search].merge!(advanced_search: 't', selected_columns: params[:selected_columns])
      session[:last_ticket_search].merge!(params[:search_id].present? ? {search_id: params[:search_id]} : {commit: 'Apply'})
    end
  end

  @selected_columns = selected_columns
  @tickets = @q.result.select('tickets.*')
                      .includes(:account, :ticket_responses, :assignee, :tags)
                      .order('tickets.created_at DESC')
                      .paginate(page: params[:page], per_page: per_page('tickets'))
end

I need to make a page for printing all objects.
For this I made the link Print in `tickets/index.html.erb

<a class="btn btn-primary print-button" href="<%= tickets_path(variant: :print) %>" target="_blank" title="Print ticket" data-tooltip data-placement="bottom">

The point is that if you click on it will open the whole list of objects here, all is well. But if I use search, I will generate the list of all objects. I need a list of objects I defined in the search. So how do I pass a  search parameter in the controller to generate the print page?

I tried that.

<%= tickets_path(q: params[:q], advanced_search: params[:advanced_search], variant: :print) %>

But the controller does not share parameters and accepts a string.

need: "utf8"=>"✓", "q"=><ActionController::Parameters {"assignee_id_eq"=>"", "status_in"=>"closed", "ticket_type_eq"=>"", "simple_search"=>""}

I get: {"q"=>"assignee_id_eq=&simple_search=&status_in=closed&ticket_type_eq=", "variant"=>"print", "controller"=>"tickets", "action"=>"index"}

Body:
Just create an instance variable with your required parameters parsed into a hash which will be available in the view:

def new
  @search_params = Rack::Utils.parse_nested_query params[:q]
  ...
end

and in the view:

<%= tickets_path(q: @search_params[:q], advanced_search: params[:advanced_search], variant: :print) %>


问:
Can't deploy to Elastic Beanstalk: ERROR_FILE_IN_USE
My Elastic Beanstalk installation won't deploy through Visual Studio due to this error:

2016-07-01 20:45:02,627 ERROR 1 AWSBeanstalkCfnDeploy.DeploymentUtils - Exception during deployment.
Microsoft.Web.Deployment.DeploymentDetailedClientServerException: Web Deploy cannot modify the file 'msvcr100.dll' on the destination because it is locked by an external process.  In order to allow the publish operation to succeed, you may need to either restart your application to release the lock, or use the AppOffline rule handler for .Net applications on your next publish attempt.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_FILE_IN_USE.

The link suggests that I create a pubxml file with settings to enable AppOffline, but this file only seems to be relevant for publishing through VS using the built-in Publish feature. I haven't found any documentation suggesting that this will work for AWS.

How do I enable AppOffline for an Elastic Beanstalk deployment?

Thanks!

答:
After quite a lot of experimentation, the only working solution I could find for this problem was

```<code>// in Project/.ebextensions/reset.config

container_commands:
  00_nuke:
    command: IISReset
    waitAfterCompletion: 0
</code>```

The cost was about 4 seconds of downtime (on a t2.micro), during which you get a 503, which certainly isn't great.

Note there's a Github issue for this (open at the time of writing).

If you have the option, deploy your service to Azure rather than AWS and there are configuration options to work around the issue (such as an environment variable MSDEPLOY_RENAME_LOCKED_FILES) - related Azure specific question.

Body:
After quite a lot of experimentation, the only working solution I could find for this problem was

// in Project/.ebextensions/reset.config

container_commands:
  00_nuke:
    command: IISReset
    waitAfterCompletion: 0

The cost was about 4 seconds of downtime (on a t2.micro), during which you get a 503, which certainly isn't great.

Note there's a Github issue for this (open at the time of writing).

If you have the option, deploy your service to Azure rather than AWS and there are configuration options to work around the issue (such as an environment variable MSDEPLOY_RENAME_LOCKED_FILES) - related Azure specific question.


问:
How to stop "if(isset($_POST['form-submit']))" from redirecting after clicking Submit?
I have a serious problem about Password Recovery Program these days.  While I was programing an if(isset($_POST['pass-submit'])) on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. When someone clicks Submit button of the form, it should stay at the same page for processing, i.e. on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. But instead it takes us to reset.php where no code would work because the variable recoverykey is empty. Even after using header("Location: reset.php?recoverykey=$recovery_code");, nothing worked.
I want it to stay where it was even after clicking the Submit button so that PHP can check whether the Password and Confirm Password fields where same or incorrect according to the program.

Here's all my code in reset.php:

<?php
    ob_start();
    session_start();
?>
<!DOCTYPE html>

                <meta name="robots" content="noindex" />
                <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
                <title>Reset Password</title>

<?php
    include('db-config.php');
    function show_change_pass_form(){
        ?>
                <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Change your Password

                    <?php echo $passError ?><input type="password" placeholder="New Password" name="new-pass" required />
                    <?php echo $Con_passError; ?><input type="password" placeholder="Confirm Password" name="confirm-new-pass" required />
                    <input type="submit" value="Change Password" name="pass-submit" />
                </form>
        <?php
    }
    $recovery_code = $_GET['recoverykey'];
    if(empty($recovery_code)){
        echo 'Looks like you landed elsewhere.';
    }
    $sql = "SELECT * FROM RegisteredMembers WHERE RecoveryCode='$recovery_code'";
    $result = mysql_query($sql);
    if($result){
        $count = mysql_num_rows($result);
        if($count==1){

            if( isset($_POST['pass-submit']) ){

               header("Location: reset.php?recoverykey=$recovery_code");

                $pass = $_POST['new-pass'];
                $Con_pass = $_POST['confirm-new-pass'];

                    // Confirmation
                        if($pass==$Con_pass){
                            $sql1 = "UPDATE RegisteredMembers SET password = '$pass' WHERE RecoveryCode = '$recovery_code'";
                            $output = mysql_query($sql1);
                            echo $output;
                            $error = false;
                            $passError = "Password successfully changed. Feel free to Log In.";
                        } else if(!($pass==$Con_pass)){
                            $error = true;
                            $Con_passError = "The Password isn't matching. Be sure you remember the New Password.";
                        } else if(empty($pass)){
                            $error = true;
                            $passError = "Please do not keep the password empty.";
                        } else if(empty($Con_pass)){
                            $error = true;
                            $Con_passError = "Please do not keep this field empty.";
                        }
            }
            show_change_pass_form();

        } else if($count==0) {
            echo "No such recovery code, please don't try Spamming around!";
        }
    }
?>
<?php ob_end_flush(); ?>```
</div>
</div>
</p>

<p>Here's my code in <code>forget.php</code> (I added it though its not much necessary):</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-html lang-html prettyprint-override"><code><?php

    ob_start();
    session_start();
    include('db-config.php');

    if(isset($_POST['forgot-submit'])){
        $recovery_user = $_POST['forgot-email'];
        $query = "SELECT * FROM RegisteredMembers WHERE userEmail='$recovery_user'";
        $output = mysql_query($query);
        $count = mysql_num_rows($output);
        $row = mysql_fetch_array($output);
        if($count==1){
            $error = false;

            // Mail the Recovery link
            $recovery_code = md5(uniqid(rand()));
            $mTo = $recovery_user;
            $mFrom = 'From: '.$website_details['name'].' Team '.'<'.$website_details['email'].'>';
            $mSubject = $website_details['name']." Account recovery Mail";
                // Message
                $mMsg[0] = "Hi ".$row['fname'].", \r\n";
                $mMsg[1] = "This is the password recovery email which you have requested just few minutes before. <b>(If you havn't requested, you may kindly ingnore this Email)</b>";
                $mMsg[2] = "Here's your Password Recovery Link. Clicking it would allow you to change your existing password into a new one.";
                $mFinMsg = $mMsg[0].$mMsg[1].$mMsg[2];
            $sendRecMail = mail( $mTo , $mSubject , $mFinMsg , $mFrom );

            // Add recovery code to Database
            $mysql = "UPDATE RegisteredMembers SET RecoveryCode='$recovery_code' WHERE userEmail='$recovery_user'";
            $result = mysql_query($mysql);
            if($result){
                $error = false;
                $forgotEmailMsg = "Thanks, Check your Email for recovering your password.";
            } else{
                echo "Looks like there's a Disturbance and Load on server. Try again later.";
            }
        } else if(strlen($recovery_user)==0){
            $error = true;
            $forgotEmailMsg = "Please do not leave this field empty.";
        } else{
            $error = true;
            $forgotEmailMsg = "No such Email found in Database.";
        }
    }

?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="robots" content="noindex" />
        <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
        <title>Password Recovery</title>
    </head>
    <body>
        <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
            <h3>Password Recovery</h3>
            <label><span class="text-danger"><?php echo $forgotEmailMsg; ?></span><input type="email" placeholder="Your registered Email" name="forgot-email" required /></label>
            <input type="submit" value="Next" name="forgot-submit" />
        </form>
    </body>
</html>
<?php ob_end_flush(); ?></code>```

Forget.php is all okay but may be you can refer something from it.

答:
Well I dont think you need to redirect the user using header function. In reset.php, in the form action, you should replace:

```<code><?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
</code>```

with:

```<code><?php echo $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']; ?>
</code>```

PHP_SELF only returns the script name but not the query string, so your page will not have recoverykey field in the url.

You should not use mysql_* functions, since the php-mysql extension is deprecated and has been removed from Php 7

Also ob_start(), ob_end_flush() and session_start() are not need in reset.php

Body:
I have a serious problem about Password Recovery Program these days.  While I was programing an if(isset($_POST['pass-submit'])) on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. When someone clicks Submit button of the form, it should stay at the same page for processing, i.e. on reset.php?recoverykey=6602f445b4736ef3363a31e05750022d. But instead it takes us to reset.php where no code would work because the variable recoverykey is empty. Even after using header("Location: reset.php?recoverykey=$recovery_code");, nothing worked.
I want it to stay where it was even after clicking the Submit button so that PHP can check whether the Password and Confirm Password fields where same or incorrect according to the program.

Here's all my code in reset.php:

<?php
    ob_start();
    session_start();
?>
<!DOCTYPE html>

                <meta name="robots" content="noindex" />
                <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
                <title>Reset Password</title>

<?php
    include('db-config.php');
    function show_change_pass_form(){
        ?>
                <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Change your Password

                    <?php echo $passError ?><input type="password" placeholder="New Password" name="new-pass" required />
                    <?php echo $Con_passError; ?><input type="password" placeholder="Confirm Password" name="confirm-new-pass" required />
                    <input type="submit" value="Change Password" name="pass-submit" />
                </form>
        <?php
    }
    $recovery_code = $_GET['recoverykey'];
    if(empty($recovery_code)){
        echo 'Looks like you landed elsewhere.';
    }
    $sql = "SELECT * FROM RegisteredMembers WHERE RecoveryCode='$recovery_code'";
    $result = mysql_query($sql);
    if($result){
        $count = mysql_num_rows($result);
        if($count==1){

            if( isset($_POST['pass-submit']) ){

               header("Location: reset.php?recoverykey=$recovery_code");

                $pass = $_POST['new-pass'];
                $Con_pass = $_POST['confirm-new-pass'];

                    // Confirmation
                        if($pass==$Con_pass){
                            $sql1 = "UPDATE RegisteredMembers SET password = '$pass' WHERE RecoveryCode = '$recovery_code'";
                            $output = mysql_query($sql1);
                            echo $output;
                            $error = false;
                            $passError = "Password successfully changed. Feel free to Log In.";
                        } else if(!($pass==$Con_pass)){
                            $error = true;
                            $Con_passError = "The Password isn't matching. Be sure you remember the New Password.";
                        } else if(empty($pass)){
                            $error = true;
                            $passError = "Please do not keep the password empty.";
                        } else if(empty($Con_pass)){
                            $error = true;
                            $Con_passError = "Please do not keep this field empty.";
                        }
            }
            show_change_pass_form();

        } else if($count==0) {
            echo "No such recovery code, please don't try Spamming around!";
        }
    }
?>
<?php ob_end_flush(); ?>

Here's my code in forget.php (I added it though its not much necessary):

<?php

    ob_start();
    session_start();
    include('db-config.php');

    if(isset($_POST['forgot-submit'])){
        $recovery_user = $_POST['forgot-email'];
        $query = "SELECT * FROM RegisteredMembers WHERE userEmail='$recovery_user'";
        $output = mysql_query($query);
        $count = mysql_num_rows($output);
        $row = mysql_fetch_array($output);
        if($count==1){
            $error = false;

            // Mail the Recovery link
            $recovery_code = md5(uniqid(rand()));
            $mTo = $recovery_user;
            $mFrom = 'From: '.$website_details['name'].' Team '.'<'.$website_details['email'].'>';
            $mSubject = $website_details['name']." Account recovery Mail";
                // Message
                $mMsg[0] = "Hi ".$row['fname'].", \r\n";
                $mMsg[1] = "This is the password recovery email which you have requested just few minutes before. (If you havn't requested, you may kindly ingnore this Email)";
                $mMsg[2] = "Here's your Password Recovery Link. Clicking it would allow you to change your existing password into a new one.";
                $mFinMsg = $mMsg[0].$mMsg[1].$mMsg[2];
            $sendRecMail = mail( $mTo , $mSubject , $mFinMsg , $mFrom );

            // Add recovery code to Database
            $mysql = "UPDATE RegisteredMembers SET RecoveryCode='$recovery_code' WHERE userEmail='$recovery_user'";
            $result = mysql_query($mysql);
            if($result){
                $error = false;
                $forgotEmailMsg = "Thanks, Check your Email for recovering your password.";
            } else{
                echo "Looks like there's a Disturbance and Load on server. Try again later.";
            }
        } else if(strlen($recovery_user)==0){
            $error = true;
            $forgotEmailMsg = "Please do not leave this field empty.";
        } else{
            $error = true;
            $forgotEmailMsg = "No such Email found in Database.";
        }
    }

?>
<!DOCTYPE html>

        <meta name="robots" content="noindex" />
        <link rel="stylesheet" type="text/css" href="assets/scripts/css/styles.css" />
        <title>Password Recovery</title>

        <form class="iqform" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

Password Recovery

            <?php echo $forgotEmailMsg; ?><input type="email" placeholder="Your registered Email" name="forgot-email" required />
            <input type="submit" value="Next" name="forgot-submit" />
        </form>

<?php ob_end_flush(); ?>

Forget.php is all okay but may be you can refer something from it.

Body:
Well I dont think you need to redirect the user using header function. In reset.php, in the form action, you should replace:

<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>

with:

<?php echo $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']; ?>

PHP_SELF only returns the script name but not the query string, so your page will not have recoverykey field in the url.

You should not use mysql_* functions, since the php-mysql extension is deprecated and has been removed from Php 7

Also ob_start(), ob_end_flush() and session_start() are not need in reset.php


问:
Bash Script that loops command line arguments
I want to write a bash script that continually runs a program over and over incrementing the first four digits by one each time until the output of the program changes from one thing to another.

For example:

./exampleProgram userName 0000-4567-4561-4564

output: Wrong

./exampleProgram userName 0001-4567-4561-4564

output: Wrong

./exampleProgram userName 0002-4567-4561-4564

output: Correct

-Loop terminates

The last three sets of four digits will stay constant, it's only the first four that change so the worst case scenario is about 10,000 loops.

答:
Just loop over the integers, and use something like printf to produce a correctly formatted argument. For example

```<code> for ((i=0; i < 10000; i++)); do
     printf -v sn '%04d-4567-4561-4564' "$i"
     ./exampleProgram userName "$sn"
 done
</code>```

Body:
Just loop over the integers, and use something like printf to produce a correctly formatted argument. For example

 for ((i=0; i < 10000; i++)); do
     printf -v sn '%04d-4567-4561-4564' "$i"
     ./exampleProgram userName "$sn"
 done


问:
Deserializing XML with different Namespaces UWP
I have following XML-Data:

```<code><?xml version="1.0"?>
  <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
    <e:property>
      <LastChange>
        <Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/">
          <InstanceID val="0">
            <RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/>
            <Volume channel="Master" val="100"/>
            <Mute channel="Master" val="0"/>
            <RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/>
          </InstanceID>
        </Event>
      </LastChange>
    </e:property>
  </e:propertyset>
</code>```

And here are my classes:

```<code>[XmlRoot("propertyset", Namespace = "urn:schemas-upnp-org:event-1-0")]
public class EventPropertySet
{
    [XmlElement("property")]
    public List<EventProperty> Properties { get; set; }
}

public class EventProperty
{
    [XmlElement("LastChange")]
    public string LastChange { get; set; }

    [XmlElement("SinkProtocolInfo")]
    public string SinkProtocolInfo { get; set; }

    [XmlElement("IndexerStatus")]
    public string IndexerStatus { get; set; }

    [XmlElement("SystemUpdateID")]
    public string SystemUpdateID { get; set; }
}
</code>```

Now when I try to deserialize the XML-Data 'LastChange' is always 'null'.
When I modify the class 'EventProperty' like so:

```<code>public class EventProperty
{
    [XmlElement("LastChange", Namespae = "")]
    public string LastChange { get; set; }

    [XmlElement("SinkProtocolInfo", Namespae = "")]
    public string SinkProtocolInfo { get; set; }

    [XmlElement("IndexerStatus", Namespae = "")]
    public string IndexerStatus { get; set; }

    [XmlElement("SystemUpdateID", Namespae = "")]
    public string SystemUpdateID { get; set; }
}
</code>```

The deserialization throws an exception:
XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements. Line 1, position 103.

Any ideas what I should do?

答:
Sorry, I found the problem. The data behind "LastChange" is normaly a parsed XML-Structure (like this:)

```<code><LastChange><Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"><InstanceID val="0"><RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/><Volume channel="Master" val="100"/><Mute channel="Master" val="0"/><RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/></InstanceID></Event></LastChange>
</code>```

Now when I don't do the "DeParse" with WebUtility.HtmlDecode, everythings works fine.

Body:
I have following XML-Data:

<?xml version="1.0"?>
  <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
    <e:property>
      <LastChange>
        <Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/">
          <InstanceID val="0">
            <RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/>
            <Volume channel="Master" val="100"/>
            <Mute channel="Master" val="0"/>
            <RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/>
          </InstanceID>
        </Event>
      </LastChange>
    </e:property>
  </e:propertyset>

And here are my classes:

[XmlRoot("propertyset", Namespace = "urn:schemas-upnp-org:event-1-0")]
public class EventPropertySet
{
    [XmlElement("property")]
    public List<EventProperty> Properties { get; set; }
}

public class EventProperty
{
    [XmlElement("LastChange")]
    public string LastChange { get; set; }

    [XmlElement("SinkProtocolInfo")]
    public string SinkProtocolInfo { get; set; }

    [XmlElement("IndexerStatus")]
    public string IndexerStatus { get; set; }

    [XmlElement("SystemUpdateID")]
    public string SystemUpdateID { get; set; }
}

Now when I try to deserialize the XML-Data 'LastChange' is always 'null'.
When I modify the class 'EventProperty' like so:

public class EventProperty
{
    [XmlElement("LastChange", Namespae = "")]
    public string LastChange { get; set; }

    [XmlElement("SinkProtocolInfo", Namespae = "")]
    public string SinkProtocolInfo { get; set; }

    [XmlElement("IndexerStatus", Namespae = "")]
    public string IndexerStatus { get; set; }

    [XmlElement("SystemUpdateID", Namespae = "")]
    public string SystemUpdateID { get; set; }
}

The deserialization throws an exception:
XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements. Line 1, position 103.

Any ideas what I should do?

Body:
Sorry, I found the problem. The data behind "LastChange" is normaly a parsed XML-Structure (like this:)

<LastChange>&lt;Event xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/RCS/&quot;&gt;&lt;InstanceID val=&quot;0&quot;&gt;&lt;RoomVolumes val=&quot;uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100&quot;/&gt;&lt;Volume channel=&quot;Master&quot; val=&quot;100&quot;/&gt;&lt;Mute channel=&quot;Master&quot; val=&quot;0&quot;/&gt;&lt;RoomMutes val=&quot;uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0&quot;/&gt;&lt;/InstanceID&gt;&lt;/Event&gt;</LastChange>

Now when I don't do the "DeParse" with WebUtility.HtmlDecode, everythings works fine.


问:
Maintaining persistent connections between multiple invocations of a Cloud Function
I am currently in the process of moving my firebase-queue workers to Cloud Functions for Firebase. One of the workers I have send push notifications to devices via APNS and GCM. For sending push notifications via APNS, I am using library node-apn in which I create a persistent connection to the APNS using

const apnConnection = new apn.Connection(connectionOptions);

Then I can just keep using the apnConnection to send push notification to devices whenever I receive a task to send one without needing to recreate it every time.

apnConnection.pushNotification(pushNotification, device);

I wanted to ask if such a persistent connection would hold between multiple of invocation of a Firebase Function also or would I need to create this connection and shut it down for every invocation of the Firebase Function. My Firebase Function would look something like

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(firebaseConfig);

const apnConnection = new apn.Connection(connectionOptions);

exports.verifyCode = functions.database.ref('/tasks/sendPushNotification/{taskId}')
  .onWrite(event => {
    const taskSnapshot = event.data
    if(!taskSnapshot.exists()) {
      return
    }
    const task = taskSnapshot.val()

    // Create pushNotification and device from the task

    return apnConnection.pushNotification(pushNotification, device);
  })
</code>```

I think it comes down to whether the functions can maintain some state between invocations or are they more like AWS lambda functions which are completely stateless and since we only initialize the admin SDK once, I think it is maintaining some sort of state between invocations but I wanted to check before I move over the code.

答: While most often your functions will be invoked within the same container, you cannot rely on this. Containers may be recycled or GCF might spin up extra containers in case your function gets invoked more than a single container can handle</p>

Body:
I am currently in the process of moving my firebase-queue workers to Cloud Functions for Firebase. One of the workers I have send push notifications to devices via APNS and GCM. For sending push notifications via APNS, I am using library node-apn in which I create a persistent connection to the APNS using

const apnConnection = new apn.Connection(connectionOptions);

Then I can just keep using the apnConnection to send push notification to devices whenever I receive a task to send one without needing to recreate it every time.

apnConnection.pushNotification(pushNotification, device);

I wanted to ask if such a persistent connection would hold between multiple of invocation of a Firebase Function also or would I need to create this connection and shut it down for every invocation of the Firebase Function. My Firebase Function would look something like

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(firebaseConfig);

const apnConnection = new apn.Connection(connectionOptions);

exports.verifyCode = functions.database.ref('/tasks/sendPushNotification/{taskId}')
  .onWrite(event => {
    const taskSnapshot = event.data
    if(!taskSnapshot.exists()) {
      return
    }
    const task = taskSnapshot.val()

    // Create pushNotification and device from the task

    return apnConnection.pushNotification(pushNotification, device);
  })

I think it comes down to whether the functions can maintain some state between invocations or are they more like AWS lambda functions which are completely stateless and since we only initialize the admin SDK once, I think it is maintaining some sort of state between invocations but I wanted to check before I move over the code.


问:
How to create a muc private chat room with existing room name?
I can create a muc room. But if i gave the room name as existing one in the database, the server rejects it.So is it possible to create two rooms with same name in ejabberd server(MYSQl backend)?

If possible, then what are the consequences? For example, i created two rooms with unique name say "newGroupChat" and same user list(user1, user2). How can ejabberd identifies it? If i send  messages in "newGroupChat", does those messages appear in one room or both of the rooms.

答:
I can create a muc room. But if i gave the room name as existing one
  in the database, the server rejects it.So is it possible to create two
  rooms with same name in ejabberd server(MYSQl backend)?

No.It is not possible to create two room with same name in a host in ejabberd(as per XEP-45,too).


问:
Cannot load obfuscated assembly
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

```<code>// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}
</code>```

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.

答:
Are your assemblies strong named or Authenticode signed?  Obfuscation changes the structure of the assemblies and in order to use them after obfuscation you need to resign them.

The commercial versions of Dotfuscator supports the resigning of assemblies (both strong name and Authenticode) while if you are using the free Community Edition you will need to resign as a post build step in Dotfuscator.

ContentLicense: CC BY-SA 2.5

Title: Cannot load obfuscated assembly

Body:
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.


问:
Sending Files over IpV6
I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.

sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.

Here is my code:

```<code>Public Class Form1
Private nSockets As ArrayList

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim IPHost As IPHostEntry
    IPHost = Dns.GetHostByName(Dns.GetHostName())
    lblStatus.Text = "My IP address is " +
 IPHost.AddressList(0).ToString()
    nSockets = New ArrayList()
    Dim thdListener As New Thread(New ThreadStart _
    (AddressOf listenerThread))
    thdListener.Start()
End Sub

Public Sub listenerThread()

    Control.CheckForIllegalCrossThreadCalls = False
    Dim tcpListener As New TcpListener(7080)
    Dim handlerSocket As Socket
    Dim thdstHandler As ThreadStart
        Dim thdHandler As Thread
        tcpListener.Start()
        Do
            handlerSocket = tcpListener.AcceptSocket()
            If handlerSocket.Connected Then
                lbConnections.Items.Add(
                handlerSocket.RemoteEndPoint.ToString() +
                "connected.")
                SyncLock (Me)
                    nSockets.Add(handlerSocket)
                End SyncLock
                thdstHandler = New ThreadStart(AddressOf _
                handlerThread)
                thdHandler = New Thread(thdstHandler)
                thdHandler.Start()
            End If
        Loop
End Sub

Public Sub handlerThread()

        Dim handlerSocket As Socket
        handlerSocket = nSockets(nSockets.Count - 1)
    Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
    Dim blockSize As Int16 = 16
        Dim thisRead As Int16
        Dim dataByte(blockSize) As Byte
        SyncLock Me
            ' Only one process can access the
            ' same file at any given time
            Dim fileStream As Stream
            fileStream = File.OpenWrite("C:\Whatever.file")
            While (True)
                thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
                fileStream.Write(dataByte, 0, thisRead)
                If thisRead = 0 Then Exit While
            End While
            fileStream.Close()
            networkStream.Close()
        End SyncLock
        lbConnections.Items.Add("File Written")
    handlerSocket = Nothing
End Sub
</code>```

How do i make it IPv6 capable?

Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.

```<code>Private Sub Sendfile()
    Dim filebuffer As Byte()
    Dim fileStream As Stream
    fileStream = File.OpenRead(tbFilename.Text)
    ' Alocate memory space for the file
    ReDim filebuffer(fileStream.Length)
    fileStream.Read(filebuffer, 0, fileStream.Length)
    ' Open a TCP/IP Connection and send the data
    Dim clientSocket As New TcpClient(tbServer.Text, 7080)
    Dim networkStream As NetworkStream
    networkStream = clientSocket.GetStream()
    networkStream.Write(filebuffer, 0, fileStream.Length)
    networkStream.Close()
End Sub
</code>```

答:
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.

You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.

```<code>Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)
</code>```

As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.

Title: Sending Files over IpV6

Body:
I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.

sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.

Here is my code:

Public Class Form1
Private nSockets As ArrayList

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim IPHost As IPHostEntry
    IPHost = Dns.GetHostByName(Dns.GetHostName())
    lblStatus.Text = "My IP address is " +
 IPHost.AddressList(0).ToString()
    nSockets = New ArrayList()
    Dim thdListener As New Thread(New ThreadStart _
    (AddressOf listenerThread))
    thdListener.Start()
End Sub

Public Sub listenerThread()

    Control.CheckForIllegalCrossThreadCalls = False
    Dim tcpListener As New TcpListener(7080)
    Dim handlerSocket As Socket
    Dim thdstHandler As ThreadStart
        Dim thdHandler As Thread
        tcpListener.Start()
        Do
            handlerSocket = tcpListener.AcceptSocket()
            If handlerSocket.Connected Then
                lbConnections.Items.Add(
                handlerSocket.RemoteEndPoint.ToString() +
                "connected.")
                SyncLock (Me)
                    nSockets.Add(handlerSocket)
                End SyncLock
                thdstHandler = New ThreadStart(AddressOf _
                handlerThread)
                thdHandler = New Thread(thdstHandler)
                thdHandler.Start()
            End If
        Loop
End Sub

Public Sub handlerThread()

        Dim handlerSocket As Socket
        handlerSocket = nSockets(nSockets.Count - 1)
    Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
    Dim blockSize As Int16 = 16
        Dim thisRead As Int16
        Dim dataByte(blockSize) As Byte
        SyncLock Me
            ' Only one process can access the
            ' same file at any given time
            Dim fileStream As Stream
            fileStream = File.OpenWrite("C:\Whatever.file")
            While (True)
                thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
                fileStream.Write(dataByte, 0, thisRead)
                If thisRead = 0 Then Exit While
            End While
            fileStream.Close()
            networkStream.Close()
        End SyncLock
        lbConnections.Items.Add("File Written")
    handlerSocket = Nothing
End Sub

How do i make it IPv6 capable?

Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.

Private Sub Sendfile()
    Dim filebuffer As Byte()
    Dim fileStream As Stream
    fileStream = File.OpenRead(tbFilename.Text)
    ' Alocate memory space for the file
    ReDim filebuffer(fileStream.Length)
    fileStream.Read(filebuffer, 0, fileStream.Length)
    ' Open a TCP/IP Connection and send the data
    Dim clientSocket As New TcpClient(tbServer.Text, 7080)
    Dim networkStream As NetworkStream
    networkStream = clientSocket.GetStream()
    networkStream.Write(filebuffer, 0, fileStream.Length)
    networkStream.Close()
End Sub

Body:
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.

You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.

Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)

As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.


问:
Docker compose, set local volume mapping with version 3
Probably simple, but I dont find any thing about this. My composer config file (version 3), define two volumes to be shared with others services :

```<code>version: "3"
  services:
    nginx:
      build: docker/nginx
      ports:
        - "80:80"
      volumes:
        - config:/etc/nginx/conf.d
        - data:/var/http
      networks:
        - default
      container_name: nginx

networks:
  default:

volumes:
  config:
  data:
</code>```

How to set/attach the local directories (ex. d:/nginx/etc, d:/nginx/http) mapped to this volumes on the config file (or the docker-compose up command) ?

答:
You may try to replace your volumes lines this way :

data:/var/http -> path/to/local/dir:/var/http

Moreover assuming that you are running Windows, it should look like this :

```<code>- //d/nginx/etc:/etc/nginx/conf.d
- //d/nginx/http:/var/http
</code>```

Then remove the global volumes section.

Body:
Probably simple, but I dont find any thing about this. My composer config file (version 3), define two volumes to be shared with others services :

version: "3"
  services:
    nginx:
      build: docker/nginx
      ports:
        - "80:80"
      volumes:
        - config:/etc/nginx/conf.d
        - data:/var/http
      networks:
        - default
      container_name: nginx

networks:
  default:

volumes:
  config:
  data:

How to set/attach the local directories (ex. d:/nginx/etc, d:/nginx/http) mapped to this volumes on the config file (or the docker-compose up command) ?

Body:
You may try to replace your volumes lines this way :

data:/var/http -> path/to/local/dir:/var/http

Moreover assuming that you are running Windows, it should look like this :

- //d/nginx/etc:/etc/nginx/conf.d
- //d/nginx/http:/var/http

Then remove the global volumes section.


问:
How to access classes with on one instance?
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

```<code>generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
</code>```

How do I do this in the best possible way?

答:
You can use inheritance and create a class that (eventually) inherits from all of them, thus inheriting their methods. Or you can make them inherit from each other (this way you'll have to use the service class that inherits from both, as it would have all the methods that can be inherited).

To put it very simply, it can go like this using inheritance (I assume the service classes were not inheriting from anything until now):

```<code>public class ServiceClassA
{
  //Certain Methods
}

public class ServiceClassB : ServiceClassA
{
  //Other methods, this class also has ServiceClassA methods
}

public class ServiceClassC : ServiceClassB
{
  //Even more methods, this class also has ServiceClassA and ServiceClassB methods
}

//... and so on
</code>```

Assuming the lowest class in the inheritance tree is ServiceClassC for example, you only need a ServiceClassC object and you'll be able to access the needed (inherited) methods.

Body:
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

generalService.AbcService.MethodName();
generalService.AbcService.MethodName();

How do I do this in the best possible way?

Body:
You can use inheritance and create a class that (eventually) inherits from all of them, thus inheriting their methods. Or you can make them inherit from each other (this way you'll have to use the service class that inherits from both, as it would have all the methods that can be inherited).

To put it very simply, it can go like this using inheritance (I assume the service classes were not inheriting from anything until now):

public class ServiceClassA
{
  //Certain Methods
}

public class ServiceClassB : ServiceClassA
{
  //Other methods, this class also has ServiceClassA methods
}

public class ServiceClassC : ServiceClassB
{
  //Even more methods, this class also has ServiceClassA and ServiceClassB methods
}

//... and so on

Assuming the lowest class in the inheritance tree is ServiceClassC for example, you only need a ServiceClassC object and you'll be able to access the needed (inherited) methods.


问:
What will happen if exception thrown of a particular type don't have a catch block corresponding to that exception in c++
For the code given below. How will the code behave and why?</p>

```<code>    // code goes here..
    try {
         if(a==0) throw "a is 0";
    }
    catch(int a) { ; }
    a = 19;
    //code goes here.....
</code>```

答:
Since you are throwing a string (aka const char*) but you are only catching values of type int, the exception will not be caught and will go on unwinding the function stack until it finds a try-block willing to catch your exception or it reaches main and aborts your program.

That is, if your catch block does not catch the thrown exception type it is as if it was not there.

Body:
For the code given below. How will the code behave and why?

    // code goes here..
    try {
         if(a==0) throw "a is 0";
    }
    catch(int a) { ; }
    a = 19;
    //code goes here.....


问:
Hide for desk top show for mobile css
I am trying to create separate page for mobile view it should be hidden for
 desk top see my css and html whats wrong in this code ?

Code:

```<code><form class="form-signin-login" method="post" id="login-form">
                    <input type="text" name="user_entered_id" id="user_entered_id" value="Email (or) Phone No" onblur="if(this.value=='') this.value='Email (or) Phone No'" onfocus="if(this.value =='Email (or) Phone No' ) this.value=''">
                     <input type="password" name="lgpassword" id="lgpassword" value="Password" onblur="if(this.value=='') this.value='Password'" onfocus="if(this.value =='Password' ) this.value=''">
                    <input type="submit" class="button" name="submit" value="Login">
            </form>

 <style>

body{
background-color:#000;}
    @media screen and (max-width:300px) {

.input[type=text], .input[type=password]{width: 100%;
padding: 12px 20px;
background-color:#000;
color:#fff;
outline:none;
border: none;
border-bottom: 1px solid #fff;

margin: 8px 0;
-webkit-box-shadow: 0 0 0px 1000px black inset;
-webkit-text-fill-color: white !important;

  }
 }

    </style>
</code>```

答:
You need to just add the following in to css

.form-signin-login { display: none;}
 @media screen and (max-width:300px) {
    .form-signin-login { display: inline;}
 }

Here is the working sample :https://jsfiddle.net/6sz8rnb2/1/

Title: Hide for desk top show for mobile css

Body:
I am trying to create separate page for mobile view it should be hidden for
 desk top see my css and html whats wrong in this code ?

Code:

<form class="form-signin-login" method="post" id="login-form">
                    <input type="text" name="user_entered_id" id="user_entered_id" value="Email (or) Phone No" onblur="if(this.value=='') this.value='Email (or) Phone No'" onfocus="if(this.value =='Email (or) Phone No' ) this.value=''">
                     <input type="password" name="lgpassword" id="lgpassword" value="Password" onblur="if(this.value=='') this.value='Password'" onfocus="if(this.value =='Password' ) this.value=''">
                    <input type="submit" class="button" name="submit" value="Login">
            </form>


问:
How get current Activity's name and store it to G class that extends Application
I want write dynamically Intent, so I want to write G.currentActivity instead of GSampleActivity.this.
G class extends Application.

I defined G class in application Tag that is before activity Tags:

答:
I don't understand why you need that... Besides, G.currentActivity is null in the shown code

Application class is a Context, so you don't need to store a static field.

Activity class is a Context, so you don't need to grab anything from the Application class.

You can use GSampleActivity.this within startActivity and keeping around static references to the current Activity is very brittle and asking for bugs and memory leaks.

P.S. Use Android Studio


问:
Matrix Transpose on RowMatrix in Spark
Suppose I have a RowMatrix.

How can I transpose it. The API documentation does not seem to have a transpose method.

The Matrix has the transpose() method. But it is not distributed. If I have a large matrix greater that the memory how can I transpose it?

I have converted a RowMatrix to DenseMatrix as follows

```<code>DenseMatrix Mat = new DenseMatrix(m,n,MatArr);
</code>```

which requires converting the RowMatrix to JavaRDD and converting JavaRDD to an array.

Is there any other convenient way to do the conversion?

Thanks in advance

答:
For very large and sparse matrix, (like the one you get from text feature extraction), the best and easiest way is:

```<code>def transposeRowMatrix(m: RowMatrix): RowMatrix = {
  val indexedRM = new IndexedRowMatrix(m.rows.zipWithIndex.map({
    case (row, idx) => new IndexedRow(idx, row)}))
  val transposed = indexedRM.toCoordinateMatrix().transpose.toIndexedRowMatrix()
  new RowMatrix(transposed.rows
    .map(idxRow => (idxRow.index, idxRow.vector))
    .sortByKey().map(_._2))
}
</code>```

For not so sparse matrix, you can use BlockMatrix as the bridge as mentioned by aletapool's answer above.

However aletapool's answer misses a very important point: When you start from RowMaxtrix -> IndexedRowMatrix -> BlockMatrix -> transpose -> BlockMatrix -> IndexedRowMatrix -> RowMatrix, in the last step (IndexedRowMatrix -> RowMatrix), you have to do a sort. Because by default, converting from IndexedRowMatrix to RowMatrix, the index is simply dropped and the order will be messed up.

```<code>val data = Array(
  MllibVectors.sparse(5, Seq((1, 1.0), (3, 7.0))),
  MllibVectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
  MllibVectors.dense(4.0, 0.0, 0.0, 6.0, 7.0),
  MllibVectors.sparse(5, Seq((2, 2.0), (3, 7.0))))

val dataRDD = sc.parallelize(data, 4)

val testMat: RowMatrix = new RowMatrix(dataRDD)
testMat.rows.collect().map(_.toDense).foreach(println)

[0.0,1.0,0.0,7.0,0.0]
[2.0,0.0,3.0,4.0,5.0]
[4.0,0.0,0.0,6.0,7.0]
[0.0,0.0,2.0,7.0,0.0]

transposeRowMatrix(testMat).
  rows.collect().map(_.toDense).foreach(println)

[0.0,2.0,4.0,0.0]
[1.0,0.0,0.0,0.0]
[0.0,3.0,0.0,2.0]
[7.0,4.0,6.0,7.0]
[0.0,5.0,7.0,0.0]
</code>```

Title: Matrix Transpose on RowMatrix in Spark

Body:
Suppose I have a RowMatrix.

How can I transpose it. The API documentation does not seem to have a transpose method.

The Matrix has the transpose() method. But it is not distributed. If I have a large matrix greater that the memory how can I transpose it?

I have converted a RowMatrix to DenseMatrix as follows

DenseMatrix Mat = new DenseMatrix(m,n,MatArr);

which requires converting the RowMatrix to JavaRDD and converting JavaRDD to an array.

Is there any other convenient way to do the conversion?

Thanks in advance

Body:
For very large and sparse matrix, (like the one you get from text feature extraction), the best and easiest way is:

def transposeRowMatrix(m: RowMatrix): RowMatrix = {
  val indexedRM = new IndexedRowMatrix(m.rows.zipWithIndex.map({
    case (row, idx) => new IndexedRow(idx, row)}))
  val transposed = indexedRM.toCoordinateMatrix().transpose.toIndexedRowMatrix()
  new RowMatrix(transposed.rows
    .map(idxRow => (idxRow.index, idxRow.vector))
    .sortByKey().map(_._2))
}

For not so sparse matrix, you can use BlockMatrix as the bridge as mentioned by aletapool's answer above.

However aletapool's answer misses a very important point: When you start from RowMaxtrix -> IndexedRowMatrix -> BlockMatrix -> transpose -> BlockMatrix -> IndexedRowMatrix -> RowMatrix, in the last step (IndexedRowMatrix -> RowMatrix), you have to do a sort. Because by default, converting from IndexedRowMatrix to RowMatrix, the index is simply dropped and the order will be messed up.

val data = Array(
  MllibVectors.sparse(5, Seq((1, 1.0), (3, 7.0))),
  MllibVectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
  MllibVectors.dense(4.0, 0.0, 0.0, 6.0, 7.0),
  MllibVectors.sparse(5, Seq((2, 2.0), (3, 7.0))))

val dataRDD = sc.parallelize(data, 4)

val testMat: RowMatrix = new RowMatrix(dataRDD)
testMat.rows.collect().map(_.toDense).foreach(println)

[0.0,1.0,0.0,7.0,0.0]
[2.0,0.0,3.0,4.0,5.0]
[4.0,0.0,0.0,6.0,7.0]
[0.0,0.0,2.0,7.0,0.0]

transposeRowMatrix(testMat).
  rows.collect().map(_.toDense).foreach(println)

[0.0,2.0,4.0,0.0]
[1.0,0.0,0.0,0.0]
[0.0,3.0,0.0,2.0]
[7.0,4.0,6.0,7.0]
[0.0,5.0,7.0,0.0]


问:
How to call ALSA allocation #define from JNA?
I am trying to use JNA to call ALSA library functions from Java. I have been successful calling the basic open/close APIs snd_pcm_open() and snd_pcm_close() so I know I have the library loading OK and the basics right.

The first thing my application needs to do with ALSA is call snd_pcm_hw_params_alloca() to allocate a hardware parameter structure. But this is defined in the C header file as a macro, not a symbol:

```<code>#define snd_pcm_hw_params_alloca(ptr) __snd_alloca(ptr, snd_pcm_hw_params)
</code>```

For a C application it would be called like this:

```<code>snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(&params);
</code>```

and "params" is then passed to many subsequent API calls.

I am not much of a C expert, I cannot figure out exactly what this is doing. I expected a memory allocation of a structure, but the next line in the header file defines snd_pcm_hw_params like:

```<code>int snd_pcm_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t *params);
</code>```

So does that mean the macro is returning a pointer to a function? How can I model this in JPA?

答:
This function returns a pointer to a structure whose definition you do not know. (This is why you need all those accessor functions.)

alloca() allocates memory from the stack, which implies that it's freed as soon as the current function returns. This means that you cannot wrap this into a function to be called from Java.

Instead of snd_pcm_hw_params_alloca(), use snd_pcm_hw_params_malloc(), and don't forget to call snd_pcm_hw_params_free() at the correct time.

Body:
I am trying to use JNA to call ALSA library functions from Java. I have been successful calling the basic open/close APIs snd_pcm_open() and snd_pcm_close() so I know I have the library loading OK and the basics right.

The first thing my application needs to do with ALSA is call snd_pcm_hw_params_alloca() to allocate a hardware parameter structure. But this is defined in the C header file as a macro, not a symbol:

#define snd_pcm_hw_params_alloca(ptr) __snd_alloca(ptr, snd_pcm_hw_params)

For a C application it would be called like this:

snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(&params);

and "params" is then passed to many subsequent API calls.

I am not much of a C expert, I cannot figure out exactly what this is doing. I expected a memory allocation of a structure, but the next line in the header file defines snd_pcm_hw_params like:

int snd_pcm_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t *params);

So does that mean the macro is returning a pointer to a function? How can I model this in JPA?


问:
Getting last added item in Firebase using REST API
how can I get the last added item in Firebase using rest api? I understand that firebase support filter as stated here
https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-filtering but I cannot find how to do it.

When I access the api endpoint https://<firebaseproject>.firebaseio.com/messages.json?shallow=true I got this data:

```<code>{
  "-KgclTDbCWnm5pxV7efg" : true,
  "-KgclglfW7bxGSeX6rlg" : true,
  "-Kgclo4-fQzWu095vELL" : true,
  "-Kgcm-R-GTJR670Co9kl" : true
}
</code>```

答:
Since you're using push IDs, the most recently added item will have the last key. You can get this item by:</p>

```<code>https://<firebaseproject>.firebaseio.com/messages.json?orderBy="$key"&limitToLast=1
</code>```

Body:
how can I get the last added item in Firebase using rest api? I understand that firebase support filter as stated here
https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-filtering but I cannot find how to do it.

When I access the api endpoint https://<firebaseproject>.firebaseio.com/messages.json?shallow=true I got this data:

{
  "-KgclTDbCWnm5pxV7efg" : true,
  "-KgclglfW7bxGSeX6rlg" : true,
  "-Kgclo4-fQzWu095vELL" : true,
  "-Kgcm-R-GTJR670Co9kl" : true
}

Body:
Since you're using push IDs, the most recently added item will have the last key. You can get this item by:

https://<firebaseproject>.firebaseio.com/messages.json?orderBy="$key"&limitToLast=1


问:
Eclipse projects are not visible in workspace folder
The weird part is I can see my projects through package explorer.

I can also export them.

But when I want to access them elsewhere e.g windows explorer, they are not there.

All I see is .metadata folder.

An unexpected shutdown of the system occurred not too long ago.

Edit: When I switched the workspace, created and opened a project, they're still not visible/accessible outside of the eclipse project explorer.

Any ideas?

答:
It is possible that the projects were not put into the default, workspace folder.

To check this, right click on such a project, select Properties (it is usually available at the bottom of the list), go to the Resources tab, where you have the location of the project files displayed.


问:
Deleting duplicates from single-linked list
Is there a way to modify linked list that way so we delete all duplicates from it.

The think is it needs to be done for linear time and constant memory usage. I tried to put all elements of the list into HashMap which gives us constant time but linear memory usage.

Is there another way?

答:
Algorithmically it sounds impossible (or someone here will surprise me).

but you can create a simulation of a list without duplicates without really make any algorithm that way:

```<code>public class SimulatedNoDuplicatesList extends LinkedList {
    private List originalList;
    SimulatedNoDuplicatesList(List original) {
        originalList = original;
    }
// override all the methods that you want to use with the old list. for example
//   @Override
    public Object get(int i) {
        if (!super.contains(i) && originalList.contains(i)) {
            super.add(originalList.get(i));
        }
        return super.get(i);
    }
}
</code>```

Body:
Algorithmically it sounds impossible (or someone here will surprise me).

but you can create a simulation of a list without duplicates without really make any algorithm that way:

public class SimulatedNoDuplicatesList extends LinkedList {
    private List originalList;
    SimulatedNoDuplicatesList(List original) {
        originalList = original;
    }
// override all the methods that you want to use with the old list. for example
//   @Override
    public Object get(int i) {
        if (!super.contains(i) && originalList.contains(i)) {
            super.add(originalList.get(i));
        }
        return super.get(i);
    }
}


问:
how to check if a string contains only lower case letters and numbers?
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

```<code>if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):
</code>```

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

答:
How about use regex:

```<code>>>> def is_digit_and_lowercase_only(s):
        return re.match("^[\da-z]+$", s)
>>> print is_digit_and_lowercase_only("dA")
None
>>> print is_digit_and_lowercase_only("adc87d6f543sc")
<_sre.SRE_Match object at 0x107c46988>
</code>```

It'll return None if match failed, so you can use it with if.

Body:
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

Body:
How about use regex:

>>> def is_digit_and_lowercase_only(s):
        return re.match("^[\da-z]+$", s)
>>> print is_digit_and_lowercase_only("dA")
None
>>> print is_digit_and_lowercase_only("adc87d6f543sc")
<_sre.SRE_Match object at 0x107c46988>

It'll return None if match failed, so you can use it with if.


问:
how can I increase the int through a method?
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

```<code>int health;
int mana;
</code>```

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

```<code>public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}
</code>```

Please give me some insight!

答:
Ok so I have been testing things out lately to see how can I use a single method to change the values for int mana and health. I do not know if this is the right way to do it, but its working very well in my case.
For those who maybe are looking for a practical answer, it might be useful:
   Basically I added a new int called CE, where everytime I called an upgrade, I equalizet it wiht the passing value (val).

```<code>public void upgrade1(int val){
            if(val < 5)
                val = val + 1;
                CE = val;
}
</code>```

when I clicked the button I set the mana and health (each individually) to be equal with CE. From there I only had to set the mana and health value to CE. The values now can be changed particularry on their own without modifying values that are not ment to be modified.
Thanks for your support and collaboration community!

Body:
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

int health;
int mana;

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}

Please give me some insight!

Body:
Ok so I have been testing things out lately to see how can I use a single method to change the values for int mana and health. I do not know if this is the right way to do it, but its working very well in my case.
For those who maybe are looking for a practical answer, it might be useful:
   Basically I added a new int called CE, where everytime I called an upgrade, I equalizet it wiht the passing value (val).

public void upgrade1(int val){
            if(val < 5)
                val = val + 1;
                CE = val;
}

when I clicked the button I set the mana and health (each individually) to be equal with CE. From there I only had to set the mana and health value to CE. The values now can be changed particularry on their own without modifying values that are not ment to be modified.
Thanks for your support and collaboration community!


问:
Templating language for both Ruby and client-side JS
Is there a templating language that has both server-side ruby (pref. rails) and JS renderer?

Here is why this would be useful: Consider you want to display a big list of songs. You render the first 50 and a "show more" button.

"Show more" would link to the next 50 songs or would load those with AJAX if JavaScript is enabled.

The simple solution is to return a rendered piece of HTML from the server, but consider how nice would it be songs were returned as JSON and then were rendered using the same template on the client side.

答:
Mustache.

It is Ruby based but there are several different implementations, including JS.


问:
SQL Server PHP Code Igniter show one to many relationship
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

```<code>table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2
</code>```

The result i was expecting on my PHP is..

```<code>Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |
</code>```

i already tried some code like

```<code>**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}
</code>```

the code i make ,fails.how did i do the right code for that case ?

Thank you

答:
the controller is for communicate between model and view in codeigniter. so your db query should in model.

make a model based on your query and maybe you can try like this:

```<code>function something(){

   $qry = 'a.* , b.tableone_id';

   $this->db->select($qry);
   $this->db->from('table_one as a');
   $this->db->join('table_two b', 'b.tableone_id = a.id', 'left');

   $q = $this->db->get();
   return $q;

}
</code>```

try follow this link too for more reference on database reference in CI:
https://www.codeigniter.com/userguide3/database/query_builder.html

Body:
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2

The result i was expecting on my PHP is..

Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |

i already tried some code like

**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}

the code i make ,fails.how did i do the right code for that case ?

Thank you

Body:
the controller is for communicate between model and view in codeigniter. so your db query should in model.

make a model based on your query and maybe you can try like this:

function something(){

   $qry = 'a.* , b.tableone_id';

   $this->db->select($qry);
   $this->db->from('table_one as a');
   $this->db->join('table_two b', 'b.tableone_id = a.id', 'left');

   $q = $this->db->get();
   return $q;

}

try follow this link too for more reference on database reference in CI:
https://www.codeigniter.com/userguide3/database/query_builder.html


问:
Generate Google Maps URL to display custom map generated by v3 API in Javascript
in my website I use Google Maps API v3 and Routeboxer to generate a map where the user can set a route and view Points of Interest around it, this is an example of output:

Now I would also like to generate a URL so that I can view the same map (including the route and custom markers) on the Google Maps website.

Is this possible at all? I can only find URL schemes to view just the route or just 1 single marker, not a combination of the 2 (the markers are not waypoints, otherwise it would be easy).

It should be possible to create a custom layer on Google Maps to display this kind of information (I believe that's what the "My Maps" feature does), but I am not sure if you can pass all this information in 1 set of calls, especially from an external website as I cannot seem to find an API call that creates a "my map".

答:
Well while Google Maps itself doesn't make this feature available, you can still make a web page that does exactly this - encode marker and route information to generate an URL, while being able to decode it and show it in an embedded Google Maps widget ;-)

Note you will likely need a domain name, a web server etc... and that will, without a doubt, cost you time and money... But can be worth the investment depending on your use of the feature.


问:
Autoformat row based on values in each cell using Excel VBA?
I have Table1

Column A has a Date e.g. 30/5/2017

Column B has Status e.g "Success"

Column C has Value e.g 500

Requirement: Apply custom Conditional formatting in VBA when a cell is changed

Let's say the change happened in Columns A, B or C in row 5

Regardless whether the change happened in Columns A, B, or C, the same logic should be executed.

If column A value is less than Now(), then row 5 should be red background and white text. No further checks should run.

Else If column B is "Success", then row 5 should be green background and white text. No further checks should run.

Else If column C has value less than 500, then row 5 should be blue background and white text. No further checks should run.

The VBA code below is to check for change on a cell - it autoformats cell in column b with a hyperlink.

What I need now is to autoformat the whole row based on the criteria above.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

          If ((Not Intersect(Target, Range("B:B")) Is Nothing) Or (Not Intersect(Target, Range("F:F")) Is Nothing) Or (Not Intersect(Target, Range("G:G")) Is Nothing) Or (Not Intersect(Target, Range("I:I")) Is Nothing)) Then

          End If

End Sub
</code>```

答:
Try this code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Rng As Range, R As Range
    Dim fCol As Long, bCol As Long

    Set Rng = Application.Intersect(Target, Columns("A:C"))

    If Not Rng Is Nothing Then

     Set Rng = Application.Intersect(Rng.EntireRow, Columns("A:C"))
     fCol = vbWhite

     For Each R In Rng.Rows

       If R.Cells(1, 1).Value <> vbNullString And R.Cells(1, 1).Value < Now Then
         bCol = vbRed
       ElseIf R.Cells(1, 2).Value <> vbNullString And R.Cells(1, 2).Value = "Success" Then
         bCol = vbGreen
       ElseIf R.Cells(1, 3).Value <> vbNullString And R.Cells(1, 3).Value < 500 Then
         bCol = vbBlue
       Else
         bCol = xlNone
         fCol = vbBlack
       End If

       R.EntireRow.Interior.Color = bCol
       R.EntireRow.Font.Color = fCol

     Next

    End If

End Sub
</code>```

Edit:

I have Table1

If Table1 is a ListObject (Excel tables) then we can modify the above code to make it watch first three columns of this table regardless of where the first column is starting (in column "A" or "B" or etc..), and format only the table row not the EntireRow :

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

  Dim LObj As ListObject
  Dim RngToWatch As Range
  Dim Rng As Range, R As Range
  Dim fCol As Long, bCol As Long

  Set LObj = ListObjects("Table1") ' the name of the table
  Set RngToWatch = Range(LObj.ListColumns(1).DataBodyRange, LObj.ListColumns(3).DataBodyRange)
  Set Rng = Application.Intersect(Target, RngToWatch)

  If Not Rng Is Nothing Then

    Set Rng = Application.Intersect(Target.EntireRow, RngToWatch)
    fCol = vbWhite

    For Each R In Rng.Rows

       If R.Cells(1, 1).Value <> vbNullString And R.Cells(1, 1).Value < Now Then
         bCol = vbRed
       ElseIf R.Cells(1, 2).Value <> vbNullString And R.Cells(1, 2).Value = "Success" Then
         bCol = vbGreen
       ElseIf R.Cells(1, 3).Value <> vbNullString And R.Cells(1, 3).Value < 500 Then
         bCol = vbBlue
       Else
         bCol = xlNone
         fCol = vbBlack
       End If

       With Application.Intersect(LObj.DataBodyRange, R.EntireRow)
          .Interior.Color = bCol
          .Font.Color = fCol
       End With

    Next

  End If

End Sub
</code>```

Body:
I have Table1

Column A has a Date e.g. 30/5/2017

Column B has Status e.g "Success"

Column C has Value e.g 500

Requirement: Apply custom Conditional formatting in VBA when a cell is changed

Let's say the change happened in Columns A, B or C in row 5

Regardless whether the change happened in Columns A, B, or C, the same logic should be executed.

If column A value is less than Now(), then row 5 should be red background and white text. No further checks should run.

Else If column B is "Success", then row 5 should be green background and white text. No further checks should run.

Else If column C has value less than 500, then row 5 should be blue background and white text. No further checks should run.

The VBA code below is to check for change on a cell - it autoformats cell in column b with a hyperlink.

What I need now is to autoformat the whole row based on the criteria above.

Private Sub Worksheet_Change(ByVal Target As Range)

          If ((Not Intersect(Target, Range("B:B")) Is Nothing) Or (Not Intersect(Target, Range("F:F")) Is Nothing) Or (Not Intersect(Target, Range("G:G")) Is Nothing) Or (Not Intersect(Target, Range("I:I")) Is Nothing)) Then

          End If

End Sub

Body:
Try this code:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Rng As Range, R As Range
    Dim fCol As Long, bCol As Long

    Set Rng = Application.Intersect(Target, Columns("A:C"))

    If Not Rng Is Nothing Then

     Set Rng = Application.Intersect(Rng.EntireRow, Columns("A:C"))
     fCol = vbWhite

     For Each R In Rng.Rows

       If R.Cells(1, 1).Value <> vbNullString And R.Cells(1, 1).Value < Now Then
         bCol = vbRed
       ElseIf R.Cells(1, 2).Value <> vbNullString And R.Cells(1, 2).Value = "Success" Then
         bCol = vbGreen
       ElseIf R.Cells(1, 3).Value <> vbNullString And R.Cells(1, 3).Value < 500 Then
         bCol = vbBlue
       Else
         bCol = xlNone
         fCol = vbBlack
       End If

       R.EntireRow.Interior.Color = bCol
       R.EntireRow.Font.Color = fCol

     Next

    End If

End Sub

Edit:

I have Table1

If Table1 is a ListObject (Excel tables) then we can modify the above code to make it watch first three columns of this table regardless of where the first column is starting (in column "A" or "B" or etc..), and format only the table row not the EntireRow :

Private Sub Worksheet_Change(ByVal Target As Range)

  Dim LObj As ListObject
  Dim RngToWatch As Range
  Dim Rng As Range, R As Range
  Dim fCol As Long, bCol As Long

  Set LObj = ListObjects("Table1") ' the name of the table
  Set RngToWatch = Range(LObj.ListColumns(1).DataBodyRange, LObj.ListColumns(3).DataBodyRange)
  Set Rng = Application.Intersect(Target, RngToWatch)

  If Not Rng Is Nothing Then

    Set Rng = Application.Intersect(Target.EntireRow, RngToWatch)
    fCol = vbWhite

    For Each R In Rng.Rows

       If R.Cells(1, 1).Value <> vbNullString And R.Cells(1, 1).Value < Now Then
         bCol = vbRed
       ElseIf R.Cells(1, 2).Value <> vbNullString And R.Cells(1, 2).Value = "Success" Then
         bCol = vbGreen
       ElseIf R.Cells(1, 3).Value <> vbNullString And R.Cells(1, 3).Value < 500 Then
         bCol = vbBlue
       Else
         bCol = xlNone
         fCol = vbBlack
       End If

       With Application.Intersect(LObj.DataBodyRange, R.EntireRow)
          .Interior.Color = bCol
          .Font.Color = fCol
       End With

    Next

  End If

End Sub


问:
How to create a Word-like document (.docx) in an app?
I would like to create a .docx file within an iPad application.  The file would be created within the app (the user would create/edit it like in Word--preferably with the same "feel" of Word) and then it would be saved as a .docx file.

So, is it possible to do this?  If so, how?  What other alternative file formats are there?

Thanks,
John

答:
You can easily generate RTF corresponding to most typical features of a word processor. It will not cover the vastness of available DOCX features, but I'm not certain a complete port of Microsoft Word to the iPhone would be practical, so most of these features would be unavailable anyway. </p>

<p>RTF is fully (read-write) supported by Microsoft Office and several other editors. </p>

Body:
You can easily generate RTF corresponding to most typical features of a word processor. It will not cover the vastness of available DOCX features, but I'm not certain a complete port of Microsoft Word to the iPhone would be practical, so most of these features would be unavailable anyway.

RTF is fully (read-write) supported by Microsoft Office and several other editors.