问:
Issues with child page's display when using Frames

Problem

This is the layout of my main pane:

```<code><Page
    x:Class="Communities.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Communities"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Loaded="Page_Loaded" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="48" />
            <RowDefinition Height="*" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        ...
        <SplitView Grid.Row="1" Name="hamburgerMenu" OpenPaneLength="200" PaneBackground="#F02A2A2A">
            <SplitView.Pane>
                <ListView ItemsSource="{Binding}" IsItemClickEnabled="True" ItemClick="HamburgerItemClick">
...             </ListView>
            </SplitView.Pane>
            <Frame Name="frame" />
        </SplitView>
        <Grid Grid.RowSpan="3" Name="popupArea" />
    </Grid>
</Page>
</code>```

the frame is where I load all my pages, so that the layout is always consistant.

Now, in most of my child pages I have defined AppBar control and attached it to the BottomAppBar property of that child page:

PostView.xaml

```<code>...
<Page.BottomAppBar>
    <CommandBar>
        <AppBarButton Label="Back" Icon="Back" Click="TryGoBack" />
        <AppBarButton Label="Refresh" Icon="Refresh" Click="TryRefreshComments" />
        <AppBarButton Label="Go to Community" Icon="Go" Click="TryOpenCommunity" />
    </CommandBar>
</Page.BottomAppBar>
...
</code>```

Here's where the trouble starts. It works fine on PC, as the layout is mostly static on desktop. There are no software keyboards required most of the time etc. On mobile it's more problematic: Screenshots

My thoughts

It seems like the frame that is used to display the child page is causing all sorts of problems. When the AppBar is defined in the main page it positions correctly.

I'd like to avoid the keyboard covering the textbox as well as the AppBar but I don't want to get rid of the frame control. I'd also prefer it if the page got "squished" when the keyboard shows up, instead of getting pushed upwards, but I'm not sure how to display the keyboard on the frame level, instead of the entire MainPage, default level.

What would be the best way to solve this situation?

Cheers!

答:
As you know, if we set the Page.BottomAppBar in the root of the Page, there is no issue with Touch keyboard. It seems it is the best way to add the Page.BottomAppBar.

If you want to add the Page.BottomAppBar in the other page in the Frame, you should be able to customize your UI. The UWP provides similar behavior on the appearance of the touch keyboard by handling the Showing and Hiding events exposed by the InputPane object.

We can use the InputPaneVisibilityEventArgs.OccludedRect to get the region of the application's window that the input pane is covering.

For example:

public PostView()
{
    this.InitializeComponent();
    InputPane.GetForCurrentView().Showing += PostView_Showing;
    InputPane.GetForCurrentView().Hiding += PostView_Hiding;
}

private void PostView_Hiding(InputPane sender, InputPaneVisibilityEventArgs args)
{
    MyTextBox.Margin = new Thickness(0, args.OccludedRect.Height, 0, 0);
}

private void PostView_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
{
    MyTextBox.Margin = new Thickness(0, 0, 0, args.OccludedRect.Height);
}
```

Body:
Problem

This is the layout of my main pane:

<Page
    x:Class="Communities.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Communities"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Loaded="Page_Loaded" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="48" />
            <RowDefinition Height="*" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        ...
        <SplitView Grid.Row="1" Name="hamburgerMenu" OpenPaneLength="200" PaneBackground="#F02A2A2A">
            <SplitView.Pane>
                <ListView ItemsSource="{Binding}" IsItemClickEnabled="True" ItemClick="HamburgerItemClick">
...             </ListView>
            </SplitView.Pane>
            <Frame Name="frame" />
        </SplitView>
        <Grid Grid.RowSpan="3" Name="popupArea" />
    </Grid>
</Page>

the frame is where I load all my pages, so that the layout is always consistant.

Now, in most of my child pages I have defined AppBar control and attached it to the BottomAppBar property of that child page:

PostView.xaml

...
<Page.BottomAppBar>
    <CommandBar>
        <AppBarButton Label="Back" Icon="Back" Click="TryGoBack" />
        <AppBarButton Label="Refresh" Icon="Refresh" Click="TryRefreshComments" />
        <AppBarButton Label="Go to Community" Icon="Go" Click="TryOpenCommunity" />
    </CommandBar>
</Page.BottomAppBar>
...

Here's where the trouble starts. It works fine on PC, as the layout is mostly static on desktop. There are no software keyboards required most of the time etc. On mobile it's more problematic: Screenshots

My thoughts

It seems like the frame that is used to display the child page is causing all sorts of problems. When the AppBar is defined in the main page it positions correctly.

I'd like to avoid the keyboard covering the textbox as well as the AppBar but I don't want to get rid of the frame control. I'd also prefer it if the page got "squished" when the keyboard shows up, instead of getting pushed upwards, but I'm not sure how to display the keyboard on the frame level, instead of the entire MainPage, default level.

What would be the best way to solve this situation?

Cheers!


来源: stackexchange

问:
django production server - Django not sending mail in 500 error case to ADMINS
i have deployed django project finally on server and now it is working, but once i go to /admin/, i am getting 500 page but not notification.

this is what i have in settings_prod.py

```<code>from settings import *
DEBUG = TEMPLATE_DEBUG = False
SERVER_EMAIL='my_mail@mail.com'
DEFAULT_FROM_EMAIL='my_mail@mail.com'
ADMINS = (
    (u'me', 'my_mail@mail.com'),
)
MANAGERS = ADMINS
</code>```

what am i doing wrong?

Do i need any SMTP setups for this? i thought, this is server mailing, so server has already everything setup to send error mails.

答:
In the official Django documentation I quickly found the solution for my environment, Apache 2.2.22 (Debian) and Django 1.9:

https://docs.djangoproject.com/en/1.9/topics/email/#console-backend

ContentLicense: CC BY-SA 3.0

Body:
i have deployed django project finally on server and now it is working, but once i go to /admin/, i am getting 500 page but not notification.

this is what i have in settings_prod.py

from settings import *
DEBUG = TEMPLATE_DEBUG = False
SERVER_EMAIL='my_mail@mail.com'
DEFAULT_FROM_EMAIL='my_mail@mail.com'
ADMINS = (
    (u'me', 'my_mail@mail.com'),
)
MANAGERS = ADMINS

what am i doing wrong?

Do i need any SMTP setups for this? i thought, this is server mailing, so server has already everything setup to send error mails.


问:
Minimising interpolation error between two data sets
In the top of the diagrams below we can see some value (y-axis) changing over time (x-axis).

As this happens we are sampling the value at different and unpredictable times, also we are alternating the sampling between two data sets, indicated by red and blue.

When computing the value at any time, we expect that both red and blue data sets will return similar values. However as shown in the three smaller boxes this is not the case. Viewed over time the values from each data set (red and blue) will appear to diverge and then converge about the original value.

Initially I used linear interpolation to obtain a value, next I tried using Catmull-Rom interpolation. The former results in a values come close together and then drift apart between each data point; the latter results in values which remain closer, but where the average error is greater.

Can anyone suggest another strategy or interpolation method which will provide greater smoothing (perhaps by using a greater number of sample points from each data set)?

答:
I'd like to quote Introduction to Catmull-Rom Splines to suggest not using Catmull-Rom for this interpolation task.

One of the features of the Catmull-Rom
  spline is that the specified curve
  will pass through all of the control
  points - this is not true of all types
  of splines.

By definition your red interpolated curve will pass through all red data points and your blue interpolated curve will pass through all blue points. Therefore you won't get a best fit for both data sets.

You might change your boundary conditions and use data points from both data sets for a piecewise approximation as shown in these slides.

ContentLicense: CC BY-SA 2.5


问:
How to scale video to be as large as possible so that the background area is completely covered by the background video
I want to create a background video using HTML5 so it will scale as large as possible so that the background area is completely covered by the background video, something similarly to the background-size: cover;, but to the video.

I want it to be as cross-platform/browser as possible.

EDIT

I meant background-size: cover;

Sorry for that :/

答:
I think what you are looking for is:</p>

```<code>video{
  object-fit:cover;
  width:100%;
  height:100%;
  }
