问:
Bootstrap 3: Stacking Order in Navbar with Custom Image Styling
I have been trying to port the functionality of a simple rounded image class to work with Bootstrap v3.3.7.  Essentially, I nest an img inside of a div, and apply an inset border with alpha-transparency.  It works great, as seen in this simple jsFiddle:

Rounded Avatar jsFiddle

CSS:

```<code>.inset {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  box-shadow:
    inset 0 0 0 2px rgba(255,255,255,0.6),
    0 1px 1px rgba(0,0,0,0.1);
}

.inset img {
  border-radius: inherit;
  width: inherit;
  height: inherit;
  display: block;
  position: relative;
  z-index: -1;
}
</code>```

And the markup would look like:

```<code><div class="inset">
  <img src="http://rs775.pbsrc.com/albums/yy35/PhoenyxStar/link-1.jpg~c200">
</div>
</code>```

However, when I attempt to use this inside of a navbar in Bootstrap v3.3.7, I am encountering what I presume to be a stacking issue that I just cannot resolve.  As in the sample above, I had started out with the img having a z-index of -1, so that it would sit below the div.  This puts it underneath the navbar.  So, I had assumed that I could simply push up the z-index of the div and the img to a physical value, trying 998 for the img and 999 for the div.

When I do that, however, the div does not show.  If I am to push the img below the div, however, I see the div and the border being correct - I just can't get it to display above the image.  I've create a minimal example of this behavior as a Bootply.

Bootply with Avatar Rounding and Missing Inset Border

I am at a loss to explain this, (and my front-end skills leave a bit to be desired).  Can only assume that there is something simple that I have to be missing.  Any help would be greatly appreciated.

Thank you, in advance.

答:
By giving it a z-index:-1, you're sending your image below the current stacking context. Because it doesn't have one, and because it doesn't have any parent with a background, it renders as you expect it to, but you shouldn't expect it to. And without giving it a z-index:-1, you can't make it render below its parent. But, again, it's not just below the parent, it's below the stacking context.

Here's what happens when I simply put your example inside: a div with background.

The problem is you want an effect applied to the parent to render above the child.

You could (and should) use either a sibling/child of the child, which could be either an unused pseudo-element of the parent or a pseudo-element of the child. But, since the child is an  tag, it cannot have pseudo-elements, so we'll stick to the parent:

.inset {
  width: 100px;
  height: 100px;
  position: relative;
  border-radius: 50%;
}
.inset::after {
  width: inherit;
  height: inherit;
  border-radius: inherit;
  box-shadow:
    inset 0 0 0 2px rgba(255,255,255,0.6),
    0 1px 2px rgba(0,0,0,0.1);
  position: absolute;
  top: 0;
  left: 0;
  content: '';
}

