问:
PHP script is not executing my statement
I am trying to post my form with PHP. But by some reason my PHP script is not posting. When I turn error reporting on I get the following errors:

```<code>Notice: Undefined index: date2
Notice: Undefined variable: newSingle_cal6
Warning: Cannot modify header information - headers already sent
</code>```

I think none of these errors are causing the problem. The scripts sends me to header('Location: ../error.php'); which means the script is not executed. Also when I look in phpmyadmin, I see that the database is not updated.

I have tried to execute the SQL statement in mysql and the sql statement is working.

Does someone know what is wrong in my script and how I can fix the problem?

Here is my full script:

```<code><?php
    include_once('../../../../includes/db_connect.php');
    include_once('../../../../includes/functions.php');
    sec_session_start();

$correct = true;

$_SESSION['user_id'];
$pers_id = $_POST['pers_id'] ;
$name = $_POST['name'] ;
$single_cal4 = $_POST['date1'] ;
$single_cal6 = $_POST['date2'] ;

try {
    $myDateTime1 = DateTime::createFromFormat('d/m/Y', $single_cal4);
} catch (Exception $e) {
    echo $e->getMessage();
}
$newSingle_cal4 = $myDateTime1->format('Y-m-d');
if(!empty($_POST['date2'])){
    try {
        $myDateTime3 = DateTime::createFromFormat('d/m/Y', $single_cal6);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    $newSingle_cal6 = $myDateTime3->format('Y-m-d');
}

if($correct){
    $db = new PDO('mysql:host=localhost;dbname=db', 'root', '');

$query = "INSERT INTO cus(user_id, pers_id, name, date1, date2) VALUES (?, ?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->execute(array($_SESSION['user_id'], $pers_id, $name, $newSingle_cal4, $newSingle_cal6));

            header('Location: ../success.php');
}else{
            header('Location: ../error.php');
}
?>
</code>```

答:
There's a few issues here:

Notice: Undefined index: date2

This is because the index date2 does not exist in your post ($_POST['date2'])

Notice: Undefined variable: newSingle_cal6

Because date2 does not exist in your post the variable newSingle_cal6 is never set.

Warning: Cannot modify header information - headers already sent

This is because the headers on your page have already been sent before you call header('Location: ../success.php');. This will happen if you call header or echo before that. The headers will also send if you have any raw non-php text in your file before. Make sure there is no space or anything before your opening php tag (<?php).

Find more information on this error here.

Body:
I am trying to post my form with PHP. But by some reason my PHP script is not posting. When I turn error reporting on I get the following errors:

Notice: Undefined index: date2
Notice: Undefined variable: newSingle_cal6
Warning: Cannot modify header information - headers already sent

I think none of these errors are causing the problem. The scripts sends me to header('Location: ../error.php'); which means the script is not executed. Also when I look in phpmyadmin, I see that the database is not updated.

I have tried to execute the SQL statement in mysql and the sql statement is working.

Does someone know what is wrong in my script and how I can fix the problem?

Here is my full script:

<?php
    include_once('../../../../includes/db_connect.php');
    include_once('../../../../includes/functions.php');
    sec_session_start();

$correct = true;

$_SESSION['user_id'];
$pers_id = $_POST['pers_id'] ;
$name = $_POST['name'] ;
$single_cal4 = $_POST['date1'] ;
$single_cal6 = $_POST['date2'] ;