</code>```

Body:
I think what you are looking for is:

video{
  object-fit:cover;
  width:100%;
  height:100%;
  }


问:
Appending/Inserting Data into MongoDB
Hi all of stackoverflow users, I am currently facing an issue regarding mongodb & nodejs. I am trying to insert data into mongodb, and I have all the data ready to be inserted into mongodb. The data I am using to insert is a csv type file.

This is the my project. There is a client and server in my project. The server will take in data from CSV file, listening to client and will send data from the CSV file in the memory space of array over to Client. The client side will connect to server, request data and append data into mongodb.

This following code inside client.js will most probably help me to use its value to append it into mongodb. Can anybody help me with it?

```<code>monitoredItem.on("changed",function(dataValue){
          console.log(" New Data Receive = ",dataValue.value.value);
       });
</code>```

I am unsure of how to append data into mongodb.

This is my client.js

/*global require,console,setTimeout */
var opcua = require("node-opcua");
var async = require("async");
var fs = require("fs");
var csv = require("fast-csv");
var sleep = require("system-sleep");

var client = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://" + require("os").hostname() + ":4334/UA/MyLittleServer";

var the_session, the_subscription;

async.series([

    // step 1 : connect to
    function(callback)  {
        client.connect(endpointUrl,function (err) {
            if(err) {
                console.log(" cannot connect to endpoint :" , endpointUrl );
            } else {
                console.log("connected !");
  console.log("Endpoint URL ", endpointUrl);
            }
            callback(err);
        });
    },

    // step 2 : createSession
    function(callback) {
        client.createSession( function(err,session) {
            if(!err) {
                the_session = session;
            }
            callback(err);
        });
    },

    // step 3 : browse
    function(callback) {
       the_session.browse("RootFolder", function(err,browse_result){
           if(!err) {
               browse_result[0].references.forEach(function(reference) {
                   console.log( reference.browseName.toString());
               });
           }
           callback(err);
       });
    },

    // step 4 : read a variable with readVariableValue
    //function(callback) {
    //   the_session.readVariableValue("ns=2000;s=TEST", function(err,dataValue) {
    //       if (!err) {
    //           console.log(" free mem % = " , dataValue.toString());
    //       }
    //       callback(err);
    //   });
    //},

    // step 4' : read a variable with read
    //function(callback) {
    //   var max_age = 0;
    //   var nodes_to_read = [
    //      { nodeId: "ns=2000;s=TEST", attributeId: opcua.AttributeIds.Value }
    //   ];
    //   the_session.read(nodes_to_read, max_age, function(err,nodes_to_read,dataValues) {
    //       if (!err) {
    //          console.log(" free mem % = " , dataValues[0]);
    //       }
    //      callback(err);
    //   });
    //},

// function(callback){
//  the_session.readVariableValue("ns=74;s=Dou", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },
//
// function(callback){
//  the_session.readVariableValue("ns=74;s=Float", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },
//
// function(callback){
//  the_session.readVariableValue("ns=74;s=String", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },

// function(callback){
//  the_session.readVariableValue("ns=1;s=CSV", function(err, dataValue) {
//   if(!err){
//    console.log(dataValue.toString());
//    sleep(5000);
//   }
//   callback(err);
//   });
//  },

// function(callback){
//  the_session.readVariableValue("ns=1;s=CSV", function(err, dataValue) {
//   if(!err){
//    fs.createReadStream(dataValue.toString())
//    console.log(dataValue.toString());
//    sleep(5000);
//     .pipe(csv())
//     .on('data', function(data){
//     console.log(csv);
//     sleep(5000);
//     })
//     .op('end', function(data){
//     console.log("Read Finish")
//     });
//   }
//   callback(err);
//  });
// },

    // step 5: install a subscription and install a monitored item for 10 seconds
    function(callback) {

       the_subscription=new opcua.ClientSubscription(the_session,{
           requestedPublishingInterval: 1000,
           requestedLifetimeCount: 10,
          requestedMaxKeepAliveCount: 2,
           maxNotificationsPerPublish: 10,
           publishingEnabled: true,
          priority: 10
       });

       the_subscription.on("started",function(){
           console.log("subscription started for 2 seconds - subscriptionId=",the_subscription.subscriptionId);
       }).on("keepalive",function(){
          console.log("keepalive");
       }).on("terminated",function(){
           callback();
       });

       setTimeout(function(){
           the_subscription.terminate();
       },10000000);

       // install monitored item
     var monitoredItem  = the_subscription.monitor({
           nodeId: opcua.resolveNodeId("ns=2000;s=TEST"),
           attributeId: opcua.AttributeIds.Value
       },
       {
           samplingInterval: 100,
           discardOldest: true,
          queueSize: 10
       },
       opcua.read_service.TimestampsToReturn.Both
       );
      console.log("-------------------------------------");

     monitoredItem.on("changed",function(dataValue){
          console.log(" New Data Receive = ",dataValue.value.value);
       });
    },

    // close session
    function(callback) {
        the_session.close(function(err){
            if(err) {
                console.log("session closed failed ?");
            }
            callback();
        });
    }

],
function(err) {
    if (err) {
        console.log(" failure ",err);
    } else {
        console.log("done!");
    }
    client.disconnect(function(){});
}) ;```
</div>
</div>
</p>

<p>This is my <code>server.js</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*global require,setInterval,console */
var opcua = require("node-opcua");
var fs = require("fs");
var csv = require("fast-csv");
var sleep = require("system-sleep");

var currentCount = 0;
var array = ["No New Data"];

 fs.createReadStream('1000data.csv')
 .pipe(csv())
 .on('data', function(data){
  array.push(JSON.stringify(data));
  //sleep(5);
 })
 .on('end', function(data) {
 });

// Let's create an instance of OPCUAServer
var server = new opcua.OPCUAServer({
    port: 4334, // the port of the listening socket of the server
    resourcePath: "UA/MyLittleServer", // this path will be added to the endpoint resource name
     buildInfo : {   //Information of the build, Retrieve the server information for the current instance of the db client
        productName: "MySampleServer1",
        buildNumber: "7658",
        buildDate: new Date(2014,5,2)
    }
});

function post_initialize() {
    console.log("initialized");
    function construct_my_address_space(server) {

        var addressSpace = server.engine.addressSpace;

        // declare a new object
        var device = addressSpace.addObject({
            organizedBy: addressSpace.rootFolder.objects,
            browseName: "MyDevice"
        });

        // add some variables
        // add a variable named MyVariable1 to the newly created folder "MyDevice"
        var variable1 = 1;

        // emulate variable1 changing every 500 ms
        setInterval(function(){  variable1+=1; }, 1000);

        addressSpace.addVariable({
            componentOf: device,
            browseName: "MyVariable1",
            dataType: "Double",
            value: {
                get: function () {
                    return new opcua.Variant({dataType: opcua.DataType.Double, value: variable1 });
                }
            }
        });

// var variableTest = "Test";

//        addressSpace.addVariable({
//            componentOf: device,
//            nodeId: "ns=1;b=1020FFAA",
//            browseName: "MyVariableTest",
//            dataType: "String",
//            value: {
//                get: function () {
//                    return new opcua.Variant({dataType: opcua.DataType.String, value: variableTest });
//                },
//                set: function (variant) {
//                    variable2 = parseFloat(variant.value);
//                    return opcua.StatusCodes.Good;
//                }
//            }
//        });

// server.jsonVar = server.engine.addVariable("MyDevice", {
//  browseName: "JSONObject",
//  dataType: "String",
//  value: {
//   get:function(){
//    return new opcua.Variant({
//     dataType: opcua.DataType.String,
//     value: get_json_string()
//    });
//   }
//  }
// });

// var varTestDou = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=Dou",
//  browseName : "VarD",
//  dataType: "Double",
//  value: new opcua.Variant({dataType: opcua.DataType.Double, value: [10.0,292.31,412.345,185,3453.245]})

// });

// var varTestFloat = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=Float",
//  browseName : "VarF",
//  dataType: "Float",
//  value: new opcua.Variant({dataType: opcua.DataType.Float, value: [10.0,402.23,123,34,643,34]})

// });

// var varTestString = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=String",
//  browseName : "VarT",
//  dataType: "String",
//  value: new opcua.Variant({dataType: opcua.DataType.String, value: "001,41,54,87,23,12/3/2016,8:39am"})

// });

 var csvFile = addressSpace.addVariable({
  componentOf: device,
  nodeId: "ns=1;s=CSV",
  browseName: "csvData",
  dataType: "String",
  value: new opcua.Variant({dataType: opcua.DataType.String, value: array[variable1]})
 });

// fs.createReadStream('1000data.csv')
// .pipe(csv())
// .on('data', function(data){
//  console.log("Data uploaded");
// })
// .on('end', function(date) {
//  console.log("Read Finish");
// });

  //look at this if you want to send data from client to server
        // add a variable named MyVariable2 to the newly created folder "MyDevice"
        var variable2 = 10.0;

        server.engine.addressSpace.addVariable({

            componentOf: device,

            nodeId: "ns=2000;b=1020FFAA", // some opaque NodeId in namespace 4

            browseName: "MyVariable2",

            dataType: "Double",

            value: {
                get: function () {
                    return new opcua.Variant({dataType: opcua.DataType.Double, value: variable2 });
                },
                set: function (variant) {
                    variable2 = parseFloat(variant.value);
                    return opcua.StatusCodes.Good;
                }
            }
        });

        var os = require("os");
        /**
         * returns the percentage of free memory on the running machine
         * @return {double}
         */
        function available_memory() {
   if (currentCount < array.length-1){
    currentCount += 1 ;
    console.log(array[currentCount]);
    return currentCount;
   } else {
    console.log(array[0]);
    return 0;
   }

        }
        server.engine.addressSpace.addVariable({

            componentOf: device,

            nodeId: "ns=2000;s=TEST", // a string nodeID
            browseName: "FreeMemory",
            dataType: "String",
            value: {
                get: function () {return new opcua.Variant({dataType: opcua.DataType.String, value: array[available_memory()] });}
            }
        });
    }
    construct_my_address_space(server);
    server.start(function() {
        console.log("Server is now listening ... ( press CTRL+C to stop)");
        console.log("port ", server.endpoints[0].port);
        var endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
        console.log(" the primary server endpoint url is ", endpointUrl );
    });
}
server.initialize(post_initialize);</code>```

This is my 1000data.csv

Machine Unit,Air Temperature,Water Temperature,Heat Temperature,Room Temperature,Date,Time
1,61,54,87,24,12/3/2016,8:39AM
2,41,57,92,23,29/9/2016,3:51PM
3,39,53,89,25,22/12/2016,5:30PM```