.inset img {
  border-radius: inherit;
  width: inherit;
  height: inherit;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="background-color: red;">
  <div class="inset">
    <img src="http://rs775.pbsrc.com/albums/yy35/PhoenyxStar/link-1.jpg~c200">
  </div>
</div></code>```

This will work anywhere you place it, regardless of current z-index or stacking context.

The other option, if you insist on Doing-it-wrong™ would be to wrap the current parent inside an element that would create a new stacking context

```<code>position:relative;
z-index: 0;
</code>```

... but I find it harder to maintain, bloated and probably confusing for anyone not familiar with how stacking contexts work. This technique comes in handy when adding color overlays to images (instead of using an extra element, you just use the wrapper background). But, again, it confuses people so it shouldn't be used.

Body:
I have been trying to port the functionality of a simple rounded image class to work with Bootstrap v3.3.7.  Essentially, I nest an img inside of a div, and apply an inset border with alpha-transparency.  It works great, as seen in this simple jsFiddle:

Rounded Avatar jsFiddle

CSS:

.inset {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  box-shadow:
    inset 0 0 0 2px rgba(255,255,255,0.6),
    0 1px 1px rgba(0,0,0,0.1);
}

.inset img {
  border-radius: inherit;
  width: inherit;
  height: inherit;
  display: block;
  position: relative;
  z-index: -1;
}

And the markup would look like:

However, when I attempt to use this inside of a navbar in Bootstrap v3.3.7, I am encountering what I presume to be a stacking issue that I just cannot resolve.  As in the sample above, I had started out with the img having a z-index of -1, so that it would sit below the div.  This puts it underneath the navbar.  So, I had assumed that I could simply push up the z-index of the div and the img to a physical value, trying 998 for the img and 999 for the div.

When I do that, however, the div does not show.  If I am to push the img below the div, however, I see the div and the border being correct - I just can't get it to display above the image.  I've create a minimal example of this behavior as a Bootply.

Bootply with Avatar Rounding and Missing Inset Border

I am at a loss to explain this, (and my front-end skills leave a bit to be desired).  Can only assume that there is something simple that I have to be missing.  Any help would be greatly appreciated.

Thank you, in advance.

Body:
By giving it a z-index:-1, you're sending your image below the current stacking context. Because it doesn't have one, and because it doesn't have any parent with a background, it renders as you expect it to, but you shouldn't expect it to. And without giving it a z-index:-1, you can't make it render below its parent. But, again, it's not just below the parent, it's below the stacking context.

Here's what happens when I simply put your example inside: a div with background.

The problem is you want an effect applied to the parent to render above the child.

You could (and should) use either a sibling/child of the child, which could be either an unused pseudo-element of the parent or a pseudo-element of the child. But, since the child is an <img /> tag, it cannot have pseudo-elements, so we'll stick to the parent:

.inset {
  width: 100px;
  height: 100px;
  position: relative;
  border-radius: 50%;
}
.inset::after {
  width: inherit;
  height: inherit;
  border-radius: inherit;
  box-shadow:
    inset 0 0 0 2px rgba(255,255,255,0.6),
    0 1px 2px rgba(0,0,0,0.1);
  position: absolute;
  top: 0;
  left: 0;
  content: '';
}

.inset img {
  border-radius: inherit;
  width: inherit;
  height: inherit;
  display: block;
}

<div style="background-color: red;">
  <div class="inset">
    <img src="http://rs775.pbsrc.com/albums/yy35/PhoenyxStar/link-1.jpg~c200">
  </div>
</div>

This will work anywhere you place it, regardless of current z-index or stacking context.

The other option, if you insist on Doing-it-wrong™ would be to wrap the current parent inside an element that would create a new stacking context

position:relative;
z-index: 0;

... but I find it harder to maintain, bloated and probably confusing for anyone not familiar with how stacking contexts work. This technique comes in handy when adding color overlays to images (instead of using an extra element, you just use the wrapper background). But, again, it confuses people so it shouldn't be used.


来源: stackexchange

问:
How to store firebase token on my server if user have more than one device
I'm using this well known code to save a new firebase token on my server (from: Retrieve the current registration token):

```<code>@Override
public void onTokenRefresh() {

    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}
</code>```

The problem is, that if the user installs the app on some other device, the same code will be executed and the former firebase token will be overridden by the new one.

So I have to distinguish between the devices, but how can I do it? Device name is for sure not unique enough for this.

EDIT: unfortunately, the suggestion by Bob Snyder did not work. The FirebaseInstanceId#getId() is always different if I remove the App data (cache) or reinstall the app.

答:
The token is unique to each device and includes the app instance ID.  The 11-character instance ID, which is the same one returned by FirebaseInstanceId.getInstance().getId(), appears first, followed by a colon, and the remainder of the token. Example:

```<code>    eiURDSe_P4q:APA91bFvtCzK...LRpzvQOSdNKioklO
</code>```

You can use the instance ID as a unique key to store the token on the server.

ContentLicense: CC BY-SA 3.0

Body:
I'm using this well known code to save a new firebase token on my server (from: Retrieve the current registration token):

@Override
public void onTokenRefresh() {

    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

The problem is, that if the user installs the app on some other device, the same code will be executed and the former firebase token will be overridden by the new one.

So I have to distinguish between the devices, but how can I do it? Device name is for sure not unique enough for this.

EDIT: unfortunately, the suggestion by Bob Snyder did not work. The FirebaseInstanceId#getId() is always different if I remove the App data (cache) or reinstall the app.

Body:
The token is unique to each device and includes the app instance ID.  The 11-character instance ID, which is the same one returned by FirebaseInstanceId.getInstance().getId(), appears first, followed by a colon, and the remainder of the token. Example:

    eiURDSe_P4q:APA91bFvtCzK...LRpzvQOSdNKioklO

You can use the instance ID as a unique key to store the token on the server.


问:
Putting names from a file into an array is causing an infinite loop
I have a text file "names" which contains 10 names, each name on its own line. What I want to do is put these names into an array "anArray". Just to check that I'm doing an alright job, I outputted a line as you can see.

Here's the code I used to try to do that:

```<code> public static void main(String[] args) throws FileNotFoundException
    {
        File file=new File("names.txt");
        Scanner my_input= new Scanner(file);
        String [] anArray;
        anArray = new String[10];
        String a = my_input.nextLine();
        while(my_input.hasNextLine())
        {
            for(int i = 0; i<10;i++)
            {
                while (!(a.equals("\n")))
                {
                    anArray[i] = a;
                    System.out.println("Element" + i + "of the array is: " + anArray[i]);

                }
                i++;
                a=my_input.next();
            }
        }
        my_input.close();
    }
</code>```

However this code fails, what happens is "Element 0 of the array is: name 1" is outputted an infinite amount of times, "name 1" being the first name in the text file. I don't know what I'm doing wrong here, could anybody enlighten me?

答:
You currently have an infinite loop on your inner while loop, you don't update a so that will loop forever once entered. I think you wanted to check that i is less than 10 and your input still has more lines. You can do that with a singe loop. I would also prefer a try-with-resources over explicitly closing. And you can guard against empty lines with String.isEmpty(). Something like,

```<code>File file = new File("names.txt");
try (Scanner my_input = new Scanner(file)) {
    String[] anArray = new String[10];
    for (int i = 0; i < 10 && my_input.hasNextLine(); i++) {
        String line = my_input.nextLine();
        if (line.isEmpty()) {
            continue;
        }
        anArray[i] = line;
        System.out.printf("Element %d of the array is: %s%n", i, anArray[i]);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

Body:
I have a text file "names" which contains 10 names, each name on its own line. What I want to do is put these names into an array "anArray". Just to check that I'm doing an alright job, I outputted a line as you can see.

Here's the code I used to try to do that:

 public static void main(String[] args) throws FileNotFoundException
    {
        File file=new File("names.txt");
        Scanner my_input= new Scanner(file);
        String [] anArray;
        anArray = new String[10];
        String a = my_input.nextLine();
        while(my_input.hasNextLine())
        {
            for(int i = 0; i<10;i++)
            {
                while (!(a.equals("\n")))
                {
                    anArray[i] = a;
                    System.out.println("Element" + i + "of the array is: " + anArray[i]);

                }
                i++;
                a=my_input.next();
            }
        }
        my_input.close();
    }

However this code fails, what happens is "Element 0 of the array is: name 1" is outputted an infinite amount of times, "name 1" being the first name in the text file. I don't know what I'm doing wrong here, could anybody enlighten me?

Body:
You currently have an infinite loop on your inner while loop, you don't update a so that will loop forever once entered. I think you wanted to check that i is less than 10 and your input still has more lines. You can do that with a singe loop. I would also prefer a try-with-resources over explicitly closing. And you can guard against empty lines with String.isEmpty(). Something like,

File file = new File("names.txt");
try (Scanner my_input = new Scanner(file)) {
    String[] anArray = new String[10];
    for (int i = 0; i < 10 && my_input.hasNextLine(); i++) {
        String line = my_input.nextLine();
        if (line.isEmpty()) {
            continue;
        }
        anArray[i] = line;
        System.out.printf("Element %d of the array is: %s%n", i, anArray[i]);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}


问:
Why are binding to my view only the first element using AngularFire?
I having troubles to show in my view the content storage on Firebase DB. I know that Firebase is asynchronous. This is my current structure on my Firebase Database:

Employees

Recognitions

Code:

```<code>    var bigObject = {};

    // Find all recognitions
    var ref = firebase.database().ref('recognitions');

    ref.once('value').then(function(snapshot) {
        bigObject = snapshot.val();
        // Loop through all recognitions
        for (o in bigObject) {
            var ref2 = firebase.database().ref('employees').child(bigObject[o].employee);
            ref2.once('value').then(function(snapshot2) {
                bigObject[o].profile = snapshot2.val();
                // Bind the content to the view
                $scope.$apply(function() {
                  $scope.data = bigObject;
                });
            });
        }
    });
</code>```

My concern is why are binding to my scope only the first element of bigObject? I guess that is an asynchronous error. How can solve that?.

答:
You are running into the infamous loop issue.

The problem is that when your callback executes, the value of o is no longer what you're expecting it to be.

Here's a simplified example, where the first version demonstrates what's essentially happening with your code, and the second version shows one way to solve the issue:

/**
 * This wont work properly
 */
var obj = {
  a: 'Original',
  b: 'Original',
  c: 'Original'
}

for (var i in obj) {
  var fn = function() {
    obj[i] = 'Updated'
  }
  setTimeout(fn, 4)
}

setTimeout(function() {
  console.log('Object 1', obj)
}, 20)

/**
 * ...but this will
 */

var obj2 = {
  a: 'Original',
  b: 'Original',
  c: 'Original'
}

for (var i in obj2) {
  var fn = function(i) {
    obj2[i] = 'Updated'
  }.bind(this, i);
  setTimeout(fn, 4)
}

setTimeout(function() {
  console.log('Object 2', obj2)
}, 60)```

There are of course many ways to go about this, but a simple solution would be to bind the proper index to your callback.

Body:
I having troubles to show in my view the content storage on Firebase DB. I know that Firebase is asynchronous. This is my current structure on my Firebase Database:

Employees

Recognitions

Code:

    var bigObject = {};

    // Find all recognitions
    var ref = firebase.database().ref('recognitions');

    ref.once('value').then(function(snapshot) {
        bigObject = snapshot.val();
        // Loop through all recognitions
        for (o in bigObject) {
            var ref2 = firebase.database().ref('employees').child(bigObject[o].employee);
            ref2.once('value').then(function(snapshot2) {
                bigObject[o].profile = snapshot2.val();
                // Bind the content to the view
                $scope.$apply(function() {
                  $scope.data = bigObject;
                });
            });
        }
    });

My concern is why are binding to my scope only the first element of bigObject? I guess that is an asynchronous error. How can solve that?.

Body:
You are running into the infamous loop issue.

The problem is that when your callback executes, the value of o is no longer what you're expecting it to be.

Here's a simplified example, where the first version demonstrates what's essentially happening with your code, and the second version shows one way to solve the issue:

/**
 * This wont work properly
 */
var obj = {
  a: 'Original',
  b: 'Original',
  c: 'Original'
}

for (var i in obj) {
  var fn = function() {
    obj[i] = 'Updated'
  }
  setTimeout(fn, 4)
}

setTimeout(function() {
  console.log('Object 1', obj)
}, 20)

/**
 * ...but this will
 */

var obj2 = {
  a: 'Original',
  b: 'Original',
  c: 'Original'
}

for (var i in obj2) {
  var fn = function(i) {
    obj2[i] = 'Updated'
  }.bind(this, i);
  setTimeout(fn, 4)
}

setTimeout(function() {
  console.log('Object 2', obj2)
}, 60)

There are of course many ways to go about this, but a simple solution would be to bind the proper index to your callback.


问:
Using QPainter over OpenGL in QGLWidget when using shaders
Many of you Qt (4.6 specifically) users will be familiar with the Overpainting example supplied in the OpenGL tutorials, I'm trying to do something very similar but using shaders for the pure OpenGL data, instead of the old fixed-function pipeline.

```<code>//  Set background and state.
makeCurrent();
qglClearColor( bgColour_ );

glEnable( GL_DEPTH_TEST );
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

if ( smoothLines_ ) {
    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable( GL_LINE_SMOOTH );
    glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
}

//  Clear the buffers.
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUseProgram( shader_ );

//  Draw the grid.
try {
    glLineWidth( 2.0f );
    manager_->setColour( centreColour_ );
    grid_->draw( oE_GLGrid::Centre );

    glLineWidth( 1.5f );
    manager_->setColour( majorColour_ );
    grid_->draw( oE_GLGrid::Major );

    glLineWidth( 1.0f );
    manager_->setColour( minorColour_ );
    grid_->draw( oE_GLGrid::Minor );
} catch( oE_GLException& e ) {
    cout << "OpenGL Error: " << e.what() << endl;
    return;
}

//  Reset OpenGL state for overlays.
glDisable( GL_DEPTH_TEST );
if ( smoothLines_ ) {
    glDisable( GL_BLEND );
    glDisable( GL_LINE_SMOOTH );
}

//  Draw the overlays.
QPainter p( this );
p.beginNativePainting();
p.fillRect( 10, 10, 100, 100,
        QColor( 255, 0, 0 ) );
p.endNativePainting();
</code>```

I'm building a 3D asset application hence the grid stuff.  To make it really obvious when it works, a big red rectangle should appear in the top left corner of the widget - but it doesn't.

The 3D works fine, but QPainter gets nothing to the screen.  The only real difference I can see between mine and the docs is that the all the projection and transformation matrix calculations are hidden away in other functions and then uploaded to the shader via glUniform.  Presumably as QPainter splits the 2D assets into triangles, this means that QPainter's shaders don't have access to my projection/transformation matrices, so my red triangle is begin drawn - but perhaps somewhere offscreen.

答:
Call beginNativePainting() before making OpenGL calls. A glPush/Pop of the OpenGL state may also be necessary. Try something like the following:</p>

```<code>QPainter p( this );
p.beginNativePainting();

// Maybe necessary
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();

// Put OpenGL code here

// Necessary if used glPush-es above
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();

p.endNativePainting();

p.fillRect( 10, 10, 100, 100,
        QColor( 255, 0, 0 ) );
</code>```

Body:
Many of you Qt (4.6 specifically) users will be familiar with the Overpainting example supplied in the OpenGL tutorials, I'm trying to do something very similar but using shaders for the pure OpenGL data, instead of the old fixed-function pipeline.

//  Set background and state.
makeCurrent();
qglClearColor( bgColour_ );

glEnable( GL_DEPTH_TEST );
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

if ( smoothLines_ ) {
    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable( GL_LINE_SMOOTH );
    glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
}

//  Clear the buffers.
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUseProgram( shader_ );

//  Draw the grid.
try {
    glLineWidth( 2.0f );
    manager_->setColour( centreColour_ );
    grid_->draw( oE_GLGrid::Centre );

    glLineWidth( 1.5f );
    manager_->setColour( majorColour_ );
    grid_->draw( oE_GLGrid::Major );

    glLineWidth( 1.0f );
    manager_->setColour( minorColour_ );
    grid_->draw( oE_GLGrid::Minor );
} catch( oE_GLException& e ) {
    cout << "OpenGL Error: " << e.what() << endl;
    return;
}

//  Reset OpenGL state for overlays.
glDisable( GL_DEPTH_TEST );
if ( smoothLines_ ) {
    glDisable( GL_BLEND );
    glDisable( GL_LINE_SMOOTH );
}

//  Draw the overlays.
QPainter p( this );
p.beginNativePainting();
p.fillRect( 10, 10, 100, 100,
        QColor( 255, 0, 0 ) );
p.endNativePainting();

I'm building a 3D asset application hence the grid stuff.  To make it really obvious when it works, a big red rectangle should appear in the top left corner of the widget - but it doesn't.

The 3D works fine, but QPainter gets nothing to the screen.  The only real difference I can see between mine and the docs is that the all the projection and transformation matrix calculations are hidden away in other functions and then uploaded to the shader via glUniform.  Presumably as QPainter splits the 2D assets into triangles, this means that QPainter's shaders don't have access to my projection/transformation matrices, so my red triangle is begin drawn - but perhaps somewhere offscreen.

Body:
Call beginNativePainting() before making OpenGL calls. A glPush/Pop of the OpenGL state may also be necessary. Try something like the following:

QPainter p( this );
p.beginNativePainting();

// Maybe necessary
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();

// Put OpenGL code here

// Necessary if used glPush-es above
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();

p.endNativePainting();

p.fillRect( 10, 10, 100, 100,
        QColor( 255, 0, 0 ) );

ContentLicense: CC BY-SA 2.5


问:
"The credentials supplied to the package were not recognized" error when authenticating as server with certificate generated using BouncyCastle
I'm trying to create a certificate using the BouncyCastle.Crypto dll, which is then used to authenticate a SslStream as the server in a Windows Service process, which runs under the Local System account.

However when I get to the SslStream.AuthenticateAsServer(certificate) call, it throws a Win32 exception with the error message "The credentials supplied to the package were not recognized".

There are several questions on here about this error message, but none of them seem to describe, or solve, my particular problem.

In the hope that someone may be able to offer some help, I include the code I am using to create and install the certificate:

```<code>// First create a certificate using the BouncyCastle classes
BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
AsymmetricCipherKeyPair keyPair = GenerateKeyPair();

X509V1CertificateGenerator generator = new X509V1CertificateGenerator();
generator.SetSerialNumber(serialNumber);
generator.SetIssuerDN(new X509Name("CN=My Issuer"));
generator.SetNotBefore(DateTime.Today);
generator.SetNotAfter(DateTime.Today.AddYears(100));
generator.SetSubjectDN(new X509Name("CN=My Issuer"));
generator.SetPublicKey(keyPair.Public);
generator.SetSignatureAlgorithm("SHA1WITHRSA");

Org.BouncyCastle.X509.X509Certificate cert = generator.Generate(
    keyPair.Private, SecureRandom.GetInstance("SHA1PRNG"));

// Ok, now we have a BouncyCastle certificate, we need to convert it to the
// System.Security.Cryptography class, by writing it out to disk and reloading
X509Certificate2 dotNetCert;

string tempStorePassword = "Password01"; // In real life I'd use a random password
FileInfo tempStoreFile = new FileInfo(Path.GetTempFileName());

try
{
    Pkcs12Store newStore = new Pkcs12Store();

    X509CertificateEntry entry = new X509CertificateEntry(cert);

    newStore.SetCertificateEntry(Environment.MachineName, entry);

    newStore.SetKeyEntry(
        Environment.MachineName,
        new AsymmetricKeyEntry(keyPair.Private),
        new [] { entry });

    using (FileStream s = tempStoreFile.Create())
    {
        newStore.Save(s,
            tempStorePassword.ToCharArray(),
            new SecureRandom(new CryptoApiRandomGenerator()));
    }

    // Reload the certificate from disk
    dotNetCert = new X509Certificate2(tempStoreFile.FullName, tempStorePassword);
}
finally
{
    tempStoreFile.Delete();
}

// Now install it into the required certificate stores
X509Store targetStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
targetStore.Open(OpenFlags.ReadWrite);
targetStore.Add(dotNetCert);
targetStore.Close();
</code>```

Ok, now I have created and installed the certificate. I then configure my Windows Service to use this certificate by supplying it with the generated certificate's thumbprint. I then use the certificate like this:

```<code>// First load the certificate
X509Certificate2 certificate = null;

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certInStore in store.Certificates)
{
    if (certInStore.Thumbprint == "...value not shown...")
    {
        certificate = certInStore;
        break;
    }
}

SslStream sslStream = new SslStream(new NetworkStream(socket, false), false);

// Now this line throws a Win32Exception
// "The credentials supplied to the package were not recognized"
sslStream.AuthenticateAsServer(certificate);
</code>```

Does anyone have any idea what the problem could be here?

I don't get the problem if I install a certificate created with 'makecert', but that isn't suitable for production certificates.

I've also tried creating a separate x509v1 CA certificate and then x509v3 certificate for server authentication, but I get the same error, so I removed this in the example code for simplicity.

答: For me works on Windows Server 2012 R2 (.net 4.6.1) - "All Tasks > Manage Private Keys" and set access to Everyone (setting to IS_IUSRS was not enough)</p>

Body:
I'm trying to create a certificate using the BouncyCastle.Crypto dll, which is then used to authenticate a SslStream as the server in a Windows Service process, which runs under the Local System account.

However when I get to the SslStream.AuthenticateAsServer(certificate) call, it throws a Win32 exception with the error message "The credentials supplied to the package were not recognized".

There are several questions on here about this error message, but none of them seem to describe, or solve, my particular problem.

In the hope that someone may be able to offer some help, I include the code I am using to create and install the certificate:

// First create a certificate using the BouncyCastle classes
BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
AsymmetricCipherKeyPair keyPair = GenerateKeyPair();

X509V1CertificateGenerator generator = new X509V1CertificateGenerator();
generator.SetSerialNumber(serialNumber);
generator.SetIssuerDN(new X509Name("CN=My Issuer"));
generator.SetNotBefore(DateTime.Today);
generator.SetNotAfter(DateTime.Today.AddYears(100));
generator.SetSubjectDN(new X509Name("CN=My Issuer"));
generator.SetPublicKey(keyPair.Public);
generator.SetSignatureAlgorithm("SHA1WITHRSA");

Org.BouncyCastle.X509.X509Certificate cert = generator.Generate(
    keyPair.Private, SecureRandom.GetInstance("SHA1PRNG"));

// Ok, now we have a BouncyCastle certificate, we need to convert it to the
// System.Security.Cryptography class, by writing it out to disk and reloading
X509Certificate2 dotNetCert;

string tempStorePassword = "Password01"; // In real life I'd use a random password
FileInfo tempStoreFile = new FileInfo(Path.GetTempFileName());

try
{
    Pkcs12Store newStore = new Pkcs12Store();

    X509CertificateEntry entry = new X509CertificateEntry(cert);

    newStore.SetCertificateEntry(Environment.MachineName, entry);

    newStore.SetKeyEntry(
        Environment.MachineName,
        new AsymmetricKeyEntry(keyPair.Private),
        new [] { entry });

    using (FileStream s = tempStoreFile.Create())
    {
        newStore.Save(s,
            tempStorePassword.ToCharArray(),
            new SecureRandom(new CryptoApiRandomGenerator()));
    }

    // Reload the certificate from disk
    dotNetCert = new X509Certificate2(tempStoreFile.FullName, tempStorePassword);
}
finally
{
    tempStoreFile.Delete();
}

// Now install it into the required certificate stores
X509Store targetStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
targetStore.Open(OpenFlags.ReadWrite);
targetStore.Add(dotNetCert);
targetStore.Close();

Ok, now I have created and installed the certificate. I then configure my Windows Service to use this certificate by supplying it with the generated certificate's thumbprint. I then use the certificate like this:

// First load the certificate
X509Certificate2 certificate = null;

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certInStore in store.Certificates)
{
    if (certInStore.Thumbprint == "...value not shown...")
    {
        certificate = certInStore;
        break;
    }
}

SslStream sslStream = new SslStream(new NetworkStream(socket, false), false);

// Now this line throws a Win32Exception
// "The credentials supplied to the package were not recognized"
sslStream.AuthenticateAsServer(certificate);

Does anyone have any idea what the problem could be here?

I don't get the problem if I install a certificate created with 'makecert', but that isn't suitable for production certificates.

I've also tried creating a separate x509v1 CA certificate and then x509v3 certificate for server authentication, but I get the same error, so I removed this in the example code for simplicity.


问:
how to handle incorrect value of difftime() function in R?
I have dataframe and there two columns of 1st_date date and 2nd_date. I used difftime() function to calculate the difference by days, and it did the job.
However, I found an incorrect value when I checked all values generated by difftime()

The incorrect value I have is:

```<code>    1st_date        2nd_date      time_diff
  12/31/68 12:11   1/13/69 19:29    -36512
</code>```

while it should be:

```<code>     1st_date         2nd_date      time_diff
  12/31/68 12:11    1/13/69 19:29      13
</code>```

the command I used is :

```<code>df$time_diff <- difftime(as.Date(df$1st_date, format="%m/%d/%y"),
                as.Date(df$2nd_date, format="%m/%d/%y"),
                units = "days")
</code>```

Any one can explain how did that happen and how to handle it?

Body:
I have dataframe and there two columns of 1st_date date and 2nd_date. I used difftime() function to calculate the difference by days, and it did the job.
However, I found an incorrect value when I checked all values generated by difftime()

The incorrect value I have is:

    1st_date        2nd_date      time_diff
  12/31/68 12:11   1/13/69 19:29    -36512

while it should be:

     1st_date         2nd_date      time_diff
  12/31/68 12:11    1/13/69 19:29      13

the command I used is :

df$time_diff <- difftime(as.Date(df$1st_date, format="%m/%d/%y"),
                as.Date(df$2nd_date, format="%m/%d/%y"),
                units = "days")

Any one can explain how did that happen and how to handle it?

Body:
Solution:

difftime(as.Date(format(as.Date("12/31/68 12:11", format="%m/%d/%y"), "19%y%m%d"), "%Y%m%d"), as.Date(format(as.Date("1/13/69 19:29", format="%m/%d/%y"), "19%y%m%d"), "%Y%m%d"), units = "days")


问:
Getting weird values on predicting MNIST dataset
I am using TF.LEARN with mnist data. I trained my neural network with 0.96 accuracy but now I am not really sure how to predict a value.

Here is my code..

```<code>#getting mnist data to a zip in the computer.
mnist.SOURCE_URL = 'https://web.archive.org/web/20160117040036/http://yann.lecun.com/exdb/mnist/'
trainX, trainY, testX, testY = mnist.load_data(one_hot=True)

# Define the neural network
def build_model():
    # This resets all parameters and variables
    tf.reset_default_graph()
    net = tflearn.input_data([None, 784])
    net = tflearn.fully_connected(net, 100, activation='ReLU')
    net = tflearn.fully_connected(net, 10, activation='softmax')
    net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
    # This model assumes that your network is named "net"
    model = tflearn.DNN(net)
    return model

# Build the model
model = build_model()

model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=8)

#Here is the problem
#lets say I want to predict what my neural network will reply back if I put back the send value from my trainX
</code>```

the value of trainX[2] is 4

```<code>pred = model.predict([trainX[2]])
print(pred)
#What I get is
[[2.6109733880730346e-05, 4.549271125142695e-06, 1.8098366126650944e-05, 0.003199575003236532, 0.20630565285682678, 0.0003870908112730831, 4.902480941382237e-05, 0.006617342587560415, 0.018498118966817856, 0.764894425868988]]
</code>```

what I want is -> 4

The problem is that I am not sure how to use this predict function and put in the trainX value to get a prediction.

答:
The prediction of tensorflow gives you a probabilistic output. It is sufficient to get the label with maximum probability from pred to get the peediction of the network.

```<code>pred = np.argmax(pred, axis=1)
</code>```

Which in this case is not 4, but 9.

Where np is numpy module imported as import numpy as np, but feel free to replace it with tf.argmax(pred, 1) to use tensorflow's argmax instead.

Body:
I am using TF.LEARN with mnist data. I trained my neural network with 0.96 accuracy but now I am not really sure how to predict a value.

Here is my code..

#getting mnist data to a zip in the computer.
mnist.SOURCE_URL = 'https://web.archive.org/web/20160117040036/http://yann.lecun.com/exdb/mnist/'
trainX, trainY, testX, testY = mnist.load_data(one_hot=True)

# Define the neural network
def build_model():
    # This resets all parameters and variables
    tf.reset_default_graph()
    net = tflearn.input_data([None, 784])
    net = tflearn.fully_connected(net, 100, activation='ReLU')
    net = tflearn.fully_connected(net, 10, activation='softmax')
    net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
    # This model assumes that your network is named "net"
    model = tflearn.DNN(net)
    return model

# Build the model
model = build_model()

model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=8)

#Here is the problem
#lets say I want to predict what my neural network will reply back if I put back the send value from my trainX

the value of trainX[2] is 4

pred = model.predict([trainX[2]])
print(pred)
#What I get is
[[2.6109733880730346e-05, 4.549271125142695e-06, 1.8098366126650944e-05, 0.003199575003236532, 0.20630565285682678, 0.0003870908112730831, 4.902480941382237e-05, 0.006617342587560415, 0.018498118966817856, 0.764894425868988]]

what I want is -> 4

The problem is that I am not sure how to use this predict function and put in the trainX value to get a prediction.

Body:
The prediction of tensorflow gives you a probabilistic output. It is sufficient to get the label with maximum probability from pred to get the peediction of the network.

pred = np.argmax(pred, axis=1)

Which in this case is not 4, but 9.

Where np is numpy module imported as import numpy as np, but feel free to replace it with tf.argmax(pred, 1) to use tensorflow's argmax instead.


问:
Build a Web Service API (SOAP) inside MVC app?
Can anyone help me on how to build a web service api (soap) inside an MVC app? WCF is fine :) (initially, WCF is not an option.)

Thank you very much.

答: Simply add a WCF service endpoint (.svc file) to your MVC application.</p>


问:
PHP formating numbers to locale and back
After a lot of research I am actually using the following function to format numbers to the locale setted by the user:

```<code>function number_format_i18n($number, $decimals=0) {
    $locale = localeconv();
    return number_format($number,$decimals, $locale['decimal_point'], $locale['thousands_sep']);
}
</code>```

I'll use this to format numbers from DB.

But if I have a form where a user can enter a number, I need a function to format it back so I can save into the DB. Here I found this solution:

```<code>function number_format_en($number) {
    // $_SESSION['lang']['locale'] has the locale like de_DE, ar_AE, tr_TR, ...
    $fmt = numfmt_create($_SESSION['lang']['locale'], NumberFormatter::DECIMAL);
    return numfmt_parse($fmt, $number);
}
</code>```

This works with the most locales I tested but not with everyone! As an example: if I use arabic (ar_AE):

```<code>$randomNumber = 3171003633.95;
$number2locale = number_format_i18n($randomNumber, 2);
// works as expected: 3,171,003,633.95
// now format it back:
$locale2number = number_format_en($number2locale);
// here I get this: 3.171
</code>```

How can I format a locale entered number in a secure way "back" to en-format? Or is there a way to detect any kind of numberformat and format it to en-format so I can save it in the DB?

答:
So, don't know really if this is a good solution or not - but it seems to be working fine:

```<code>function number_format_en($number) {
    // first remove everything execpt -,.
    $cleanNumber = preg_replace('/[^\\d-,.]+/', '', $number);

    $last_dot = strrpos($cleanNumber, '.');
    $last_comma = strrpos($cleanNumber, ',');

    if($last_dot !== false || $last_comma !== false) {
        if($last_dot > $last_comma) { // decimal seperator = dot
            $decimal_point = '.';
            if(substr_count($cleanNumber, '.') > 1) {
                // could be totaly wrong 1,234.567.890
                // or there are no decimals 1.234.567.890
                // removing all dots and commas and returning the value
                return preg_replace('/[^\\d-]+/', '', $cleanNumber);
            }
        } else { // decimal seperator = comma
            $decimal_point = ',';
            if(substr_count($cleanNumber, ',') > 1) {
                // could be totaly wrong 1.234,567,890
                // or there are no decimals 1,234,567,890
                // removing all dots and commas and returning the value
                return preg_replace('/[^\\d-]+/', '', $cleanNumber);
            }
        }
    } else { // no decimals
        $decimal_point = false;
        $decimals = 0;
    }

    if($decimal_point !== false) {
        // if decimals are delivered, get the count of them
        $length = strlen($cleanNumber);
        $position = strpos($cleanNumber, $decimal_point);
        $decimals = $length - $position - 1;

        if($decimal_point == '.') {
            // remove all commas if seperator = .
            $cleanNumber = str_replace(',', '', $cleanNumber);
        } elseif($decimal_point == ',') {
            // remove all dots if seperator = ,
            $cleanNumber = str_replace('.', '', $cleanNumber);
            // now switch comma with dot
            $cleanNumber = str_replace(',', '.', $cleanNumber);
        }
    }
    return $cleanNumber;
}
</code>```

I'll check the last dot or comma and depending on that I format the number, function returns the same count of decimals as the original number. there is a "known" bug: if someone enters a full number like 1.000.000 or 1,000,000 it returns 1000000.

As an example:

```<code>number_format_en('1.234.567,89') // 1234567.89
number_format_en('-1,234,567.89') // -1234567.89
number_format_en('1.234.567.89') // 123456789 (only dots)
number_format_en('1,234,567,89') // 123456789 (only commas)
</code>```

Would be nice if someone can post a comment if this is a good way or not or an answer with a better solution :)

Body:
After a lot of research I am actually using the following function to format numbers to the locale setted by the user:

function number_format_i18n($number, $decimals=0) {
    $locale = localeconv();
    return number_format($number,$decimals, $locale['decimal_point'], $locale['thousands_sep']);
}

I'll use this to format numbers from DB.

But if I have a form where a user can enter a number, I need a function to format it back so I can save into the DB. Here I found this solution:

function number_format_en($number) {
    // $_SESSION['lang']['locale'] has the locale like de_DE, ar_AE, tr_TR, ...
    $fmt = numfmt_create($_SESSION['lang']['locale'], NumberFormatter::DECIMAL);
    return numfmt_parse($fmt, $number);
}

This works with the most locales I tested but not with everyone! As an example: if I use arabic (ar_AE):

$randomNumber = 3171003633.95;
$number2locale = number_format_i18n($randomNumber, 2);
// works as expected: 3,171,003,633.95
// now format it back:
$locale2number = number_format_en($number2locale);
// here I get this: 3.171

How can I format a locale entered number in a secure way "back" to en-format? Or is there a way to detect any kind of numberformat and format it to en-format so I can save it in the DB?

Body:
So, don't know really if this is a good solution or not - but it seems to be working fine:

function number_format_en($number) {
    // first remove everything execpt -,.
    $cleanNumber = preg_replace('/[^\\d-,.]+/', '', $number);

    $last_dot = strrpos($cleanNumber, '.');
    $last_comma = strrpos($cleanNumber, ',');

    if($last_dot !== false || $last_comma !== false) {
        if($last_dot > $last_comma) { // decimal seperator = dot
            $decimal_point = '.';
            if(substr_count($cleanNumber, '.') > 1) {
                // could be totaly wrong 1,234.567.890
                // or there are no decimals 1.234.567.890
                // removing all dots and commas and returning the value
                return preg_replace('/[^\\d-]+/', '', $cleanNumber);
            }
        } else { // decimal seperator = comma
            $decimal_point = ',';
            if(substr_count($cleanNumber, ',') > 1) {
                // could be totaly wrong 1.234,567,890
                // or there are no decimals 1,234,567,890
                // removing all dots and commas and returning the value
                return preg_replace('/[^\\d-]+/', '', $cleanNumber);
            }
        }
    } else { // no decimals
        $decimal_point = false;
        $decimals = 0;
    }

    if($decimal_point !== false) {
        // if decimals are delivered, get the count of them
        $length = strlen($cleanNumber);
        $position = strpos($cleanNumber, $decimal_point);
        $decimals = $length - $position - 1;

        if($decimal_point == '.') {
            // remove all commas if seperator = .
            $cleanNumber = str_replace(',', '', $cleanNumber);
        } elseif($decimal_point == ',') {
            // remove all dots if seperator = ,
            $cleanNumber = str_replace('.', '', $cleanNumber);
            // now switch comma with dot
            $cleanNumber = str_replace(',', '.', $cleanNumber);
        }
    }
    return $cleanNumber;
}

I'll check the last dot or comma and depending on that I format the number, function returns the same count of decimals as the original number. there is a "known" bug: if someone enters a full number like 1.000.000 or 1,000,000 it returns 1000000.

As an example:

number_format_en('1.234.567,89') // 1234567.89
number_format_en('-1,234,567.89') // -1234567.89
number_format_en('1.234.567.89') // 123456789 (only dots)
number_format_en('1,234,567,89') // 123456789 (only commas)

Would be nice if someone can post a comment if this is a good way or not or an answer with a better solution :)


问:
ImportError Tensorflow
I am having a serious problem trying to import Tensorflow. When I do it, I get the following error:

```<code>Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)])
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 54, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "D:/Google Drive/Python/test.py", line 1, in <module>
    import tensorflow as tf
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 60, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)])
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 54, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'

