问:
Can git tell me if a rebase will conflict without actually rebasing?
I would like to programmatically determine with of my feature branches would have rebase conflicts if I tried to rebase them.  Is there a way I can get git to tell me this information without actually performing the rebase?

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

My question is similar to these two, which are the same but for merge instead of rebase

Can git tell me if a merge will conflict without actually merging?

Is there a git-merge --dry-run option?

答:
Based on the answer of SVSchmidt, you could extend his first command to revert even in the case of success:

```<code>git rebase master && (echo "Success" && git reset --hard ORIG_HEAD) || (echo "Fail" && git rebase --abort)
</code>```

This will still run the rebase, however in the case of success reset your HEAD back to the old HEAD of before the rebase. Produced commits and changes of the reflog will remain, only the reference of your branch is resetted.

You might want to add redirections for the output of the commands to avoid unneeded output. When doing so keep in mind that the rebase might fail due to other circumstances than merge conflicts, e.g. unstaged changes in the working directory.

Body:
Based on the answer of SVSchmidt, you could extend his first command to revert even in the case of success:

git rebase master && (echo "Success" && git reset --hard ORIG_HEAD) || (echo "Fail" && git rebase --abort)

This will still run the rebase, however in the case of success reset your HEAD back to the old HEAD of before the rebase. Produced commits and changes of the reflog will remain, only the reference of your branch is resetted.

You might want to add redirections for the output of the commands to avoid unneeded output. When doing so keep in mind that the rebase might fail due to other circumstances than merge conflicts, e.g. unstaged changes in the working directory.


来源: stackexchange

问:
In-app purchases made via promo codes return empty developer payload string
I have an app published to the alpha channel, with an in-app (un)managed item that costs $1.

When I purchase normally, i.e, use a credit/debit card Google returns the correct developer payload string, but if I choose to "redeem" a promo code and enter said code, Google returns an empty developer payload string, and thus authentication fails in 'onIabPurchaseFinished()'.

I should mention that this only occurs if I choose to redeem a code from the app's purchase flow, and everything works flawlessly if I open Play Store first, redeem the code, and then come back and open the app.

Is this a bug on  Google's part?

EDIT: The Play Store thing is expected, since it can't know your payload and the purchase is done without having to check for it.

答:
This issue was opened on the google's android-play-billing samples repo.
Looks like it was ignored for a long time and was eventually closed with this comment. In short, they have following suggestions.

We reviewed our guidelines and internal APIs, and since the developerPayload is not supported across all features on In-App Billing API (including promocodes), we are removing the recommendation to use it as a security check.

As you can see in our documentation, on the page Implementing In-app Billing (https://developer.android.com/google/play/billing/billing_integrate.html) we've added a recommendation:

Caution: Don't use the developerPayload field for security validation purposes. This field isn't always available when completing tasks related to In-app Billing. For more information about security best practices, see the In-app Billing Security and Design guide.

Our recommendation is to validate on your own backend, using the Play Developer API.

ContentLicense: CC BY-SA 3.0


问:
Asp.Identity OWIN Cookie not Authenticating
Below is the code I use to sign in. It comes back and says success. But If I tried to get the UserID, or do a User.Identity.IsAuthenticated on any page, it says false.

I can't figure out what could be going on here.

```<code>var SignInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

        var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);

        switch (result)
        {
            case SignInStatus.Success:
                Response.Redirect(User.IsInRole("Admin") ? "~/Admin/Dashboard.aspx" : "~/User/Dashboard.aspx");
                break;
            case SignInStatus.LockedOut:
                Response.Redirect("~/Account/Lockout");
                break;
            case SignInStatus.RequiresVerification:
                Response.Redirect("~/Account/Unknown",true);
                break;
            case SignInStatus.Failure:
            default:
                txtErrorMessage.Text = "Invalid Username/Password";
                txtPassword.Text = "";
                break;
        }
</code>```

It's almost like its saying Success, but its really not working correctly.
I've tried a lot of different things, but nothing seems to keep me authenticated at all.

答:
Try use SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, true, true);

The third parameter should set true, because if this parameter is false the browser will don't know  that it is authenticated.

In summary on methotd is written:

isPersistent:
          //     Flag indicating whether the sign-in cookie should persist after the browser is
          //     closed.

Body:
Below is the code I use to sign in. It comes back and says success. But If I tried to get the UserID, or do a User.Identity.IsAuthenticated on any page, it says false.

I can't figure out what could be going on here.

var SignInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

        var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);

        switch (result)
        {
            case SignInStatus.Success:
                Response.Redirect(User.IsInRole("Admin") ? "~/Admin/Dashboard.aspx" : "~/User/Dashboard.aspx");
                break;
            case SignInStatus.LockedOut:
                Response.Redirect("~/Account/Lockout");
                break;
            case SignInStatus.RequiresVerification:
                Response.Redirect("~/Account/Unknown",true);
                break;
            case SignInStatus.Failure:
            default:
                txtErrorMessage.Text = "Invalid Username/Password";
                txtPassword.Text = "";
                break;
        }

It's almost like its saying Success, but its really not working correctly.
I've tried a lot of different things, but nothing seems to keep me authenticated at all.


问:
Perl - call an instance of a class
Is there way to catch the event of calling an instance of a Perl class?

```<code>my $obj = ExampleClass->new();
$obj(); # do something without producing error
</code>```

I would like to be able to handle this from within the class/module definition. Something similar to the __call__ method in Python, or the __call metamethod in Lua.

答:
Overloading "&{}" is obviously the way to go, but you could base your object on a sub instead of the commonly-preferred hash.

ExampleClass.pm:

```<code>package ExampleClass;

use strict;
use warnings;
use feature qw( current_sub say );

my %objects;

sub new {
   my $class = shift;
   my $dummy;  # Force each evaluation of sub{} to return a new variable.
   my $self = bless(sub { $dummy if 0; __SUB__ ->__call__(@_) }, $class) }, $class);
   my $inner = $objects{$self} = {};
   return $self;
}

sub DESTROY {
   my $self = shift;
   delete($objects{$self});
}

sub __call__ {
   my $inner = $objects{ my $self = shift };
   say "__call__(".join(", ", @_).")";
}

sub some_attribute {
   my $inner = $objects{ my $self = shift };
   if (@_) { $inner->{some_attribute} = $_[0]; }
   return $inner->{some_attribute};
}

1;
</code>```

The main program:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use feature qw( say );

use ExampleClass qw( );

{
   my $obj = ExampleClass->new();

   $obj->some_attribute("value");
   say $obj->some_attribute();

   $obj->(qw( a b c ));
}

{
   my $obj1 = ExampleClass->new();
   $obj1->some_attribute("value1");

   my $obj2 = ExampleClass->new();
   $obj2->some_attribute("value2");

   say $obj1->some_attribute();
   say $obj2->some_attribute();
}
</code>```

Output:

```<code>value
__call__(a, b, c)
value1
value2
</code>```

This is basically what's called an "inside-out" object.

Title: Perl - call an instance of a class

Body:
Is there way to catch the event of calling an instance of a Perl class?

my $obj = ExampleClass->new();
$obj(); # do something without producing error

I would like to be able to handle this from within the class/module definition. Something similar to the __call__ method in Python, or the __call metamethod in Lua.

Body:
Overloading "&{}" is obviously the way to go, but you could base your object on a sub instead of the commonly-preferred hash.

ExampleClass.pm:

package ExampleClass;

use strict;
use warnings;
use feature qw( current_sub say );

my %objects;

sub new {
   my $class = shift;
   my $dummy;  # Force each evaluation of sub{} to return a new variable.
   my $self = bless(sub { $dummy if 0; __SUB__ ->__call__(@_) }, $class) }, $class);
   my $inner = $objects{$self} = {};
   return $self;
}

sub DESTROY {
   my $self = shift;
   delete($objects{$self});
}

sub __call__ {
   my $inner = $objects{ my $self = shift };
   say "__call__(".join(", ", @_).")";
}

sub some_attribute {
   my $inner = $objects{ my $self = shift };
   if (@_) { $inner->{some_attribute} = $_[0]; }
   return $inner->{some_attribute};
}

1;

The main program:

#!/usr/bin/perl

use strict;
use warnings;
use feature qw( say );

use ExampleClass qw( );

{
   my $obj = ExampleClass->new();

   $obj->some_attribute("value");
   say $obj->some_attribute();

   $obj->(qw( a b c ));
}

{
   my $obj1 = ExampleClass->new();
   $obj1->some_attribute("value1");

   my $obj2 = ExampleClass->new();
   $obj2->some_attribute("value2");

   say $obj1->some_attribute();
   say $obj2->some_attribute();
}

Output:

value
__call__(a, b, c)
value1
value2

This is basically what's called an "inside-out" object.


问:
PHP PDO - Uncaught Error: Call to a member function prepare() on null
I am trying to run a query using database credentials from a config file but I keep getting the following error: Uncaught Error: Call to a member function prepare() on null

config.php file:

```<code>$host = 'xxxx';
$dbname = 'xxxx';
$username = 'xxxx';
$password = 'xxxx.';

try {
    $conn = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "$e->getMessage()";
}
</code>```

functions.php

```<code>session_start();
include 'config.php';

    function getAddress(){
       $output = "";
       if (isset($_SESSION['userid'])){
            $userid = $_SESSION['userid'];
            try {
                $stmt = $conn->prepare('SELECT address FROM users WHERE id = :userid');
                $stmt->bindParam(':userid', $userid);
                $stmt->execute();
                $result = $stmt -> fetch();
                if(empty($result)){
                    $output = "Your information cannot be retrieved";
                } else {
                    $output = $result['address'];
                }
            } catch (PDOException $e) {
                $output = $e->getMessage();
            }
            $conn = null;
            } else {
            $output = "An error has occured, please try again";
            }
        return $output;
    }