答:
You could add a function which adds the monitoring and gets a callback which is called when the data changes. Therein you add the data to mongoDB.

The function could look like this:

...

function addMonitoring(callback) {
  const monitoredItem = the_subscription.monitor({
      nodeId: opcua.resolveNodeId("ns=2000;s=TEST"),
      attributeId: opcua.AttributeIds.Value
    }, {
      samplingInterval: 100,
      discardOldest: true,
      queueSize: 10
    },
    opcua.read_service.TimestampsToReturn.Both
  );

  monitoredItem.on("changed", dataValue => {
    if (dataValue === undefined || dataValue.value === null) {
      callback(`The subscription for the Opc Servernode failed.`);
    } else {
      callback(null, dataValue.value.value);
    }
  });
}

...```
</div>
</div>
</p>

<p>Now on step 5 you could add something like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import mongooseModel from 'mongooseModel';

...

setTimeout(function() {
  the_subscription.terminate();
}, 10000000);

addMonitoring((error, value) => {
  if (!error) {
    mongooseModel.findByIdAndUpdate(1 /*your id*/ , {
      $push: {
        "data": value
      }
    })
  } else {
    // handle error
  }
});</code>```

The model might look like this:

...

const schema = mongoose.Schema({
  data: {
    type: [Number],
    required: true
  }
  timestamp: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model("TestData", schema);

...```

The schema of the database depends on the data you want to save

Title: Appending/Inserting Data into MongoDB

Body:
Hi all of stackoverflow users, I am currently facing an issue regarding mongodb & nodejs. I am trying to insert data into mongodb, and I have all the data ready to be inserted into mongodb. The data I am using to insert is a csv type file.

This is the my project. There is a client and server in my project. The server will take in data from CSV file, listening to client and will send data from the CSV file in the memory space of array over to Client. The client side will connect to server, request data and append data into mongodb.

This following code inside client.js will most probably help me to use its value to append it into mongodb. Can anybody help me with it?

monitoredItem.on("changed",function(dataValue){
          console.log(" New Data Receive = ",dataValue.value.value);
       });

I am unsure of how to append data into mongodb.

This is my client.js

/*global require,console,setTimeout */
var opcua = require("node-opcua");
var async = require("async");
var fs = require("fs");
var csv = require("fast-csv");
var sleep = require("system-sleep");

var client = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://" + require("os").hostname() + ":4334/UA/MyLittleServer";

var the_session, the_subscription;

async.series([

    // step 1 : connect to
    function(callback)  {
        client.connect(endpointUrl,function (err) {
            if(err) {
                console.log(" cannot connect to endpoint :" , endpointUrl );
            } else {
                console.log("connected !");
  console.log("Endpoint URL ", endpointUrl);
            }
            callback(err);
        });
    },

    // step 2 : createSession
    function(callback) {
        client.createSession( function(err,session) {
            if(!err) {
                the_session = session;
            }
            callback(err);
        });
    },

    // step 3 : browse
    function(callback) {
       the_session.browse("RootFolder", function(err,browse_result){
           if(!err) {
               browse_result[0].references.forEach(function(reference) {
                   console.log( reference.browseName.toString());
               });
           }
           callback(err);
       });
    },

    // step 4 : read a variable with readVariableValue
    //function(callback) {
    //   the_session.readVariableValue("ns=2000;s=TEST", function(err,dataValue) {
    //       if (!err) {
    //           console.log(" free mem % = " , dataValue.toString());
    //       }
    //       callback(err);
    //   });
    //},

    // step 4' : read a variable with read
    //function(callback) {
    //   var max_age = 0;
    //   var nodes_to_read = [
    //      { nodeId: "ns=2000;s=TEST", attributeId: opcua.AttributeIds.Value }
    //   ];
    //   the_session.read(nodes_to_read, max_age, function(err,nodes_to_read,dataValues) {
    //       if (!err) {
    //          console.log(" free mem % = " , dataValues[0]);
    //       }
    //      callback(err);
    //   });
    //},

// function(callback){
//  the_session.readVariableValue("ns=74;s=Dou", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },
//
// function(callback){
//  the_session.readVariableValue("ns=74;s=Float", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },
//
// function(callback){
//  the_session.readVariableValue("ns=74;s=String", function(err,dataValue) {
//   if(!err){
//    console.log("Test Success", dataValue.toString());
//   }
//   callback(err);
//   });
//  },

// function(callback){
//  the_session.readVariableValue("ns=1;s=CSV", function(err, dataValue) {
//   if(!err){
//    console.log(dataValue.toString());
//    sleep(5000);
//   }
//   callback(err);
//   });
//  },

// function(callback){
//  the_session.readVariableValue("ns=1;s=CSV", function(err, dataValue) {
//   if(!err){
//    fs.createReadStream(dataValue.toString())
//    console.log(dataValue.toString());
//    sleep(5000);
//     .pipe(csv())
//     .on('data', function(data){
//     console.log(csv);
//     sleep(5000);
//     })
//     .op('end', function(data){
//     console.log("Read Finish")
//     });
//   }
//   callback(err);
//  });
// },

    // step 5: install a subscription and install a monitored item for 10 seconds
    function(callback) {

       the_subscription=new opcua.ClientSubscription(the_session,{
           requestedPublishingInterval: 1000,
           requestedLifetimeCount: 10,
          requestedMaxKeepAliveCount: 2,
           maxNotificationsPerPublish: 10,
           publishingEnabled: true,
          priority: 10
       });

       the_subscription.on("started",function(){
           console.log("subscription started for 2 seconds - subscriptionId=",the_subscription.subscriptionId);
       }).on("keepalive",function(){
          console.log("keepalive");
       }).on("terminated",function(){
           callback();
       });

       setTimeout(function(){
           the_subscription.terminate();
       },10000000);

       // install monitored item
     var monitoredItem  = the_subscription.monitor({
           nodeId: opcua.resolveNodeId("ns=2000;s=TEST"),
           attributeId: opcua.AttributeIds.Value
       },
       {
           samplingInterval: 100,
           discardOldest: true,
          queueSize: 10
       },
       opcua.read_service.TimestampsToReturn.Both
       );
      console.log("-------------------------------------");

     monitoredItem.on("changed",function(dataValue){
          console.log(" New Data Receive = ",dataValue.value.value);
       });
    },

    // close session
    function(callback) {
        the_session.close(function(err){
            if(err) {
                console.log("session closed failed ?");
            }
            callback();
        });
    }

],
function(err) {
    if (err) {
        console.log(" failure ",err);
    } else {
        console.log("done!");
    }
    client.disconnect(function(){});
}) ;

This is my server.js

/*global require,setInterval,console */
var opcua = require("node-opcua");
var fs = require("fs");
var csv = require("fast-csv");
var sleep = require("system-sleep");

var currentCount = 0;
var array = ["No New Data"];

 fs.createReadStream('1000data.csv')
 .pipe(csv())
 .on('data', function(data){
  array.push(JSON.stringify(data));
  //sleep(5);
 })
 .on('end', function(data) {
 });

// Let's create an instance of OPCUAServer
var server = new opcua.OPCUAServer({
    port: 4334, // the port of the listening socket of the server
    resourcePath: "UA/MyLittleServer", // this path will be added to the endpoint resource name
     buildInfo : {   //Information of the build, Retrieve the server information for the current instance of the db client
        productName: "MySampleServer1",
        buildNumber: "7658",
        buildDate: new Date(2014,5,2)
    }
});

function post_initialize() {
    console.log("initialized");
    function construct_my_address_space(server) {

        var addressSpace = server.engine.addressSpace;

        // declare a new object
        var device = addressSpace.addObject({
            organizedBy: addressSpace.rootFolder.objects,
            browseName: "MyDevice"
        });

        // add some variables
        // add a variable named MyVariable1 to the newly created folder "MyDevice"
        var variable1 = 1;

        // emulate variable1 changing every 500 ms
        setInterval(function(){  variable1+=1; }, 1000);

        addressSpace.addVariable({
            componentOf: device,
            browseName: "MyVariable1",
            dataType: "Double",
            value: {
                get: function () {
                    return new opcua.Variant({dataType: opcua.DataType.Double, value: variable1 });
                }
            }
        });

// var variableTest = "Test";

//        addressSpace.addVariable({
//            componentOf: device,
//            nodeId: "ns=1;b=1020FFAA",
//            browseName: "MyVariableTest",
//            dataType: "String",
//            value: {
//                get: function () {
//                    return new opcua.Variant({dataType: opcua.DataType.String, value: variableTest });
//                },
//                set: function (variant) {
//                    variable2 = parseFloat(variant.value);
//                    return opcua.StatusCodes.Good;
//                }
//            }
//        });

// server.jsonVar = server.engine.addVariable("MyDevice", {
//  browseName: "JSONObject",
//  dataType: "String",
//  value: {
//   get:function(){
//    return new opcua.Variant({
//     dataType: opcua.DataType.String,
//     value: get_json_string()
//    });
//   }
//  }
// });

// var varTestDou = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=Dou",
//  browseName : "VarD",
//  dataType: "Double",
//  value: new opcua.Variant({dataType: opcua.DataType.Double, value: [10.0,292.31,412.345,185,3453.245]})

// });

// var varTestFloat = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=Float",
//  browseName : "VarF",
//  dataType: "Float",
//  value: new opcua.Variant({dataType: opcua.DataType.Float, value: [10.0,402.23,123,34,643,34]})

// });

// var varTestString = addressSpace.addVariable({
//  componentOf: device,
//  nodeId: "ns=74;s=String",
//  browseName : "VarT",
//  dataType: "String",
//  value: new opcua.Variant({dataType: opcua.DataType.String, value: "001,41,54,87,23,12/3/2016,8:39am"})

// });

 var csvFile = addressSpace.addVariable({
  componentOf: device,
  nodeId: "ns=1;s=CSV",
  browseName: "csvData",
  dataType: "String",
  value: new opcua.Variant({dataType: opcua.DataType.String, value: array[variable1]})
 });

// fs.createReadStream('1000data.csv')
// .pipe(csv())
// .on('data', function(data){
//  console.log("Data uploaded");
// })
// .on('end', function(date) {
//  console.log("Read Finish");
// });

  //look at this if you want to send data from client to server
        // add a variable named MyVariable2 to the newly created folder "MyDevice"
        var variable2 = 10.0;

        server.engine.addressSpace.addVariable({

            componentOf: device,

            nodeId: "ns=2000;b=1020FFAA", // some opaque NodeId in namespace 4

            browseName: "MyVariable2",

            dataType: "Double",

            value: {
                get: function () {
                    return new opcua.Variant({dataType: opcua.DataType.Double, value: variable2 });
                },
                set: function (variant) {
                    variable2 = parseFloat(variant.value);
                    return opcua.StatusCodes.Good;
                }
            }
        });

        var os = require("os");
        /**
         * returns the percentage of free memory on the running machine
         * @return {double}
         */
        function available_memory() {
   if (currentCount < array.length-1){
    currentCount += 1 ;
    console.log(array[currentCount]);
    return currentCount;
   } else {
    console.log(array[0]);
    return 0;
   }

        }
        server.engine.addressSpace.addVariable({

            componentOf: device,

            nodeId: "ns=2000;s=TEST", // a string nodeID
            browseName: "FreeMemory",
            dataType: "String",
            value: {
                get: function () {return new opcua.Variant({dataType: opcua.DataType.String, value: array[available_memory()] });}
            }
        });
    }
    construct_my_address_space(server);
    server.start(function() {
        console.log("Server is now listening ... ( press CTRL+C to stop)");
        console.log("port ", server.endpoints[0].port);
        var endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
        console.log(" the primary server endpoint url is ", endpointUrl );
    });
}
server.initialize(post_initialize);

This is my 1000data.csv

Machine Unit,Air Temperature,Water Temperature,Heat Temperature,Room Temperature,Date,Time
1,61,54,87,24,12/3/2016,8:39AM
2,41,57,92,23,29/9/2016,3:51PM
3,39,53,89,25,22/12/2016,5:30PM

Body:
You could add a function which adds the monitoring and gets a callback which is called when the data changes. Therein you add the data to mongoDB.

The function could look like this:

...

function addMonitoring(callback) {
  const monitoredItem = the_subscription.monitor({
      nodeId: opcua.resolveNodeId("ns=2000;s=TEST"),
      attributeId: opcua.AttributeIds.Value
    }, {
      samplingInterval: 100,
      discardOldest: true,
      queueSize: 10
    },
    opcua.read_service.TimestampsToReturn.Both
  );

  monitoredItem.on("changed", dataValue => {
    if (dataValue === undefined || dataValue.value === null) {
      callback(`The subscription for the Opc Servernode failed.`);
    } else {
      callback(null, dataValue.value.value);
    }
  });
}

...

Now on step 5 you could add something like:

import mongooseModel from 'mongooseModel';

...

setTimeout(function() {
  the_subscription.terminate();
}, 10000000);

addMonitoring((error, value) => {
  if (!error) {
    mongooseModel.findByIdAndUpdate(1 /*your id*/ , {
      $push: {
        "data": value
      }
    })
  } else {
    // handle error
  }
});

The model might look like this:

...

const schema = mongoose.Schema({
  data: {
    type: [Number],
    required: true
  }
  timestamp: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model("TestData", schema);

...

The schema of the database depends on the data you want to save


问:
Issue when trying to iterate through textfile lines
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

```<code>Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
</code>```

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

```<code>with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])
</code>```

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

答:
readlines() advances the file pointer to the end of the file, so any further invocations will not yield anything unless the file has been enlarged in the meantime. Instead, read all the lines into memory (using the iterator protocol), and then index. In addition, your parsing is incorrect.

```<code># Make sure to correctly escape backslashes!
old_fn = 'G:\\Mayeul\\Distribution images\\Features_importance\\LogDecisionTree.txt'
new_fn = 'G:\\Mayeul\\Distribution images\\Features_importance\\LogDecisionTree2.txt'