Error importing tensorflow.  Unless you are using bazel,
you should not try to import tensorflow from its source directory;
please exit the tensorflow source tree, and relaunch your python interpreter from there.
</code>```

I have VC 2015.

答:
(Posted on behalf of the OP).

The problem was that I had Python 3.6, while Tensorflow only supports Python 3.5.

Title: ImportError Tensorflow

Body:
I am having a serious problem trying to import Tensorflow. When I do it, I get the following error:

Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)])
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 54, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/Google Drive/Python/test.py", line 1, in <module>
    import tensorflow as tf
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 60, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)])
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\imp.py", line 296, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 54, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\Luka\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'

Error importing tensorflow.  Unless you are using bazel,
you should not try to import tensorflow from its source directory;
please exit the tensorflow source tree, and relaunch your python interpreter from there.

I have VC 2015.


问:
Save own Class with NSCoder
I'm trying to store some custom class/data to a file in my iPhone/iPad app.

I have a Class RSHighscoreList

```<code>@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}
</code>```

which contains objects of RSHighscore in the list

```<code>@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}
</code>```

When I try to store all to file

```<code>- (void)writeDataStore {
    RSDataStore *tmpStore = [[RSDataStore alloc] init];
    _tmpStore.highscorelist = self.highscorelist.list;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:tmpStore forKey:kDataKey];
    [archiver finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];

    [archiver release];
    [data release];
}