try {
    $myDateTime1 = DateTime::createFromFormat('d/m/Y', $single_cal4);
} catch (Exception $e) {
    echo $e->getMessage();
}
$newSingle_cal4 = $myDateTime1->format('Y-m-d');
if(!empty($_POST['date2'])){
    try {
        $myDateTime3 = DateTime::createFromFormat('d/m/Y', $single_cal6);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    $newSingle_cal6 = $myDateTime3->format('Y-m-d');
}

if($correct){
    $db = new PDO('mysql:host=localhost;dbname=db', 'root', '');

$query = "INSERT INTO cus(user_id, pers_id, name, date1, date2) VALUES (?, ?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->execute(array($_SESSION['user_id'], $pers_id, $name, $newSingle_cal4, $newSingle_cal6));

            header('Location: ../success.php');
}else{
            header('Location: ../error.php');
}
?>


来源: stackexchange

问:
Jquery .then not waiting for function to finish
I have a semi complicated chain of promises that need to happen in a certain order. One of the functions that is part of the promise chain is returning the promise before it has been resolved from another function. Example:

```<code>this.triOverlay = new Image();
this.triOverlayFinal = new Image();

//Start the promise chain for overlay stuff
$.when($.loadImage(this.triOverlay, 'art/small.png'), this.loadAgentImages()).then(function () {
    console.log(">>> ALL DONE!!!! <<<<");
});
</code>```

LoadImage is a simple jQuery function that builds a deferred object and sets it up for image loading and processing:

```<code>    $.loadImage = function (image, url) {
    // Define a "worker" function that should eventually resolve or reject the deferred object.
    var loadImage = function (deferred) {

        image.onload = loaded;
        image.onerror = errored; // URL returns 404, etc
        image.onabort = errored; // IE may call this if user clicks "Stop"

        image.src = url;

        function loaded() {
            unbindEvents();
            console.log(">>>>> resolved image! URL: ");
            deferred.resolve(image);
        }
        function errored() {
            unbindEvents();
            deferred.reject(image);
        }
        function unbindEvents() {
            // Ensures the event callbacks only get called once.
            image.onload = null;
            image.onerror = null;
            image.onabort = null;
        }
    };
    return $.Deferred(loadImage).promise();
};
</code>```

Where it gets complicated is that in the loadAgentImages I have another set of images that need to be loaded with a clause that needs to happen once those are loaded:

```<code>CubePan.prototype.loadAgentImages = function () {

    var largePhotoPath = 'someURL'; //Just an example
    var smallPhotoPath = 'someURL2'; //Just an example

    //This cubePan
    var me = this;

    return $.when($.loadImage(this.agent.photo, smallPhotoPath), $.loadImage(this.agent.blurAgentPhoto, largePhotoPath)).then(function () {
        //return deferred.promise();
        console.log(">>>> before start on bluid blur and build TriOverlay <<<<");
        return buildBlur(me);
        //return blur;
    }, function () { console.log(">>>> blur rejected <<<<"); });
};
</code>```

The original images and call to the loadAgentImages are in the same object. I know i didn't include that above.

Once the two images have been resolved in the when, the then fires correctly and It calls buildBlur(me):

```<code>function buildBlur(me) {
    console.log(">>>> buildBlur <<<<");
    var blurCanvas = document.createElement('canvas');
    var blurCTX = blurCanvas.getContext('2d');
    blurCanvas.height = me.agent.blurAgentPhoto.height;
    blurCanvas.width = me.agent.blurAgentPhoto.width;
    blurCTX.drawImage(me.agent.blurAgentPhoto, 0, 0, blurCanvas.width, blurCanvas.height);

    //This function can be found in stackBlur.js
    boxBlurCanvasRGBA(blurCanvas, 0, 0, blurCanvas.width, blurCanvas.height, 20);
    return $.loadImage(me.agent.blurAgentPhotoFinal, blurCanvas.toDataURL('image/png', 1.0));

};
</code>```

However, BuildBlur does not return the promise once its been resolved its returning it right away. Making the rest of the chain think its resolved, even though the final image (blurAgentPhotoFinal) has not been loaded and resolved yet.

The $.loadImage works in all the instances from above, just not in the instance with buildBlur.

Any ideas why it isnt waiting for the $.loadImage in buildBlur to finish before fully resolving the chain?

Thanks!

答: Found the Issue. The code was using a very old version of jquery. 1.7. When upgraded to the newest the .Then started working correctly.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a semi complicated chain of promises that need to happen in a certain order. One of the functions that is part of the promise chain is returning the promise before it has been resolved from another function. Example:

this.triOverlay = new Image();
this.triOverlayFinal = new Image();

//Start the promise chain for overlay stuff
$.when($.loadImage(this.triOverlay, 'art/small.png'), this.loadAgentImages()).then(function () {
    console.log(">>> ALL DONE!!!! <<<<");
});

LoadImage is a simple jQuery function that builds a deferred object and sets it up for image loading and processing:

    $.loadImage = function (image, url) {
    // Define a "worker" function that should eventually resolve or reject the deferred object.
    var loadImage = function (deferred) {

        image.onload = loaded;
        image.onerror = errored; // URL returns 404, etc
        image.onabort = errored; // IE may call this if user clicks "Stop"

        image.src = url;

        function loaded() {
            unbindEvents();
            console.log(">>>>> resolved image! URL: ");
            deferred.resolve(image);
        }
        function errored() {
            unbindEvents();
            deferred.reject(image);
        }
        function unbindEvents() {
            // Ensures the event callbacks only get called once.
            image.onload = null;
            image.onerror = null;
            image.onabort = null;
        }
    };
    return $.Deferred(loadImage).promise();
};

Where it gets complicated is that in the loadAgentImages I have another set of images that need to be loaded with a clause that needs to happen once those are loaded:

CubePan.prototype.loadAgentImages = function () {

    var largePhotoPath = 'someURL'; //Just an example
    var smallPhotoPath = 'someURL2'; //Just an example

    //This cubePan
    var me = this;

    return $.when($.loadImage(this.agent.photo, smallPhotoPath), $.loadImage(this.agent.blurAgentPhoto, largePhotoPath)).then(function () {
        //return deferred.promise();
        console.log(">>>> before start on bluid blur and build TriOverlay <<<<");
        return buildBlur(me);
        //return blur;
    }, function () { console.log(">>>> blur rejected <<<<"); });
};

The original images and call to the loadAgentImages are in the same object. I know i didn't include that above.

Once the two images have been resolved in the when, the then fires correctly and It calls buildBlur(me):

function buildBlur(me) {
    console.log(">>>> buildBlur <<<<");
    var blurCanvas = document.createElement('canvas');
    var blurCTX = blurCanvas.getContext('2d');
    blurCanvas.height = me.agent.blurAgentPhoto.height;
    blurCanvas.width = me.agent.blurAgentPhoto.width;
    blurCTX.drawImage(me.agent.blurAgentPhoto, 0, 0, blurCanvas.width, blurCanvas.height);

    //This function can be found in stackBlur.js
    boxBlurCanvasRGBA(blurCanvas, 0, 0, blurCanvas.width, blurCanvas.height, 20);
    return $.loadImage(me.agent.blurAgentPhotoFinal, blurCanvas.toDataURL('image/png', 1.0));

};

However, BuildBlur does not return the promise once its been resolved its returning it right away. Making the rest of the chain think its resolved, even though the final image (blurAgentPhotoFinal) has not been loaded and resolved yet.

The $.loadImage works in all the instances from above, just not in the instance with buildBlur.

Any ideas why it isnt waiting for the $.loadImage in buildBlur to finish before fully resolving the chain?

Thanks!


问:
Makefile for project with code in multiple directories but same directory structure
I have the following directory structure for a C++ project:

```<code>.
├── bin
├── build
├── include
│   ├── dir1
│   │   ├── file1.hpp
│   │   └── file2.hpp
│   ├── dir2
│   │   ├── file3.hpp
│   │   └── file4.hpp
│   └── third_party
│       └── catch.hpp
├── Makefile
├── src
│   ├── dir1
│   │   ├── file1.cpp
│   │   └── file2.cpp
│   └── dir2
│       ├── file3.cpp
│       └── file4.cpp
└── test
    ├── dir1
    │   ├── file1.test.cpp
    │   └── file2.test.cpp
    └── dir2
        ├── file3.test.cpp
        └── file4.test.cpp
</code>```

How can I write the Makefile to compile the code in src and test directories and obtain the object files in the build directory and the binaries in the bin directory, maintaining the same directory structure within them, without having to name every file and its dependency explicitly? Would it be better to use multiple Makefiles in each dir* within src and test?

My Makefile currently looks like this: (it's probably nonsensical, sorry about that!)

```<code>binaries_dir = bin
build_dir = build
sources_dir = src
include_dir = include

compile_flags = -std=c++14 -Wall

binaries := $(wildcard *.out)
objects := $(wildcard *.o)
sources := $(wildcard *.cpp)
headers := $(wildcard *.hpp)

objects: $(sources)
    g++ $(compile_flags) -c $(sources_dir)/$(sources) -I $(include_dir)

binaries: $(objects)
    for object in $(objects); do
        g++ $(compile_flags) -o $(binaries_dir)/ $(build_dir)/$object
    done
</code>```

答: You might find some inspiration from this: https://github.com/jschmerge/DasBuild</p>

Body:
I have the following directory structure for a C++ project:

.
├── bin
├── build
├── include
│   ├── dir1
│   │   ├── file1.hpp
│   │   └── file2.hpp
│   ├── dir2
│   │   ├── file3.hpp
│   │   └── file4.hpp
│   └── third_party
│       └── catch.hpp
├── Makefile
├── src
│   ├── dir1
│   │   ├── file1.cpp
│   │   └── file2.cpp
│   └── dir2
│       ├── file3.cpp
│       └── file4.cpp
└── test
    ├── dir1
    │   ├── file1.test.cpp
    │   └── file2.test.cpp
    └── dir2
        ├── file3.test.cpp
        └── file4.test.cpp

How can I write the Makefile to compile the code in src and test directories and obtain the object files in the build directory and the binaries in the bin directory, maintaining the same directory structure within them, without having to name every file and its dependency explicitly? Would it be better to use multiple Makefiles in each dir* within src and test?

My Makefile currently looks like this: (it's probably nonsensical, sorry about that!)

binaries_dir = bin
build_dir = build
sources_dir = src
include_dir = include

compile_flags = -std=c++14 -Wall

binaries := $(wildcard *.out)
objects := $(wildcard *.o)
sources := $(wildcard *.cpp)
headers := $(wildcard *.hpp)

objects: $(sources)
    g++ $(compile_flags) -c $(sources_dir)/$(sources) -I $(include_dir)

binaries: $(objects)
    for object in $(objects); do
        g++ $(compile_flags) -o $(binaries_dir)/ $(build_dir)/$object
    done


问:
Java How to read a TEXT log file that contains separate XML and extract the XML Blocks
Using Java

I have an application that writes all the XML messages it receives into Log files.  Each XML message is appended to the log file by log4j.

This should work for any type of text file that has a unique start and end of a block of text.  This is not specific.

There can be thousands of XML messages in each log file and new log files are created each day.

I have no need to parse the XML in the log files into it's elements other than to pull each XML message (block of XML) from the log file into a memory variable in Java.  (The entire block of XML from the first tag to the last needs to be in a memory variable).

I will be sending this XML to a Web Service to be processed similar to the way it is being sent over from our Middleware today.

I already have that part working to send the XML and am able to process files as long as the XML is on one row in the log file but the XML writer in the application writs the XML in some cases in an indented new line format hence the need to be able to pluck the blocks of XML messages from the log file.

So -I need to read the XML in the log file from the first tag:

```<code><?xml version='1.0' encoding='UTF-8'?>
</code>```

Until the last tag of the last tag:

```<code></MyXML>
</code>```

No matter if there are carriage returns or blank lines in the file and it has to skip invalid rows.

Each XML message can be small to very large - easily over 20k.

The XML log file will look something like the following and may have blank rows between each XML message or other text as shown below:

```<code><?xml version='1.0' encoding='UTF-8'?>
<MyXML>
<Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/>
<Payload><SetProfile allowInvalidProfile="F">
<Partner publisherID="52725" act="Update">
<Contact languageCode="EN" firstName="Luis" lastName="Dini" email="Dini@email.com" act="Update" publisherID="ldini" securityRoleCode="6"/>
</Partner></SetProfile>
</Payload>
</MyXML>

<?xml version='1.0' encoding='UTF-8'?><MyXML><Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/><Payload><SetProfile allowInvalidProfile="F"><Partner publisherID="9857684" act="Update"><Contact languageCode="EN" firstName="Bill" lastName="Jones" email="Jones@email.com" act="Update" publisherID="BJones" securityRoleCode="3"/></Partner></SetProfile></Payload></MyXML>

======================
#]
<?xml version='1.0' encoding='UTF-8'?><MyXML><Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/>
<Payload><SetProfile allowInvalidProfile="F"><Partner publisherID="7465737" act="Update">
<Contact languageCode="EN" firstName="John" lastName="Smith" email="Smith@email.com" act="Update" publisherID="JSmith" securityRoleCode="3"/></Partner></SetProfile></Payload></MyXML>
</code>```

In short this will be a tool that will read a log file of XML messages and extract each individual XML message to be forwarded to a Web Service similar to the way the middleware is creating and sending each XML message today.

This will be used for volume testing and other development needs.

Any suggestions are appreciated.

答:
A simple way to do it would be to load the log file content into a String and then use a regular expression, something like this:</p>

```<code>Pattern p = Pattern.compile(Pattern.quote("<?xml version='1.0' encoding='UTF-8'?>") + ".*?" + Pattern.quote("</MyXML>"));
Matcher m = p.matcher(allText);
while (m.find()) {
    System.out.println(m.group());
}
</code>```

Body:
Using Java

I have an application that writes all the XML messages it receives into Log files.  Each XML message is appended to the log file by log4j.

This should work for any type of text file that has a unique start and end of a block of text.  This is not specific.

There can be thousands of XML messages in each log file and new log files are created each day.

I have no need to parse the XML in the log files into it's elements other than to pull each XML message (block of XML) from the log file into a memory variable in Java.  (The entire block of XML from the first tag to the last needs to be in a memory variable).

I will be sending this XML to a Web Service to be processed similar to the way it is being sent over from our Middleware today.

I already have that part working to send the XML and am able to process files as long as the XML is on one row in the log file but the XML writer in the application writs the XML in some cases in an indented new line format hence the need to be able to pluck the blocks of XML messages from the log file.

So -I need to read the XML in the log file from the first tag:

<?xml version='1.0' encoding='UTF-8'?>

Until the last tag of the last tag:

</MyXML>

No matter if there are carriage returns or blank lines in the file and it has to skip invalid rows.

Each XML message can be small to very large - easily over 20k.

The XML log file will look something like the following and may have blank rows between each XML message or other text as shown below:

<?xml version='1.0' encoding='UTF-8'?>
<MyXML>
<Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/>
<Payload><SetProfile allowInvalidProfile="F">
<Partner publisherID="52725" act="Update">
<Contact languageCode="EN" firstName="Luis" lastName="Dini" email="Dini@email.com" act="Update" publisherID="ldini" securityRoleCode="6"/>
</Partner></SetProfile>
</Payload>
</MyXML>

<?xml version='1.0' encoding='UTF-8'?><MyXML><Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/><Payload><SetProfile allowInvalidProfile="F"><Partner publisherID="9857684" act="Update"><Contact languageCode="EN" firstName="Bill" lastName="Jones" email="Jones@email.com" act="Update" publisherID="BJones" securityRoleCode="3"/></Partner></SetProfile></Payload></MyXML>

======================
#]
<?xml version='1.0' encoding='UTF-8'?><MyXML><Envelope documentType="SetProfile" trader="BEA" dtdRev="2.0" xid="03-JUL-17 14:38:49" traderLogin="middleware" traderPassword="abc123"/>
<Payload><SetProfile allowInvalidProfile="F"><Partner publisherID="7465737" act="Update">
<Contact languageCode="EN" firstName="John" lastName="Smith" email="Smith@email.com" act="Update" publisherID="JSmith" securityRoleCode="3"/></Partner></SetProfile></Payload></MyXML>

In short this will be a tool that will read a log file of XML messages and extract each individual XML message to be forwarded to a Web Service similar to the way the middleware is creating and sending each XML message today.

This will be used for volume testing and other development needs.

Any suggestions are appreciated.

Body:
A simple way to do it would be to load the log file content into a String and then use a regular expression, something like this:

Pattern p = Pattern.compile(Pattern.quote("<?xml version='1.0' encoding='UTF-8'?>") + ".*?" + Pattern.quote("</MyXML>"));
Matcher m = p.matcher(allText);
while (m.find()) {
    System.out.println(m.group());
}


问:
Is it possible to remove an object in an array rather than its index? (Java)
When I tried self-answering this question, I could only find other questions regarding removing items from an array so that items past the removed object get moved down 1 in the index.

In the code below, I have two arrays that hold the class SomeObject (with a name property): SomeObject_ONE and SomeObject_TWO.

Below I put an object "some-object" in the first array, and then set the second array to equal the object in the first array. I can still change the properties of the object in the first array by changing the properties of the object in the second array (the 3rd indent.)

However, when I try setting the object in the second array to null, it doesn't set the first array to null, rather it only removes the index for the object in the second array (4th indent).

Is there anyway to delete an object in an array rather than removing its array index?

Thanks.

```<code>    SomeObject[] ObjectArray_ONE = new SomeObject[10];
    SomeObject[] ObjectArray_TWO = new SomeObject[10];

    ObjectArray_ONE[0] = new SomeObject();
    ObjectArray_TWO[0] = ObjectArray_ONE[0];

    System.out.println(ObjectArray_ONE[0].name+" outputs default name");
    ObjectArray_TWO[0].name = "Name changed from OA2";
    System.out.println(ObjectArray_ONE[0].name+" outputs Name changed from OA2");

    System.out.println("Should not be null        : "+ObjectArray_ONE[0]);
    ObjectArray_TWO[0] = null;
    System.out.println("Should be null            : "+ObjectArray_ONE[0]);
    ObjectArray_ONE[0] = null;
    System.out.println("Only now is it really null: "+ObjectArray_ONE[0]);
</code>```

答:
The reason for this is exactly what Max said. Its the same reason that if you set one of your method parameters to null (inside the method) it won't affect the caller.

If you want you can store an array of wrapper classes of that object and then calling the setter of the wrapper class... Not exactly neat though.

PS. Don't capitalise variable names... it confuses people.

Body:
When I tried self-answering this question, I could only find other questions regarding removing items from an array so that items past the removed object get moved down 1 in the index.

In the code below, I have two arrays that hold the class SomeObject (with a name property): SomeObject_ONE and SomeObject_TWO.

Below I put an object "some-object" in the first array, and then set the second array to equal the object in the first array. I can still change the properties of the object in the first array by changing the properties of the object in the second array (the 3rd indent.)

However, when I try setting the object in the second array to null, it doesn't set the first array to null, rather it only removes the index for the object in the second array (4th indent).

Is there anyway to delete an object in an array rather than removing its array index?

Thanks.

    SomeObject[] ObjectArray_ONE = new SomeObject[10];
    SomeObject[] ObjectArray_TWO = new SomeObject[10];

    ObjectArray_ONE[0] = new SomeObject();
    ObjectArray_TWO[0] = ObjectArray_ONE[0];

    System.out.println(ObjectArray_ONE[0].name+" outputs default name");
    ObjectArray_TWO[0].name = "Name changed from OA2";
    System.out.println(ObjectArray_ONE[0].name+" outputs Name changed from OA2");

    System.out.println("Should not be null        : "+ObjectArray_ONE[0]);
    ObjectArray_TWO[0] = null;
    System.out.println("Should be null            : "+ObjectArray_ONE[0]);
    ObjectArray_ONE[0] = null;
    System.out.println("Only now is it really null: "+ObjectArray_ONE[0]);


问:
UI less application in iOS4
I'm new to mac/iOS development. I'm thinking of to develop a UI less application by using existing Apps/Libraries.

I want to know whether following things will be possible to make or not, it will be great if someone provides me some insight.

Here are my questions:

Is it possible to show/hook additional buttons on existing contacts
-> contacts view (some additional buttons under FaceTime button)?

Is it possible to route some messages to SMS inbox? where the user
feels like he received/sent the real SMS?

答:
In short: no.

In somewhat longer: iOS applications run in a sandbox that rather severely limits their ability to interact with the outside world. This is for the purpose of protecting the user's security and experience using the device. It MIGHT be possible to accomplish both of those things if you were running on a jailbroken device and using non-public APIS (though frankly I doubt you'd be able to add buttons to the existing contacts list by any means at all). But such an app couldn't be sold in Apple's app store.

Title: UI less application in iOS4

ContentLicense: CC BY-SA 2.5


问:
Change Azure Backup Vault Redundancy
We use Azure Backup and set our backup vaults to use GRS. We want to use LRS instead. It is understood that this cannot be changed once machines have been added to the vault, and we need to start from scratch. Two questions:

Do I need to remove the current vault first before I set up a new vault for that same server?

Can the current backups be transferred to the new vault?

答:
Changing a Recovery Service Vault's storage replication type can be achieved via the Portal or PowerShell.  Unfortunately, this option is greyed-out in the Portal, and whilst the cmdlet successfully executes, it doesn't change the underlying value: if there is one or more Protected Instances already contained in the vault.

Because of this, and because the default value is GeoRedundant, this must be set before any items have been protected.

To set the storage to Locally Redundant via the Portal:

Create/Open the Recovery Services Vault

Scroll-down and select Backup Infrastructure

Select Backup Configuration

Set Storage replication type to Locally-redundant

To achieve the same via PowerShell:

```<code>$RG = 'testResourceGroup'
$VaultName = 'testVault'
$Location = 'Central US'

$vault = Get-AzureRmRecoveryServicesVault -ResourceGroupName $RG -Name $VaultName
If (-not $vault) {
    $vault = New-AzureRmRecoveryServicesVault -ResourceGroupName $RG -Location $Location -Name $VaultName
}
Set-AzureRmRecoveryServicesBackupProperties -Vault $vault -BackupStorageRedundancy LocallyRedundant
</code>```

With regards removing existing vaults and transferring existing backup points:

The existing vault does not need to be deleted, however any protected items will need to be removed from the vault before they can be added to a new vault.  It is not sufficient to simply stop backup on the protected item - all the restore points must also be deleted before the item can be added to the new vault

I cannot find any documentation, facility in the Portal or PowerShell which would allow the migration of existing protected items and/or restore points

Title: Change Azure Backup Vault Redundancy

Body:
Changing a Recovery Service Vault's storage replication type can be achieved via the Portal or PowerShell.  Unfortunately, this option is greyed-out in the Portal, and whilst the cmdlet successfully executes, it doesn't change the underlying value: if there is one or more Protected Instances already contained in the vault.

Because of this, and because the default value is GeoRedundant, this must be set before any items have been protected.

To set the storage to Locally Redundant via the Portal:

Create/Open the Recovery Services Vault

Scroll-down and select Backup Infrastructure

Select Backup Configuration

Set Storage replication type to Locally-redundant

To achieve the same via PowerShell:

$RG = 'testResourceGroup'
$VaultName = 'testVault'
$Location = 'Central US'

$vault = Get-AzureRmRecoveryServicesVault -ResourceGroupName $RG -Name $VaultName
If (-not $vault) {
    $vault = New-AzureRmRecoveryServicesVault -ResourceGroupName $RG -Location $Location -Name $VaultName
}
Set-AzureRmRecoveryServicesBackupProperties -Vault $vault -BackupStorageRedundancy LocallyRedundant

With regards removing existing vaults and transferring existing backup points:

The existing vault does not need to be deleted, however any protected items will need to be removed from the vault before they can be added to a new vault.  It is not sufficient to simply stop backup on the protected item - all the restore points must also be deleted before the item can be added to the new vault

I cannot find any documentation, facility in the Portal or PowerShell which would allow the migration of existing protected items and/or restore points


问:
Is there Linux or U-Boot support to read a MAC address from a chip at startup?
My company builds custom hardware in such low quantities that it doesn't make financial sense to buy a whole block of MAC addresses.  What chip, if any, could I design into my embedded Linux board that could be used to automatically assign a globally unique MAC address at startup?

I've searched for Linux and u-boot driver support for MAC chips and EUI-48 chips, but come up empty.  MicroChip part number 24AA02E48 is an I2C chip that holds an EUI-48 address suitable as a MAC address.  There is also DS2502-48, a serial 1-wire chip that we've previously used by writing a separate u-boot application to read its MAC address, and assign it to the U-Boot ethaddr environment variable, but that was a manual step that I want to eliminate.  The 1-wire timing was so tight that the u-boot application occasionally failed to properly read the MAC address, so we never fully automated the process.

Is there any Linux or u-boot driver than can be configured to read a MAC address chip automatically at startup?

答:
As far as I know, you don't need a chip at all. The standards for MAC allow you to generate a "locally administered" MAC address which falls short of guaranteed global uniqueness. For small manufacturers like yourself, that's nearly always good enough, which is why the standards allow it.

Just be sure to follow those standards when picking a number, such as setting the U/L bit to "1" to guarantee that it cannot match a registered address (U/L bit == "0"). A "tl;dr" way to generate a valid local MAC address is to make the first three pairs "02:00:00:" and the last three pairs random hex digits; but if you're building hardware, I suggest taking the time to read the standards or at least the Wikipedia page.

In the event of a coincidental clash in the the pseudo-random digits, if at all possible give the customer a way to change your default MAC choice. Even if you have a registered address, it's still good to let the customer change it. Sometimes admins will tweak MAC's in ways that make routing and/or load-balancing easier, and very occasoinally they need to dodge a MAC generated by someone who thought it was OK to hard-code "00:00:00:00:00:00" or pick 12 random hex digits.

As for reading the MAC from Linux drivers or U-Boot, I don't know about your device, but I find it easiest to use U-Boot because it works at a lower level. U-Boot stores the MAC's it finds in the environment variables "ethaddr", "eth1addr", and "eth2addr". The command "printenv" is one way to view them. Here's an example from a board that happens to be in front of me right now:

```<code>U-Boot# printenv ethaddr eth1addr eth2addr
ethaddr=98:5d:ad:43:dd:38
eth1addr=98:5d:ad:43:dd:3a
## Error: "eth2addr" not defined
</code>```

The U-Boot command "bdinfo" might also be useful. Again from the board in front of me:

```<code>U-Boot# bdinfo
arch_number = 0x0000106E
boot_params = 0x80000100
DRAM bank   = 0x00000000
-> start    = 0x80000000
-> size     = 0x20000000
eth0name    = cpsw
ethaddr     = 98:5d:ad:43:dd:38
current eth = cpsw
ip_addr     = <NULL>
baudrate    = 115200 bps
TLB addr    = 0x9FFF0000
relocaddr   = 0x9F753000
reloc off   = 0x1EF53000
irq_sp      = 0x9F332F38
sp start    = 0x9F332F28
</code>```

U-Boot even includes an optional "gen_eth_addr" tool to generate valid locally administered addresses. Here's a usage example, excerpted from their wiki page at: https://www.denx.de/wiki/DULG/WhereCanIGetAValidMACAddress

```<code>$ make tools/gen_eth_addr
cc     tools/gen_eth_addr.c   -o tools/gen_eth_addr
$ tools/gen_eth_addr
ba:d0:4a:9c:4e:ce
</code>```

Body:
As far as I know, you don't need a chip at all. The standards for MAC allow you to generate a "locally administered" MAC address which falls short of guaranteed global uniqueness. For small manufacturers like yourself, that's nearly always good enough, which is why the standards allow it.

Just be sure to follow those standards when picking a number, such as setting the U/L bit to "1" to guarantee that it cannot match a registered address (U/L bit == "0"). A "tl;dr" way to generate a valid local MAC address is to make the first three pairs "02:00:00:" and the last three pairs random hex digits; but if you're building hardware, I suggest taking the time to read the standards or at least the Wikipedia page.

In the event of a coincidental clash in the the pseudo-random digits, if at all possible give the customer a way to change your default MAC choice. Even if you have a registered address, it's still good to let the customer change it. Sometimes admins will tweak MAC's in ways that make routing and/or load-balancing easier, and very occasoinally they need to dodge a MAC generated by someone who thought it was OK to hard-code "00:00:00:00:00:00" or pick 12 random hex digits.

As for reading the MAC from Linux drivers or U-Boot, I don't know about your device, but I find it easiest to use U-Boot because it works at a lower level. U-Boot stores the MAC's it finds in the environment variables "ethaddr", "eth1addr", and "eth2addr". The command "printenv" is one way to view them. Here's an example from a board that happens to be in front of me right now:

U-Boot# printenv ethaddr eth1addr eth2addr
ethaddr=98:5d:ad:43:dd:38
eth1addr=98:5d:ad:43:dd:3a
## Error: "eth2addr" not defined

The U-Boot command "bdinfo" might also be useful. Again from the board in front of me:

U-Boot# bdinfo
arch_number = 0x0000106E
boot_params = 0x80000100
DRAM bank   = 0x00000000
-> start    = 0x80000000
-> size     = 0x20000000
eth0name    = cpsw
ethaddr     = 98:5d:ad:43:dd:38
current eth = cpsw
ip_addr     = <NULL>
baudrate    = 115200 bps
TLB addr    = 0x9FFF0000
relocaddr   = 0x9F753000
reloc off   = 0x1EF53000
irq_sp      = 0x9F332F38
sp start    = 0x9F332F28

U-Boot even includes an optional "gen_eth_addr" tool to generate valid locally administered addresses. Here's a usage example, excerpted from their wiki page at: https://www.denx.de/wiki/DULG/WhereCanIGetAValidMACAddress

$ make tools/gen_eth_addr
cc     tools/gen_eth_addr.c   -o tools/gen_eth_addr
$ tools/gen_eth_addr
ba:d0:4a:9c:4e:ce


问:
Android Studio 2.2 preview throwing error while implementing databinding
I have updated my android studio to 2.2 preview 1 and applied the specified dependencies for google and firebase as specified but still getting the following error</p>

```<code>EmptyThrowable: Wrong dependency type: class com.android.tools.idea.databinding.DataBindingUtil$LightBRField

dataBinding {
    enabled true
}
</code>```

答:
You can update the Google repository in the Android Software Development Kit (SDK). The fastest way to do it to click:

Help> Check for updates

Body:
I have updated my android studio to 2.2 preview 1 and applied the specified dependencies for google and firebase as specified but still getting the following error

EmptyThrowable: Wrong dependency type: class com.android.tools.idea.databinding.DataBindingUtil$LightBRField

dataBinding {
    enabled true
}


问:
Fastest primality test
Could you suggest a fast, deterministic method that is usable in practice, for testing if a large number is prime or not?

Also, I would like to know how to use non-deterministic primality tests correctly. For example, if I'm using such a method, I can be sure that a number is not prime if the output is "no", but what about the other case, when the output is "probably"? Do I have to test for primality manually in this case?

Thanks in advance.

答: The only deterministic, polynomial-time algorithm for primality testing I know of is the AKS primality test (http://en.wikipedia.org/wiki/AKS_primality_test).  However, there are a lot of very good randomized primality tests that are fast and have extremely good probability of success.  They usually work by finding whether the number is composite with exponentially good probability, so they'll either report that the number is composite or will require you to say "maybe" with very good confidence.</p>

Title: Fastest primality test


问:
How do get a timestamp on an ASP.NET MVC App
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

```<code>columns.Bound(c => c.LastStatusDateDiff).Title("Updated");
</code>```

My Linq code looks as such

```<code>select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };
</code>```

Any suggestions greatly appreciated

答:
use TimeSpan

TimeSpan diff = Math.Abs(dateTime1 - dateTime2);

Formatting a TimeSpan Value

A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. That is, a time interval consists of a positive or negative number of days without a time of day, or a number of days with a time of day, or only a time of day.

The TimeSpan.ToString(String) overload lets you specify a format string that defines the string representation of the time interval. The TimeSpan.ToString(String, IFormatProvider) overload lets you specify a format string and the culture whose formatting conventions are used to create the string representation of the time interval. TimeSpan supports both standard and custom format strings. (For more information, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.) However, only standard format strings are culture-sensitive.

Body:
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

columns.Bound(c => c.LastStatusDateDiff).Title("Updated");

My Linq code looks as such

select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };

Any suggestions greatly appreciated


问:
Detect when a node is deleted (or removed from the DOM because a parent was)
I want to detect when a node (nodeX, say) is no longer available, either because it was deleted or because its parent (or its parents parent) was deleted.

So far, all I can think of is to use Mutation Observer to see any deletions on the page, and check if the deleted nodes was nodeX or had nodeX for a descendant.

Is there an easier way?

Please note: as far as I understand, the linked question (that this question "is a duplicate of") asks "how can I detect a [direct] deletion of a node". Mine asks "How can I detect the deletion of a node or its parent (or any other ancestor)".

As far as I understand, this is not straightforward with mutation observers: You need to check every deleted node to see if it was an ancestor.

This is what I seek to confirm or deny.

As far as I understand, that is different from the linked question.

答:
Here is an implementation that identifies how the element was removed (either directly or because a parent was removed)

var target = document.querySelector('#to-be-removed');

var observer = new MutationObserver(function(mutations) {
  // check for removed target
  mutations.forEach(function(mutation) {
    var nodes = Array.from(mutation.removedNodes);
    var directMatch = nodes.indexOf(target) > -1
    var parentMatch = nodes.some(parent => parent.contains(target));
    if (directMatch) {
      console.log('node', target, 'was directly removed!');
    } else if (parentMatch) {
      console.log('node', target, 'was removed through a removed parent!');
    }

  });
});

var config = {
  subtree: true,
  childList: true
};
observer.observe(document.body, config);

var qs = document.querySelector.bind(document);
qs('#ul').addEventListener('click', function(){qs('ul').remove();}, false)
qs('#li').addEventListener('click', function(){qs('#to-be-removed').remove();}, false)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li id="to-be-removed">list item 3</li>
  <li>list item 4</li>
</ul>

<button id="ul">remove ul</button>
<button id="li">remove li</button></code>```

Body:
Here is an implementation that identifies how the element was removed (either directly or because a parent was removed)

var target = document.querySelector('#to-be-removed');

var observer = new MutationObserver(function(mutations) {
  // check for removed target
  mutations.forEach(function(mutation) {
    var nodes = Array.from(mutation.removedNodes);
    var directMatch = nodes.indexOf(target) > -1
    var parentMatch = nodes.some(parent => parent.contains(target));
    if (directMatch) {
      console.log('node', target, 'was directly removed!');
    } else if (parentMatch) {
      console.log('node', target, 'was removed through a removed parent!');
    }

  });
});

var config = {
  subtree: true,
  childList: true
};
observer.observe(document.body, config);

var qs = document.querySelector.bind(document);
qs('#ul').addEventListener('click', function(){qs('ul').remove();}, false)
qs('#li').addEventListener('click', function(){qs('#to-be-removed').remove();}, false)

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li id="to-be-removed">list item 3</li>
  <li>list item 4</li>
</ul>

<button id="ul">remove ul</button>
<button id="li">remove li</button>


问:
Calling methods in pharo smalltalk
I'm trying to call a function from another class (Binario) but it says it's not implemented.

This is the code for the method in Binario class:

```<code>  genlista
  ^ (1 to: 30) collect: [ :i | 2 atRandom - 1 ]
</code>```

And this is the code for the other class method:

```<code> ListadelistasBin
  | bin |
  bin := Binario new.
  ^ (1 to: 30) collect: [ :i | bin genlista ]
</code>```

Please, help me :(

答:
Most likely @Uko is right and you defined the method in the class side of Binario rather than in the instance side. One way to check this would be to modify your second method like this:

```<code>ListadelistasBin
  | bin |
  bin := Binario.                            "<- new removed"
  ^ (1 to: 30) collect: [:i | bin genlista]
</code>```

If now you get the answer, then what happened is that your genlista method is in the wrong place (class side instead of instance side).

In Smalltalk every method belongs in a class. However, there are two "sides" of a class. The instance side is where you put methods for the instances of the class. The class side is where you put methods for the class itself.

How can you tell in what side of a class you have saved a method? Just look for the switch that every browser has to select one or the other side. In Pharo, for example, there is a toggle button that you use to select each of the sides.

While instance methods define the behavior of the instance of your class (and subclasses), class methods are meant to be sent to the class. This is just a consequence of classes being objects. For example, Binario new is a message sent to the class Binario, and we believe that your intention was to define the genlista method for instances of Binario. If this is the case, then copy the source code of the method and paste it on the instance side of the class. Then remove the class method and try again. Ah! and don't forget to put the new message back next to Binario in your ListadelistasBin!

Title: Calling methods in pharo smalltalk

Body:
I'm trying to call a function from another class (Binario) but it says it's not implemented.

This is the code for the method in Binario class:

  genlista
  ^ (1 to: 30) collect: [ :i | 2 atRandom - 1 ]

And this is the code for the other class method:

 ListadelistasBin
  | bin |
  bin := Binario new.
  ^ (1 to: 30) collect: [ :i | bin genlista ]

Please, help me :(

Body:
Most likely @Uko is right and you defined the method in the class side of Binario rather than in the instance side. One way to check this would be to modify your second method like this:

ListadelistasBin
  | bin |
  bin := Binario.                            "<- new removed"
  ^ (1 to: 30) collect: [:i | bin genlista]

If now you get the answer, then what happened is that your genlista method is in the wrong place (class side instead of instance side).

In Smalltalk every method belongs in a class. However, there are two "sides" of a class. The instance side is where you put methods for the instances of the class. The class side is where you put methods for the class itself.

How can you tell in what side of a class you have saved a method? Just look for the switch that every browser has to select one or the other side. In Pharo, for example, there is a toggle button that you use to select each of the sides.

While instance methods define the behavior of the instance of your class (and subclasses), class methods are meant to be sent to the class. This is just a consequence of classes being objects. For example, Binario new is a message sent to the class Binario, and we believe that your intention was to define the genlista method for instances of Binario. If this is the case, then copy the source code of the method and paste it on the instance side of the class. Then remove the class method and try again. Ah! and don't forget to put the new message back next to Binario in your ListadelistasBin!


问:
In R, how do you subset rows of a dataframe based on values in a vector
I'd like to generate a subset based on factor values contained in a vector. I've included my working code for a simple example. However, what if I have many columns (>10) and I don't wish to list each column using "|" (OR), is there a better way to do this? My example below uses LETTERS but I am dealing with factors (people's names).</p>

```<code>set.seed(37)
df <- data.frame(id1=sample(LETTERS, 20),id2=sample(LETTERS, 20))
L <- c("A","B","E")
subset(df, id1 %in% L | id2 %in% L )
   id1 id2
2    B   V
10   C   B
11   F   A
14   A   F
19   E   S
</code>```

答:
```<code>df[sort(unique(unlist(lapply(df, function(x) which(x %in% L))))),]
#   id1 id2
#2    B   V
#10   C   B
#11   F   A
#14   A   F
#19   E   S
</code>```

Body:
I'd like to generate a subset based on factor values contained in a vector. I've included my working code for a simple example. However, what if I have many columns (>10) and I don't wish to list each column using "|" (OR), is there a better way to do this? My example below uses LETTERS but I am dealing with factors (people's names).

set.seed(37)
df <- data.frame(id1=sample(LETTERS, 20),id2=sample(LETTERS, 20))
L <- c("A","B","E")
subset(df, id1 %in% L | id2 %in% L )
   id1 id2
2    B   V
10   C   B
11   F   A
14   A   F
19   E   S


问:
How to Save listview items to a text file on VB6
I have data in my listview1 like this:

And i want to save Quantity until Total cost Coloum from that listview to .txt
but i dont know how to save it to .txt

i found the referencee drom another web, they used this code:

```<code>Private Sub testfile as String = application.startupPath & "\testfile.txt"
</code>```

print(click)

```<code>Dim mywriter as new.IO.streamwriter(testfile)
    for eacy myItem as ListviewItem in Listview1.items
        mywriter.writeLine(myitem.text & "#" & myItem.SubItem(1).text & "#" & myitem.subitem(2).text)
    next
    mywriter.close()
</code>```

but VB6 can't compile this code.
please help me

答:
ListItems and ListSubItems are Base 1, this means they are starting from index 1 and you will find it in the same order as you have added it to the ListView.

For example: the Price for product "a" is in ListView1.ListItems(2).SubItems(4) because the first column is the ListItem Itself, which you can get as follows : ListView1.ListItems(2).Text.

So, if your question is about printing to file, you may need some small, optional, helper functions, which you can always keep in your snippet library, for example in a module, and (maybe) reuse.

Please, keep in mind there are really a lot of ways to get your task done, this is just an example.

```<code>Public Function NormalizePath(path As String) As String
    ' Normalize a Windows path with Backslash
    Const DirSeparator = "\"
    If Right(path, 1) = DirSeparator Then
        NormalizePath = path
    Else
        NormalizePath = path & DirSeparator
    End If
End Function

Public Function Formatted(TextValue, FormatType, ColumnWidth) As String
    ' Make fixed length fields
    Dim Result As String, PlaceHolder As String
    Dim CurrencyValue As Currency
    PlaceHolder = Space(ColumnWidth)
    Select Case FormatType
        Case "Text"
            Result = Left(TextValue & PlaceHolder, ColumnWidth)
        Case "Integer"
            Result = Right(PlaceHolder & TextValue, ColumnWidth)
        Case "Currency"
            CurrencyValue = CCur(TextValue)
            Result = Right(PlaceHolder & Format(CurrencyValue, "0.00"), ColumnWidth)
    End Select
    Formatted = Result
End Function
</code>```

Now to the point: double-click your CommandButton labeled Print Receipt and write this code:

```<code>PrintReceipt
</code>```

Copy and paste following function to your form:

```<code>Private Sub PrintReceipt()
On Error GoTo PrintReceipt_Error
    Dim LineText As String, CellText As String
    Dim TotalAmt As Currency, FormattedTotalAmt As String
    Dim FileNum As Integer, FullFileName As String, i As Long, l As Long

    FullFileName = NormalizePath(App.path) & "Receipt.txt"
    FileNum = FreeFile
    Open FullFileName For Output As #FileNum
    Print #FileNum, "| " & Formatted("Qty.", "Text", 5) & " | " & Formatted("Product Name", "Text", 12) & " | " & Formatted("Unit Amt.", "Text", 9) & " | " & Formatted("Amount", "Text", 12) & " | "
    Print #FileNum, String(2 * 2 + 3 * 3 + 5 + 12 + 9 + 12, "-")
    l = ListView1.ListItems.Count
    For i = 1 To l
        LineText = "| "
        CellText = ListView1.ListItems(i).SubItems(2) 'Quantity
        LineText = LineText & Formatted(CellText, "Integer", 5) & " | "
        CellText = ListView1.ListItems(i).SubItems(3) 'Product_Name
        LineText = LineText & Formatted(CellText, "Text", 12) & " | "
        CellText = ListView1.ListItems(i).SubItems(4) 'Price
        LineText = LineText & Formatted(CellText, "Currency", 9) & " | "
        CellText = ListView1.ListItems(i).SubItems(5)  'Total_Cost
        LineText = LineText & Formatted(CellText, "Currency", 12) & " | "
        TotalAmt = TotalAmt + CCur(CellText)
        Print #FileNum, LineText
    Next
    FormattedTotalAmt = Format(TotalAmt, "0.00")
    Print #FileNum, String(2 * 2 + 3 * 3 + 5 + 12 + 9 + 12, "-")
    Print #FileNum, Formatted("", "Text", 2 + 3 + 5) & Formatted("Total Amount", "Text", 12) & String(27 - Len(FormattedTotalAmt), ".") & FormattedTotalAmt
    Close #FileNum 'Close the file
    Exit Sub
PrintReceipt_Error:
    Close #FileNum 'Always close the file
End Sub
</code>```

If you did it all right, you will find inside the path of your project a nicely formatted copy of your received data. Open the text file with Notepad and from menu Format->Font choose a fixed-width font, for example Courier New. You should be able to see something like this:

The coolest thing you can do now with this file, is to send it back to your device as Order Confirmation.

Final notes:

familiarize and try to understand the terms: Quantity, Base
Quantity, Unit Price and Unit Cost. They have all different
meanings. Will be the Quantity always an Integer?

you haven't assigned to your received data any identifier, so i
believe your biggest problem now will be how to keep track of all the
received messages because the file will be always overwritten without
warning. Up to you, if you need it, to analyze the problem and find
out how to set your filename to a meaningful unique identifier, for
example: Receipt_0001.txt or something like this.

Happy learning!

Body:
I have data in my listview1 like this:

And i want to save Quantity until Total cost Coloum from that listview to .txt
but i dont know how to save it to .txt

i found the referencee drom another web, they used this code:

Private Sub testfile as String = application.startupPath & "\testfile.txt"

print(click)

Dim mywriter as new.IO.streamwriter(testfile)
    for eacy myItem as ListviewItem in Listview1.items
        mywriter.writeLine(myitem.text & "#" & myItem.SubItem(1).text & "#" & myitem.subitem(2).text)
    next
    mywriter.close()

but VB6 can't compile this code.
please help me

Body:
ListItems and ListSubItems are Base 1, this means they are starting from index 1 and you will find it in the same order as you have added it to the ListView.

For example: the Price for product "a" is in ListView1.ListItems(2).SubItems(4) because the first column is the ListItem Itself, which you can get as follows : ListView1.ListItems(2).Text.

So, if your question is about printing to file, you may need some small, optional, helper functions, which you can always keep in your snippet library, for example in a module, and (maybe) reuse.

Please, keep in mind there are really a lot of ways to get your task done, this is just an example.

Public Function NormalizePath(path As String) As String
    ' Normalize a Windows path with Backslash
    Const DirSeparator = "\"
    If Right(path, 1) = DirSeparator Then
        NormalizePath = path
    Else
        NormalizePath = path & DirSeparator
    End If
End Function

Public Function Formatted(TextValue, FormatType, ColumnWidth) As String
    ' Make fixed length fields
    Dim Result As String, PlaceHolder As String
    Dim CurrencyValue As Currency
    PlaceHolder = Space(ColumnWidth)
    Select Case FormatType
        Case "Text"
            Result = Left(TextValue & PlaceHolder, ColumnWidth)
        Case "Integer"
            Result = Right(PlaceHolder & TextValue, ColumnWidth)
        Case "Currency"
            CurrencyValue = CCur(TextValue)
            Result = Right(PlaceHolder & Format(CurrencyValue, "0.00"), ColumnWidth)
    End Select
    Formatted = Result
End Function

Now to the point: double-click your CommandButton labeled Print Receipt and write this code:

PrintReceipt

Copy and paste following function to your form:

Private Sub PrintReceipt()
On Error GoTo PrintReceipt_Error
    Dim LineText As String, CellText As String
    Dim TotalAmt As Currency, FormattedTotalAmt As String
    Dim FileNum As Integer, FullFileName As String, i As Long, l As Long

    FullFileName = NormalizePath(App.path) & "Receipt.txt"
    FileNum = FreeFile
    Open FullFileName For Output As #FileNum
    Print #FileNum, "| " & Formatted("Qty.", "Text", 5) & " | " & Formatted("Product Name", "Text", 12) & " | " & Formatted("Unit Amt.", "Text", 9) & " | " & Formatted("Amount", "Text", 12) & " | "
    Print #FileNum, String(2 * 2 + 3 * 3 + 5 + 12 + 9 + 12, "-")
    l = ListView1.ListItems.Count
    For i = 1 To l
        LineText = "| "
        CellText = ListView1.ListItems(i).SubItems(2) 'Quantity
        LineText = LineText & Formatted(CellText, "Integer", 5) & " | "
        CellText = ListView1.ListItems(i).SubItems(3) 'Product_Name
        LineText = LineText & Formatted(CellText, "Text", 12) & " | "
        CellText = ListView1.ListItems(i).SubItems(4) 'Price
        LineText = LineText & Formatted(CellText, "Currency", 9) & " | "
        CellText = ListView1.ListItems(i).SubItems(5)  'Total_Cost
        LineText = LineText & Formatted(CellText, "Currency", 12) & " | "
        TotalAmt = TotalAmt + CCur(CellText)
        Print #FileNum, LineText
    Next
    FormattedTotalAmt = Format(TotalAmt, "0.00")
    Print #FileNum, String(2 * 2 + 3 * 3 + 5 + 12 + 9 + 12, "-")
    Print #FileNum, Formatted("", "Text", 2 + 3 + 5) & Formatted("Total Amount", "Text", 12) & String(27 - Len(FormattedTotalAmt), ".") & FormattedTotalAmt
    Close #FileNum 'Close the file
    Exit Sub
PrintReceipt_Error:
    Close #FileNum 'Always close the file
End Sub

If you did it all right, you will find inside the path of your project a nicely formatted copy of your received data. Open the text file with Notepad and from menu Format->Font choose a fixed-width font, for example Courier New. You should be able to see something like this:

The coolest thing you can do now with this file, is to send it back to your device as Order Confirmation.

Final notes:

familiarize and try to understand the terms: Quantity, Base
Quantity, Unit Price and Unit Cost. They have all different
meanings. Will be the Quantity always an Integer?

you haven't assigned to your received data any identifier, so i
believe your biggest problem now will be how to keep track of all the
received messages because the file will be always overwritten without
warning. Up to you, if you need it, to analyze the problem and find
out how to set your filename to a meaningful unique identifier, for
example: Receipt_0001.txt or something like this.

Happy learning!


问:
how to compile c++ files with cygwin on windows 7
I have installed cygwin. But when I try to compile a c++ file it gives the following error:

```<code>/usr/lib/gcc/i686-pc-cygwin/4.3.4/cc1plus.exe: error while loading shared libraries: cygmpfr-1.dll: cannot open shared object file: No such file or directory
</code>```

I checked in the lib folder there is no library with the name cygmpfr-1.dll. So is it that I have to put that dll in the lib folder. I have tried to search for the dll but could not find this dll so that i can download. I am just a beginner in C++. I have tried to setup cygwin support in netbeans as well, but there also if I try to run the sample files given, it throws the above error.

Can anybody give me a clue?

答:
You need to install the gcc4-g++ package via http://cygwin.com/setup.exe
You only have gcc4 installed.

This will also install your missing dependencies.

Body:
I have installed cygwin. But when I try to compile a c++ file it gives the following error:

/usr/lib/gcc/i686-pc-cygwin/4.3.4/cc1plus.exe: error while loading shared libraries: cygmpfr-1.dll: cannot open shared object file: No such file or directory

I checked in the lib folder there is no library with the name cygmpfr-1.dll. So is it that I have to put that dll in the lib folder. I have tried to search for the dll but could not find this dll so that i can download. I am just a beginner in C++. I have tried to setup cygwin support in netbeans as well, but there also if I try to run the sample files given, it throws the above error.

Can anybody give me a clue?


问:
Keras: Lambda layer function with multiple parameters
I am trying to write a Lambda layer in Keras which calls a function connection, that runs a loop for i in range(0,k) where k is fed in as an input to the function, connection(x,k). Now, when I try to call the function in the Functional API, I tried using:

```<code>k = 5
y = Lambda(connection)(x)
</code>```

Also,

```<code>y = Lambda(connection)(x,k)
</code>```

But neither of those approaches worked. How can I feed in the value of k without assigning it as a global parameter?

答:
Found the solution to the problem in this GitHub Pull Request. Using

```<code>y = Lambda(connection, arguments={'k':k})(x)
</code>```

worked!

Body:
I am trying to write a Lambda layer in Keras which calls a function connection, that runs a loop for i in range(0,k) where k is fed in as an input to the function, connection(x,k). Now, when I try to call the function in the Functional API, I tried using:

k = 5
y = Lambda(connection)(x)

Also,

y = Lambda(connection)(x,k)

But neither of those approaches worked. How can I feed in the value of k without assigning it as a global parameter?

Body:
Found the solution to the problem in this GitHub Pull Request. Using

y = Lambda(connection, arguments={'k':k})(x)

worked!


问:
Need direction (JSON related)
I want to show m.aliexpress.com search with filters, Example:

https://m.aliexpress.com/search.htm?keywords=flashlight#/

The filters (such as "free shipping" etc) are sending in post method and with JSON i think.

I'm not sure how should i find/do this request to get page with this filters.
I tried to find the address with HTTP Headers extension but not succeed much..
I need direction..

thanks!

答:
I don't think this is a JSON issue.  I believe it is an url encoding issue.  In the example you gave, "free shipping", html will stop after the word free and query for that.  You have to "encode" the space character in your url.  In the case of "free shipping", your url properly encoded would be:
https://m.aliexpress.com/search.htm?keywords=free%20shipping

There are many other characters other than "space" that must be encoded.  I'll leave it to your to research those html encoded characters.

Title: Need direction (JSON related)


问:
Removing Stencils from Visio Document
Is there any ways to remove an existing Stencil from a Visio Document ?
(C# Win App)

I Couldnt find a way to remove an existing stencil.
But here is a sample to Add 1.

```<code>VisioDrawing.Document.Application.ActiveDocument.OpenStencilWindow();
VisioDrawing.Document.Application.Documents.OpenEx(_StencilPath + "BASFLO_M.vss",
(short)VisOpenSaveArgs.visOpenDocked);
</code>```

答:
If don't want/need the stencils to load you can rename the Visio Content folder that stores the stencils.

For Visio2013 it's C:\Program Files (x86)\Microsoft Office\Office15\Visio Content\1033.  Add a new folder and dump the files in there. This hides the stencils so that Visio cant see them. Then launch your Visio file.

Title: Removing Stencils from Visio Document

Body:
Is there any ways to remove an existing Stencil from a Visio Document ?
(C# Win App)

I Couldnt find a way to remove an existing stencil.
But here is a sample to Add 1.

VisioDrawing.Document.Application.ActiveDocument.OpenStencilWindow();
VisioDrawing.Document.Application.Documents.OpenEx(_StencilPath + "BASFLO_M.vss",
(short)VisOpenSaveArgs.visOpenDocked);


问:
'wget' full web site based on frames
I have a little problem. I want recursively download that web page, but it based on "frames". Standard methods can't help me. I try different variants, but nothing. Maximum I can download one recursion, I found example there. How can I grab that web site fully, and than use it offline? Thx.</p>

答:
If you want a local copy of a site use --mirror:

```<code>wget --mirror http://www.example.com/
</code>```

Some of the other options are useful too:

--convert-links converts absolute links to local links, so you can browse the site locally.

--HTML-extension adds .html to any resources that do not have a suffix (this is useful for browsing otherwise very dynamic sites locally via apache)

-p gets images, css and all resources required for the page to load

So:

```<code>wget --mirror --convert-links --HTML-extension -p http://www.example.com/
</code>```

Finally, if it's not your site, then be polite and add a -w (wait between requests, in seconds)

Title: 'wget' full web site based on frames

Body:
If you want a local copy of a site use --mirror:

wget --mirror http://www.example.com/

Some of the other options are useful too:

--convert-links converts absolute links to local links, so you can browse the site locally.

--HTML-extension adds .html to any resources that do not have a suffix (this is useful for browsing otherwise very dynamic sites locally via apache)

-p gets images, css and all resources required for the page to load

So:

wget --mirror --convert-links --HTML-extension -p http://www.example.com/

Finally, if it's not your site, then be polite and add a -w (wait between requests, in seconds)


问:
How to efficiently store and use Authentication in Ionic 3
I'm currently developing an Ionic (3.4) app for iOS/Android.
I'm not familiar with authentification processes or with applications.

After using HTTP request in a provider, I get my object, the user. But I have absolutely no idea how to store it or to deal with it. What are the good practices:

Am I suppose to just store the object in the provider and call in in every single page I have?

Am I suppose to store it as a sort of global object in the app?

Or am I suppose (as bellow) to transfer it as a Navigation variable from one page to another? (I guess that's not the right answer)

And finally, how will the application react on reloading/restarting: how to avoid people to fill the form again and again?

Here is my service:

```<code>@Injectable()
export class UserProvider {
    data = {};
    username: string;
    password: string;

    constructor(private _http: Http) {
        console.log('Hello UserProvider Provider');
    }

    getUser(username:string, password:string){

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let params = urlSearchParams.toString()

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        return this._http
        .post("http://api.minesdedouai.fr/user/login", params, {headers:headers} )
        .map(response => response.json())

    }

}
</code>```

I'm aware that a login request is supposed to use some token, but as I said, this is a small student's API, we're not pro and it's working.

And this is the method that uses the service, somewhere in a component (a page).

```<code>onLogin(form: NgForm) {
  if (form.valid) {
    this._userProvider.getUser(this.login.username, this.login.password)
    .subscribe((response) => {
      this.user = response;
      console.log("Authentification Success");
      this.navCtrl.push(TabsPage, {user: this.user});
    },
    (error) => {
      if (error.status===403){
        console.log("Wrong User")
      }
      else{
        console.log(error);
      }

    });
  }
}
</code>```

Thank you very much

答:
I will expose you how I deal with authentification on my ionic app.

The first step consists of creating a representation of the data you want to store. I used to store some user's information and a jwt token for the authentification.

user.ts :

```<code>export class AuthenticatedUser {
  private _username: string;
  private _id: number;
  private _token: string;

  public static GetNewInstance(): AuthenticatedUser {
    return new AuthenticatedUser(null, null, null)
  }

  public static ParseFromObject(object): AuthenticatedUser {
    const model = AuthenticatedUser.GetNewInstance();

    if (object) {
      model.username = object.username;
      model.id = object.id;
      model.token = object.token;
    }

    return model;
  }

  constructor(username: string, id: number, token: string) {
    this._username = username;
    this._id = id;
    this._token = token;
  }

  get username(): string {
    return this._username;
  }

  set username(value: string) {
    this._username = value;
  }

  get id(): number {
    return this._id;
  }

  set id(value: number) {
    this._id = value;
  }

  get token(): string {
    return this._token;
  }

  set token(value: string) {
    this._token = value;
  }
}
</code>```

The GetNewInstance method is used to return an instantiated AuthenticatedUser variable.

The ParseFromObject method is used to return an AuthenticatedUser from an object. It's very useful to convert an api response object into a model.

After that I create some services. The first one is the UserService. I use it to access my AuthenticatedUser inside my local storage. In the local storage the data are persistence and will not be delete when you close the app.

user.service.ts :

```<code>export class UsersService {

  private _user: Subject<AuthenticatedUser> = new Subject<AuthenticatedUser>();

  constructor(private storage: Storage) {}

  /* ---------------------------------------------------------------------------------------------------------------- */
  /* Observable use object                                                                                */

  public subscribeToUserService(callback) {
    return this._user.subscribe(callback);
  }

  public updateUserService(user: AuthenticatedUser) {
    this._user.next(user);
  }

  /* ---------------------------------------------------------------------------------------------------------------- */
  /* User storage management                                                                                */

  /**
   * Write user properties in the local storage.
   *
   * @param user
   * @returns {Promise<AuthenticatedUser>}
   */
  createOnStorage(user: AuthenticatedUser): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.getOnStorage().then((res) => {
        if (res) {
          this.deleteOnStorage().then(() => {

          });
        }
      }).then(() => {
        this.updateUserService(user);
        this.storage.set('user', JSON.stringify(user));
        resolve();
      });
    });
  }

  /**
   * Get user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  getOnStorage(): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.updateUserService(JSON.parse(this.storage.get('user')));
      resolve(this.storage.get('user'));
    });
  }

  /**
   * Get user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  getOnStorageSync() {
    this.updateUserService(JSON.parse(this.storage.get('user')));
    return this.storage.get('user');
  }

  /**
   * Update user properties from local storage.
   *
   * @param user
   * @returns {Promise<AuthenticatedUser>}
   */
  updateOnStorage(user: AuthenticatedUser): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      resolve(this.storage.get('user'));
    });
  }

  /**
   * Delete user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  deleteOnStorage(): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.storage.clear();
      resolve();
    });
  }
}
</code>```

The second service is ApiService. This service is use to send different HTTP methods and handled answers. In this service we will Format the header and access to the authenticatedUser's token.

```<code>@Injectable()
export class ApiService {

  private baseUrl = "https://my.api.co";
  private user: AuthenticatedUser;

  /* ---------------------------------------------------------------------------------------------------------------- */

  constructor(private userService: UserService, private http: Http) {
     getAuthUser()
  }

   private getAuthUser() {
     this.userService.getOnStorage.then(
       (user) => {
         this.user = user;
       });
   }

   /**
   * Get the Json Web Token from the local storage.
   *
   * @returns {RequestOptions}
   */
  private formatHeader(): RequestOptions {
    const headers: Headers = new Headers();
    if (this.user.token) {
      headers.append('Authorization', 'Bearer ' + this.user.token);
    }
    return new RequestOptions({headers});
  }

  /**
   * Get the body of an HTTP response.
   *
   * @param res
   * @returns {any|{}}
   */
  private handleBody(res: Response) {
    return res.json() || {};
  }

  /**
   * Format the error message of an HTTP response.
   *
   * @param error
   * @returns {any}
   */
  private handleError(error: Response | any) {
    let errorModel: any = {};

    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);

      errorModel = { status: error.status, message: `${error.status} - ${err.cause} ` };
    } else {
      errorModel = { status: error.status, message: error.toString()};
    }
    return Observable.throw(errorModel);
  }
  /* ---------------------------------------------------------------------------------------------------------------- */

  /**
   * Perform a PUT request.
   *
   * @param url
   * @param auth
   * @param body
   * @returns {Observable<>}
   */
  putRequest(url: string, body: Object, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.put(this.BASE_URL + url, body, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a POST request.
   *
   * @param url
   * @param auth
   * @param body
   * @returns {Observable<>}
   */
  postRequest(url: string, body: Object, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.post(this.BASE_URL + url, body, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a HEAD request.
   *
   * @param url
   * @param auth
   * @returns {Observable<>}
   */
  headRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.head(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a GET request.
   *
   * @param url
   * @param auth
   * @returns {Promise<>}
   */
  getRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null

    if(auth) {
      header = ApiService.formatHeader();
    }

    return this.http.get(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a DELETE request.
   *
   * @param url
   * @param auth
   * @returns {Observable<>}
   */
  deleteRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.delete(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }
</code>```

And the last service is the AuthService. This service will send login/logout requests.

auth.service.ts :

```<code>@Injectable()
export class AuthService {
   private user: AuthenticatedUser;
  /* ---------------------------------------------------------------------------------------------------------------- */

  constructor(private userService: userService, private apiService: ApiService) {
  this.getAuthUser();
}
   getAuthUser() {
     this.userService.getOnStorage().then(
        (user) => {
          this.user = user;
        }
     );
   }

  /* ---------------------------------------------------------------------------------------------------------------- */

  /**
   * Request an authentication access.
   *
   * @param email the email of the user
   * @param password the password of the user
   * @returns {Promise<any>}
   */
  login(email: string, password: string): Promise<AuthentificatedUser> {
    return new Promise((resolve, reject) => {
      this.apiService.postRequest('/auth', {email: email, password: password})
        .subscribe(
          res => resolve(AuthentificatedUser.ParseFromObject(res)),
          error => reject(<any>error));
    });
  }

  /**
   * Logout a user from the authentication process.
   *
   * @returns {Promise<any>}
   */
  logout(): Promise<any> {
    return new Promise((resolve) => {
      this.userService.deleteOnStorage().then(() => {
        resolve();
      });
    });
  }

  /**
   * Check whether a user is already logged in.
   *
   * @returns {boolean}
   */
  isLoggedIn() {
    if (this.user.token) {
      return true;
    } else {
      return false;
    }
  }

  /* ---------------------------------------------------------------------------------------------------------------- */
}
</code>```

In your login page :

```<code>this.authService.login('login', 'password').then(
  (user) => {
    this.userSerivce.createOnStorage(user);
    this.navCtrl.push(HomePage);
  }).catch(
    (err) => {
      //show the error
    }
  );
</code>```

The last thing you have to do this to check if a user is connected or redirect the user to the login screen.

```<code>export HomePage() {
  private user: AuthenticatedUser;

  constructor(private userService: UserService) {
    this.getAuthUser();
  }

  private getAuthUser() {
    this.userService.getOnStorage().then(
      (user) => {
        this.user = user;

        if (!this.user.token) {
          this.navCtrl.push(LoginPage)
        }
      }
    );
  }
}
</code>```

Body:
I'm currently developing an Ionic (3.4) app for iOS/Android.
I'm not familiar with authentification processes or with applications.

After using HTTP request in a provider, I get my object, the user. But I have absolutely no idea how to store it or to deal with it. What are the good practices:

Am I suppose to just store the object in the provider and call in in every single page I have?

Am I suppose to store it as a sort of global object in the app?

Or am I suppose (as bellow) to transfer it as a Navigation variable from one page to another? (I guess that's not the right answer)

And finally, how will the application react on reloading/restarting: how to avoid people to fill the form again and again?

Here is my service:

@Injectable()
export class UserProvider {
    data = {};
    username: string;
    password: string;

    constructor(private _http: Http) {
        console.log('Hello UserProvider Provider');
    }

    getUser(username:string, password:string){

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let params = urlSearchParams.toString()

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        return this._http
        .post("http://api.minesdedouai.fr/user/login", params, {headers:headers} )
        .map(response => response.json())

    }

}

I'm aware that a login request is supposed to use some token, but as I said, this is a small student's API, we're not pro and it's working.

And this is the method that uses the service, somewhere in a component (a page).

onLogin(form: NgForm) {
  if (form.valid) {
    this._userProvider.getUser(this.login.username, this.login.password)
    .subscribe((response) => {
      this.user = response;
      console.log("Authentification Success");
      this.navCtrl.push(TabsPage, {user: this.user});
    },
    (error) => {
      if (error.status===403){
        console.log("Wrong User")
      }
      else{
        console.log(error);
      }

    });
  }
}

Thank you very much

Body:
I will expose you how I deal with authentification on my ionic app.

The first step consists of creating a representation of the data you want to store. I used to store some user's information and a jwt token for the authentification.

user.ts :

export class AuthenticatedUser {
  private _username: string;
  private _id: number;
  private _token: string;

  public static GetNewInstance(): AuthenticatedUser {
    return new AuthenticatedUser(null, null, null)
  }

  public static ParseFromObject(object): AuthenticatedUser {
    const model = AuthenticatedUser.GetNewInstance();

    if (object) {
      model.username = object.username;
      model.id = object.id;
      model.token = object.token;
    }

    return model;
  }

  constructor(username: string, id: number, token: string) {
    this._username = username;
    this._id = id;
    this._token = token;
  }

  get username(): string {
    return this._username;
  }

  set username(value: string) {
    this._username = value;
  }

  get id(): number {
    return this._id;
  }

  set id(value: number) {
    this._id = value;
  }

  get token(): string {
    return this._token;
  }

  set token(value: string) {
    this._token = value;
  }
}

The GetNewInstance method is used to return an instantiated AuthenticatedUser variable.

The ParseFromObject method is used to return an AuthenticatedUser from an object. It's very useful to convert an api response object into a model.

After that I create some services. The first one is the UserService. I use it to access my AuthenticatedUser inside my local storage. In the local storage the data are persistence and will not be delete when you close the app.

user.service.ts :

export class UsersService {

  private _user: Subject<AuthenticatedUser> = new Subject<AuthenticatedUser>();

  constructor(private storage: Storage) {}

  /* ---------------------------------------------------------------------------------------------------------------- */
  /* Observable use object                                                                                */

  public subscribeToUserService(callback) {
    return this._user.subscribe(callback);
  }

  public updateUserService(user: AuthenticatedUser) {
    this._user.next(user);
  }

  /* ---------------------------------------------------------------------------------------------------------------- */
  /* User storage management                                                                                */

  /**
   * Write user properties in the local storage.
   *
   * @param user
   * @returns {Promise<AuthenticatedUser>}
   */
  createOnStorage(user: AuthenticatedUser): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.getOnStorage().then((res) => {
        if (res) {
          this.deleteOnStorage().then(() => {

          });
        }
      }).then(() => {
        this.updateUserService(user);
        this.storage.set('user', JSON.stringify(user));
        resolve();
      });
    });
  }

  /**
   * Get user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  getOnStorage(): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.updateUserService(JSON.parse(this.storage.get('user')));
      resolve(this.storage.get('user'));
    });
  }

  /**
   * Get user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  getOnStorageSync() {
    this.updateUserService(JSON.parse(this.storage.get('user')));
    return this.storage.get('user');
  }

  /**
   * Update user properties from local storage.
   *
   * @param user
   * @returns {Promise<AuthenticatedUser>}
   */
  updateOnStorage(user: AuthenticatedUser): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      resolve(this.storage.get('user'));
    });
  }

  /**
   * Delete user properties from local storage.
   *
   * @returns {Promise<AuthenticatedUser>}
   */
  deleteOnStorage(): Promise<AuthenticatedUser> {
    return new Promise((resolve) => {
      this.storage.clear();
      resolve();
    });
  }
}

The second service is ApiService. This service is use to send different HTTP methods and handled answers. In this service we will Format the header and access to the authenticatedUser's token.

@Injectable()
export class ApiService {

  private baseUrl = "https://my.api.co";
  private user: AuthenticatedUser;

  /* ---------------------------------------------------------------------------------------------------------------- */

  constructor(private userService: UserService, private http: Http) {
     getAuthUser()
  }

   private getAuthUser() {
     this.userService.getOnStorage.then(
       (user) => {
         this.user = user;
       });
   }

   /**
   * Get the Json Web Token from the local storage.
   *
   * @returns {RequestOptions}
   */
  private formatHeader(): RequestOptions {
    const headers: Headers = new Headers();
    if (this.user.token) {
      headers.append('Authorization', 'Bearer ' + this.user.token);
    }
    return new RequestOptions({headers});
  }

  /**
   * Get the body of an HTTP response.
   *
   * @param res
   * @returns {any|{}}
   */
  private handleBody(res: Response) {
    return res.json() || {};
  }

  /**
   * Format the error message of an HTTP response.
   *
   * @param error
   * @returns {any}
   */
  private handleError(error: Response | any) {
    let errorModel: any = {};

    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);

      errorModel = { status: error.status, message: `${error.status} - ${err.cause} ` };
    } else {
      errorModel = { status: error.status, message: error.toString()};
    }
    return Observable.throw(errorModel);
  }
  /* ---------------------------------------------------------------------------------------------------------------- */

  /**
   * Perform a PUT request.
   *
   * @param url
   * @param auth
   * @param body
   * @returns {Observable<>}
   */
  putRequest(url: string, body: Object, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.put(this.BASE_URL + url, body, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a POST request.
   *
   * @param url
   * @param auth
   * @param body
   * @returns {Observable<>}
   */
  postRequest(url: string, body: Object, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.post(this.BASE_URL + url, body, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a HEAD request.
   *
   * @param url
   * @param auth
   * @returns {Observable<>}
   */
  headRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.head(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a GET request.
   *
   * @param url
   * @param auth
   * @returns {Promise<>}
   */
  getRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null

    if(auth) {
      header = ApiService.formatHeader();
    }

    return this.http.get(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

  /**
   * Perform a DELETE request.
   *
   * @param url
   * @param auth
   * @returns {Observable<>}
   */
  deleteRequest(url: string, auth: boolean = true): Observable<Object> {
    let header = null;

    if (auth) {
      header = ApiService.formatHeader();
    }
    return this.http.delete(this.BASE_URL + url, header)
      .map(ApiService.handleBody)
      .catch(ApiService.handleError);
  }

And the last service is the AuthService. This service will send login/logout requests.

auth.service.ts :

@Injectable()
export class AuthService {
   private user: AuthenticatedUser;
  /* ---------------------------------------------------------------------------------------------------------------- */

  constructor(private userService: userService, private apiService: ApiService) {
  this.getAuthUser();
}
   getAuthUser() {
     this.userService.getOnStorage().then(
        (user) => {
          this.user = user;
        }
     );
   }

  /* ---------------------------------------------------------------------------------------------------------------- */

  /**
   * Request an authentication access.
   *
   * @param email the email of the user
   * @param password the password of the user
   * @returns {Promise<any>}
   */
  login(email: string, password: string): Promise<AuthentificatedUser> {
    return new Promise((resolve, reject) => {
      this.apiService.postRequest('/auth', {email: email, password: password})
        .subscribe(
          res => resolve(AuthentificatedUser.ParseFromObject(res)),
          error => reject(<any>error));
    });
  }

  /**
   * Logout a user from the authentication process.
   *
   * @returns {Promise<any>}
   */
  logout(): Promise<any> {
    return new Promise((resolve) => {
      this.userService.deleteOnStorage().then(() => {
        resolve();
      });
    });
  }

  /**
   * Check whether a user is already logged in.
   *
   * @returns {boolean}
   */
  isLoggedIn() {
    if (this.user.token) {
      return true;
    } else {
      return false;
    }
  }

  /* ---------------------------------------------------------------------------------------------------------------- */
}

In your login page :

this.authService.login('login', 'password').then(
  (user) => {
    this.userSerivce.createOnStorage(user);
    this.navCtrl.push(HomePage);
  }).catch(
    (err) => {
      //show the error
    }
  );

The last thing you have to do this to check if a user is connected or redirect the user to the login screen.

export HomePage() {
  private user: AuthenticatedUser;

  constructor(private userService: UserService) {
    this.getAuthUser();
  }

  private getAuthUser() {
    this.userService.getOnStorage().then(
      (user) => {
        this.user = user;

        if (!this.user.token) {
          this.navCtrl.push(LoginPage)
        }
      }
    );
  }
}

ContentLicense: CC BY-SA 4.0


问:
How to get max resolution of MediaCodec before configuring
My app create several instance of MediaCodec which work parallel as video/audio decoders and encoders.

I know that video codec has limiting buffer space and this limit depends on device.

For example on tab Samsung SM-P600 I can create four MediaCodecs with resolution 720p:

1280*720*4=3686400

but not five:

1280*720*5=4608000

Because codec will return error during configuring:

```<code>E/OMX:  setParam  sum(4608000) > max resolution(4177920)
E/ACodec: [OMX.Exynos.AVC.Encoder] failed to set input port definition parameters.
E/ACodec:  configureCodec multi window instance fail  appPid : 17054
E/ACodec: [OMX.Exynos.AVC.Encoder] configureCodec returning error -1021
E/ACodec: signalError(omxError 0x80001001, internalError -1021)
E/MediaCodec: Codec reported err 0xfffffc03, actionCode 0, while in state 3
E/MediaCodec: configure failed with err 0xfffffc03, resetting...
</code>```

How can I get max resolution(4177920) before configuring MediaCodecs to count max available resolutions for all MediaCodecs I need?

答:
Try to use getMaxSupportedInstances () in MediaCodecInfo.CodecCapabilities.
https://developer.android.com/reference/android/media/MediaCodecInfo.CodecCapabilities.html

Or isSizeSupported(int width,
                int height) in MediaCodecInfo.VideoCapabilities.
https://developer.android.com/reference/android/media/MediaCodecInfo.VideoCapabilities.html

Body:
My app create several instance of MediaCodec which work parallel as video/audio decoders and encoders.

I know that video codec has limiting buffer space and this limit depends on device.

For example on tab Samsung SM-P600 I can create four MediaCodecs with resolution 720p:

1280*720*4=3686400

but not five:

1280*720*5=4608000

Because codec will return error during configuring:

E/OMX:  setParam  sum(4608000) > max resolution(4177920)
E/ACodec: [OMX.Exynos.AVC.Encoder] failed to set input port definition parameters.
E/ACodec:  configureCodec multi window instance fail  appPid : 17054
E/ACodec: [OMX.Exynos.AVC.Encoder] configureCodec returning error -1021
E/ACodec: signalError(omxError 0x80001001, internalError -1021)
E/MediaCodec: Codec reported err 0xfffffc03, actionCode 0, while in state 3
E/MediaCodec: configure failed with err 0xfffffc03, resetting...

How can I get max resolution(4177920) before configuring MediaCodecs to count max available resolutions for all MediaCodecs I need?


问:
reporteRs "table of content"
I am using a docx template in reporteRs, using bookmarks to replace text and add tables (empty_template = FALSE). I also have bookmarked the posistion of the table of content. This does not seem to work and the table of content is inserted at the end of the document. Is there a way I can insert the TOC in its proper place?</p>

答: addTOC does not support bookmark argument. Package officer has body_add_toc and cursor_bookmark that should do the job.

Title: reporteRs "table of content"


问:
How do I properly pass arguments to a scriptblock using powershell runspaces?
While using runspaces I would like to pass predictable arguments to my scriptblock from outside. In order to do this without utilizing $args (to avoid making the code less readable), I am storing my argument in a variable called $var and adding the variable to the InitialSessionState of the RunspacePool. To do this I am using the Add method of System.Management.Automation.Runspaces.InitialSessionState.Create().Variables

This works for my purposes, but I also noticed the PowerShell.AddParameter method of [PowerShell]::Create()which would add my parameter to each powershell process as it is created.

And finally there is the PowerShell.AddArgument which I could use like AddParameter, and use a param() block. this would work, however, each argument will be passed in order, and ends up working as well as $args.

So my question is what is the recommended way of passing arguments\parameters\variables into a scriptblock for the purposes I have defined? Is there a performance advantage of one over the other? Can you expand on what purpose you may use one over the other?

答:
You can use cmdlet binding inside of the script block definition.

```<code>$ScriptBlock = {
    Param (
        [int]$NumberofHours,
        [string]$ClientName
    )
    $LogPath = 'd:\Program Files\Exchange\Logging\RPC Client Access\*.LOG'
    $today = (Get-Date).AddHours($NumberofHours)
}
</code>```

Then define call these parameters when you execute the script block.

```<code>Invoke-Command -ComputerName $servers -ScriptBlock $ScriptBlock -ArgumentList -1,$cn -ErrorAction SilentlyContinue
</code>```

Body:
You can use cmdlet binding inside of the script block definition.

$ScriptBlock = {
    Param (
        [int]$NumberofHours,
        [string]$ClientName
    )
    $LogPath = 'd:\Program Files\Exchange\Logging\RPC Client Access\*.LOG'
    $today = (Get-Date).AddHours($NumberofHours)
}

Then define call these parameters when you execute the script block.

Invoke-Command -ComputerName $servers -ScriptBlock $ScriptBlock -ArgumentList -1,$cn -ErrorAction SilentlyContinue


问:
Understanding macros in C
Why is the output from the following code the value 5?</p>

```<code>#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}
</code>```

答:
each #define preprocessing directive will insert in the environment of the preprocessor a variable assigned to a value made of a list of preprocessing directives.

```<code>{A -> -B; B->-C; C->5}
</code>```

is the environment in the moment when A  is evaluated.  Now, making the evaluation process of A, we have

```<code>  A  ->  -B   (the identifier `A` is transformed in the stream of preprocessing tokens `-B`)
 -B  ->  --C
--C  ->  --5
->  5
</code>```

and this one will not be evaluated any more by the Prosser's algorithm, as it has no more identifiers.

So, reducing,

```<code> A->5
</code>```

the stream A is converted in the stream 5 and this one will be converted from preprocessing tokens in C-tokens and sent further to the C compiler.

Title: Understanding macros in C

Body:
Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}

Body:
each #define preprocessing directive will insert in the environment of the preprocessor a variable assigned to a value made of a list of preprocessing directives.

{A -> -B; B->-C; C->5}

is the environment in the moment when A  is evaluated.  Now, making the evaluation process of A, we have

  A  ->  -B   (the identifier `A` is transformed in the stream of preprocessing tokens `-B`)
 -B  ->  --C
--C  ->  --5
->  5

and this one will not be evaluated any more by the Prosser's algorithm, as it has no more identifiers.

So, reducing,

 A->5

the stream A is converted in the stream 5 and this one will be converted from preprocessing tokens in C-tokens and sent further to the C compiler.