with open(old_fn) as oldfile:
     old_lines = list(oldfile)

with open(new_fn, 'w') as newfile:
     print(len(old_lines))
     for line in range(1, len(old_lines)):
         print(line)
         if line % 3 == 0:
             f = old_lines[line-2]
             accuracy = f.split(' ')[2]
             if float(accuracy) > 0.90:
                 newfile.write(old_lines[line-2])
                 newfile.write(old_lines[line-1])
                 newfile.write(old_lines[line])
</code>```

Body:
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

Body:
readlines() advances the file pointer to the end of the file, so any further invocations will not yield anything unless the file has been enlarged in the meantime. Instead, read all the lines into memory (using the iterator protocol), and then index. In addition, your parsing is incorrect.

# Make sure to correctly escape backslashes!
old_fn = 'G:\\Mayeul\\Distribution images\\Features_importance\\LogDecisionTree.txt'
new_fn = 'G:\\Mayeul\\Distribution images\\Features_importance\\LogDecisionTree2.txt'

with open(old_fn) as oldfile:
     old_lines = list(oldfile)

with open(new_fn, 'w') as newfile:
     print(len(old_lines))
     for line in range(1, len(old_lines)):
         print(line)
         if line % 3 == 0:
             f = old_lines[line-2]
             accuracy = f.split(' ')[2]
             if float(accuracy) > 0.90:
                 newfile.write(old_lines[line-2])
                 newfile.write(old_lines[line-1])
                 newfile.write(old_lines[line])


问:
Integer to Byte() array troubles
I'm trying to transmit data through the stream in Visual Basic .NET
I try the next:

Client:

```<code>tcpclnt = New TcpClient()
tcpclnt.Connect("127.0.0.115", 40000)
clientstream = tcpclnt.GetStream()

 Dim I As Integer
 Dim msg() As Byte
 For I = 1 To 1000
     msg = BitConverter.GetBytes(I) ' HERE IS THE PROBLEM
     clientstream.Write(msg, 0, msg.Length)
 Next