@interface RSDataStore : NSObject <NSCoding, NSCopying> {
    NSMutableArray *highscorelist;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:highscorelist forKey:@"Highscorelist"];
}
</code>```

The app will crash with an error message

```-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20'```

I wonder why the error tells about RSHighscore, even if that is 'wrapped'. Does anyone have a good idea?

答:
RSDataStore has an -encodeWithCoder: method, but (according to the error message) RSHighscore doesn't. You need to implement the NSCoding protocol for every class you're serializing.

```<code>@implementation RSHighscore
static NSString *const kPlayerName = @"PlayerName";
static NSString *const kPoints = @"Points";

-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super init])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:playerName forKey:kPlayerName];
    [encoder encodeInt:points forKey:kPoints];
}
...
</code>```

If the base class of RSHighscore is ever changed to something other than NSObject, the -initWithCoder: method might need to be changed to call [super initWithCoder:decoder] rather than [super init]. Alternatively, add <NSCoding> to NSObject and change RSHighscore's -initWithCoder: now.

```<code>@interface NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder;
-(void)encodeWithCoder:(NSCoder*)encoder;
@end

@implementation NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder {
    return [self init];
}
-(void)encodeWithCoder:(NSCoder*)encoder {}
@end

@implementation RSHighscore
-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super initWithCoder:decoder])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
...
</code>```