</code>```

index.php (html page)

```<code><?php
session_start();
include 'functions.php';
?>
...
<p><?php echo getAddress();?></p>
...
</code>```

So my index page runs a function (getAddress()) from the functions.php script which connects to a db using credentials stored in config.php.

答:
try doing</p>

```<code>function getAddress()
{
  global $conn;
  // rest of code
}
</code>```

Body:
I am trying to run a query using database credentials from a config file but I keep getting the following error: Uncaught Error: Call to a member function prepare() on null

config.php file:

$host = 'xxxx';
$dbname = 'xxxx';
$username = 'xxxx';
$password = 'xxxx.';

try {
    $conn = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "$e->getMessage()";
}

functions.php

session_start();
include 'config.php';

    function getAddress(){
       $output = "";
       if (isset($_SESSION['userid'])){
            $userid = $_SESSION['userid'];
            try {
                $stmt = $conn->prepare('SELECT address FROM users WHERE id = :userid');
                $stmt->bindParam(':userid', $userid);
                $stmt->execute();
                $result = $stmt -> fetch();
                if(empty($result)){
                    $output = "Your information cannot be retrieved";
                } else {
                    $output = $result['address'];
                }
            } catch (PDOException $e) {
                $output = $e->getMessage();
            }
            $conn = null;
            } else {
            $output = "An error has occured, please try again";
            }
        return $output;
    }

index.php (html page)

<?php
session_start();
include 'functions.php';
?>
...

<?php echo getAddress();?>

...

So my index page runs a function (getAddress()) from the functions.php script which connects to a db using credentials stored in config.php.

Body:
try doing

function getAddress()
{
  global $conn;
  // rest of code
}


问:
php register to database
I am very new to stackoverflow. I want to create this form which uploads information to the database. When I click submit it does not get uploaded. I have checked my connections file and that is correct. Code below. Please help.</p>

```<code><?php
 include("/connections/db_conx.php");

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

$title = mysqli_real_escape_string($_POST['title']);
 $text = mysqli_real_escape_string($_POST['text']);
   $picture = mysqli_real_escape_string($_POST['picture']);

  $sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture', now(),now(),now())";

    $query = mysqli_query ($db_conx, $sql);

     echo 'Entered into the news table';
     }
     ?>

  <html>

  <head>

 </head>

 <body>

  <table border="0">
  <tr>
  <form method="post" action="index.php" id="tech">
  <td>Title</td><td> <input type="text" name="title"></td> </tr>
  <tr> <td>Text</td><td> <textarea rows="4" name="text" cols="50"       name="comment"       form="tech"> </textarea>
       </td> </tr>

 <tr> <td>Picture</td><td> <input type="varchar" name="picture"></td> </tr>

 <tr> <td><input id="button" type="submit" name="submit" value="Submit"></td>

 </tr>
 </form>

 </table>

</body>

</html>
</code>```

答:
Here is the code you need to use:

```<code><?php
    include("/connections/db_conx.php");
    if(isset($_POST['submit'])) {
        $title   = mysqli_real_escape_string($db_conx, $_POST['title']);
        $text    = mysqli_real_escape_string($db_conx, $_POST['text']);
        $picture = mysqli_real_escape_string($db_conx, $_POST['picture']);
        $sql     = "INSERT INTO news (`title`, `text`, `picture`) VALUES('$title','$text','$picture');";
        if(!$result = $db_conx->query($sql)){
            die('There was an error running the query [' . $db_conx->error . ']');
        }
        echo 'Entered into the news table';
    }
?>

<html>
    <head>
    </head>
    <body>
        <form method="post" action="index.php" id="tech">
            <table border="0">
                <tr>
                    <td>Title</td>
                    <td> <input type="text" name="title"></td>
                </tr>
                <tr>
                    <td>Text</td>
                    <td><textarea rows="4" name="text" cols="50" name="comment" form="tech"> </textarea></td>
                </tr>
                <tr>
                    <td>Picture</td>
                    <td> <input type="varchar" name="picture"></td>
                </tr>
                <tr>
                    <td><input id="button" type="submit" name="submit" value="Submit"></td>
                </tr>
            </table>
        </form>
    </body>
</html>
</code>```

Your problem is that the mysqli_real_escape_string() function requires 2 parameters: the database connection, and the string to escape.

I've also included completely reformatted code, and error checking as well.

Title: php register to database

Body:
I am very new to stackoverflow. I want to create this form which uploads information to the database. When I click submit it does not get uploaded. I have checked my connections file and that is correct. Code below. Please help.

<?php
 include("/connections/db_conx.php");

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

$title = mysqli_real_escape_string($_POST['title']);
 $text = mysqli_real_escape_string($_POST['text']);
   $picture = mysqli_real_escape_string($_POST['picture']);

  $sql = "INSERT INTO news  (title, text, picture) VALUES('$title','$text','$picture', now(),now(),now())";

    $query = mysqli_query ($db_conx, $sql);

     echo 'Entered into the news table';
     }
     ?>

  <form method="post" action="index.php" id="tech">
  Title	 <input type="text" name="title">

 Text	 <textarea rows="4" name="text" cols="50"       name="comment"       form="tech"> </textarea>

 Picture	 <input type="varchar" name="picture">

 <input id="button" type="submit" name="submit" value="Submit">

 </form>

Body:
Here is the code you need to use:

<?php
    include("/connections/db_conx.php");
    if(isset($_POST['submit'])) {
        $title   = mysqli_real_escape_string($db_conx, $_POST['title']);
        $text    = mysqli_real_escape_string($db_conx, $_POST['text']);
        $picture = mysqli_real_escape_string($db_conx, $_POST['picture']);
        $sql     = "INSERT INTO news (`title`, `text`, `picture`) VALUES('$title','$text','$picture');";
        if(!$result = $db_conx->query($sql)){
            die('There was an error running the query [' . $db_conx->error . ']');
        }
        echo 'Entered into the news table';
    }
?>

<html>
    <head>
    </head>
    <body>
        <form method="post" action="index.php" id="tech">
            <table border="0">
                <tr>
                    <td>Title</td>
                    <td> <input type="text" name="title"></td>
                </tr>
                <tr>
                    <td>Text</td>
                    <td><textarea rows="4" name="text" cols="50" name="comment" form="tech"> </textarea></td>
                </tr>
                <tr>
                    <td>Picture</td>
                    <td> <input type="varchar" name="picture"></td>
                </tr>
                <tr>
                    <td><input id="button" type="submit" name="submit" value="Submit"></td>
                </tr>
            </table>
        </form>
    </body>
</html>

Your problem is that the mysqli_real_escape_string() function requires 2 parameters: the database connection, and the string to escape.

I've also included completely reformatted code, and error checking as well.


问:
google chrome console, print image
About year ago i created a plugin to enhance console logs, main idea was to print images in console, so for example You could add some icons or glyphs.

It was working pretty nice, i saw that there is many of those available online right now. The problem is that none of them are working atm.

I noticed it after last chrome update i think. currently i have version 49.0.2623.112.

All of those plugins including mine works in the same way:

```<code>console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width * scale) + "px " + (this.height * scale) + "px; color: transparent;");
</code>```

For example this one: plugin link on github

Does anyone know how we can print images in console in newer versions of chrome ?

答:
Try a code example with console F12:

console.log('%c ', 'font-size:400px; background:url(https://pics.me.me/codeit-google-until-youfinda-stackoverflow-answerwith-code-to-copy-paste-34126823.png) no-repeat;');```

Title: google chrome console, print image

Body:
About year ago i created a plugin to enhance console logs, main idea was to print images in console, so for example You could add some icons or glyphs.

It was working pretty nice, i saw that there is many of those available online right now. The problem is that none of them are working atm.

I noticed it after last chrome update i think. currently i have version 49.0.2623.112.

All of those plugins including mine works in the same way:

console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width * scale) + "px " + (this.height * scale) + "px; color: transparent;");

For example this one: plugin link on github

Does anyone know how we can print images in console in newer versions of chrome ?

ContentLicense: CC BY-SA 4.0


问:
How can I add a column with a value to a new Dataset in Spark Java?
So, I'm creating some Datasets from the java Spark API. These datasets are populated from hive table, using the spark.sql() method.

So, after performing some sql operations (like joins), I have a final dataset. What I want to do is that I want to add a new column to that final dataset, with a value of "1" to all the rows in the dataset. So, you could probably see it as adding a constrain to the Dataset.

So, for example I have this dataset:

```<code>Dataset<Row> final = otherDataset.select(otherDataset.col("colA"), otherDataSet.col("colB"));
</code>```

I want to add a new column to the "final" Dataset, something like this

```<code>final.addNewColumn("colName", 1); //I know this doesn't work, but just to give you an idea.
</code>```

Is there a feasible way to add the new column to all the rows of the Dataset with a value of 1?

答:
If you want to add a constant value then you can use lit function

```<code>lit(Object literal)
Creates a Column of literal value.
</code>```

Also, change the variable name final to something else

```<code>Dataset<Row> final12 = otherDataset.select(otherDataset.col("colA"), otherDataSet.col("colB"));

Dataset<Row> result = final12.withColumn("columnName", lit(1))
</code>```

Hope this helps!

Body:
So, I'm creating some Datasets from the java Spark API. These datasets are populated from hive table, using the spark.sql() method.

So, after performing some sql operations (like joins), I have a final dataset. What I want to do is that I want to add a new column to that final dataset, with a value of "1" to all the rows in the dataset. So, you could probably see it as adding a constrain to the Dataset.

So, for example I have this dataset:

Dataset<Row> final = otherDataset.select(otherDataset.col("colA"), otherDataSet.col("colB"));

I want to add a new column to the "final" Dataset, something like this

final.addNewColumn("colName", 1); //I know this doesn't work, but just to give you an idea.

Is there a feasible way to add the new column to all the rows of the Dataset with a value of 1?

Body:
If you want to add a constant value then you can use lit function

lit(Object literal)
Creates a Column of literal value.

Also, change the variable name final to something else

Dataset<Row> final12 = otherDataset.select(otherDataset.col("colA"), otherDataSet.col("colB"));

Dataset<Row> result = final12.withColumn("columnName", lit(1))

Hope this helps!


问:
How to initialize a convolution layer with an arbitrary kernel in Keras?
I want to initialize the convolution layer by a specific kernel which is not defined in Keras. For instance, if I define the below function to initialize the kernel:

```<code>def init_f(shape):
      ker=np.zeros((shape,shape))
      ker[int(np.floor(shape/2)),int(np.floor(shape/2))]=1
      return ker
</code>```

And the convolution layer is designed as follows:

```<code>model.add(Conv2D(filters=32, kernel_size=(3,3),
                      kernel_initializer=init_f(3)))
</code>```

I get the error:

Could not interpret initializer identifier

I have followed a similar issue at:
https://groups.google.com/forum/#!topic/keras-users/J46pplO64-8
But I could not adapt it to my code.
Could you please help me to define the arbitrary kernel in Keras?

答:
A few items to fix. Let's start with the kernel initializer. From the documentation:

If passing a custom callable, then it must take the argument shape (shape of the variable to initialize) and dtype (dtype of generated values)

So the signature should become:

```<code>def init_f(shape, dtype=None)
</code>```

The function will work without the dtype, but it's good practice to keep it there. That way you can specify the dtype to calls inside your function, e.g.:

```<code>np.zeros(shape, dtype=dtype)
</code>```

This also addresses your second issue: the shape argument is a tuple, so you just need to pass it straight to np.zeros and don't need to make another tuple.

I'm guessing you're trying to initialize the kernel with a 1 in the middle, so you could also generalize your function to work with whatever shape it receives:

```<code>ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1
</code>```

Putting it all together:

```<code>def init_f(shape, dtype=None):
    ker = np.zeros(shape, dtype=dtype)
    ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1
    return ker
</code>```

One last problem. You need to pass the function to the layer, not the result of the call:

```<code>model.add(Conv2D(filters=32, kernel_size=(3,3),
                  kernel_initializer=init_f))
</code>```

The layer function will pass the arguments to init_f.

Body:
I want to initialize the convolution layer by a specific kernel which is not defined in Keras. For instance, if I define the below function to initialize the kernel:

def init_f(shape):
      ker=np.zeros((shape,shape))
      ker[int(np.floor(shape/2)),int(np.floor(shape/2))]=1
      return ker

And the convolution layer is designed as follows:

model.add(Conv2D(filters=32, kernel_size=(3,3),
                      kernel_initializer=init_f(3)))

I get the error:

Could not interpret initializer identifier

I have followed a similar issue at:
https://groups.google.com/forum/#!topic/keras-users/J46pplO64-8
But I could not adapt it to my code.
Could you please help me to define the arbitrary kernel in Keras?

Body:
A few items to fix. Let's start with the kernel initializer. From the documentation:

If passing a custom callable, then it must take the argument shape (shape of the variable to initialize) and dtype (dtype of generated values)

So the signature should become:

def init_f(shape, dtype=None)

The function will work without the dtype, but it's good practice to keep it there. That way you can specify the dtype to calls inside your function, e.g.:

np.zeros(shape, dtype=dtype)

This also addresses your second issue: the shape argument is a tuple, so you just need to pass it straight to np.zeros and don't need to make another tuple.

I'm guessing you're trying to initialize the kernel with a 1 in the middle, so you could also generalize your function to work with whatever shape it receives:

ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1

Putting it all together:

def init_f(shape, dtype=None):
    ker = np.zeros(shape, dtype=dtype)
    ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1
    return ker

One last problem. You need to pass the function to the layer, not the result of the call:

model.add(Conv2D(filters=32, kernel_size=(3,3),
                  kernel_initializer=init_f))

The layer function will pass the arguments to init_f.


问:
Display annotations for 3D model object on iOS
Please suggest me a solution for displaying annotations (text or images) for 3D model object on iOS.

For details, so far, I'm able to load and display an 3D model object on iOS by following the guide at http://iosdeveloperzone.com/2016/05/10/getting-started-with-modelio/. But I cannot find a way to add annotations, then display them with the 3D model object. I expect the implementation on iOS will be similar with https://sketchfab.com/models/363e92268ff04a6ba8322332004bdaab (on web version).

Thank you for any suggestions and answers.

答: Project the locations of your 3D locations into screen space. Then use the overlaySKScene to draw the annotations. This will get the annotations in the right spot, and keep the text a constant size, independent of the distance from the camera to each annotation's location.


问:
Do C++ Templates play nicely with VCL classes?
I'm trying to use C++ Template 'mixins' to create some new VCL components with shared additional functionality. Example...

```<code>template <class T> class Mixin : public T
{
private:
  typedef T inherited;

// ...additional methods

public:
  Mixin(TComponent *owner) : inherited(owner)
  {
  // .. do stuff here
  };
};
</code>```

Used like this:

```<code>class MyLabel : public Mixin<TLabel>
{
  ....
}

class MyEdit : public Mixin<TEdit>
{
  ....
}
</code>```

Now, everything compiles fine, and the mixin stuff seems to work - until I try and save the component to a stream using TStream->WriteComponent, where the inherited properties (eg TLabel.Width/Height/etc.) don't get written. This is even with a 'null' mixin like the one shown above.

My code works fine when just deriving classes directly from TForm, TEdit, etc - and the class is correctly registered with the streaming system.

答:
The quick/simple answer is: no; when dealing with a template, the compiler won't generate the proper descriptors to make streaming working. However, since this has come up before, I peeked under the cover to find out what's missing. And what I found is that it's almost there. So here's a little more information.

Upfront the compiler will never treat a template-based type as a Delphi. For example, do something like this:

```<code>void testing()
{
  __classid(Mixin<Stdctrls::TLabel>); // Error Here
}
</code>```

... and you'll see the error

"Error E2242 test.cpp 53: __classid requires Delphi style class type (i.e. class marked __declspec(delphiclass) or derived from System::TObject) in function testing()"

This basically says the compiler does not consider this type/class as compatible with Delphi-classes [i.e. those that derive from TObject]. Internally there's just a flag on the symbol that says whether the type is delphi-compatible or not. And I noticed that I could trick the compiler into marking the type as delphi-style if I forced it to walk up the hierarchy.. which is something it has to do if I create an instance of the object. So, with this hack the error goes away:

```<code>void testing()
{
  typedef Mixin<Stdctrls::TLabel> __ttype;
  std::auto_ptr<__ttype> c2(new __ttype(0));
  __classid(Mixin<Stdctrls::TLabel>); // No more errors here
}
</code>```

But much nicer was actually to use the __declspec(delphiclass) directly on the template, as in:

```<code>template <class T>
class __declspec(delphiclass) Mixin : public T {
private:
  int i;
  typedef T inherited;
public:
  __fastcall Mixin(TComponent *owner) : inherited(owner) {};
};
</code>```