</code>```

Server:

```<code>Public Shared bytes(1024) As Byte
Public Shared data As String = Nothing

Server = New TcpListener(IPAddress.Any, 40000)
Server.Start()
' ... some server routine

Dim serverstream As NetworkStream = myClient.GetStream()
Dim i As Int32
i = serverstream.Read(bytes, 0, bytes.Length)
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Invoke(Sub() TextBox3.Text = "Received: " + data)
</code>```

The problem is: to get data from stream it have to be Byte() type. So to put data to stream it also have to be in Byte(). But I want to transmit integers (1000 for example). It converts in 4 bytes and when server reads it he takes four different symbols, not the number 1000!

Instead of 1000 I got two spaces.

答:
Thank you for the perfect answer, @xanatos.
I find one more way and use it, so I want to post it too.

I used this way:

```<code> For I = 1 To 1000
        msg = Encoding.UTF8.GetBytes(Convert.ToString(I))
        clientstream.Write(msg, 0, msg.Length)
 Next
</code>```

I suppose your solution is better in the way of controlling packages and I will use it for transmitting numeric data, but for my current case I used my solution.

Title: Integer to Byte() array troubles

Body:
I'm trying to transmit data through the stream in Visual Basic .NET
I try the next:

Client:

tcpclnt = New TcpClient()
tcpclnt.Connect("127.0.0.115", 40000)
clientstream = tcpclnt.GetStream()

 Dim I As Integer
 Dim msg() As Byte
 For I = 1 To 1000
     msg = BitConverter.GetBytes(I) ' HERE IS THE PROBLEM
     clientstream.Write(msg, 0, msg.Length)
 Next

Server:

Public Shared bytes(1024) As Byte
Public Shared data As String = Nothing

Server = New TcpListener(IPAddress.Any, 40000)
Server.Start()
' ... some server routine

Dim serverstream As NetworkStream = myClient.GetStream()
Dim i As Int32
i = serverstream.Read(bytes, 0, bytes.Length)
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Invoke(Sub() TextBox3.Text = "Received: " + data)

The problem is: to get data from stream it have to be Byte() type. So to put data to stream it also have to be in Byte(). But I want to transmit integers (1000 for example). It converts in 4 bytes and when server reads it he takes four different symbols, not the number 1000!

Instead of 1000 I got two spaces.

Body:
Thank you for the perfect answer, @xanatos.
I find one more way and use it, so I want to post it too.

I used this way:

 For I = 1 To 1000
        msg = Encoding.UTF8.GetBytes(Convert.ToString(I))
        clientstream.Write(msg, 0, msg.Length)
 Next

I suppose your solution is better in the way of controlling packages and I will use it for transmitting numeric data, but for my current case I used my solution.


问:
UICollection is very slow in showing Image with Swift 3
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

```<code>  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale
</code>```

and

```<code>extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}
</code>```

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?

答:
I got the same console error when I am getting the data from the API call and reload the UITableView (as per my requirement). My issue is solved by using

```<code>DispatchQueue.global(qos: .background).async { // load data in back ground mode so that main thread can be safed.
let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
    DispatchQueue.main.async(execute: {
                                cell.movieTitle.text = list.name
                cell.imageView?.image = image
                            })
self.images_cache[imageName!] = image
        }
</code>```

Screen Shot of Error I got on my Console Before

Body:
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale

and

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?

Body:
I got the same console error when I am getting the data from the API call and reload the UITableView (as per my requirement). My issue is solved by using

DispatchQueue.global(qos: .background).async { // load data in back ground mode so that main thread can be safed.
let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
    DispatchQueue.main.async(execute: {
                                cell.movieTitle.text = list.name
                cell.imageView?.image = image
                            })
self.images_cache[imageName!] = image
        }

Screen Shot of Error I got on my Console Before


问:
PhpStorm - Mark multiple lines
Is it possible to mark multiple lines in PhpStorm?

e.g.

```<code>LineA
LineB
LineC
</code>```

lets say I try to mark LineA and LineC to copy paste them to another place, is this possible?

```<code>LineA
LineC
</code>```

答:
Sure .. but it requires a bit of "precision pointing" and using mouse (not sure if it's easily doable with keyboard only).

Basically -- the idea is to use Multiple Carets functionality:

Place caret at the beginning of first line

Now Alt + Click on the beginning of the other line to create new caret there (shortcut depends on OS -- on Linux it might be different shortcut/combo as that shortcut may used by Desktop/Window manager for own stuff)

Now you have 2 carets on the beginning of Line A and Line C

Just use Shift + End to select text to the end of line -- it will be done in both lines.

Now just Copy + Paste it elsewhere (or whatever you wanted to do).

Use Esc to get rid of carets.

Title: PhpStorm - Mark multiple lines

Body:
Is it possible to mark multiple lines in PhpStorm?

e.g.

LineA
LineB
LineC

lets say I try to mark LineA and LineC to copy paste them to another place, is this possible?

LineA
LineC


问:
How to get visitors location using Angular 2 or TypeScript
I started use get by ServerVariables["HTTP_CF_IPCOUNTRY"] by backend server, but it is too slow, I need an Angular or TypeScript solution for this.

答:
If you wanted to take location from front-end side , we can get the location simply via javascript

```<code>var x = document.getElementById("demo");
function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude;
    }
</code>```

This will ask user from browser to share the location , and its done.

More Details.

In Angular 2 Component implements OnInit , put that code inside ngOnInit

```<code>import { Component, OnInit } from '@angular/core';
export class LocationComponent implements OnInit {
    ngOnInit(){
        if(window.navigator.geolocation){
            window.navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
            };
        }
    }
}
</code>```

Body:
If you wanted to take location from front-end side , we can get the location simply via javascript

var x = document.getElementById("demo");
function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude;
    }

This will ask user from browser to share the location , and its done.

More Details.

In Angular 2 Component implements OnInit , put that code inside ngOnInit

import { Component, OnInit } from '@angular/core';
export class LocationComponent implements OnInit {
    ngOnInit(){
        if(window.navigator.geolocation){
            window.navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
            };
        }
    }
}


问:
Amazon Titan: data is unevenly distributed on DynamoDB partitions
We have 314m records to be added to Titan. Working with Amazon Titan with DynamoDB tables as backend, we realized that around 10% of our data is located on one partition out of 125.

This uneven distribution causes issues both on write and read operations. What could be the reason for this uneven distribution? We are using single-item model, would that be the reason for the issue?

答: Uneven distribution of data is caused by clustering around the same partition keys in DynamoDB. As partition keys correspond to out-vertex ids in Titan, if you have lots of properties on one vertex or if you have lots of edges coming out of a vertex (super nodes) you should try to load your graph with vertex partitioning enabled on that vertex label. When you create the vertex label in TitanManagement, all you need to do is call .partition() before committing the TitanManagement operation. If your DynamoDB table has 125 partitions you will want around 256 max-partitions to guarantee that the data is spread around your physical partitions evenly.</p>


问:
Wp7 Listbox Scrolling issue in PivotItem - Can't stay on very last item, fixed height does not assistance
I have a simple listbox with more items than fit on the screen. If you scroll to the last item it is shown but then drops back off the screen - I can't leave it in view. After an hour of Googling it seems to be a known issue in early versions of the Listbox but it still seems to be the case in the latest tools. There also seems to be a problem with fixed heights and virtualization, but setting the height at item level or listbox level makes no difference. I see the Listbox in the WindowsPhoneDataBound app template works fine with scrolling and no heights.

I would also like a solution without fixed heights so that it does not require a new state for Landscape orientation.

Any suggestions please?

My listbox is in a usercontrol that is in a PivotItem:

```<code>        <controls:PivotItem x:Name="pivotItemSetup" Header="setup">
            <local:listBoxBlindsControl Margin="0,0,-12,0"/>
        </controls:PivotItem>