Title: Save own Class with NSCoder

Body:
I'm trying to store some custom class/data to a file in my iPhone/iPad app.

I have a Class RSHighscoreList

@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}

which contains objects of RSHighscore in the list

@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}

When I try to store all to file

- (void)writeDataStore {
    RSDataStore *tmpStore = [[RSDataStore alloc] init];
    _tmpStore.highscorelist = self.highscorelist.list;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:tmpStore forKey:kDataKey];
    [archiver finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];

    [archiver release];
    [data release];
}

@interface RSDataStore : NSObject <NSCoding, NSCopying> {
    NSMutableArray *highscorelist;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:highscorelist forKey:@"Highscorelist"];
}

The app will crash with an error message

-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20'

I wonder why the error tells about RSHighscore, even if that is 'wrapped'. Does anyone have a good idea?

Body:
RSDataStore has an -encodeWithCoder: method, but (according to the error message) RSHighscore doesn't. You need to implement the NSCoding protocol for every class you're serializing.

@implementation RSHighscore
static NSString *const kPlayerName = @"PlayerName";
static NSString *const kPoints = @"Points";

-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super init])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:playerName forKey:kPlayerName];
    [encoder encodeInt:points forKey:kPoints];
}
...

If the base class of RSHighscore is ever changed to something other than NSObject, the -initWithCoder: method might need to be changed to call [super initWithCoder:decoder] rather than [super init]. Alternatively, add <NSCoding> to NSObject and change RSHighscore's -initWithCoder: now.

@interface NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder;
-(void)encodeWithCoder:(NSCoder*)encoder;
@end

@implementation NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder {
    return [self init];
}
-(void)encodeWithCoder:(NSCoder*)encoder {}
@end

@implementation RSHighscore
-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super initWithCoder:decoder])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
...


问:
objective c - HTML to NSAttributedString
I have written a function that converts HTML text to NSAttributedString. It is working fine. However, I have noticed that some tags when nested inside another tag, their fonts get overwritten.

Here's my code.