So now that the compiler treats the type as a delphi-style class without hacks, I peeked a little more and found the issue you're probably running into: Delphi classes have the TTypeData.PropCount field - http://docwiki.embarcadero.com/VCL/en/TypInfo.TTypeData - which is a sum of the class' properties, including those of its base classes. Due to the way the various pieces of information are computed, the compiler writes out a '0' for that field when a template is involved:(

You can see this by printing out the PropCount, as in:

```<code>#include <Stdctrls.hpp>
#include <cstdio>
#include <memory>
#include <utilcls.h>

class TCppComp : public Classes::TComponent {
  int i;
public:
  __fastcall TCppComp(TComponent* owner): Classes::TComponent(owner) {};
__published:
  __property int AAAA = {read=i, write=i};
};

template <class T>
class __declspec(delphiclass) Mixin : public T {
private:
  int i;
  typedef T inherited;
public:
  __fastcall Mixin(TComponent *owner) : inherited(owner) {};
};

typedef Mixin<TCppComp> TMixinComp;

void showProps(TClass meta) {
  PTypeInfo pInfo = PTypeInfo(meta->ClassInfo());
  int Count = GetPropList(pInfo, tkAny, NULL);
  TAPtr<PPropInfo> List(new PPropInfo[Count]);
  std::printf("Class: %s - Total Props:%d\n",
                   AnsiString(pInfo->Name).c_str(), Count);
  GetPropList(pInfo, tkAny, *(reinterpret_cast<PPropList*>(&List)));
  for (int i = 0; i < Count; i++) {
    AnsiString propName(List[i]->Name);
    std::printf("\t%s\n", propName.c_str());
  }
}

void test() {
  showProps(__classid(TCppComp));
  showProps(__classid(TMixinComp));
}

int main() {
  test();
  return 0;
}
</code>```

When run the above prints:

```<code>  Class: TCppComp - Total Props:3
    AAAA
    Name
    Tag
  Class: @%Mixin$8TCppComp% - Total Props:0
</code>```

IOW, Mixin shows up with '0' published properties while its base type has 3:(

I suspect the streaming system relies on this count and that's why inherited properties are not being written out in your setup.

I considered tweaking the generated descriptors at runtime but since we write them to _TEXT it's bound to trigger DEP.

I'll look at the logic that computes the PropCount to see if there's some way to get it to compute the correct number. If time allows, please do open a QC for this: now that I've peek underneath, I believe it would not require much effort to get this working as expected.

Cheers,

Bruneau

PS: In my sample I even had the Mixin publish a property and the compiler generated the correct descriptor for that property; however, the total count was still zero.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use C++ Template 'mixins' to create some new VCL components with shared additional functionality. Example...

template <class T> class Mixin : public T
{
private:
  typedef T inherited;

// ...additional methods

public:
  Mixin(TComponent *owner) : inherited(owner)
  {
  // .. do stuff here
  };
};

Used like this:

class MyLabel : public Mixin<TLabel>
{
  ....
}

class MyEdit : public Mixin<TEdit>
{
  ....
}

Now, everything compiles fine, and the mixin stuff seems to work - until I try and save the component to a stream using TStream->WriteComponent, where the inherited properties (eg TLabel.Width/Height/etc.) don't get written. This is even with a 'null' mixin like the one shown above.

My code works fine when just deriving classes directly from TForm, TEdit, etc - and the class is correctly registered with the streaming system.

Body:
The quick/simple answer is: no; when dealing with a template, the compiler won't generate the proper descriptors to make streaming working. However, since this has come up before, I peeked under the cover to find out what's missing. And what I found is that it's almost there. So here's a little more information.

Upfront the compiler will never treat a template-based type as a Delphi. For example, do something like this:

void testing()
{
  __classid(Mixin<Stdctrls::TLabel>); // Error Here
}

... and you'll see the error

"Error E2242 test.cpp 53: __classid requires Delphi style class type (i.e. class marked __declspec(delphiclass) or derived from System::TObject) in function testing()"

This basically says the compiler does not consider this type/class as compatible with Delphi-classes [i.e. those that derive from TObject]. Internally there's just a flag on the symbol that says whether the type is delphi-compatible or not. And I noticed that I could trick the compiler into marking the type as delphi-style if I forced it to walk up the hierarchy.. which is something it has to do if I create an instance of the object. So, with this hack the error goes away:

void testing()
{
  typedef Mixin<Stdctrls::TLabel> __ttype;
  std::auto_ptr<__ttype> c2(new __ttype(0));
  __classid(Mixin<Stdctrls::TLabel>); // No more errors here
}

But much nicer was actually to use the __declspec(delphiclass) directly on the template, as in:

template <class T>
class __declspec(delphiclass) Mixin : public T {
private:
  int i;
  typedef T inherited;
public:
  __fastcall Mixin(TComponent *owner) : inherited(owner) {};
};

So now that the compiler treats the type as a delphi-style class without hacks, I peeked a little more and found the issue you're probably running into: Delphi classes have the TTypeData.PropCount field - http://docwiki.embarcadero.com/VCL/en/TypInfo.TTypeData - which is a sum of the class' properties, including those of its base classes. Due to the way the various pieces of information are computed, the compiler writes out a '0' for that field when a template is involved:(

You can see this by printing out the PropCount, as in:

#include <Stdctrls.hpp>
#include <cstdio>
#include <memory>
#include <utilcls.h>

class TCppComp : public Classes::TComponent {
  int i;
public:
  __fastcall TCppComp(TComponent* owner): Classes::TComponent(owner) {};
__published:
  __property int AAAA = {read=i, write=i};
};

template <class T>
class __declspec(delphiclass) Mixin : public T {
private:
  int i;
  typedef T inherited;
public:
  __fastcall Mixin(TComponent *owner) : inherited(owner) {};
};

typedef Mixin<TCppComp> TMixinComp;

void showProps(TClass meta) {
  PTypeInfo pInfo = PTypeInfo(meta->ClassInfo());
  int Count = GetPropList(pInfo, tkAny, NULL);
  TAPtr<PPropInfo> List(new PPropInfo[Count]);
  std::printf("Class: %s - Total Props:%d\n",
                   AnsiString(pInfo->Name).c_str(), Count);
  GetPropList(pInfo, tkAny, *(reinterpret_cast<PPropList*>(&List)));
  for (int i = 0; i < Count; i++) {
    AnsiString propName(List[i]->Name);
    std::printf("\t%s\n", propName.c_str());
  }
}

void test() {
  showProps(__classid(TCppComp));
  showProps(__classid(TMixinComp));
}

int main() {
  test();
  return 0;
}

When run the above prints:

  Class: TCppComp - Total Props:3
    AAAA
    Name
    Tag
  Class: @%Mixin$8TCppComp% - Total Props:0

IOW, Mixin shows up with '0' published properties while its base type has 3:(

I suspect the streaming system relies on this count and that's why inherited properties are not being written out in your setup.

I considered tweaking the generated descriptors at runtime but since we write them to _TEXT it's bound to trigger DEP.

I'll look at the logic that computes the PropCount to see if there's some way to get it to compute the correct number. If time allows, please do open a QC for this: now that I've peek underneath, I believe it would not require much effort to get this working as expected.

Cheers,

Bruneau

PS: In my sample I even had the Mixin publish a property and the compiler generated the correct descriptor for that property; however, the total count was still zero.


问:
How can I exec a file and provide hooked imports in Python 3?
I'm using Python 3 to emulate the Python scripting interface provided by another tool. (When scripting this tool, you run Python scripts, which can do import mytool to access the scripting API.)

I've implemented the interfaces exposed by this tool, and would like to write a loader that you'd invoke such as:

```<code>python run_mytool_script.py dump_menu_items.py
</code>```

This loader would allow you to interact with some portion of the tool's functionality without the tool actually being installed. Ideally, this should allow me to run existing scripts designed for the tool without modification.

Within run_mytool_script.py I expect to:

initialize the emulated scripting interface

prepare import hooks

exec the script dump_menu_items.py

However, I can't quite figure out how to create the import hooks. How can I install a hook so that my emulated scripting interface is exposed as mytool once the script does import mytool?

Note, the emulated scripting interface must be initialized at runtime, so installing a package named mytool doesn't do the trick.

答:
Following the example from the cPython tests here, I've come up with the following potential solution. I'll update this post as I realize its pros and cons.

```<code>class HookedImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader):
    def __init__(self, hooks=None):
        self.hooks = hooks

    def find_spec(self, name, path, target=None):
        if name not in self.hooks:
            return None

        spec = importlib.util.spec_from_loader(name, self)
        return spec

    def create_module(self, spec):
        # req'd in 3.6
        logger.info('hooking import: %s', spec.name)
        module = importlib.util._Module(spec.name)
        mod = self.hooks[spec.name]
        for attr in dir(mod):
            if attr.startswith('__'):
                continue
            module.__dict__[attr] = getattr(mod, attr)
        return module

    def exec_module(self, module):
        # module is already loaded (imported by line `import idb` above),
        # so no need to re-execute.
        #
        # req'd in 3.6.
        return

    def install(self):
        sys.meta_path.insert(0, self)
</code>```

... somewhere later on ...

```<code>api = mytool.from_config(...)
hooks = {
    'mytool': api.mytool,
}

importer = HookedImporter(hooks=hooks)
importer.install()

with open(args.script_path, 'rb') as f:
    g = {
        '__name__': '__main__',
    }
    g.update(hooks)
    exec(f.read(), g)
</code>```

Body:
I'm using Python 3 to emulate the Python scripting interface provided by another tool. (When scripting this tool, you run Python scripts, which can do import mytool to access the scripting API.)

I've implemented the interfaces exposed by this tool, and would like to write a loader that you'd invoke such as:

python run_mytool_script.py dump_menu_items.py

This loader would allow you to interact with some portion of the tool's functionality without the tool actually being installed. Ideally, this should allow me to run existing scripts designed for the tool without modification.

Within run_mytool_script.py I expect to:

initialize the emulated scripting interface

prepare import hooks

exec the script dump_menu_items.py

However, I can't quite figure out how to create the import hooks. How can I install a hook so that my emulated scripting interface is exposed as mytool once the script does import mytool?

Note, the emulated scripting interface must be initialized at runtime, so installing a package named mytool doesn't do the trick.

Body:
Following the example from the cPython tests here, I've come up with the following potential solution. I'll update this post as I realize its pros and cons.

class HookedImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader):
    def __init__(self, hooks=None):
        self.hooks = hooks

    def find_spec(self, name, path, target=None):
        if name not in self.hooks:
            return None

        spec = importlib.util.spec_from_loader(name, self)
        return spec

    def create_module(self, spec):
        # req'd in 3.6
        logger.info('hooking import: %s', spec.name)
        module = importlib.util._Module(spec.name)
        mod = self.hooks[spec.name]
        for attr in dir(mod):
            if attr.startswith('__'):
                continue
            module.__dict__[attr] = getattr(mod, attr)
        return module

    def exec_module(self, module):
        # module is already loaded (imported by line `import idb` above),
        # so no need to re-execute.
        #
        # req'd in 3.6.
        return

    def install(self):
        sys.meta_path.insert(0, self)

... somewhere later on ...

api = mytool.from_config(...)
hooks = {
    'mytool': api.mytool,
}

importer = HookedImporter(hooks=hooks)
importer.install()

with open(args.script_path, 'rb') as f:
    g = {
        '__name__': '__main__',
    }
    g.update(hooks)
    exec(f.read(), g)


问:
How does Java know which class to use in this example?
I am beginning to learn the principles of OOP and inheritance, and I came across this question while writing some code:

Suppose there is a package which contains a class called ClassA. Then, in a separate folder, I have another class called MyClass. Inside the same folder as MyClass, I have another class called ClassA, which is unrelated to the ClassA in the package. When I write the code for MyClass, I make it extend ClassA.

Which ClassA does MyClass extend from? Does MyClass inherit the ClassA which is in the imported package, or does MyClass inherit the ClassA which is in the same folder as MyClass? Would the code even compile?

I am trying to understand this from a theory perspective before diving into examples.

答:
Since you're new to programming, I'm going to explain it in really simple words. Say there is a package called Salads. In that package, you have a class called Caesar. Then, you have another package called People. In that package, you have another class called Caesar. Obviously, Salads.Caesar refers to Caesar salad, and People.Caesar refers to a person named Caesar. But both classes have the same name: Caesar.

So when you're writing java code, java looks in two places for class definitions:

classes defined in the same folder (because they are implicitly in the same package if they are in the same folder assuming you're following all the normal rules.

classes defined in any imported packages

So the question is asking if you just say Caesar in the code, will it recognize it as the one in the same folder or the one in the imported package? Well, this is a bad question to ask because first of all, you should not name your classes so ambiguously. Secondly, if it can't be helped, you should always refer to the fully qualified name in your code.

If you mean People.Caesar then type People.Caesar and if you mean Salads.Caesar, type Salads.Caesar. Don't take shortcuts. You can only take shortcuts if there is no ambiguity. The compiler will probably complain about it anyway asking you to specify. AKA your code will not work unless you change all references of Caesar to Salads.Caesar or People.Caesar.


问:
"Show code structure in the margin" with VS2017
The Productivity Power Tools for Visual Studio 2015 have a setting "Show code structure in the margin" (Options / Productivity Power Tools / Other Extensions) that, well, showed the code structure in the margin, at least for C# and some other languages, see this screenshot:

Left side is VS2015 with this option on, right is VS2017, both showing the same C# file. I’m referring to the blueish lines and half-ellipse-shaped things.

Now the Productivity Power Tools have been refactored for Visual Studio 2017, and I wasn’t able to turn this feature on. Is it still there, and if yes, how can I turn it on?

答: Looks like it's being rewritten to use Roslyn instead of the old API. A C++ version is already available. See also.</p>


问:
Is it possible to configure retries with the AWS CLI?
I have a script which uses the AWS CLI (currently v1.11.90) to coordinate various AWS resources. Amongst other things it calls aws cloudformation list-stacks three or four times in a row.

I fairly frequently get errors because my requests are being throttled:

```<code>An error occurred (Throttling) when calling the ListStacks operation (reached max retries: 4): Rate exceeded
</code>```

In particular if I happen to have the CloudFormation console open in my browser this happens pretty reliably.

I would like to configure it to be more forgiving in these cases -- either to back off more aggressively, or to retry more times. I've tried to find a way of doing this and have seen a few references to being able to do it in boto, but I can't see how to do it via the CLI.

答:
Seems you're using ListStack for cloudformation service maybe implementing a polling and retry, a simpler solution is now built into the CLI for this: aws <service> wait <condition> so the polling is already implemented.

```<code>$ aws cloudformation wait stack-exists --stack-name <name of the stack>
</code>```

Body:
I have a script which uses the AWS CLI (currently v1.11.90) to coordinate various AWS resources. Amongst other things it calls aws cloudformation list-stacks three or four times in a row.

I fairly frequently get errors because my requests are being throttled:

An error occurred (Throttling) when calling the ListStacks operation (reached max retries: 4): Rate exceeded

In particular if I happen to have the CloudFormation console open in my browser this happens pretty reliably.

I would like to configure it to be more forgiving in these cases -- either to back off more aggressively, or to retry more times. I've tried to find a way of doing this and have seen a few references to being able to do it in boto, but I can't see how to do it via the CLI.

Body:
Seems you're using ListStack for cloudformation service maybe implementing a polling and retry, a simpler solution is now built into the CLI for this: aws <service> wait <condition> so the polling is already implemented.

$ aws cloudformation wait stack-exists --stack-name <name of the stack>


答:
Well, there are a couple of ways to do that. Let's start with the most complex one - a fully dynamic creation of mytool. You can use the imp module to create a new module, then define its structure and, finally, add it to the global module list so that everything running in the same interpreter stack can import it:

run_mytool_script.py:

```<code>import imp
import sys

# lets first deal with loading of our external script so we don't waste cycles if a script
# was not provided as an argument
pending_script = None  # hold a script path we should execute
if __name__ == "__main__":  # make sure we're running this script directly, not imported
    if len(sys.argv) > 1:  # we need at least one argument to tell us which script to run
        pending_script = sys.argv[1]  # set the script to run as the first argument
    else:
        print("Please provide a path for a script to run")  # a script was not provided
        exit(1)

# now lets create the `mytool` module dynamically
mytool = imp.new_module("mytool")  # create a new module

def hello(name):  # define a local function
    print("Hello {}!".format(name))
mytool.__dict__["hello"] = hello  # add the function to the `mytool` module

sys.modules["mytool"] = mytool  # add 'mytool' to the global list so it can be imported

# now everything running in the same Python interpreter stack is able to import mytool
# lets run our `pending_script` if we're running the main script
if pending_script:
    try:
        execfile(pending_script)  # run the script
    except NameError:  # Python 3.x doesn't have execfile, use the exec function instead
        with open(pending_script, "r") as f:
            exec(f.read())  # read and run the script
</code>```

Now you can create another script that trusts you that there is a mytool module when being run through your proxy script, e.g.:

dump_menu_items.py:

```<code>import mytool
mytool.hello("Dump Menu Items")
</code>```

And now when you run it:

```<code>$ python run_mytool_script.py dump_menu_items.py
Hello Dump Menu Items!
</code>```

While neat, this is a rather tedious task - I'd suggest you to create a proper mytool module in the same folder where run_mytool_script.py is, have run_mytool_script.py initialize everything that's needed and then just use the last portion of the script to run your external script - that's much easier to manage and generally a much nicer approach.

Title: How can I exec a file and provide hooked imports in Python 3?

Body:
Well, there are a couple of ways to do that. Let's start with the most complex one - a fully dynamic creation of mytool. You can use the imp module to create a new module, then define its structure and, finally, add it to the global module list so that everything running in the same interpreter stack can import it:

run_mytool_script.py:

import imp
import sys

# lets first deal with loading of our external script so we don't waste cycles if a script
# was not provided as an argument
pending_script = None  # hold a script path we should execute
if __name__ == "__main__":  # make sure we're running this script directly, not imported
    if len(sys.argv) > 1:  # we need at least one argument to tell us which script to run
        pending_script = sys.argv[1]  # set the script to run as the first argument
    else:
        print("Please provide a path for a script to run")  # a script was not provided
        exit(1)

# now lets create the `mytool` module dynamically
mytool = imp.new_module("mytool")  # create a new module

def hello(name):  # define a local function
    print("Hello {}!".format(name))
mytool.__dict__["hello"] = hello  # add the function to the `mytool` module

sys.modules["mytool"] = mytool  # add 'mytool' to the global list so it can be imported

# now everything running in the same Python interpreter stack is able to import mytool
# lets run our `pending_script` if we're running the main script
if pending_script:
    try:
        execfile(pending_script)  # run the script
    except NameError:  # Python 3.x doesn't have execfile, use the exec function instead
        with open(pending_script, "r") as f:
            exec(f.read())  # read and run the script

Now you can create another script that trusts you that there is a mytool module when being run through your proxy script, e.g.:

dump_menu_items.py:

import mytool
mytool.hello("Dump Menu Items")

And now when you run it:

$ python run_mytool_script.py dump_menu_items.py
Hello Dump Menu Items!

While neat, this is a rather tedious task - I'd suggest you to create a proper mytool module in the same folder where run_mytool_script.py is, have run_mytool_script.py initialize everything that's needed and then just use the last portion of the script to run your external script - that's much easier to manage and generally a much nicer approach.


问:
Ubuntu Linux - Spawning an application when a USB device is plugged in
I'm trying to get an application to run whenever a USB device is plugged in: Flash drive, Camera, phone, etc. I'll probably start with a simple application like "Hello World". So basically, when I plug in a camera, flash drive, or phone I want my computer to spawn a "Hello World" application.

Is it possible to create this sort of functionality on the latest version of Ubuntu Linux? Would I need to create an application to listen for this event? What I would rather do is just have it work without having an to have an application running to catch it. Is this possible?

Anything I need to write will be in C. If someone could point me in the right direction, I would be very grateful.

Thanks,
T

答:
You should look into UDEV: http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html

On top of that I would suggest looking into hal: http://www.freedesktop.org/wiki/Software/hal Though it is starting to get old

Finally udisks: http://www.freedesktop.org/wiki/Software/udisks


问:
How to use a Tensorflow estimator
I was following this Tensorflow tutorial on creating a Convolutional Neural Network.

I'm at the step where the training and test data is read:

```<code>def main(unused_argv):
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)
</code>```

Up to here, everything is fine.

But then suddenly an estimator is created:

```<code>mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")
</code>```

My questions are:

What is an Estimator?

The previous code doesn't save anything under "/tmp/mnist_convnet_model". How come there is a model saved under that directory?
How did it get there?

EDIT:

When I run the code, I get:

```<code> Couldn't find trained model at ../tmp/mnist_convnet_model.
</code>```

This is because the model isn't found under that directory structure.

How can I put the model there? Also, why do I have to put it there, instead of storing it in memory for the execution of the script.

答:
The first question is answered right there in the tutorial. Estimator is "a TensorFlow class for performing high-level model training, evaluation, and inference".

The answer to the second question is that no, nothing is saved to that directory yet. The estimator object will use this directory to save training checkpoints, logs etc. When you run this code the first time, it will not load anything. But once you train the model, it will load the saved state from there.

Title: How to use a Tensorflow estimator

Body:
I was following this Tensorflow tutorial on creating a Convolutional Neural Network.

I'm at the step where the training and test data is read:

def main(unused_argv):
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

Up to here, everything is fine.

But then suddenly an estimator is created:

mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

My questions are:

What is an Estimator?

The previous code doesn't save anything under "/tmp/mnist_convnet_model". How come there is a model saved under that directory?
How did it get there?

EDIT:

When I run the code, I get:

 Couldn't find trained model at ../tmp/mnist_convnet_model.

This is because the model isn't found under that directory structure.

How can I put the model there? Also, why do I have to put it there, instead of storing it in memory for the execution of the script.


问:
Why is my Flask-SocketIO server not sending messages successfully to my client-side JavaScript?
I work on a home automation project with raspberry pi3 and flask. I would like to be able to send real-time info that will be displayed on a web page (html + javascript). For this I use the extension flask-socketio but it does not seem to work. Here is an excerpt of my code:

EDIT: After a lot of research, I thought it was necessary to create a thread so that the server sends messages to the client while it is processing other tasks. Then I modified my code as below. But I encounter a problem: the client receives a notification only once, when the first movement is captured. It receives nothing when other movements are captured and in my console I have an error of the kind:

return self.greenlet.switch() timeout: timed out

```<code>#-*- coding:utf-8 -*-
import eventlet
eventlet.monkey_patch()
from flask import Flask, render_template, send_from_directory, jsonify, request
from flask_socketio import SocketIO, send, emit
import os
import sys
import threading
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
PIN=4
GPIO.setup(PIN, GPIO.IN)

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'secret'
async_mode = "eventlet"
socketio = SocketIO(app, async_mode = async_mode)
thread = threading.Thread()
thread_stop_event = threading.Event()

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

class MotionThread(threading.Thread):
    def __init__(self):
        self.delay = 1
        super(MotionThread, self).__init__()

    def startMotion(self):
        try:
            mouv = False
            while not thread_stop_event.isSet():
                if GPIO.input(PIN):
                    if mouv == False:
                        socketio.emit('motion', "Motion detected", namespace='/test')
                        sleep(self.delay)
                        mouv = True

                else:
                        mouv = False

        except: pass

    def run(self):
        self.startMotion()

@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    print('Client connected')

    if not thread.isAlive():
        print "Starting Thread"
        thread = RandomThread()
        thread.start()

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port= 5000, debug=True)
</code>```

FIRST CODE:

```<code>from flask import Flask, render_template, send_from_directory, jsonify, request
from flask_socketio import SocketIO, emit, send
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
PIN=4
GPIO.setup(PIN, GPIO.IN)

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

@app.route('/')
def index():
    return render_template ('index.html')

@app.route('/_startMotion')
def startMotion():
    try:
        motion = False
        while True:
            if GPIO.input(PIN):
                if motion == False: test_message()
                motion = True
            else:
                motion = False
            time.sleep(.3)
    except: pass
    return 'ok'

@socketio.on('motion', namespace = '/motion-socket')
def test_message():
    emit('motion detected', {'data': 'Motion detected'})

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)
</code>```

EDIT2: Depending on my first code, the javascript code now looks like this:

```<code><script type=text/javascript>
    $(document).ready(function(){
        var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
        socket.on('motion', function(msg){
            alert("Server message" + msg);
        });
    });
</script>
</code>```

I would like to be able to post a message on my web page, whenever a movement is detected. Then an idea of what does not work in my code? I need help figuring out why the thread runs only once. Thanks

答:
I'm not very familiar with SocketIO, but it seems your JavaScript code isn't specifying what URL the socket should connect to.

Here's what your JavaScript should maybe look like instead, based on the example in Miguel Grinberg's tutorial:

```<code>$(document).ready(function(){
    var socket = io.connect('http://' + document.domain + ':' + location.port + '/motion-socket');
    socket.on('motion', function(msg){
        $('#message').text(msg.data);
        $('#message').fadeIn().delay(3000).fadeOut();
    });
});
</code>```

Also, your JavaScript seems to be listening for an event with name "motion", but your Python test_message() socket function sends the event with the send() function, which doesn't allow for specifying an event name, rather than using the emit() function, which does allow specifying an event name:

To send events a Flask server can use the send() and emit() functions provided by Flask-SocketIO. The send() function sends a standard message of string or JSON type to the client. The emit() function sends a message under a custom event name.

Source

It seems like you'll want the function to look more like this:

```<code>@socketio.on('motion', namespace='/motion-socket')
def test_message():
    emit('motion detected', {'data': 'Motion Detected'})
</code>```

Body:
I work on a home automation project with raspberry pi3 and flask. I would like to be able to send real-time info that will be displayed on a web page (html + javascript). For this I use the extension flask-socketio but it does not seem to work. Here is an excerpt of my code:

EDIT: After a lot of research, I thought it was necessary to create a thread so that the server sends messages to the client while it is processing other tasks. Then I modified my code as below. But I encounter a problem: the client receives a notification only once, when the first movement is captured. It receives nothing when other movements are captured and in my console I have an error of the kind:

return self.greenlet.switch() timeout: timed out

#-*- coding:utf-8 -*-
import eventlet
eventlet.monkey_patch()
from flask import Flask, render_template, send_from_directory, jsonify, request
from flask_socketio import SocketIO, send, emit
import os
import sys
import threading
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
PIN=4
GPIO.setup(PIN, GPIO.IN)

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'secret'
async_mode = "eventlet"
socketio = SocketIO(app, async_mode = async_mode)
thread = threading.Thread()
thread_stop_event = threading.Event()

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

class MotionThread(threading.Thread):
    def __init__(self):
        self.delay = 1
        super(MotionThread, self).__init__()

    def startMotion(self):
        try:
            mouv = False
            while not thread_stop_event.isSet():
                if GPIO.input(PIN):
                    if mouv == False:
                        socketio.emit('motion', "Motion detected", namespace='/test')
                        sleep(self.delay)
                        mouv = True

                else:
                        mouv = False

        except: pass

    def run(self):
        self.startMotion()

@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    print('Client connected')

    if not thread.isAlive():
        print "Starting Thread"
        thread = RandomThread()
        thread.start()

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port= 5000, debug=True)

FIRST CODE:

from flask import Flask, render_template, send_from_directory, jsonify, request
from flask_socketio import SocketIO, emit, send
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
PIN=4
GPIO.setup(PIN, GPIO.IN)

app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

@app.route('/')
def index():
    return render_template ('index.html')

@app.route('/_startMotion')
def startMotion():
    try:
        motion = False
        while True:
            if GPIO.input(PIN):
                if motion == False: test_message()
                motion = True
            else:
                motion = False
            time.sleep(.3)
    except: pass
    return 'ok'

@socketio.on('motion', namespace = '/motion-socket')
def test_message():
    emit('motion detected', {'data': 'Motion detected'})

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)

EDIT2: Depending on my first code, the javascript code now looks like this:

I would like to be able to post a message on my web page, whenever a movement is detected. Then an idea of what does not work in my code? I need help figuring out why the thread runs only once. Thanks

Body:
I'm not very familiar with SocketIO, but it seems your JavaScript code isn't specifying what URL the socket should connect to.

Here's what your JavaScript should maybe look like instead, based on the example in Miguel Grinberg's tutorial:

$(document).ready(function(){
    var socket = io.connect('http://' + document.domain + ':' + location.port + '/motion-socket');
    socket.on('motion', function(msg){
        $('#message').text(msg.data);
        $('#message').fadeIn().delay(3000).fadeOut();
    });
});

Also, your JavaScript seems to be listening for an event with name "motion", but your Python test_message() socket function sends the event with the send() function, which doesn't allow for specifying an event name, rather than using the emit() function, which does allow specifying an event name:

To send events a Flask server can use the send() and emit() functions provided by Flask-SocketIO. The send() function sends a standard message of string or JSON type to the client. The emit() function sends a message under a custom event name.

Source

It seems like you'll want the function to look more like this:

@socketio.on('motion', namespace='/motion-socket')
def test_message():
    emit('motion detected', {'data': 'Motion Detected'})


问:
How to test your django model using shell
I am trying to learn Django and have a very simple question that I am not able to get around with. I have coded my Django model as:

```<code>class Work(models.Model):
    STATES = (
        ('STARTED', 'started'),
        ('IN_PROGRESS', 'running'),
        ('FINISHED', 'completed'),
        ('ERROR', 'Error'),
    )
    owner = models.ForeignKey("auth.User")
    temp  = models.CharField(max_length=50, null=True, blank=True)
    current_run = models.CharField(max_length=50, null=True, blank=True)
    completion_percentage = models.IntegerField(blank=True, null=True)
    status = models.CharField(choices=STATES, max_length=50, blank=True, null=True)
</code>```

I have regenerated the db and now I want to use it Django views. But, before that is there a way to test it using python manage.py shell?

I am trying to do:

```<code>d_ = Work.objects.create(owner='admin')
</code>```

I get the error

```<code>ValueError: Cannot assign "'admin'": "Work.owner" must be a "User" instance.
</code>```

Currently, I have userid as 'admin' in Users.
I have tried doing few things to get around the error but I keep getting some kind of error because of the owner field (which is set to foreign key of auth.User).

Any help will be appreciated here. Thank you!

答:
You need to use an actual user object. Try this</p>

```<code>from django.contrib.auth.models import User
admin = User.objects.get(username='admin')
d_ = Work.objects.create(owner=admin)
</code>```

Body:
I am trying to learn Django and have a very simple question that I am not able to get around with. I have coded my Django model as:

class Work(models.Model):
    STATES = (
        ('STARTED', 'started'),
        ('IN_PROGRESS', 'running'),
        ('FINISHED', 'completed'),
        ('ERROR', 'Error'),
    )
    owner = models.ForeignKey("auth.User")
    temp  = models.CharField(max_length=50, null=True, blank=True)
    current_run = models.CharField(max_length=50, null=True, blank=True)
    completion_percentage = models.IntegerField(blank=True, null=True)
    status = models.CharField(choices=STATES, max_length=50, blank=True, null=True)

I have regenerated the db and now I want to use it Django views. But, before that is there a way to test it using python manage.py shell?

I am trying to do:

d_ = Work.objects.create(owner='admin')

I get the error

ValueError: Cannot assign "'admin'": "Work.owner" must be a "User" instance.

Currently, I have userid as 'admin' in Users.
I have tried doing few things to get around the error but I keep getting some kind of error because of the owner field (which is set to foreign key of auth.User).

Any help will be appreciated here. Thank you!

Body:
You need to use an actual user object. Try this

from django.contrib.auth.models import User
admin = User.objects.get(username='admin')
d_ = Work.objects.create(owner=admin)


问:
Maintaining Relationships Between Models that are Filled Through Signals After Saving
Look at answers to see how I solved it and what my problem was :)

I have a base model called stars that contains most relationships with other models, and some of the other models are taken through a signal to perform certain scripts that will enter into the database more information about the base model. My problem is when running the signals, I don't know how to maintain relationships with the models that are already a one to one field of the base model. If I try to make the empty models used for a signal a foreign key of their instance, it gives me errors since their instance is already connected to stars through its own foreign key. I'll post part of my code here, first part of my models, and then the part of my signal:

from django.db import models

# Create your models here.

'''define table with star name and its found relationships in the cards'''

class Star(models.Model):
 name = models.CharField(max_length=100, unique = True, verbose_name = "Star Name")

 def __str__(self):
  return self.name

class RA(models.Model):
 name = models.OneToOneField(Star,default = 1,to_field = "name")
 Ra = models.CharField(max_length = 10, help_text=("
  e.g. if the RA is 1 hour, 44 minutes, and 38 seconds, input the RA in this manner:  014438
"), verbose_name = "RA", unique = True)
 def __str__(self):
  return self.Ra

class DEC(models.Model):
 name = models.OneToOneField(Star,default = 1,to_field = "name")
 Dec = models.CharField(max_length = 10, help_text=("
  e.g if the DEC is +3 degrees, and 48.6 arc-minutes, input the DEC in this manner:  +0348.6  DON'T FORGET THE 0s FOR ONE DIGIT INPUTS.
"), verbose_name = "DEC", unique = True)
 def __str__(self):
  return self.Dec

class RAnew(models.Model):
 ra_new = models.CharField(max_length = 10)
 class Meta:
  verbose_name = "new RA"

 def __str__(self):
  return self.ra_new

class DECnew(models.Model):
 dec_new = models.CharField(max_length = 10)
 class Meta:
  verbose_name = "new Dec"

 def __str__(self):
  return self.dec_new

from .signals import perform_and_save_query, clean_URL, separate_ra, separate_dec
#this connects the astroquery and other signals and runs them yay```
</div>
</div>
</p>

<p>The signal script:</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>#create signals to run scripts

from astroquery.simbad import Simbad
from .models import Aliases, ReferenceURL, Bibcode, RA, DEC, RAnew, DECnew, Star
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.exceptions import ValidationError

@receiver(post_save, sender=RA)

def separate_ra(sender, **kwargs):
    if kwargs.get('created', False):
        RA.objects.get_or_create(Ra=kwargs.get('instance'))
        z = kwargs['instance']
        z = str(z)
        if len(z) < 6:
            raise ValidationError({'Ra': ["The RA needs to be 6 characters long, make sure you're using 0s in one digit pairs of numbers.",]})
        else:
            makenew = z[:2]+' h '+z[2:4]+' m '+z[4:]+' s'
            d = RAnew(ra_new = makenew)
            d.save()

@receiver(post_save, sender = DEC)

def separate_dec(sender, **kwargs):
    if kwargs.get('created', False):
        DEC.objects.get_or_create(Dec=kwargs.get('instance'))
        j = kwargs['instance']
        j = str(j)
        if len(j) < 7:
            raise ValidationError({'Dec': ["The Dec needs to be greater than 7 characters long, use zeros for 1 digit numbers and .0 in case of no decimals at the end",]})
        else:
            makenewdec = j[:3]+' degrees '+j[3:]+' arcmin'
            e =DECnew(dec_new = makenewdec)
            e.save()</code>```

The only signal that maintains a relationship to its instance is the first one "perform and save query" since it deals directly with the model "stars". Is there a way that the new saved "bibcode", "New RA" and "New Dec" can maintain their relationship to either their instance or their star?

答:
I was forgetting the format " model.objects.get(field = x) " to save an object for the other signals and that's why I was getting an error. I thought it had to do with the fact that the models were foreign keys of stars but it was just a syntax error!

To add to this, I recently learned of regex validators for models, this removes my need to have a signal that validates the way an entry is written because regex validators can really deal head-on with that type of need. I highly recommend it!

Body:
Look at answers to see how I solved it and what my problem was :)

I have a base model called stars that contains most relationships with other models, and some of the other models are taken through a signal to perform certain scripts that will enter into the database more information about the base model. My problem is when running the signals, I don't know how to maintain relationships with the models that are already a one to one field of the base model. If I try to make the empty models used for a signal a foreign key of their instance, it gives me errors since their instance is already connected to stars through its own foreign key. I'll post part of my code here, first part of my models, and then the part of my signal:

from django.db import models

# Create your models here.

'''define table with star name and its found relationships in the cards'''

class Star(models.Model):
 name = models.CharField(max_length=100, unique = True, verbose_name = "Star Name")

 def __str__(self):
  return self.name

class RA(models.Model):
 name = models.OneToOneField(Star,default = 1,to_field = "name")
 Ra = models.CharField(max_length = 10, help_text=("
  e.g. if the RA is 1 hour, 44 minutes, and 38 seconds, input the RA in this manner:  014438
"), verbose_name = "RA", unique = True)
 def __str__(self):
  return self.Ra

class DEC(models.Model):
 name = models.OneToOneField(Star,default = 1,to_field = "name")
 Dec = models.CharField(max_length = 10, help_text=("
  e.g if the DEC is +3 degrees, and 48.6 arc-minutes, input the DEC in this manner:  +0348.6  DON'T FORGET THE 0s FOR ONE DIGIT INPUTS.
"), verbose_name = "DEC", unique = True)
 def __str__(self):
  return self.Dec

class RAnew(models.Model):
 ra_new = models.CharField(max_length = 10)
 class Meta:
  verbose_name = "new RA"

 def __str__(self):
  return self.ra_new

class DECnew(models.Model):
 dec_new = models.CharField(max_length = 10)
 class Meta:
  verbose_name = "new Dec"

 def __str__(self):
  return self.dec_new

from .signals import perform_and_save_query, clean_URL, separate_ra, separate_dec
#this connects the astroquery and other signals and runs them yay

The signal script:

#create signals to run scripts

from astroquery.simbad import Simbad
from .models import Aliases, ReferenceURL, Bibcode, RA, DEC, RAnew, DECnew, Star
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.exceptions import ValidationError

@receiver(post_save, sender=RA)

def separate_ra(sender, **kwargs):
    if kwargs.get('created', False):
        RA.objects.get_or_create(Ra=kwargs.get('instance'))
        z = kwargs['instance']
        z = str(z)
        if len(z) < 6:
            raise ValidationError({'Ra': ["The RA needs to be 6 characters long, make sure you're using 0s in one digit pairs of numbers.",]})
        else:
            makenew = z[:2]+' h '+z[2:4]+' m '+z[4:]+' s'
            d = RAnew(ra_new = makenew)
            d.save()

@receiver(post_save, sender = DEC)

def separate_dec(sender, **kwargs):
    if kwargs.get('created', False):
        DEC.objects.get_or_create(Dec=kwargs.get('instance'))
        j = kwargs['instance']
        j = str(j)
        if len(j) < 7:
            raise ValidationError({'Dec': ["The Dec needs to be greater than 7 characters long, use zeros for 1 digit numbers and .0 in case of no decimals at the end",]})
        else:
            makenewdec = j[:3]+' degrees '+j[3:]+' arcmin'
            e =DECnew(dec_new = makenewdec)
            e.save()

The only signal that maintains a relationship to its instance is the first one "perform and save query" since it deals directly with the model "stars". Is there a way that the new saved "bibcode", "New RA" and "New Dec" can maintain their relationship to either their instance or their star?


问:
List all camera images in Android
How do you get a list of all camera images of an Android device?

Is it through the MediaStore? How?

答:
The Gallery app obtains camera images by using a content resolver over Images.Media.EXTERNAL_CONTENT_URI and filtering the results by Media.BUCKET_ID. The bucket identifier is determined with the following code:

```<code>public static final String CAMERA_IMAGE_BUCKET_NAME =
        Environment.getExternalStorageDirectory().toString()
        + "/DCIM/Camera";
public static final String CAMERA_IMAGE_BUCKET_ID =
        getBucketId(CAMERA_IMAGE_BUCKET_NAME);

/**
 * Matches code in MediaProvider.computeBucketValues. Should be a common
 * function.
 */
public static String getBucketId(String path) {
    return String.valueOf(path.toLowerCase().hashCode());
}
</code>```

Based on that, here's a snippet to get all camera images:

```<code>public static List<String> getCameraImages(Context context) {
    final String[] projection = { MediaStore.Images.Media.DATA };
    final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
    final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
    final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);
    ArrayList<String> result = new ArrayList<String>(cursor.getCount());
    if (cursor.moveToFirst()) {
        final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        do {
            final String data = cursor.getString(dataColumn);
            result.add(data);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return result;
}
</code>```

For more info, review the ImageManager and ImageList classes of the Gallery app source code.

Title: List all camera images in Android

Body:
The Gallery app obtains camera images by using a content resolver over Images.Media.EXTERNAL_CONTENT_URI and filtering the results by Media.BUCKET_ID. The bucket identifier is determined with the following code:

public static final String CAMERA_IMAGE_BUCKET_NAME =
        Environment.getExternalStorageDirectory().toString()
        + "/DCIM/Camera";
public static final String CAMERA_IMAGE_BUCKET_ID =
        getBucketId(CAMERA_IMAGE_BUCKET_NAME);

/**
 * Matches code in MediaProvider.computeBucketValues. Should be a common
 * function.
 */
public static String getBucketId(String path) {
    return String.valueOf(path.toLowerCase().hashCode());
}

Based on that, here's a snippet to get all camera images:

public static List<String> getCameraImages(Context context) {
    final String[] projection = { MediaStore.Images.Media.DATA };
    final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
    final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
    final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);
    ArrayList<String> result = new ArrayList<String>(cursor.getCount());
    if (cursor.moveToFirst()) {
        final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        do {
            final String data = cursor.getString(dataColumn);
            result.add(data);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return result;
}

For more info, review the ImageManager and ImageList classes of the Gallery app source code.


问:
replace-char in Emacs Lisp ?
Emacs Lisp has replace-string but has no replace-char. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:

```<code>(replace-string (make-string 1 ?\x53979) "'")
</code>```

I think it would be better with replace-char.

What is the best way to do this?

答:
This is the way I replace characters in elisp:

```<code>(subst-char-in-string ?' ?’ "John's")
</code>```

gives:

```<code>"John’s"
</code>```

Note that this function doesn't accept characters as string. The first and second argument must be a literal character (either using the ? notation or string-to-char).

Also note that this function can be destructive if the optional inplace argument is non-nil.

OwnerDisplayName: bortzmeyer

Title: replace-char in Emacs Lisp ?

Body:
Emacs Lisp has replace-string but has no replace-char. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:

(replace-string (make-string 1 ?\x53979) "'")

I think it would be better with replace-char.

What is the best way to do this?

LastEditorDisplayName: Chris Conway

Body:
This is the way I replace characters in elisp:

(subst-char-in-string ?' ?’ "John's")

gives:

"John’s"

Note that this function doesn't accept characters as string. The first and second argument must be a literal character (either using the ? notation or string-to-char).

Also note that this function can be destructive if the optional inplace argument is non-nil.


问:
Detect which position on tab layout
I want to know or someone to give me an idea to detect which position I am on a tab layout, i got a tab layout and i cant seem to figure out where i should do what i want, i tried doing it here at an extended FragmentPagerAdapter:

```<code>@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position

    return tabTitles[position];
}
</code>```

Basically i check if im at position 1 and do what ever and then do something else but it doesnt work, only calls the code once and neva again
ANd here at an extended fragment

```<code> @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = null;

    switch (p) {
        case 1:
            view = RenderFactory.getClass("Page1", inflater, container).displayContent();
            break;
        case 2:
            view = RenderFactory.getClass("Page2", inflater, container).displayContent();
            break;
        case 3:

            view = RenderFactory.getClass("Page3", inflater, container).displayContent();
            break;

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

here i just put the code within each case and the code doesnt get called more then once. Any ideas ??

答:
You can get the current item with this code :

```<code>tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
    @Override
    public void onTabSelected(TabLayout.Tab tab){
        int current_position = tab.getPosition();
    }
});
</code>```

or :

```<code>int current_position = mViewPager.getCurrentItem();
</code>```

Title: Detect which position on tab layout

Body:
I want to know or someone to give me an idea to detect which position I am on a tab layout, i got a tab layout and i cant seem to figure out where i should do what i want, i tried doing it here at an extended FragmentPagerAdapter:

@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position

    return tabTitles[position];
}

Basically i check if im at position 1 and do what ever and then do something else but it doesnt work, only calls the code once and neva again
ANd here at an extended fragment

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = null;

    switch (p) {
        case 1:
            view = RenderFactory.getClass("Page1", inflater, container).displayContent();
            break;
        case 2:
            view = RenderFactory.getClass("Page2", inflater, container).displayContent();
            break;
        case 3:

            view = RenderFactory.getClass("Page3", inflater, container).displayContent();
            break;

    }
    return view;
}

here i just put the code within each case and the code doesnt get called more then once. Any ideas ??

Body:
You can get the current item with this code :

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
    @Override
    public void onTabSelected(TabLayout.Tab tab){
        int current_position = tab.getPosition();
    }
});

or :

int current_position = mViewPager.getCurrentItem();


问:
How to create a list of string in nth position of every line in Python
What would be a pythonic way to create a list of (to illustrate with an example) the fifth string of every line of a text file, assuming it ressembles something like this:

12, 27.i, 3, 6.7, Hello, 438

In this case, the script would add "Hello" (without quotes) to the list.

In other words (to generalize), with an input "input.txt", how could I get a list in python that takes the nth string (n being a defined number) of every line?

Many thanks in advance!

答: This may not be the most efficient solution, but you could also just hard code it e.g. create a variable equivalent to zero, add one to the variable for each word in the line, and append the word to a list when variable = 5. Then reset the variable equal to zero. </p>


问:
how to check the tag name corresponds to specific tag in Python
I am parsing html file through all its tags and when I encounter body tag I want to perform some string operations and save the results back to html file. When I try

```<code>if tag.name == 'body':
  // go inside the loop
</code>```

the if loop itself is not getting processed. What is the correct method to check whether the tag name corresponds to body tag

答: Found the answer using beautifulsoup and would like to update it to others : Soup.body.name</p>

Body:
I am parsing html file through all its tags and when I encounter body tag I want to perform some string operations and save the results back to html file. When I try

if tag.name == 'body':
  // go inside the loop

the if loop itself is not getting processed. What is the correct method to check whether the tag name corresponds to body tag


问:
Rails STI conditional sub-classing from base class
I'm developing a project where I have an entity which may have two kinds of assets: Pictures and Videos, basically.

Since I want all the assets to be on the same table and a single upload form for either Pictures or Videos, I'm using Single Table Inheritance having both Picture and Video descending from the Asset class. Also, I'll be running different validations/callbacks depending on whether it is a Video or a Picture.

I'm using paperclip to deal with the upload process, and my idea is to when uploading a file and creating an Asset with it, the application will instantiate the correct subclass (Picture or Video) depending on the mime-type of the uploaded file.

This is a sketch of my classes:

```<code>class Project < ActiveRecord::Base
  has_many :assets
  accepts_nested_attributes_for :assets
end

class Asset < ActiveRecord::Base
  belongs_to :project
  has_uploaded_file :content, ...
end

class Picture < Asset
  validate :image_size
  ...
end

class Video < Asset
  after_save :convert_format
  ...
end
</code>```

My idea is to implement a before_save callback on the Asset class and try to instantiate the correct class there, but I'm not sure how to do it or if it's a good idea.

Any idea about this?

答: While you should favor fat models and skinny controllers, this to me seems better placed in the controller.  My primary rationale is that by doing this in your Asset model you are coupling a base type to its subtypes, which doesn't feel right to me (although I see APIs do it all the time).

Body:
I'm developing a project where I have an entity which may have two kinds of assets: Pictures and Videos, basically.

Since I want all the assets to be on the same table and a single upload form for either Pictures or Videos, I'm using Single Table Inheritance having both Picture and Video descending from the Asset class. Also, I'll be running different validations/callbacks depending on whether it is a Video or a Picture.

I'm using paperclip to deal with the upload process, and my idea is to when uploading a file and creating an Asset with it, the application will instantiate the correct subclass (Picture or Video) depending on the mime-type of the uploaded file.

This is a sketch of my classes:

class Project < ActiveRecord::Base
  has_many :assets
  accepts_nested_attributes_for :assets
end

class Asset < ActiveRecord::Base
  belongs_to :project
  has_uploaded_file :content, ...
end

class Picture < Asset
  validate :image_size
  ...
end

class Video < Asset
  after_save :convert_format
  ...
end

My idea is to implement a before_save callback on the Asset class and try to instantiate the correct class there, but I'm not sure how to do it or if it's a good idea.

Any idea about this?


问:
Why do i get an exception when inspecting at debug time and not at runtime / what is the best practice for mapping an enum from DB
Consider the following code snippet

```<code>public class Class1
{
    public enum TestEnum
    {
        Value1 = 1,
        Value2 = 2
    }
    public void TestCall()
    {
        /*some standard DB code returning an SqlDataReader...*/
        SqlDataReader rdr = com.ExecuteReader();
        Item item = new Item();

        /*original code*/
        /*Database "Type" is a varchar() field containing an integer, please dont ask why :)*/
        if (rdr["Type"].GetType() == typeof(DBNull))
        {
            item.Type = TestEnum.Value1;
        }
        else if ((string)rdr["Type"] == "1")
        {
            item.Type = TestEnum.Value2;
        }
        else if ((string)rdr["Type"] == "2")
        {
            item.Type = TestEnum.Value1;
        }
        else
        {
            item.Type = TestEnum.Value1;
        }

        /*suggested code*/
        item.Type = rdr["Type"] as TestEnum? ?? TestEnum.Value1; //<- default / null value to use
    }
}
public class Item
{
    public Class1.TestEnum Type;
}
</code>```

During code review, a colleague of mine pointed out that i could replace the cascading IFs ("original code") with a single line ("suggested code")

While the suggested code runs just fine, I get a NullReferenceException when inspecting "rdr["Type"] as TestEnum?" at debug time.

I was wondering if this is a sign of underlying problems with the suggested code, what is the prefered way of mapping a database value to an enum, and what are your thoughts on this kind of code generally speaking.

答:
The suggested code is just wrong - it will not throw exception, but will always evaluate to TestEnum.Value1.

Why? The reader returns the value as object. The as T? operator will evaluate to non null value only if the object represents a boxed T value. When the object contains string as in your case, or even if was a boxed int (the underlying type of your enum), still the operator as TestEnum? will evaluate to null, hence the expression will hit the ?? TestEnum.Value1 condition.

Shortly, don't rely on such tricks. If you want to improve that code, create a method (which can be reused from other places if needed):

```<code>static TestEnum ToTestEnum(object dbValue)
{
    TestEnum value;
    return Enum.TryParse(dbValue as string, out value) ? value : TestEnum.Value1;
}
</code>```

and then change the original code like

```<code>item.Type = ToTestEnum(rdr["Type"]);
</code>```

Body:
Consider the following code snippet

public class Class1
{
    public enum TestEnum
    {
        Value1 = 1,
        Value2 = 2
    }
    public void TestCall()
    {
        /*some standard DB code returning an SqlDataReader...*/
        SqlDataReader rdr = com.ExecuteReader();
        Item item = new Item();

        /*original code*/
        /*Database "Type" is a varchar() field containing an integer, please dont ask why :)*/
        if (rdr["Type"].GetType() == typeof(DBNull))
        {
            item.Type = TestEnum.Value1;
        }
        else if ((string)rdr["Type"] == "1")
        {
            item.Type = TestEnum.Value2;
        }
        else if ((string)rdr["Type"] == "2")
        {
            item.Type = TestEnum.Value1;
        }
        else
        {
            item.Type = TestEnum.Value1;
        }

        /*suggested code*/
        item.Type = rdr["Type"] as TestEnum? ?? TestEnum.Value1; //<- default / null value to use
    }
}
public class Item
{
    public Class1.TestEnum Type;
}

During code review, a colleague of mine pointed out that i could replace the cascading IFs ("original code") with a single line ("suggested code")

While the suggested code runs just fine, I get a NullReferenceException when inspecting "rdr["Type"] as TestEnum?" at debug time.

I was wondering if this is a sign of underlying problems with the suggested code, what is the prefered way of mapping a database value to an enum, and what are your thoughts on this kind of code generally speaking.

Body:
The suggested code is just wrong - it will not throw exception, but will always evaluate to TestEnum.Value1.

Why? The reader returns the value as object. The as T? operator will evaluate to non null value only if the object represents a boxed T value. When the object contains string as in your case, or even if was a boxed int (the underlying type of your enum), still the operator as TestEnum? will evaluate to null, hence the expression will hit the ?? TestEnum.Value1 condition.

Shortly, don't rely on such tricks. If you want to improve that code, create a method (which can be reused from other places if needed):

static TestEnum ToTestEnum(object dbValue)
{
    TestEnum value;
    return Enum.TryParse(dbValue as string, out value) ? value : TestEnum.Value1;
}

and then change the original code like

item.Type = ToTestEnum(rdr["Type"]);