</code>```

and the user control:

```<code> <Grid x:Name="LayoutRoot" Background="Transparent">
        <ListBox x:Name="listBoxBlinds" ItemsSource="{Binding BlindSet.Blinds}" SelectionChanged="MainListBox_SelectionChanged" Height="500">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Height="80" Margin="0,0,0,17" Width="103">
                        <StackPanel Orientation="Horizontal"  Visibility="{Binding IsBreak, ConverterParameter=true, Converter={StaticResource boolToVisibility}}" VerticalAlignment="Top" d:LayoutOverrides="Width">
                            <TextBlock Text="{Binding LevelNumber, ConverterParameter='level \{0\} - ', Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding SmallBlind, ConverterParameter=\{0\}/, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding BigBlind}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                        </StackPanel>
                        <TextBlock x:Name="txtbreak" Text="break" TextWrapping="NoWrap" Margin="0,0,0,23" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width, Height" Visibility="{Binding IsBreak, ConverterParameter=false, Converter={StaticResource boolToVisibility}}" Foreground="{StaticResource PhoneAccentBrush}" />
                        <StackPanel Orientation="Horizontal" Margin="0,0,0,23" VerticalAlignment="Bottom" d:LayoutOverrides="Width">
                            <TextBlock Text="{Binding MinutesPerBlind, ConverterParameter=\{0\} minutes, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextSubtleStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding Ante, ConverterParameter=\, \{0\} ante, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextSubtleStyle}" d:LayoutOverrides="Width" Visibility="{Binding Ante, ConverterParameter=0, Converter={StaticResource valueToVisibility}}"/>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</code>```

Some more info: I copied and pasted the exact XAML from the WindowsPhoneDataBoundApp (which works) into my usercontrol so that it now looks like this:

```<code><Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="listBoxBlinds" Margin="0,0,-12,0" ItemsSource="{Binding BlindSet.Blinds}" SelectionChanged="MainListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,17" Width="432">
                    <TextBlock Text="{Binding LevelNumber}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                    <TextBlock Text="{Binding SmallBlind}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
</code>```

and it does not work... so is it something to do with the PivotItem?
Update: I took this code out of the PivotItem and it works fine.. so any ideas how to get it working in a pivotitem?

答:
Put a Grid around your list box in the PivotItem.  This will force the listbox into a scrolling mode.</p>

```<code><controls:PivotItem x:Name="pivotItemSetup" Header="setup">
  <Grid>
    <local:listBoxBlindsControl Margin="0,0,-12,0"/>
  </Grid>
</controls:PivotItem>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple listbox with more items than fit on the screen. If you scroll to the last item it is shown but then drops back off the screen - I can't leave it in view. After an hour of Googling it seems to be a known issue in early versions of the Listbox but it still seems to be the case in the latest tools. There also seems to be a problem with fixed heights and virtualization, but setting the height at item level or listbox level makes no difference. I see the Listbox in the WindowsPhoneDataBound app template works fine with scrolling and no heights.

I would also like a solution without fixed heights so that it does not require a new state for Landscape orientation.

Any suggestions please?

My listbox is in a usercontrol that is in a PivotItem:

        <controls:PivotItem x:Name="pivotItemSetup" Header="setup">
            <local:listBoxBlindsControl Margin="0,0,-12,0"/>
        </controls:PivotItem>

and the user control:

 <Grid x:Name="LayoutRoot" Background="Transparent">
        <ListBox x:Name="listBoxBlinds" ItemsSource="{Binding BlindSet.Blinds}" SelectionChanged="MainListBox_SelectionChanged" Height="500">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Height="80" Margin="0,0,0,17" Width="103">
                        <StackPanel Orientation="Horizontal"  Visibility="{Binding IsBreak, ConverterParameter=true, Converter={StaticResource boolToVisibility}}" VerticalAlignment="Top" d:LayoutOverrides="Width">
                            <TextBlock Text="{Binding LevelNumber, ConverterParameter='level \{0\} - ', Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding SmallBlind, ConverterParameter=\{0\}/, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding BigBlind}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width"/>
                        </StackPanel>
                        <TextBlock x:Name="txtbreak" Text="break" TextWrapping="NoWrap" Margin="0,0,0,23" Style="{StaticResource PhoneTextExtraLargeStyle}" d:LayoutOverrides="Width, Height" Visibility="{Binding IsBreak, ConverterParameter=false, Converter={StaticResource boolToVisibility}}" Foreground="{StaticResource PhoneAccentBrush}" />
                        <StackPanel Orientation="Horizontal" Margin="0,0,0,23" VerticalAlignment="Bottom" d:LayoutOverrides="Width">
                            <TextBlock Text="{Binding MinutesPerBlind, ConverterParameter=\{0\} minutes, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextSubtleStyle}" d:LayoutOverrides="Width"/>
                            <TextBlock Text="{Binding Ante, ConverterParameter=\, \{0\} ante, Converter={StaticResource stringTextConverter}}" TextWrapping="NoWrap" Margin="0" Style="{StaticResource PhoneTextSubtleStyle}" d:LayoutOverrides="Width" Visibility="{Binding Ante, ConverterParameter=0, Converter={StaticResource valueToVisibility}}"/>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

Some more info: I copied and pasted the exact XAML from the WindowsPhoneDataBoundApp (which works) into my usercontrol so that it now looks like this:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="listBoxBlinds" Margin="0,0,-12,0" ItemsSource="{Binding BlindSet.Blinds}" SelectionChanged="MainListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,17" Width="432">
                    <TextBlock Text="{Binding LevelNumber}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                    <TextBlock Text="{Binding SmallBlind}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

and it does not work... so is it something to do with the PivotItem?
Update: I took this code out of the PivotItem and it works fine.. so any ideas how to get it working in a pivotitem?

Body:
Put a Grid around your list box in the PivotItem.  This will force the listbox into a scrolling mode.

<controls:PivotItem x:Name="pivotItemSetup" Header="setup">
  <Grid>
    <local:listBoxBlindsControl Margin="0,0,-12,0"/>
  </Grid>
</controls:PivotItem>


问:
How to build .sqlproj projects on a build server?
I have many .sqlproj projects that need to be built on our build server. I don't want to install all of Visual Studio on the build server just so I can install SSDT to build these. How can I build .sqlproj projects without a full VS install?

Here's the raw error I get on the build server when trying to build without SSDT intstalled:

```<code>C:\MyProject\MyProj.sqlproj (4): The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
</code>```

答:
The Microsoft SQL Server Data Tools team has released a NuGet package named Microsoft.Data.Tools.Msbuild, which helps to build SQL Projects on build servers.

see : https://blogs.msdn.microsoft.com/ssdt/2016/08/22/releasing-ssdt-with-visual-studio-15-preview-4-and-introducing-ssdt-msbuild-nuget-package/

NuGet package : https://www.nuget.org/packages/Microsoft.Data.Tools.Msbuild/

Body:
I have many .sqlproj projects that need to be built on our build server. I don't want to install all of Visual Studio on the build server just so I can install SSDT to build these. How can I build .sqlproj projects without a full VS install?

Here's the raw error I get on the build server when trying to build without SSDT intstalled:

C:\MyProject\MyProj.sqlproj (4): The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.


问:
when I running a command (composer) in the command prompt, it doesn't show me the proper green text command instead of showing me some garbage value
here is an example of the result:

[32mComposer [39m version [33m1.1.3[39m 2016-06-26 15:42:08

      [33mUsage:[39m

        command[options][arguments]

      [33mOptions:[39m
      [32m-h, --help[39m  Display this help message

I am in the process of learning to install php Laravel and I get stuck here.
p/s: I've learn php for awhile and now I am trying to create a project in Laravel.Please help.

答:
You can also add --no-ansi to the composer.bat file at

C:\ProgramData\ComposerSetup\bin\composer.bat

change the line to

php "%~dp0composer.phar" %* --no-ansi


问:
How to use connection from one class into another
```<code>class Database {

    public $isConn;
    private static $_instance = null;
    private $datab;

    // connect to db
    public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
        $this->isConn = TRUE;
        try {
            $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
            $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new Database();
        }
        return self::$_instance;
    }
</code>```

Now in every class that needs database connection

```<code>class test {

    private $_db = null;

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
        }
</code>```

Now it gives me an error saying cannot use $this, then how i can use it using self:: ??
    }

Now how can i use it in static function and non static function together

答:
Get database instance when it is needed.</p>

```<code>class test {

    public function test(){
       return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }
}
</code>```

Body:
class Database {

    public $isConn;
    private static $_instance = null;
    private $datab;

    // connect to db
    public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
        $this->isConn = TRUE;
        try {
            $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
            $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new Database();
        }
        return self::$_instance;
    }

Now in every class that needs database connection

class test {

    private $_db = null;

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
        }

Now it gives me an error saying cannot use $this, then how i can use it using self:: ??
    }

Now how can i use it in static function and non static function together

Body:
Get database instance when it is needed.

class test {

    public function test(){
       return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }
}


问:
Debug HTML/JS in UIWebView on Windows
I have a HTML page with JS code which works perfectly on Android and Desktop browsers, but fails on iOS. Is there any way to debug this page in iOS UIWebView on Windows with Chrome (like remote devices with Android)?</p>

答: I made some search about this, and i think it may work if you use Weinre, give it a try. </p>

Title: Debug HTML/JS in UIWebView on Windows


问:
Save object Android not working

onRestoreInstanceState(Bundle savedInstanceState)

is not geting called, I am pasting my code below. Actually I want to redraw all the points that are saved when my activity went in background.

```<code>    package com.geniteam.mytest;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;

public class Tutorial2D extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new Panel(this));
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     Panel panel = new Panel(this);
     outState.putSerializable("test", panel._graphics);

    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
     super.onRestoreInstanceState(savedInstanceState);
     Panel panel = new Panel(this);
     panel.set_graphics((ArrayList<GraphicObject>) savedInstanceState.getSerializable("test"));
    }

    class Panel extends SurfaceView implements SurfaceHolder.Callback {
        private TutorialThread _thread;
        private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();

        public ArrayList<GraphicObject> get_graphics() {
   return _graphics;
  }

  public void set_graphics(ArrayList<GraphicObject> graphics) {
   _graphics = graphics;
  }

  public Panel(Context context) {
            super(context);
            getHolder().addCallback(this);
            _thread = new TutorialThread(getHolder(), this);
            setFocusable(true);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            synchronized (_thread.getSurfaceHolder()) {
               // if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
                    graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
                    graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
                    _graphics.add(graphic);
                //}
                return true;
            }
        }

        @Override
        public void onDraw(Canvas canvas) {
            canvas.drawColor(Color.BLACK);
            Bitmap bitmap;
            GraphicObject.Coordinates coords;
            for (GraphicObject graphic : _graphics) {
                bitmap = graphic.getGraphic();
                coords = graphic.getCoordinates();
                canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // TODO Auto-generated method stub
        }

        public void surfaceCreated(SurfaceHolder holder) {
            try{
         _thread.setRunning(true);
            _thread.start();
            }catch(Exception ex){
             _thread = new TutorialThread(getHolder(), this);
             _thread.start();
            }

        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // simply copied from sample application LunarLander:
            // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
        }
    }

    class TutorialThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private Panel _panel;
        private boolean _run = false;

        public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }

        public void setRunning(boolean run) {
            _run = run;
        }

        public SurfaceHolder getSurfaceHolder() {
            return _surfaceHolder;
        }

        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }

    class GraphicObject {
        /**
         * Contains the coordinates of the graphic.
         */
        public class Coordinates {
            private int _x = 100;
            private int _y = 0;

            public int getX() {
                return _x + _bitmap.getWidth() / 2;
            }

            public void setX(int value) {
                _x = value - _bitmap.getWidth() / 2;
            }

            public int getY() {
                return _y + _bitmap.getHeight() / 2;
            }

            public void setY(int value) {
                _y = value - _bitmap.getHeight() / 2;
            }

            public String toString() {
                return "Coordinates: (" + _x + "/" + _y + ")";
            }
        }

        private Bitmap _bitmap;
        private Coordinates _coordinates;

        public GraphicObject(Bitmap bitmap) {
            _bitmap = bitmap;
            _coordinates = new Coordinates();
        }

        public Bitmap getGraphic() {
            return _bitmap;
        }

        public Coordinates getCoordinates() {
            return _coordinates;
        }
    }
}
</code>```

答: onRestoreInstanceState only gets called if the app is destroyed and re-created.  Putting the app in the background then bringing it up again will call onResume, but not onRestoreInstanceState.</p>

Title: Save object Android not working

Body:
onRestoreInstanceState(Bundle savedInstanceState)

is not geting called, I am pasting my code below. Actually I want to redraw all the points that are saved when my activity went in background.

    package com.geniteam.mytest;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;

public class Tutorial2D extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new Panel(this));
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     Panel panel = new Panel(this);
     outState.putSerializable("test", panel._graphics);

    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
     super.onRestoreInstanceState(savedInstanceState);
     Panel panel = new Panel(this);
     panel.set_graphics((ArrayList<GraphicObject>) savedInstanceState.getSerializable("test"));
    }

    class Panel extends SurfaceView implements SurfaceHolder.Callback {
        private TutorialThread _thread;
        private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();

        public ArrayList<GraphicObject> get_graphics() {
   return _graphics;
  }

  public void set_graphics(ArrayList<GraphicObject> graphics) {
   _graphics = graphics;
  }

  public Panel(Context context) {
            super(context);
            getHolder().addCallback(this);
            _thread = new TutorialThread(getHolder(), this);
            setFocusable(true);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            synchronized (_thread.getSurfaceHolder()) {
               // if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
                    graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
                    graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
                    _graphics.add(graphic);
                //}
                return true;
            }
        }

        @Override
        public void onDraw(Canvas canvas) {
            canvas.drawColor(Color.BLACK);
            Bitmap bitmap;
            GraphicObject.Coordinates coords;
            for (GraphicObject graphic : _graphics) {
                bitmap = graphic.getGraphic();
                coords = graphic.getCoordinates();
                canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // TODO Auto-generated method stub
        }

        public void surfaceCreated(SurfaceHolder holder) {
            try{
         _thread.setRunning(true);
            _thread.start();
            }catch(Exception ex){
             _thread = new TutorialThread(getHolder(), this);
             _thread.start();
            }

        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // simply copied from sample application LunarLander:
            // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            _thread.setRunning(false);
            while (retry) {
                try {
                    _thread.join();
                    retry = false;
                } catch (InterruptedException e) {
                    // we will try it again and again...
                }
            }
        }
    }

    class TutorialThread extends Thread {
        private SurfaceHolder _surfaceHolder;
        private Panel _panel;
        private boolean _run = false;

        public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }

        public void setRunning(boolean run) {
            _run = run;
        }

        public SurfaceHolder getSurfaceHolder() {
            return _surfaceHolder;
        }

        @Override
        public void run() {
            Canvas c;
            while (_run) {
                c = null;
                try {
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder) {
                        _panel.onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        _surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }

    class GraphicObject {
        /**
         * Contains the coordinates of the graphic.
         */
        public class Coordinates {
            private int _x = 100;
            private int _y = 0;

            public int getX() {
                return _x + _bitmap.getWidth() / 2;
            }

            public void setX(int value) {
                _x = value - _bitmap.getWidth() / 2;
            }

            public int getY() {
                return _y + _bitmap.getHeight() / 2;
            }

            public void setY(int value) {
                _y = value - _bitmap.getHeight() / 2;
            }

            public String toString() {
                return "Coordinates: (" + _x + "/" + _y + ")";
            }
        }

        private Bitmap _bitmap;
        private Coordinates _coordinates;

        public GraphicObject(Bitmap bitmap) {
            _bitmap = bitmap;
            _coordinates = new Coordinates();
        }

        public Bitmap getGraphic() {
            return _bitmap;
        }

        public Coordinates getCoordinates() {
            return _coordinates;
        }
    }
}


问:
Ruby: map array of strings into array of arrays
Let's assume I have an array which looks like this:

```<code>["aaa", "bbb", "ccc"]
</code>```

I want to replace each of these items of an array into an array adding the same value, like this:

```<code>[["aaa", 0], ["bbb", 0], ["ccc", 0]]
</code>```

I don't understand why using:

```<code>arr_of_arr = arr.map{|single_item| single_item = [single_item, 0]}
</code>```

does not work, but rather returns the following error:

```<code> syntax error, unexpected keyword_end, expecting '}'
</code>```

答:
arr = ["aaa", "bbb", "ccc"]

arr_of_arr = arr.map { |single_item| [single_item, 0] }

Body:
Let's assume I have an array which looks like this:

["aaa", "bbb", "ccc"]

I want to replace each of these items of an array into an array adding the same value, like this:

[["aaa", 0], ["bbb", 0], ["ccc", 0]]

I don't understand why using:

arr_of_arr = arr.map{|single_item| single_item = [single_item, 0]}

does not work, but rather returns the following error:

 syntax error, unexpected keyword_end, expecting '}'


问:
label containing a-href-tag doesn't trigger it's input
I have a label containing an a-href-tag:

```<code><input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

<p><label for="sn_menu01_close" class="close">angebot<a href="#angebot">Angebot und Preise</a></label></p>
</code>```

When clicking the link the corresponding radiobutton doesn't trigger. When clicking the text outside the link it works. How can I make it work for the link too? Both have to work, triggering the radio button and skipping to the links destination (anchor).
I'm looking for a pure-CSS solution, using javascript or jQuery it's no problem.

答:
Try to trigger it with jQuery function:

$('input[type="radio"] ~ p label a').click(function(event) {
  event.preventDefault();
  var radio = $(this).parent().attr('for');
  $('#' + radio).prop("checked", true);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

<p>
  <label for="sn_menu01_close" class="close">angebotAngebot und Preise</label>
</p></code>```

EDITED for Pure CSS:
Try to use pointer-events: none to disable the link:

input[type="radio"] ~ p label a {
    pointer-events: none
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

<p>
  <label for="sn_menu01_close" class="close">angebotAngebot und Preise</label>
</p></code>```

Body:
I have a label containing an a-href-tag:

<input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

angebotAngebot und Preise

When clicking the link the corresponding radiobutton doesn't trigger. When clicking the text outside the link it works. How can I make it work for the link too? Both have to work, triggering the radio button and skipping to the links destination (anchor).
I'm looking for a pure-CSS solution, using javascript or jQuery it's no problem.

Body:
Try to trigger it with jQuery function:

$('input[type="radio"] ~ p label a').click(function(event) {
  event.preventDefault();
  var radio = $(this).parent().attr('for');
  $('#' + radio).prop("checked", true);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

<p>
  <label for="sn_menu01_close" class="close">angebot<a href="#angebot">Angebot und Preise</a></label>
</p>

EDITED for Pure CSS:
Try to use pointer-events: none to disable the link:

input[type="radio"] ~ p label a {
    pointer-events: none
}

<input id="sn_menu01_close" class="sn_menu_close" name="sn_menu" type="radio">

<p>
  <label for="sn_menu01_close" class="close">angebot<a href="#angebot">Angebot und Preise</a></label>
</p>


问:
In the DVM architecture where is the machine code?
Have been searching stackoverflow for an answer but to no avail.
From a link in this site
How an Android application is executed on Dalvik Virtual Machine.
There is a diagram of the code compiling flow

Simple question is where is the machine code(or the final code or the native instructions)?

Is the dalvik byte code the machine code(the final converted or compiled code)?

Or there is another compilation step?

Also where is the traced JIT compilation present in among the block?Is it in DEX compiler or in DVM?

Thanks for your time.

答:
Ok think have found an answer.

1.Compilation flow

.java file -- given to -- java compiler -- to generate -- .class file.

all .class files -- given to -- dx tool -- to generate single -- dex file

dex file -- given to -- dvm -- to generate -- final machine code.

final machine code -- given to -- CPU -- to execute.

2.A JIT compiler is a feature of JVM that compiles chunks of JVM instructions to native machine code.

If there is any misintepretation please notify in comments.Will fix the answer.

Thanks for your time.


问:
Meaning of overlapping when using memcpy
I am trying to understand the function memcpy() which is defined in the C library <string.h>

Syntax: void *memcpy(void*dst,const void*src,size_t n);

I know this function is used to copy the contents of the memory pointed by pointer src to the location pointed by the dst pointer and return the address pointed by dst.

I am not able to understand the following important statement regarding memcpy():

When using memcpy(), the memory address should not overlap, if it overlaps then the memcpy() is undefined.

Another query is:
Is the value passed to the third argument of the function i.e size_t n always an integer value?

答:
From the comments your problem is that you don't understand what "overlapping" means:

Overlapping means this:

Here the two memory regions src and dst do overlap:

But here they don't:

So if you have overlapping memory regions, then you cannot use memcpy but you have to use memmove.

Second question:

Yes, size_t is an unsigned integer type. The third argument is the number of bytes to copy, so it can hardly be anything else than an unsigned integer type.


问:
Parsing Json Array
I have been using the the Json library to try and parse the following Json data:

```<code>{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}
</code>```

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

```<code>    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }
</code>```

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!

答: That's not a valid JSON object, Just add '}' and gameentry not a root element you should get dailygamesschedule first and then get the gameentry </p>

Title: Parsing Json Array

Body:
I have been using the the Json library to try and parse the following Json data:

{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!


问:
Why is the ASP.NET/Visual Studio Web Development Server so slow?
(xkcd)

I know that compiling nowadays is much faster than it was before. Yet, for me, it seems that compiling and especially running/debugging ASP.NET projects with the Visual Studio Web Development Server is incredibly slow.

Since the beginning of last summer, I've been working heavily on ASP.NET MVC projects. Of course, the best way to debug them is by using the web server that comes with Visual Studio. When doing that, I get horrendously slow loading times. Chrome dev tools typically report that loading one of my pages had a 3 minute wait time, followed by a short loading time.

I've seen these two questions, but they don't help. While I do most of my debugging work in Chrome, the same happens in IE.

Has anyone else had this problem before? If so, any tips?

Also, I doubt that the problem lies with the speed of my machine. This computer is really fast running Windows 7 and Visual Studio 2010, so I don't see why ASP.NET debugging should be so slow.

UPDATE: In his answer below, Jon Skeet suggested attempting to identify whether the problem is being caused by the environment or by the code itself. I created a brand new MVC project and ran it. The first test appeared to be much faster. However, after testing it a few more times, it's safe to say that the first test was an anomaly - usually, it takes as long as my big project (2 - 3 minutes). Thus, this is a problem with the environment. Thanks in advance for any help!

UPDATE #2: It's been a while since I updated this question. Here are some details I've gathered since my last update:

This delay is occuring on both of my development machines, both running Windows 7 and Visual Studio 2010

This delay is happening for all my MVC2 and MVC3 projects (but I haven't experimented with plain ASP.NET yet)

Plain/vanilla MVC projects experience the same delay as MVC projects with big codebases

Disabling IntelliTrace did not help

Disabling IPv6 did not help

I haven't found a solution for this problem, so I've been stuck with huge wait times. Does anyone know how to solve this?

答:
This is actually a known performance issue with MVC, caused by throwing a ton of exceptions internally on startup.  If you have IntelliTrace turned on, this will wreck havoc with it.  Try disabling IntelliTrace and see if that improves it at all.

Source: http://connect.microsoft.com/VisualStudio/feedback/details/535799/debugging-mvc-is-very-very-slow