```<code>+(NSMutableAttributedString*) replaceHTMLTags : (NSString*) text : (NSString*) fontName : (CGFloat) fontSize
{
    UIFont* font = [UIFont fontWithName:fontName size:fontSize];
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentJustified;

    text = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    NSMutableAttributedString* finalText = [[NSMutableAttributedString alloc]initWithString:text];

    [finalText setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, [finalText string].length)];

    finalText = [self recurseFunc:finalText :@"" : font : paragraphStyle];
    return finalText;
}

+(NSMutableAttributedString*) recurseFunc : (NSMutableAttributedString*) text : (NSString*) tag : (UIFont*) font : (NSMutableParagraphStyle*) paragraphStyle
{
    NSMutableAttributedString* finalText = text;

    NSRange newOpenTagRange;
    //RECURSE IF THERE ARE MORE TAGS
    while((newOpenTagRange = [[text string] rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    {
        NSString* openTagName = [[text string] substringWithRange:newOpenTagRange];
        NSString* closeTagName = [self getCloseTagName: openTagName];
        NSRange newCloseTagRange = [[text string ]rangeOfString:closeTagName];

        if(newCloseTagRange.location != NSNotFound)
        {
            NSString* textWithTags = [[text string] substringWithRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length)];
            NSString* newPlainText = [textWithTags stringByReplacingOccurrencesOfString:openTagName withString:@""];
            newPlainText = [newPlainText stringByReplacingOccurrencesOfString:closeTagName withString:@""];

            NSMutableAttributedString* newText = [[NSMutableAttributedString alloc]initWithString:newPlainText attributes:@{NSFontAttributeName:font,  NSParagraphStyleAttributeName:paragraphStyle}];

            newText = [self recurseFunc:newText :openTagName : font : paragraphStyle];
            [finalText replaceCharactersInRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length) withAttributedString:newText];
        }
        else
        {
            NSLog(@"Cannot find closing tag for tag %@", openTagName);
        }
    }

    //FORMAT HTML TAGS
    if([tag containsString:@"<p"])
    {
        [finalText.mutableString appendString:@"\n\n"];
    }

    else if ([tag isEqualToString:@"<i>"])
    {
        UIFont* italicFont = [UIFont fontWithName:@"Arial-ItalicMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:italicFont range:NSMakeRange(0, [finalText string].length)];
    }
    else if ([tag isEqualToString:@"<b>"])
    {
        UIFont* boldFont = [UIFont fontWithName:@"Arial-BoldMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:boldFont range:NSMakeRange(0, [finalText string].length)];

    }
    else if([tag isEqualToString:@"<ul>"])
    {
        NSMutableParagraphStyle* tempStyle = [[NSMutableParagraphStyle alloc]init];
        tempStyle.headIndent = 30;
        tempStyle.firstLineHeadIndent = 10;
        tempStyle.lineBreakMode = NSLineBreakByWordWrapping;
        tempStyle.alignment = NSTextAlignmentJustified;

        NSString* temp = [[finalText string]stringByReplacingOccurrencesOfString:@"###" withString:@"•\t"];
        temp = [NSString stringWithFormat:@"\n%@", temp];
        [finalText setAttributedString:[[NSAttributedString alloc] initWithString:temp]];

        [finalText addAttribute:NSParagraphStyleAttributeName value:tempStyle range:NSMakeRange(0, [finalText string].length)];

    }
    else if ([tag isEqualToString:@"<li>"])
    {
        NSMutableAttributedString* tempAS = [[NSMutableAttributedString alloc]initWithString:@"###$$$\n"];
        NSRange r = [[tempAS string]rangeOfString:@"$$$"];
        [tempAS replaceCharactersInRange:r withAttributedString:finalText];
        [finalText setAttributedString:tempAS];

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

This does exactly what it is supposed to do, except for one specific case.

For instance, if I have a  or an  tag inside a

 tag, the  or  don't get rendered.

答:
For converting HTML to NSAttributedString you can use the following code:

```<code>[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                             options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                       NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                  documentAttributes:nil error:nil];
</code>```

Body:
I have written a function that converts HTML text to NSAttributedString. It is working fine. However, I have noticed that some tags when nested inside another tag, their fonts get overwritten.

Here's my code.

+(NSMutableAttributedString*) replaceHTMLTags : (NSString*) text : (NSString*) fontName : (CGFloat) fontSize
{
    UIFont* font = [UIFont fontWithName:fontName size:fontSize];
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentJustified;

    text = [text stringByReplacingOccurrencesOfString:@"
" withString:@"\n"];
    NSMutableAttributedString* finalText = [[NSMutableAttributedString alloc]initWithString:text];

    [finalText setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, [finalText string].length)];

    finalText = [self recurseFunc:finalText :@"" : font : paragraphStyle];
    return finalText;
}

+(NSMutableAttributedString*) recurseFunc : (NSMutableAttributedString*) text : (NSString*) tag : (UIFont*) font : (NSMutableParagraphStyle*) paragraphStyle
{
    NSMutableAttributedString* finalText = text;

    NSRange newOpenTagRange;
    //RECURSE IF THERE ARE MORE TAGS
    while((newOpenTagRange = [[text string] rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    {
        NSString* openTagName = [[text string] substringWithRange:newOpenTagRange];
        NSString* closeTagName = [self getCloseTagName: openTagName];
        NSRange newCloseTagRange = [[text string ]rangeOfString:closeTagName];

        if(newCloseTagRange.location != NSNotFound)
        {
            NSString* textWithTags = [[text string] substringWithRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length)];
            NSString* newPlainText = [textWithTags stringByReplacingOccurrencesOfString:openTagName withString:@""];
            newPlainText = [newPlainText stringByReplacingOccurrencesOfString:closeTagName withString:@""];

            NSMutableAttributedString* newText = [[NSMutableAttributedString alloc]initWithString:newPlainText attributes:@{NSFontAttributeName:font,  NSParagraphStyleAttributeName:paragraphStyle}];

            newText = [self recurseFunc:newText :openTagName : font : paragraphStyle];
            [finalText replaceCharactersInRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length) withAttributedString:newText];
        }
        else
        {
            NSLog(@"Cannot find closing tag for tag %@", openTagName);
        }
    }

    //FORMAT HTML TAGS
    if([tag containsString:@"<p"])
    {
        [finalText.mutableString appendString:@"\n\n"];
    }

    else if ([tag isEqualToString:@""])
    {
        UIFont* italicFont = [UIFont fontWithName:@"Arial-ItalicMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:italicFont range:NSMakeRange(0, [finalText string].length)];
    }
    else if ([tag isEqualToString:@""])
    {
        UIFont* boldFont = [UIFont fontWithName:@"Arial-BoldMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:boldFont range:NSMakeRange(0, [finalText string].length)];

    }
    else if([tag isEqualToString:@"
"])
    {
        NSMutableParagraphStyle* tempStyle = [[NSMutableParagraphStyle alloc]init];
        tempStyle.headIndent = 30;
        tempStyle.firstLineHeadIndent = 10;
        tempStyle.lineBreakMode = NSLineBreakByWordWrapping;
        tempStyle.alignment = NSTextAlignmentJustified;

        NSString* temp = [[finalText string]stringByReplacingOccurrencesOfString:@"###" withString:@"•\t"];
        temp = [NSString stringWithFormat:@"\n%@", temp];
        [finalText setAttributedString:[[NSAttributedString alloc] initWithString:temp]];

        [finalText addAttribute:NSParagraphStyleAttributeName value:tempStyle range:NSMakeRange(0, [finalText string].length)];

    }
    else if ([tag isEqualToString:@"
"])
    {
        NSMutableAttributedString* tempAS = [[NSMutableAttributedString alloc]initWithString:@"###$$$\n"];
        NSRange r = [[tempAS string]rangeOfString:@"$$$"];
        [tempAS replaceCharactersInRange:r withAttributedString:finalText];
        [finalText setAttributedString:tempAS];

    }
    return finalText;
}

This does exactly what it is supposed to do, except for one specific case.

For instance, if I have a  or an  tag inside a

 tag, the  or  don't get rendered.

Body:
For converting HTML to NSAttributedString you can use the following code:

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                             options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                       NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                  documentAttributes:nil error:nil];


问:
Accessing intArray by its name without knowing it
I have an xml file, that is in ./values and looks like this:

```<code><resources>
    <integer-array name="Bulbasaur">
        <item name="hp">0</item>
        <item name="atk">0</item>
        <item name="def">0</item>
        <item name="speatk">1</item>
        <item name="spedef">0</item>
        <item name="speed">0</item>
    </integer-array>

    <integer-array name="Ivysaur">
        <item name="hp">0</item>
        <item name="atk">0</item>
        <item name="def">0</item>
        <item name="speatk">1</item>
        <item name="spedef">2</item>
        <item name="speed">0</item>
    </integer-array>
...
</resources>
</code>```

I'd like to access the intArrays by their name, but I can't use the R.id.stuff, because I get the name from an input. I already tried to use getIdentifier() then getIntArray(), like this:

```<code>getResources().getIntArray(getResources().getIdentifier("nameOfArray", "int[]", MyActivity.this.getPackageName())
</code>```

But it didn't work. What am I doing wrong? How do I access those arrays?

答: Please take a look at the answer here. You rather want to use "array" instead of "int[]" as a second parameter of Resources#getIdentifier method.

Body:
I have an xml file, that is in ./values and looks like this:

<resources>
    <integer-array name="Bulbasaur">
        <item name="hp">0</item>
        <item name="atk">0</item>
        <item name="def">0</item>
        <item name="speatk">1</item>
        <item name="spedef">0</item>
        <item name="speed">0</item>
    </integer-array>

    <integer-array name="Ivysaur">
        <item name="hp">0</item>
        <item name="atk">0</item>
        <item name="def">0</item>
        <item name="speatk">1</item>
        <item name="spedef">2</item>
        <item name="speed">0</item>
    </integer-array>
...
</resources>

I'd like to access the intArrays by their name, but I can't use the R.id.stuff, because I get the name from an input. I already tried to use getIdentifier() then getIntArray(), like this:

getResources().getIntArray(getResources().getIdentifier("nameOfArray", "int[]", MyActivity.this.getPackageName())

But it didn't work. What am I doing wrong? How do I access those arrays?


问:
I am getting two plots for one data set in python
I am working through example 8.1 titled Euler's Method from Mark Newman's book Computational Physics. I rewrote the example as a method with Numpy arrays but when I plot it I get two plots on the same figure not sure how to correct it. Also is there better way to convert my 2 1D arrays into 1 2D array to use for plotting in Matplotlib, thanks.

Newman's example :

```<code>from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show

def f(x,t):
    return -x**3 + sin(t)

a = 0.0           # Start of the interval
b = 10.0          # End of the interval
N = 1000          # Number of steps
h = (b-a)/N       # Size of a single step
x = 0.0           # Initial condition

tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
    xpoints.append(x)
    x += h*f(x,t)

plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()
</code>```

My modifications:

```<code>from pylab import plot,show,xlabel,ylabel
from numpy import linspace,exp,sin,zeros,vstack,column_stack

def f(x,t):
    return (-x**(3) + sin(t))

def Euler(f,x0,a,b):
    N=1000
    h = (b-a)/N
    t = linspace(a,b,N)
    x = zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return column_stack((t,x)) #vstack((t,x)).T

plot(Euler(f,0.0,0.0,10.0))
xlabel("t")
ylabel("x(t)")
show()
</code>```

答:
The reason you get two lines is that t as well as x are plotted against their index, instead of x plotted against t

I don't see why you'd want to stack the two arrays. Just keep then separate, which will also solve the problem of the two plots.

The following works fine.

```<code>import numpy as np
import matplotlib.pyplot as plt
f = lambda x,t: -x**3 + np.sin(t)

def Euler(f,x0,a,b):
    N=1000
    h = (b-a)/N
    t = np.linspace(a,b,N)
    x = np.zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return t,x

t,x = Euler(f,0.0,0.0,10.0)
plt.plot(t,x)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.show()
</code>```

Body:
I am working through example 8.1 titled Euler's Method from Mark Newman's book Computational Physics. I rewrote the example as a method with Numpy arrays but when I plot it I get two plots on the same figure not sure how to correct it. Also is there better way to convert my 2 1D arrays into 1 2D array to use for plotting in Matplotlib, thanks.

Newman's example :

from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show

def f(x,t):
    return -x**3 + sin(t)

a = 0.0           # Start of the interval
b = 10.0          # End of the interval
N = 1000          # Number of steps
h = (b-a)/N       # Size of a single step
x = 0.0           # Initial condition

tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
    xpoints.append(x)
    x += h*f(x,t)

plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()

My modifications:

from pylab import plot,show,xlabel,ylabel
from numpy import linspace,exp,sin,zeros,vstack,column_stack

def f(x,t):
    return (-x**(3) + sin(t))

def Euler(f,x0,a,b):
    N=1000
    h = (b-a)/N
    t = linspace(a,b,N)
    x = zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return column_stack((t,x)) #vstack((t,x)).T

plot(Euler(f,0.0,0.0,10.0))
xlabel("t")
ylabel("x(t)")
show()

Body:
The reason you get two lines is that t as well as x are plotted against their index, instead of x plotted against t

I don't see why you'd want to stack the two arrays. Just keep then separate, which will also solve the problem of the two plots.

The following works fine.

import numpy as np
import matplotlib.pyplot as plt
f = lambda x,t: -x**3 + np.sin(t)

def Euler(f,x0,a,b):
    N=1000
    h = (b-a)/N
    t = np.linspace(a,b,N)
    x = np.zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return t,x

t,x = Euler(f,0.0,0.0,10.0)
plt.plot(t,x)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.show()


答:
You are getting a 9, which is quite similar to a 4.

What model.predict returns is score and while the 5-th value in the results array (the 5th value is 4 since it starts with a zero) gets a relatively high score (0.26-second high) - your model gives the last digit (9) the highest score-0.76. It just means your classifier is a bit wrong here - so you should consider using a different one or play with the hyper-parameters.

Title: Getting weird values on predicting MNIST dataset


问:
Saving struct to a file in C
In my assignment I was given two functions to write

```<code>int openFileFromConsole(FILE *fp)
</code>```

It takes an empty file pointer as input to the function using call by reference. And updates the pointer to point to the appropriate HDD address. IMPORTANT: Later, it asks the user through the console to provide the name and also asks for the file open type: "w", "r", "a" and UPDATES the file pointer. It returns 1 if succeeded, or 0 if fails.

```<code>void saveStudentGradeInfoTofile(FILE *fp)
</code>```

This function gets the student info and saves it first into the student data-type (which is struct but disguised using typedef) then saves it to file. The student information is being provided by the register through the console. This takes the file pointer by reference as input and update the file using fprint.

This program is supposed to open a file through console depending on the user input then collect information and store them to a struct and save it to that file.I have written the two functions(correctly I think?).But I am having a hard time implementing them to main() since the first one is an int type function.Any help would be appreciated.

```<code>typedef struct student {
    char name[50];
    char id [20];
    int score;
}student;

int openFileFromConsole(FILE *fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main()
{
   return 0;
}

int openFileFromConsole(FILE *fp){
    char filePath[100],fileOpenType[10];
    printf("Enter Path name: ");
    scanf("%s", filePath);
    printf("Enter file open type w, r or a: ");
    scanf("%s", fileOpenType);

     fp = fopen(filePath,fileOpenType);
     if(fp != NULL) {
        printf("File has been opened");
     return 1;

     }
     else printf("File not found");
     return 0;
}
void saveStudentGradeInfoTofile(FILE *fp){

     int numOfStudent ;
     student s[100];
     printf ("Get the number of students :");
     scanf("%d",&numOfStudent);

     for(int i = 0; i < numOfStudent; i++) {

         printf("\nEnter ID number:");

         scanf(" %s",s[i].id);

         printf("Enter name: ");
         scanf("%s,",s[i].name);

         printf("Enter score: ");
         scanf("%d",&s[i].score);

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",s[i].id,s[i].name,s[i].score);

         printf("\n");
}
}
</code>```

答:
the posted code has a few problems.

it does not follow the axiom: only one statement per line and (at most) one variable declaration per statement.  The result is the code is much more difficult to understand, debug, maintain.

The calls to system functions need to have their returned values checked to assure the operation was successful.

To modify where a pointer, located in the calling function, points, the pointer must be passed as a 'pointer to a pointer'.

when calling any of the scanf() family of functions, when using the '%s' input conversion specifier, always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer, so the user cannot overrun the input buffer.  Such overrun results in undefined behavior and can lead to a seg fault event.

when using the '%s' input conversion specifier, insert a space before the specifier to consume any leading 'white space', like any newline sequence.

always cleanup when exiting a program.  Do not leave the cleanup to the OS.

when working with numeric values that will never be less than 0, it is best to use size_t rather than int

The posted code is never reading from the student grade info file, so should never be opened with r

the 'mode' in a call to fopen() is always a string, even if it is only a single char, so needs to be written as "w" not just a w

the code contains lots of 'magic' numbers.  'magic' numbers are numbers with no basis.  Such numbers make understanding, debugging, etc much more difficult than necessary. Suggest using an enum statement or #define statements to give those 'magic' numbers meaningful names, then use those meaningful names throughout the code.

for ease of readability and understanding, consistently indent the code.  indent after every opening brace '{'.  unindent after every closing brace '}'.  Suggest using 4 spaces for each indent level as that is visible even with variable width fonts.

it is a poor programming practice to combine a 'struct' definition with a 'typedef'.  code them separately.

when posting code, include the needed header file statements, so we do not have to guess what your code actually uses.

for ease of readability and understanding, separate code blocks (for, if, else, while, do...while, switch, case, default) via a single blank line.  Separate functions by 2 or 3 blank lines (be consistent).

While modern compilers will handle the duplication of names, as modern compilers keep the struct names in a separate namespace from the typedef names,  it is a poor programming practice that easily leads to confusion. Suggest keeping names unique (although that was not followed in this answer.

Here is a possible implementation of the desired functionality:

```<code>#include <stdio.h>  // fopen(), fclose(), perror(), FILE
#include <stdlib.h> // exit(), EXIT_FAILURE

enum {
    MAX_NAME_LEN     =50,
    MAX_ID_LEN       =20,
    MAX_PATH_LEN     =100,
    MAX_TYPE_LEN     =10,
    MAX_NUM_STUDENTS =100
};

struct student
{
    char name[ MAX_NAME_LEN ];
    char id [ MAX_ID_LEN ];
    int score;
};

typedef struct student student;

int openFileFromConsole(FILE **fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main( void )
{
    FILE * fp = NULL;

    int openStatus = openFileFromConsole(&fp);

    if( 0 == openStatus )
    {
        saveStudentGradeInfoTofile( fp );
    }

    fclose( fp );
   return 0;
} // end function: main

int openFileFromConsole(FILE **fp)
{
    char filePath[ MAX_PATH_LEN ];
    char fileOpenType;

    printf("Enter Path name: ");
    if( 1 != scanf("%100s", filePath) )
    {
        perror( "scanf for file path failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("Enter file open type w, r or a: ");
    if( 1 != scanf(" %c", &fileOpenType) )
    {
        perror( "scanf for file open type failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    char buffer[ MAX_TYPE_LEN ];
    buffer[0] = '\"';
    buffer[1] = fileOpenType;
    buffer[2] = '\"';
    buffer[3] = '\0';
    *fp = fopen(filePath, buffer);
    if( *fp )
    {
        return 1;
    }

    else
    {
         perror( "fopen failed" );
         return 0;
    }
} // end function: openFileFromConsole

void saveStudentGradeInfoTofile(FILE *fp)
{
     size_t numOfStudent;
     student s[ MAX_NUM_STUDENTS ];

     printf ("Get the number of students :");
     if( 1 != scanf("%lu",&numOfStudent) )
     {
         perror( "scanf for number of students failed:" );
         fclose( fp );
         exit( EXIT_FAILURE );
     }

     // implied else, scanf successful

     for( size_t i = 0; i < numOfStudent; i++)
     {
         printf("\nEnter ID number:");
         if( 1 != scanf(" %19s",s[i].id) )
         {
             perror( "scanf for student ID failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         printf("Enter name: ");
         if( 1 != scanf(" %49s,",s[i].name) )
         {
             perror( "scanf for student ID failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         printf("Enter score: ");
         if( 1 != scanf("%d",&s[i].score) )
         {
             perror( "scanf for student Score failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",
                s[i].id,
                s[i].name,
                s[i].score);

         printf("\n");
    } // end while
} // end function: saveStudentGradeInfoToFile
</code>```

Title: Saving struct to a file in C

Body:
In my assignment I was given two functions to write

int openFileFromConsole(FILE *fp)

It takes an empty file pointer as input to the function using call by reference. And updates the pointer to point to the appropriate HDD address. IMPORTANT: Later, it asks the user through the console to provide the name and also asks for the file open type: "w", "r", "a" and UPDATES the file pointer. It returns 1 if succeeded, or 0 if fails.

void saveStudentGradeInfoTofile(FILE *fp)

This function gets the student info and saves it first into the student data-type (which is struct but disguised using typedef) then saves it to file. The student information is being provided by the register through the console. This takes the file pointer by reference as input and update the file using fprint.

This program is supposed to open a file through console depending on the user input then collect information and store them to a struct and save it to that file.I have written the two functions(correctly I think?).But I am having a hard time implementing them to main() since the first one is an int type function.Any help would be appreciated.

typedef struct student {
    char name[50];
    char id [20];
    int score;
}student;

int openFileFromConsole(FILE *fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main()
{
   return 0;
}

int openFileFromConsole(FILE *fp){
    char filePath[100],fileOpenType[10];
    printf("Enter Path name: ");
    scanf("%s", filePath);
    printf("Enter file open type w, r or a: ");
    scanf("%s", fileOpenType);

     fp = fopen(filePath,fileOpenType);
     if(fp != NULL) {
        printf("File has been opened");
     return 1;

     }
     else printf("File not found");
     return 0;
}
void saveStudentGradeInfoTofile(FILE *fp){

     int numOfStudent ;
     student s[100];
     printf ("Get the number of students :");
     scanf("%d",&numOfStudent);

     for(int i = 0; i < numOfStudent; i++) {

         printf("\nEnter ID number:");

         scanf(" %s",s[i].id);

         printf("Enter name: ");
         scanf("%s,",s[i].name);

         printf("Enter score: ");
         scanf("%d",&s[i].score);

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",s[i].id,s[i].name,s[i].score);

         printf("\n");
}
}

Body:
the posted code has a few problems.

it does not follow the axiom: only one statement per line and (at most) one variable declaration per statement.  The result is the code is much more difficult to understand, debug, maintain.

The calls to system functions need to have their returned values checked to assure the operation was successful.

To modify where a pointer, located in the calling function, points, the pointer must be passed as a 'pointer to a pointer'.

when calling any of the scanf() family of functions, when using the '%s' input conversion specifier, always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer, so the user cannot overrun the input buffer.  Such overrun results in undefined behavior and can lead to a seg fault event.

when using the '%s' input conversion specifier, insert a space before the specifier to consume any leading 'white space', like any newline sequence.

always cleanup when exiting a program.  Do not leave the cleanup to the OS.

when working with numeric values that will never be less than 0, it is best to use size_t rather than int

The posted code is never reading from the student grade info file, so should never be opened with r

the 'mode' in a call to fopen() is always a string, even if it is only a single char, so needs to be written as "w" not just a w

the code contains lots of 'magic' numbers.  'magic' numbers are numbers with no basis.  Such numbers make understanding, debugging, etc much more difficult than necessary. Suggest using an enum statement or #define statements to give those 'magic' numbers meaningful names, then use those meaningful names throughout the code.

for ease of readability and understanding, consistently indent the code.  indent after every opening brace '{'.  unindent after every closing brace '}'.  Suggest using 4 spaces for each indent level as that is visible even with variable width fonts.

it is a poor programming practice to combine a 'struct' definition with a 'typedef'.  code them separately.

when posting code, include the needed header file statements, so we do not have to guess what your code actually uses.

for ease of readability and understanding, separate code blocks (for, if, else, while, do...while, switch, case, default) via a single blank line.  Separate functions by 2 or 3 blank lines (be consistent).

While modern compilers will handle the duplication of names, as modern compilers keep the struct names in a separate namespace from the typedef names,  it is a poor programming practice that easily leads to confusion. Suggest keeping names unique (although that was not followed in this answer.

Here is a possible implementation of the desired functionality:

#include <stdio.h>  // fopen(), fclose(), perror(), FILE
#include <stdlib.h> // exit(), EXIT_FAILURE

enum {
    MAX_NAME_LEN     =50,
    MAX_ID_LEN       =20,
    MAX_PATH_LEN     =100,
    MAX_TYPE_LEN     =10,
    MAX_NUM_STUDENTS =100
};

struct student
{
    char name[ MAX_NAME_LEN ];
    char id [ MAX_ID_LEN ];
    int score;
};

typedef struct student student;

int openFileFromConsole(FILE **fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main( void )
{
    FILE * fp = NULL;

    int openStatus = openFileFromConsole(&fp);

    if( 0 == openStatus )
    {
        saveStudentGradeInfoTofile( fp );
    }

    fclose( fp );
   return 0;
} // end function: main

int openFileFromConsole(FILE **fp)
{
    char filePath[ MAX_PATH_LEN ];
    char fileOpenType;

    printf("Enter Path name: ");
    if( 1 != scanf("%100s", filePath) )
    {
        perror( "scanf for file path failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("Enter file open type w, r or a: ");
    if( 1 != scanf(" %c", &fileOpenType) )
    {
        perror( "scanf for file open type failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    char buffer[ MAX_TYPE_LEN ];
    buffer[0] = '\"';
    buffer[1] = fileOpenType;
    buffer[2] = '\"';
    buffer[3] = '\0';
    *fp = fopen(filePath, buffer);
    if( *fp )
    {
        return 1;
    }

    else
    {
         perror( "fopen failed" );
         return 0;
    }
} // end function: openFileFromConsole

void saveStudentGradeInfoTofile(FILE *fp)
{
     size_t numOfStudent;
     student s[ MAX_NUM_STUDENTS ];

     printf ("Get the number of students :");
     if( 1 != scanf("%lu",&numOfStudent) )
     {
         perror( "scanf for number of students failed:" );
         fclose( fp );
         exit( EXIT_FAILURE );
     }

     // implied else, scanf successful

     for( size_t i = 0; i < numOfStudent; i++)
     {
         printf("\nEnter ID number:");
         if( 1 != scanf(" %19s",s[i].id) )
         {
             perror( "scanf for student ID failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         printf("Enter name: ");
         if( 1 != scanf(" %49s,",s[i].name) )
         {
             perror( "scanf for student ID failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         printf("Enter score: ");
         if( 1 != scanf("%d",&s[i].score) )
         {
             perror( "scanf for student Score failed" );
             fclose( fp );
             exit( EXIT_FAILURE );
         }

         // implied else, scanf successful

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",
                s[i].id,
                s[i].name,
                s[i].score);

         printf("\n");
    } // end while
} // end function: saveStudentGradeInfoToFile


问:
Printing Even and Odd using two Threads in Java
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

```<code>public class PrintEvenOddTester {

    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}
</code>```

Can someone help me in fixing this?

EDIT
Expected result:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9

答:
```<code>        public class OddAndEvenThreadProblems {
            private static Integer i = 0;

            public static void main(String[] args) {
                new EvenClass().start();
                new OddClass().start();

            }

            public static class EvenClass extends Thread {

                public void run() {
                    while (i < 10) {
                        synchronized (i) {
                            if (i % 2 == 0 ) {
                                try {
                                    Thread.sleep(1000);
                                    System.out.println(" EvenClass " + i);
                                    i = i + 1;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }
                }
            }

            public static class OddClass extends Thread {

                @Override
                public void run() {
                    while (i < 10) {
                        synchronized (i) {
                            if (i % 2 == 1) {
                                try {
                                    Thread.sleep(1000);
                                    System.out.println(" OddClass  " + i);
                                    i = i + 1;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                    }
                }
            }
        }
    }

OUTPUT will be :-

 EvenClass 0
 OddClass  1
 EvenClass 2
 OddClass  3
 EvenClass 4
 OddClass  5
 EvenClass 6
 OddClass  7
 EvenClass 8
 OddClass  9
</code>```

Body:
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

public class PrintEvenOddTester {

    public static void main(String ... args){
        Printer print = new Printer(false);
        Thread t1 = new Thread(new TaskEvenOdd(print));
        Thread t2 = new Thread(new TaskEvenOdd(print));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    int number=1;
    Printer print;

    TaskEvenOdd(Printer print){
        this.print = print;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        while(number<10){

            if(number%2 == 0){
                System.out.println("Number is :"+ number);
                print.printEven(number);
                number+=2;
            }
            else {
                System.out.println("Number is :"+ number);
                print.printOdd(number);
                number+=2;
            }
        }

      }

    }

class Printer {

    boolean isOdd;

    Printer(boolean isOdd){
        this.isOdd = isOdd;
    }

    synchronized void printEven(int number) {

        while(isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = true;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while(!isOdd){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = false;
        notifyAll();
    }

}

Can someone help me in fixing this?

EDIT
Expected result:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9