问:
How can I set the time zone in Dockerfile using gliderlabs/alpine:3.3
My Dockerfile is:

```<code>FROM gliderlabs/alpine:3.3
RUN set -x \
    && buildDeps='\
        python-dev \
        py-pip \
        build-base \
    ' \
    && apk --update add python py-lxml py-mysqldb $buildDeps \
    && rm -rf /var/cache/apk/* \
    && mkdir -p /app
ENV INSTALL_PATH /app
ENV TZ=Asia/Shanghai
WORKDIR $INSTALL_PATH
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY requirements-docker.txt ./
RUN pip install -r requirements-docker.txt
COPY . .
RUN apk del --purge $buildDeps
ENTRYPOINT ["celery", "-A", "tasks", "worker", "-l", "info", "-B"]
</code>```

I setted the timezone as Asia/Shanghai, but it did not work and gave me the UTC which had 8 hours deviation, the result is :

```<code>2016-01-24 11:25:07:[2016-01-24 03:25:07,893: WARNING/Worker-2] 2016-01-24 03:25:07.892718
2016-01-24 11:25:08:[2016-01-24 03:25:08,339: INFO/MainProcess] Task tasks.crawl[98c9a9fc-0817-45cb-a2fc-40320d63c41a] succeeded in 0.447403368002s: None
2016-01-24 11:27:07:[2016-01-24 03:27:07,884: INFO/Beat] Scheduler: Sending due task spider (tasks.crawl)
</code>```

Then I tried other methods like:

```<code>RUN echo "Asia/Shanghai" > /etc/timezone && dpkg-reconfigure -f noninteractive tzdata
</code>```

and

```<code>RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
</code>```

none of them did work, how can set the timezone? Thanks very much.

答:
//dockerfile</p>

```<code>RUN apk update && apk add tzdata \
     && cp -r -f /usr/share/zoneinfo/YOUR_TIMEZONE /etc/localtime
</code>```

Body:
My Dockerfile is:

FROM gliderlabs/alpine:3.3
RUN set -x \
    && buildDeps='\
        python-dev \
        py-pip \
        build-base \
    ' \
    && apk --update add python py-lxml py-mysqldb $buildDeps \
    && rm -rf /var/cache/apk/* \
    && mkdir -p /app
ENV INSTALL_PATH /app
ENV TZ=Asia/Shanghai
WORKDIR $INSTALL_PATH
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY requirements-docker.txt ./
RUN pip install -r requirements-docker.txt
COPY . .
RUN apk del --purge $buildDeps
ENTRYPOINT ["celery", "-A", "tasks", "worker", "-l", "info", "-B"]

I setted the timezone as Asia/Shanghai, but it did not work and gave me the UTC which had 8 hours deviation, the result is :

2016-01-24 11:25:07:[2016-01-24 03:25:07,893: WARNING/Worker-2] 2016-01-24 03:25:07.892718
2016-01-24 11:25:08:[2016-01-24 03:25:08,339: INFO/MainProcess] Task tasks.crawl[98c9a9fc-0817-45cb-a2fc-40320d63c41a] succeeded in 0.447403368002s: None
2016-01-24 11:27:07:[2016-01-24 03:27:07,884: INFO/Beat] Scheduler: Sending due task spider (tasks.crawl)

Then I tried other methods like:

RUN echo "Asia/Shanghai" > /etc/timezone && dpkg-reconfigure -f noninteractive tzdata

and

RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

none of them did work, how can set the timezone? Thanks very much.

Body:
//dockerfile

RUN apk update && apk add tzdata \
     && cp -r -f /usr/share/zoneinfo/YOUR_TIMEZONE /etc/localtime


来源: stackexchange

问:
How to create a table from a json api using HTML tables
We are using an api to retrieve data from MySQL database and turning it into a json file type. What would be the best way to get that data into an HTML table.

This is the api: https://nauticmc.com/dev/top.php?type=kills&start=0&end=9

Depending on what you change the type to it will change ascending order of the data I.E Kills will display the heights amount of kills first.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('
');
        tr.append("" + json[i].username + "	");
        tr.append("" + json[i].kills + "	");
        tr.append("" + json[i].deaths + "	");
        tr.append("" + json[i].broken + "	");
        tr.append("" + json[i].placed + "	");
        tr.append("" + json[i].fish + "	");
        tr.append("" + json[i].onlinetime + "	");
        tr.append("" + json[i].mobskilled + "	");
        tr.append("" + json[i].crops + "	");
        $('table').append(tr);
    }
});```

I am using Local JSON for now because Ajax does not allow access cross domain but I would parse it into a var to get it.

I also want people to be able to see what data is on top by corresponding arrows in each column I tried to use datatables.js but that did not work so well

This is just the table without any js or json

https://strixdesigns.com/Stats1/ < I want the arrows to work like this

答:
Why dont use datatable and set the options like this
your thead field must the same on your json field count

HTML

```<code><table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Username</th>
            <th>Kills</th>
            ....
        </tr>
    </thead>

</table>
</code>```

JQUERY

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
            "url": "https://nauticmc.com/dev/top.php?type=kills&start=0&end=9",
           "type": "POST",
           "data":{
                     'type': 'kills',
                     'start': 0,
                     'end': 9
                 }
        },
        "columns": [
            { "data": "username " },
            { "data": "kills " },
            ...
        ]
    } );
} );
</code>```

check documentation here: https://datatables.net/examples/ajax/custom_data_flat.html

ContentLicense: CC BY-SA 3.0

Body:
We are using an api to retrieve data from MySQL database and turning it into a json file type. What would be the best way to get that data into an HTML table.

This is the api: https://nauticmc.com/dev/top.php?type=kills&start=0&end=9

Depending on what you change the type to it will change ascending order of the data I.E Kills will display the heights amount of kills first.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('
');
        tr.append("" + json[i].username + "	");
        tr.append("" + json[i].kills + "	");
        tr.append("" + json[i].deaths + "	");
        tr.append("" + json[i].broken + "	");
        tr.append("" + json[i].placed + "	");
        tr.append("" + json[i].fish + "	");
        tr.append("" + json[i].onlinetime + "	");
        tr.append("" + json[i].mobskilled + "	");
        tr.append("" + json[i].crops + "	");
        $('table').append(tr);
    }
});

I am using Local JSON for now because Ajax does not allow access cross domain but I would parse it into a var to get it.

I also want people to be able to see what data is on top by corresponding arrows in each column I tried to use datatables.js but that did not work so well

This is just the table without any js or json

https://strixdesigns.com/Stats1/ < I want the arrows to work like this

Body:
Why dont use datatable and set the options like this
your thead field must the same on your json field count

HTML

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Username</th>
            <th>Kills</th>
            ....
        </tr>
    </thead>

</table>

JQUERY

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
            "url": "https://nauticmc.com/dev/top.php?type=kills&start=0&end=9",
           "type": "POST",
           "data":{
                     'type': 'kills',
                     'start': 0,
                     'end': 9
                 }
        },
        "columns": [
            { "data": "username " },
            { "data": "kills " },
            ...
        ]
    } );
} );

check documentation here: https://datatables.net/examples/ajax/custom_data_flat.html


问:
Jupyter Notebook error. No such file or directory C:.../HOME
I have installed Anaconda2, and today decided to update to Anaconda3. I installed Anaconda3 at the same time as I uninstalled Anaconda2.

Now, Jupyter Notebook shows this error and quits every time I try to start it.

The path in the error message is: "C:\Users\Hongyi\Documents\%HOME%"

What is causing Jupyter Notebook to quit?

答:
After readed this solution I tried another one (a comfortable one for me):
Open the location of the "Jupyter Notebook" shortcut (right click > More > File location) and right click again > Properties. In the Destination field (Sorry if the label is another ... the thing is that my Windows is in Spanish and I don't remember how it's labeled this field in English) just change the %HOME% at the end for a path to your "Work Folder" (if you have not created one then just create it). And this way It works also.</p>


问:
cordova filetransfer plugin download doesnt show up in image gallery
I have this code that downloads an image from a URL and saves in my phone device but the problem is that it doesnt show up in the image gallery of the phone device rather it shows up in the file storage directory. So, i would like to have it show up in the image gallery. </p>

```<code>$scope.downloadImage = function(images) {
    var imageName = angular.fromJson(images);
    $scope.$applyAsync(function() {
      $scope.indexchosen === undefined ? $scope.indexchosen = 0 : $scope.indexchosen;
      console.log($scope.indexchosen)
      index = $scope.indexchosen;
      imageToDownload = imageName[index].filename;
    })

    $scope.$applyAsync(function() {
      window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
    });

    function onSuccess(fileSystem) {
      var directoryEntry = fileSystem.root;
      countImage+=1;

      var name = countImage + '-' + imageToDownload.split('/').pop();
      var imageUrl = encodeURI(decodeURIComponent(AppSettings.baseApiUrl + imageToDownload));
      var fp = fileSystem.root.toURL();

      var filepath = fp + '/' + name;
      console.log(filepath)
      var ft = new window.FileTransfer();
      var f =  ft.download(imageUrl, filepath,
        function (entry) {
          $cordovaToast.show("Image Saved", "long", "bottom");
        },
        function (error) {
        }
      );
    }
    function onError(error) {
    }
  }
</code>```

<p>Any help is appreciated thanks. </p>

答:
If download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.

so i made a plugin ,

It is a plugin that updates the gallery after downloading.

https://github.com/pouu69/cordova-plugin-gallery-refresh

Body:
I have this code that downloads an image from a URL and saves in my phone device but the problem is that it doesnt show up in the image gallery of the phone device rather it shows up in the file storage directory. So, i would like to have it show up in the image gallery.

$scope.downloadImage = function(images) {
    var imageName = angular.fromJson(images);
    $scope.$applyAsync(function() {
      $scope.indexchosen === undefined ? $scope.indexchosen = 0 : $scope.indexchosen;
      console.log($scope.indexchosen)
      index = $scope.indexchosen;
      imageToDownload = imageName[index].filename;
    })

    $scope.$applyAsync(function() {
      window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
    });

    function onSuccess(fileSystem) {
      var directoryEntry = fileSystem.root;
      countImage+=1;

      var name = countImage + '-' + imageToDownload.split('/').pop();
      var imageUrl = encodeURI(decodeURIComponent(AppSettings.baseApiUrl + imageToDownload));
      var fp = fileSystem.root.toURL();

      var filepath = fp + '/' + name;
      console.log(filepath)
      var ft = new window.FileTransfer();
      var f =  ft.download(imageUrl, filepath,
        function (entry) {
          $cordovaToast.show("Image Saved", "long", "bottom");
        },
        function (error) {
        }
      );
    }
    function onError(error) {
    }
  }

Any help is appreciated thanks.


问:
mongorestore from standalone to replicaset
I have dumped a standalone mongo database (14Gb big) running on the default port as follows:

```<code>mongodump --username <username> --password <password> --db <dbname>
</code>```

and I am trying to restore it onto a replica set with the following:

```<code>mongorestore --host myReplSet/127.0.0.1:27020 --drop --username <username> --password <password>
</code>```

The restore seems to work (it takes a minute or so and the output looks good) the database is created and all the collections are created but there is no data in the collections, they are all empty. What am I doing wrong?

For what it is worth, the local database is showing that it is 10 Gb big (I am not sure how big it was before the restore)

答:
Make sure the mongorestore version is the same version as the mongodb.

```<code>mongorestore --version

mongo --version
</code>```

Same thing goes for the mongodump.

```<code>mongodump --version
</code>```

They need to be the same or close enough versions.
These are issues that you will run into on a distributed system.
It will create the collections, but they will be empty if versions don't match.

Body:
I have dumped a standalone mongo database (14Gb big) running on the default port as follows:

mongodump --username <username> --password <password> --db <dbname>

and I am trying to restore it onto a replica set with the following:

mongorestore --host myReplSet/127.0.0.1:27020 --drop --username <username> --password <password>

The restore seems to work (it takes a minute or so and the output looks good) the database is created and all the collections are created but there is no data in the collections, they are all empty. What am I doing wrong?

For what it is worth, the local database is showing that it is 10 Gb big (I am not sure how big it was before the restore)

Body:
Make sure the mongorestore version is the same version as the mongodb.

mongorestore --version

mongo --version

Same thing goes for the mongodump.

mongodump --version

They need to be the same or close enough versions.
These are issues that you will run into on a distributed system.
It will create the collections, but they will be empty if versions don't match.


问:
How to pass parameters to a partial view in ASP.NET MVC?
Suppose that I have this partial view:

```<code>Your name is <strong>@firstName @lastName</strong>
</code>```

which is accessible through a child only action like:

```<code>[ChildActionOnly]
public ActionResult FullName(string firstName, string lastName)
{

}
</code>```

And I want to use this partial view inside another view with:

```<code>@Html.RenderPartial("FullName")
</code>```

In other words, I want to be able to pass firstName ans lastName from view to partial view. How should I do that?

答:
Just:</p>

```<code>@Html.Partial("PartialName", Model);
</code>```

Body:
Suppose that I have this partial view:

Your name is @firstName @lastName

which is accessible through a child only action like:

[ChildActionOnly]
public ActionResult FullName(string firstName, string lastName)
{

}

And I want to use this partial view inside another view with:

@Html.RenderPartial("FullName")

In other words, I want to be able to pass firstName ans lastName from view to partial view. How should I do that?

Body:
Just:

@Html.Partial("PartialName", Model);


问:
Is there a glutDisplayFunc equivalent in GLFW3?
I'm developing an OpenGL application in C, and I'm using glew/glfw3, and in glut I'm used to registering a looping function with glutDisplayFunc. Is there any such function in glew/glfw3, or do I have to write the loop myself?

I'm mainly asking because I want to use glew/glfw3 properly, and I feel like if such a function existed, it should be used.

Thanks!

答:
You will have to write your own loop.  This might help Learn OpenGL.

It shows setting up event callbacks and a while loop using mostly glfw functions.


问:
Why is EF4 trying to re-create my database even though the model hasn't changed?
I have an ASP.NET MVC 3 Beta website using SQL Server CE 4.0. With both ScottGu's NerdDinner example and my own code, I will sometimes get the following exception as soon as I try to access the database:

```
File already exists. Try using a different database name.
[ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]

Line 17:         public ActionResult Index()
Line 18:         {
Line 19:             var dinners = from d in nerdDinners.Dinners
Line 20:                           where d.EventDate > DateTime.Now
Line 21:                           select d;

[SqlCeException (0x80004005): File already exists. Try using a different database name. [ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]]
   System.Data.SqlServerCe.SqlCeEngine.ProcessResults(IntPtr pError, Int32 hr) +92
   System.Data.SqlServerCe.SqlCeEngine.CreateDatabase() +1584
   System.Data.SqlServerCe.SqlCeProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 timeOut, StoreItemCollection storeItemCollection) +287
   System.Data.Objects.ObjectContext.CreateDatabase() +84
   System.Data.Entity.Internal.DatabaseOperations.Create(ObjectContext objectContext) +35
   System.Data.Entity.Infrastructure.Database.Create() +70
   System.Data.Entity.Infrastructure.CreateDatabaseOnlyIfNotExists`1.InitializeDatabase(TContext context) +360
   System.Data.Entity.Infrastructure.Database.Initialize() +272
   System.Data.Entity.Internal.InternalContext.Initialize() +90
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +34
   System.Data.Entity.Internal.Linq.EfInternalQuery`1.Initialize() +140
   System.Data.Entity.Internal.Linq.EfInternalQuery`1.get_Provider() +29
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +34
   System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
   NerdDinner.Controllers.HomeController.Index() in D:\Sourcecode\NerdDinner\NerdDinner\Controllers\HomeController.cs:19
```

I cannot figure out why this works sometimes with an existing .dbf file and other times it complains. I have even tried explicitly setting the default behaviour with

```<code>Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<...>());
</code>```

Has anyone else experienced this?

Restarting Cassini doesn't seem to make a difference.

Hitting refresh in IE after receiving this error will make the exact same page load properly.

答:
Sorry to resurrect such an old question, but I was experiencing this today and have found a workaround which does not involve installing an older version of the CTP.

From The correct url for the blogpost is http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx (about half-way through the blog post)

*Go into your AppStart_SQLCEEntityFramework.cs file and the DefaultConnectionFactory line to this:*

```<code>Database.DefaultConnectionFactory = new SqlCeConnectionFactory(
    "System.Data.SqlServerCe.4.0",
    HostingEnvironment.MapPath("~/App_Data/"),"");
</code>```

My particular database is placed in the App_Data folder but I'm assuming that if yours is not you should be able to change the path to suit and it will work.

Hope this helps!

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET MVC 3 Beta website using SQL Server CE 4.0. With both ScottGu's NerdDinner example and my own code, I will sometimes get the following exception as soon as I try to access the database:

File already exists. Try using a different database name.
[ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]

Line 17:         public ActionResult Index()
Line 18:         {
Line 19:             var dinners = from d in nerdDinners.Dinners
Line 20:                           where d.EventDate > DateTime.Now
Line 21:                           select d;

[SqlCeException (0x80004005): File already exists. Try using a different database name. [ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]]
   System.Data.SqlServerCe.SqlCeEngine.ProcessResults(IntPtr pError, Int32 hr) +92
   System.Data.SqlServerCe.SqlCeEngine.CreateDatabase() +1584
   System.Data.SqlServerCe.SqlCeProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 timeOut, StoreItemCollection storeItemCollection) +287
   System.Data.Objects.ObjectContext.CreateDatabase() +84
   System.Data.Entity.Internal.DatabaseOperations.Create(ObjectContext objectContext) +35
   System.Data.Entity.Infrastructure.Database.Create() +70
   System.Data.Entity.Infrastructure.CreateDatabaseOnlyIfNotExists`1.InitializeDatabase(TContext context) +360
   System.Data.Entity.Infrastructure.Database.Initialize() +272
   System.Data.Entity.Internal.InternalContext.Initialize() +90
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +34
   System.Data.Entity.Internal.Linq.EfInternalQuery`1.Initialize() +140
   System.Data.Entity.Internal.Linq.EfInternalQuery`1.get_Provider() +29
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +34
   System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
   NerdDinner.Controllers.HomeController.Index() in D:\Sourcecode\NerdDinner\NerdDinner\Controllers\HomeController.cs:19

I cannot figure out why this works sometimes with an existing .dbf file and other times it complains. I have even tried explicitly setting the default behaviour with

Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<...>());

Has anyone else experienced this?

Restarting Cassini doesn't seem to make a difference.

Hitting refresh in IE after receiving this error will make the exact same page load properly.

Body:
Sorry to resurrect such an old question, but I was experiencing this today and have found a workaround which does not involve installing an older version of the CTP.

From The correct url for the blogpost is http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx (about half-way through the blog post)

*Go into your AppStart_SQLCEEntityFramework.cs file and the DefaultConnectionFactory line to this:*

Database.DefaultConnectionFactory = new SqlCeConnectionFactory(
    "System.Data.SqlServerCe.4.0",
    HostingEnvironment.MapPath("~/App_Data/"),"");

My particular database is placed in the App_Data folder but I'm assuming that if yours is not you should be able to change the path to suit and it will work.

Hope this helps!


问:
No resource found that matches the given name AppCompat.Light.DarkActionBar
I tried everything but I am still getting errors in

```<code> <style name="AppTheme" parent="AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

and

```<code><style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
</code>```

In my styles folder, I tried using

compile 'com.android.support:appcompat-v7:25.3.1'

and even tried changing the theme to Apptheme in layout but unable to render. I tried every step possible with even downloading sdk tools 19.1 and 20.  What am I doing wrong?

EDIT: My app gradle file:

```<code>    apply plugin: 'com.android.application'

android {
    signingConfigs {
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.examples.test"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 2
        versionName "1.1"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {

    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
The problem seems to be in the build.gradle project file (thanks IntelliJ Amiya)

I changed this:

```<code>classpath 'com.android.tools.build:gradle:2.3.1'
</code>```

To

```<code>classpath 'com.android.tools.build:gradle:2.2.2'
</code>```

And now I don't get any erros in AppCompat.Light.DarkActionBar

Body:
I tried everything but I am still getting errors in

and

Body:
The problem seems to be in the build.gradle project file (thanks IntelliJ Amiya)

I changed this:

classpath 'com.android.tools.build:gradle:2.3.1'

To

classpath 'com.android.tools.build:gradle:2.2.2'

And now I don't get any erros in AppCompat.Light.DarkActionBar


问:
Apollo Subscription Resolver Never Activates?
My component is calling a subscription query, but for some reason the subscription resolver isn't being accessed: a breakpoint in it is never activated. And yet on the client I get the GraphQL subscription error:

"Subscription must return Async Iterable. Received: undefined"

What could be causing this?

Thanks in advance to all for any info.

SUBSCRIPTION QUERY

```<code>const IM_SUBSCRIPTION_QUERY = gql`
      subscription getIMsViaSubscription($fromID: String!, $toID: String!){
          IMAdded(fromID:$fromID, toID: $toID){
            id,
            fromID,
            toID,
            msgText,
            myUserData{
                id,
                name_first,
                name_last,
                picture_large,
                picture_medium,
                picture_thumbnail
                my_category
            }
          }
        }
`;
</code>```

RESOLVER

```<code>Subscription: {
    IMAdded(IMThatWasAdded) {
        debugger; <== IS NEVER ACTIVATED
        subscribe: withFilter(() => SubscriptionServer.pubsub.asyncIterator(IM_ADDED_CHANNEL), (newIM, args) => {
            const callIsFromMsgFoldersComponent = args.toID == 0;
            var result;
            if (callIsFromMsgFoldersComponent){
                result = (newIM.fromID === args.fromID || newIM.toID === args.fromID);
            } else {
                result = ((newIM.fromID === args.fromID && newIM.toID === args.toID) || (newIM.fromID === args.toID && newIM.toID === args.fromID));
            }
            return result;
        })
</code>```

COMPONENT

```<code>const withDataAndSubscription = graphql(GETIMS_QUERY, {
    options({toID}) {
        console.log(GETIMS_QUERY);
        const fromID = Meteor.userId();
        return {
            fetchPolicy: 'cache-and-network',
            variables: {fromID: `${fromID}`, toID: `${toID}`}
        };
    }
    ,
    props: props => {
        debugger;
        return {
            loading: props.data.loading,
            instant_message: props.data.instant_message,
            subscribeToMore: props.data.subscribeToMore,
            subscribeToNewIMs: params => {
                debugger;  <==IS ACTIVATED AS EXPECTED
                console.log(IM_SUBSCRIPTION_QUERY); <==IS OKAY
                const fromID = Meteor.userId();
                const toID = params.toID;
                return props.data.subscribeToMore({
                    document: IM_SUBSCRIPTION_QUERY,
                    variables: {fromID: `${fromID}`, toID: `${toID}`},
                    updateQuery: (previousResult, {subscriptionData}) => {
                        if (!subscriptionData.data) {
                            return previousResult;
                        }
                        const newMsg = subscriptionData.data.createIM;
                        return update(previousResult, {
                            instant_message: {
                                $push: [newMsg],
                            },
                        });
                    }
                });
            }
        };
    },
})
;
</code>```

答:
Server-side setup, and mutation/subscription resolvers have changed quite a bit since the code in my post, which was based on Apollo libs from late last year. Here is code that works with current Apollo libs, via this tutorial:

SERVER SETUP

```<code>import express from 'express';
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
import bodyParser from 'body-parser';
import  cors  from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';

import schema from '/imports/api/schema';

//SET UP APOLLO QUERY / MUTATIONS / PUBSUB
const METEOR_PORT = 3000;
const GRAPHQL_PORT = 4000;
const server = express();

server.use('*', cors({ origin: 'http://localhost:${METEOR_PORT}' }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
    schema
}));

server.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
    subscriptionsEndpoint: `ws://localhost:${GRAPHQL_PORT}/subscriptions`
}));

// Wrap the Express server
const ws = createServer(server);
ws.listen(GRAPHQL_PORT, () => {
    console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`);
    // Set up the WebSocket for handling GraphQL subscriptions
    new SubscriptionServer({
        execute,
        subscribe,
        schema
    }, {
        server: ws,
        path: '/subscriptions',
    });
});
//END OF SET UP APOLLO PUBSUB
</code>```

MUTATION RESOLVER

```<code>   Mutation: {
        createIM(root, args, context) {
            var associatedUsers = [];
            associatedUsers.push(args.fromID);
            associatedUsers.push(args.toID);
            var IDofNewIM;

            return Promise.resolve()
                .then(() => {
                    const newIM = connectors.IMs.create(args);
                    return newIM;
                })
                .then(IMAdded => {
                    // publish subscription notification
                    pubsub.publish(IM_ADDED_CHANNEL, { IMAdded, args});
                    return IMAdded;
                })
                .catch((err)=> {
                    console.log(err);
                });
        },
</code>```

SUBSCRIPTION RESOLVER

```<code>IMAdded: {
    subscribe: withFilter(
        () => pubsub.asyncIterator(IM_ADDED_CHANNEL),
        (IMAdded, args) => {
            IMAdded = IMAdded.IMAdded;
            var result = ((IMAdded.fromID === args.fromID && IMAdded.toID === args.toID) || (IMAdded.fromID === args.toID && IMAdded.toID === args.fromID));
            return result;
        }
    )
},
</code>```

Body:
My component is calling a subscription query, but for some reason the subscription resolver isn't being accessed: a breakpoint in it is never activated. And yet on the client I get the GraphQL subscription error:

"Subscription must return Async Iterable. Received: undefined"

What could be causing this?

Thanks in advance to all for any info.

SUBSCRIPTION QUERY

const IM_SUBSCRIPTION_QUERY = gql`
      subscription getIMsViaSubscription($fromID: String!, $toID: String!){
          IMAdded(fromID:$fromID, toID: $toID){
            id,
            fromID,
            toID,
            msgText,
            myUserData{
                id,
                name_first,
                name_last,
                picture_large,
                picture_medium,
                picture_thumbnail
                my_category
            }
          }
        }
`;

RESOLVER

Subscription: {
    IMAdded(IMThatWasAdded) {
        debugger; <== IS NEVER ACTIVATED
        subscribe: withFilter(() => SubscriptionServer.pubsub.asyncIterator(IM_ADDED_CHANNEL), (newIM, args) => {
            const callIsFromMsgFoldersComponent = args.toID == 0;
            var result;
            if (callIsFromMsgFoldersComponent){
                result = (newIM.fromID === args.fromID || newIM.toID === args.fromID);
            } else {
                result = ((newIM.fromID === args.fromID && newIM.toID === args.toID) || (newIM.fromID === args.toID && newIM.toID === args.fromID));
            }
            return result;
        })

COMPONENT

const withDataAndSubscription = graphql(GETIMS_QUERY, {
    options({toID}) {
        console.log(GETIMS_QUERY);
        const fromID = Meteor.userId();
        return {
            fetchPolicy: 'cache-and-network',
            variables: {fromID: `${fromID}`, toID: `${toID}`}
        };
    }
    ,
    props: props => {
        debugger;
        return {
            loading: props.data.loading,
            instant_message: props.data.instant_message,
            subscribeToMore: props.data.subscribeToMore,
            subscribeToNewIMs: params => {
                debugger;  <==IS ACTIVATED AS EXPECTED
                console.log(IM_SUBSCRIPTION_QUERY); <==IS OKAY
                const fromID = Meteor.userId();
                const toID = params.toID;
                return props.data.subscribeToMore({
                    document: IM_SUBSCRIPTION_QUERY,
                    variables: {fromID: `${fromID}`, toID: `${toID}`},
                    updateQuery: (previousResult, {subscriptionData}) => {
                        if (!subscriptionData.data) {
                            return previousResult;
                        }
                        const newMsg = subscriptionData.data.createIM;
                        return update(previousResult, {
                            instant_message: {
                                $push: [newMsg],
                            },
                        });
                    }
                });
            }
        };
    },
})
;

Body:
Server-side setup, and mutation/subscription resolvers have changed quite a bit since the code in my post, which was based on Apollo libs from late last year. Here is code that works with current Apollo libs, via this tutorial:

SERVER SETUP

import express from 'express';
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
import bodyParser from 'body-parser';
import  cors  from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';

import schema from '/imports/api/schema';

//SET UP APOLLO QUERY / MUTATIONS / PUBSUB
const METEOR_PORT = 3000;
const GRAPHQL_PORT = 4000;
const server = express();

server.use('*', cors({ origin: 'http://localhost:${METEOR_PORT}' }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
    schema
}));

server.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
    subscriptionsEndpoint: `ws://localhost:${GRAPHQL_PORT}/subscriptions`
}));

// Wrap the Express server
const ws = createServer(server);
ws.listen(GRAPHQL_PORT, () => {
    console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`);
    // Set up the WebSocket for handling GraphQL subscriptions
    new SubscriptionServer({
        execute,
        subscribe,
        schema
    }, {
        server: ws,
        path: '/subscriptions',
    });
});
//END OF SET UP APOLLO PUBSUB

MUTATION RESOLVER

   Mutation: {
        createIM(root, args, context) {
            var associatedUsers = [];
            associatedUsers.push(args.fromID);
            associatedUsers.push(args.toID);
            var IDofNewIM;

            return Promise.resolve()
                .then(() => {
                    const newIM = connectors.IMs.create(args);
                    return newIM;
                })
                .then(IMAdded => {
                    // publish subscription notification
                    pubsub.publish(IM_ADDED_CHANNEL, { IMAdded, args});
                    return IMAdded;
                })
                .catch((err)=> {
                    console.log(err);
                });
        },

SUBSCRIPTION RESOLVER

IMAdded: {
    subscribe: withFilter(
        () => pubsub.asyncIterator(IM_ADDED_CHANNEL),
        (IMAdded, args) => {
            IMAdded = IMAdded.IMAdded;
            var result = ((IMAdded.fromID === args.fromID && IMAdded.toID === args.toID) || (IMAdded.fromID === args.toID && IMAdded.toID === args.fromID));
            return result;
        }
    )
},


问:
Lagom PubSubRef subscriber drops messages
[Attention] The question is Lagom framework specific!

In my current project, the problem with cutting the list of messages from Source to Kafka topic publisher has been observed when upstream is of high speed and looks like downstream can't handle all messages in time. As realized, the cutting is related to the behavior of PubSubRef.subscribe() method https://github.com/lagom/lagom/blob/master/pubsub/javadsl/src/main/scala/com/lightbend/lagom/javadsl/pubsub/PubSubRef.scala#L85

The full method definition:

```<code>def subscriber(): Source[T, NotUsed] = {
scaladsl.Source.actorRef[T](bufferSize, OverflowStrategy.dropHead)
  .mapMaterializedValue { ref =>
    mediator ! Subscribe(topic.name, ref)
    NotUsed
  }.asJava
}
</code>```

There's OverflowStrategy.dropHead is used. Can it be changed to use back-pressure strategy?

UPD#1:
The use case is pretty simple, when a query request is published into command topic, get it and query objects from DB table, the resulting list is pushed into result Kafka topic. Code snippet:

```<code>objectsResultTopic = pubSub.refFor(TopicId.of(CustomObject.class, OBJECTS_RESULT_TOPIC));
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(event -> LOG.trace("Sending object {}", object)))
        .to(objectsResultTopic.publisher()),
    Source.repeat(Done.getInstance())
    )
)
</code>```

In case of objects stream generated by deserializeCommandAndQueryObjects function is more than default buffer-size = 1000 it starts cutting the elements (our case is ~ 2.5k objects).

UPD#2:
The source of objects data is:

```<code>// returns CompletionStage<Source<CustomObject, ?>>
jdbcSession.withConnection(
  connection -> Source.from(runQuery(connection, rowConverter))
)
</code>```

And there's a subscription to Kafka objectsResultTopic:

```<code>TopicProducer.singleStreamWithOffset(
offset -> objectsResultTopic.subscriber().map(gm -> {
    JsonNode node = mapper.convertValue(gm, JsonNode.class);
    return Pair.create(node, offset);
}));
</code>```

答:
It sounds like Lagom's distributed publish-subscribe feature may not be the best tool for the job you have.

Your question mentions Kafka, but this feature does not make use of Kafka. Instead, it works by directly broadcasting messages to all subscribers in the cluster. This is an "at most once" messaging transport that may indeed lose messages, and is intended for consumers who care more about keeping up with recent messages than processing every single one. The overflow strategy is not customizable, and you would not want to use back-pressure in these use cases, as it would mean that one slow consumer could slow down delivery to all of the other subscribers.

There are a few other options that you have:

If you do want to use Kafka, you should use Lagom's message broker API. This supports "at least once" delivery semantics, and can be used to ensure that each consumer processes every message (at the cost of possibly increasing latency).

In this case, Kafka acts as a giant durable buffer, so it's even better than back-pressure: the producer and consumer can proceed at different paces, and (when used with partitioning) you can add consumers in order to scale out and process messages more quickly when needed.

The message broker API can be used when producers and consumers are all in the same service, but it is particularly suitable for communication between services.

If the messages you are sending are persistent entity events, and the consumers are part of the same service, then a persistent read-side processor might be a good option.

This also provides "at least once" delivery, and if the only effects of processing messages are database updates, then the built-in support for Cassandra read-side databases and relational read-side databases provide "effectively once" semantics, where the database updates are run transactionally to ensure that failures that occur during event processing cannot result in partial updates.

If the messages you are sending are persistent entity events, the consumers are part of the same service, but you want to process the events as a stream, you can access a raw stream of events.

If your use case does not fit into one of the use cases that Lagom supports explicitly, you can use lower-level Akka APIs, including distributed publish-subscribe, to implement something more tailored to your needs.

The best choice will depend on the specifics of your use case: the source of the messages and the types of consumers you want. If you update your question with more details and add a comment to this answer, I can edit the answer with more specific suggestions.

Body:
[Attention] The question is Lagom framework specific!

In my current project, the problem with cutting the list of messages from Source to Kafka topic publisher has been observed when upstream is of high speed and looks like downstream can't handle all messages in time. As realized, the cutting is related to the behavior of PubSubRef.subscribe() method https://github.com/lagom/lagom/blob/master/pubsub/javadsl/src/main/scala/com/lightbend/lagom/javadsl/pubsub/PubSubRef.scala#L85

The full method definition:

def subscriber(): Source[T, NotUsed] = {
scaladsl.Source.actorRef[T](bufferSize, OverflowStrategy.dropHead)
  .mapMaterializedValue { ref =>
    mediator ! Subscribe(topic.name, ref)
    NotUsed
  }.asJava
}

There's OverflowStrategy.dropHead is used. Can it be changed to use back-pressure strategy?

UPD#1:
The use case is pretty simple, when a query request is published into command topic, get it and query objects from DB table, the resulting list is pushed into result Kafka topic. Code snippet:

objectsResultTopic = pubSub.refFor(TopicId.of(CustomObject.class, OBJECTS_RESULT_TOPIC));
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(event -> LOG.trace("Sending object {}", object)))
        .to(objectsResultTopic.publisher()),
    Source.repeat(Done.getInstance())
    )
)

In case of objects stream generated by deserializeCommandAndQueryObjects function is more than default buffer-size = 1000 it starts cutting the elements (our case is ~ 2.5k objects).

UPD#2:
The source of objects data is:

// returns CompletionStage<Source<CustomObject, ?>>
jdbcSession.withConnection(
  connection -> Source.from(runQuery(connection, rowConverter))
)

And there's a subscription to Kafka objectsResultTopic:

TopicProducer.singleStreamWithOffset(
offset -> objectsResultTopic.subscriber().map(gm -> {
    JsonNode node = mapper.convertValue(gm, JsonNode.class);
    return Pair.create(node, offset);
}));


问:
Lingering No 'Access-Control-Allow-Origin' error with S3
I'm having a weird issue loading assets from S3. I have a stylesheet that's being served from S3 and seems to be loading with no issues, but I'm still getting a No 'Access-Control-Allow-Origin' header is present on the requested resource. error in the console. The assets are public, and here's the CORS configuration on my bucket

```<code><CORSRule>
  <AllowedOrigin>MYDOMAINHERE</AllowedOrigin>
  <AllowedMethod>GET</AllowedMethod>
  <MaxAgeSeconds>3000</MaxAgeSeconds>
  <AllowedHeader>*</AllowedHeader>
</CORSRule>
</code>```

Again, the styles are all loading and everything seems to be fine but I'm just trying to figure out why it would still be throwing that error and hoping to eliminate it if possible. Thanks!

答:
The behavior described in the question is most likely due to either the browser having cached the resource and continuing to serve it from its cache or else something on the server side or an intermediate network proxy/cache is still serving a stale copy.

If the caching problem is on the client side you try navigating to the URL for the resource directly in your browser and then force-reloading it.

But if the problem’s with a cache/proxy on the network side, it can be more difficult to get a fresh copy. In those cases you may just have to wait for the cache to expire. Looking at the values of the Expires and Cache-Control response headers can give you an idea when that will happen.

Body:
I'm having a weird issue loading assets from S3. I have a stylesheet that's being served from S3 and seems to be loading with no issues, but I'm still getting a No 'Access-Control-Allow-Origin' header is present on the requested resource. error in the console. The assets are public, and here's the CORS configuration on my bucket

<CORSRule>
  <AllowedOrigin>MYDOMAINHERE</AllowedOrigin>
  <AllowedMethod>GET</AllowedMethod>
  <MaxAgeSeconds>3000</MaxAgeSeconds>
  <AllowedHeader>*</AllowedHeader>
</CORSRule>

Again, the styles are all loading and everything seems to be fine but I'm just trying to figure out why it would still be throwing that error and hoping to eliminate it if possible. Thanks!


问:
WCF: The message could not be processed:
I have created a WCF service which I am hosting as an application under my site on an IIS7. It is running on one server and now I am trying to make it run on a second server. When I call the service I get the following error:

The message could not be processed.
  This is most likely because the action
  \u0027http://tempuri.org/IMyService/myMethod\u0027
  is incorrect or because the message
  contains an invalid or expired
  security context token or because
  there is a mismatch between bindings.

I have set the security in the wsHttpBinding to None, so in my naive mind I conclude that it is not a security problem.

What might I do wrong and how should I proceed to determine what the exact problem is?

答: Maybe you have the same channel URI. Change it for second server. You can't use same URI for boths.</p>


问:
Get all mondays in the year
I always have problems figuring out dates functions

```<code>var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
</code>```

I am using this function to get all mondays in a month, current month.

How can I adapt this code to get all remaining mondays in the year?

答:
This is just an alternative, it uses a simpler method of getting the first day of the month.

// Get all Mondays in year from provided date
// Default today's date
function getMondays(d) {
  // Copy d if provided
  d = d ? new Date(+d) : new Date();
  // Set to start of month
  d.setDate(1);
  // Store end year and month
  var endYear = d.getFullYear() + 1;
  var endMonth = d.getMonth();

  // Set to first Monday
  d.setDate(d.getDate() + (8 - (d.getDay() || 7)) % 7);
  var mondays = [new Date(+d)];

  // Create Dates for all Mondays up to end year and month
  while (d.getFullYear() < endYear || d.getMonth() != endMonth) {
    mondays.push(new Date(d.setDate(d.getDate() + 7)));
  }
  return mondays;
}

// Get all Mondays and display result
// SO console doensn't show all results
var mondays = getMondays();
mondays.forEach(function(mon) {
  console.log(mon.toLocaleString(void 0, {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    year: 'numeric'
  }));
});

// Count of Mondays, not all shown in SO console
console.log('There are ' + mondays.length + ' Mondays, the first is ' + mondays[0].toString())```

Title: Get all mondays in the year

Body:
I always have problems figuring out dates functions

var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}

I am using this function to get all mondays in a month, current month.

How can I adapt this code to get all remaining mondays in the year?


问:
Test result reporting
I am using TestNG and Selenium webdriver via Java.

Is there any tool that can help generate detailed test results, for example, suppose I have a test case that fails more often than not, is there a tool that can statistically report those test cases that fail more often than the others like in a graph, or pie chart, etc?

答: Tesults - it handles all this including identifying recurring / continuing fails. In general it's a great central place for a team to view and assign failing tests. Please be aware that I work at Tesults.</p>

Title: Test result reporting


问:
Is Rectangle A = Rectangle(3, 4); equivalent to Rectangle A(3,4);?
Below is my code:

```<code>#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}
</code>```

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!

答:
Rectangle* C = new Rectangle(3,4);, there's grammar error in your code.

operator =(Rectangle& rho) is by-default defined returning reference. Thus, Rectangle B = Rectangle(3, 4); won't create tmp object as you described above.

Body:
Below is my code:

#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!


答:
Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

No, that isn't true, but it's not really your fault: this is confusing.

T obj2 = obj1 is not an assignment, but an initialisation.

So you're right that obj1 will be created first (in your case, a temporary), but obj2 will be constructed using the copy constructor, not default constructed then assigned-to.

For Rectangle C = new Rectangle(3, 4);, the only difference is that the memory space of the temporary variable is allocated to the heap instead of stack.

No, it won't compile, but Rectangle* C would. There are plenty of explanations of dynamic allocation here already.

Title: Is Rectangle A = Rectangle(3, 4); equivalent to Rectangle A(3,4);?


问:
uploading files from python to GCS
I'm able to list the buckets of GCS from Python boto.
Able to copy files to GCS using gsutil command.
Able to download files from GCS to compute instance using python API.
I have followed steps from below document.

https://cloud.google.com/storage/docs/xml-api/gspythonlibrary

Getting below error in uploading files from instance to GCS.

GSResponseError: 403 Forbidden
AccessDeniedAccess denied.Provided scope(s) are not authorized

答:
That generally happens when you did not include the storage scopes in the access scopes when you set up the vm.  Unfortunately you cannot change them after you start the vm, you will need to recreate it.

https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam

Title: uploading files from python to GCS


问:
What are these errors in my Unity project and how do I correct them?
    si.atlasOffsetX > systemInfo.atlasOffsetX || si.atlasOffsetY > systemInfo.atlasOffsetY

```<code>terrainInstanceHashes.find (instances[i].instanceID) != terrainInstanceHashes.end ()
</code>```

I have used baked light, terrain and some 3D box objects.

答: I ran into this issue today. It seems that ticking off "generating ligthmap UVS" when importing gameobjects was the culprit. I simply turned this off and all of those and the errors would disappear. As for prefabs with this error. You need to turn lightmap static off under the mesh renderer.</p>

Body:
    si.atlasOffsetX > systemInfo.atlasOffsetX || si.atlasOffsetY > systemInfo.atlasOffsetY

terrainInstanceHashes.find (instances[i].instanceID) != terrainInstanceHashes.end ()

I have used baked light, terrain and some 3D box objects.


问:
How to update mobile app UI(android and iOS) when web UI is changed
I had a requirement in our company by senior management.We are working on a business app that can create,initialise and submit a process.This is both for web and mobile.Below is the flow of the app.

User logins in to the app.

Creates a process(a process is a form) by using a drag and drop UI.

Created process is initialised and submitted for approval.

Above is the flow of the application.Now,the requirement for mobile is,once the process is created in web that has to be dynamically updated in the mobile app.

What will be the better approach for this kind of requirements.

**Note:**Please don't get confused with the term process.Creation of process is some thing like leave request process,HR processes etc which are just normal forms.

Technically speaking,need solution for a form customisation using a drag and drop that has to be updated in mobile dynamically when changes are made in web.

答:
If I understand your question correctly, then what you want to do is keep a process in sync between the web and your app.

You have two choices. You can either make a call to your API every x seconds and check if there are any changes. The other way would be to use WebSockets which allow you to push data from the server to the client instantly. (So you when there is a change you can notify the app and update immediately).

Both ways have advantages and disadvantages, especially when scaling your app. If you want to have a "real-time" feeling in our app, I would recommend using WebSockets.


问:
FFMPEG image not updating
THE INPUT FILES

An overlay image that has is being updated every 5 seconds by a Python script

A small MP4 file that will be looped by a concat input

An MP3 file as audio source

THE COMMAND (UPDATED)

This is the command I'm currently using to combine and stream the inputs.

```<code>ffmpeg -re -i music.mp3 -f concat -i videoincludes.txt
-r 1 -loop 1 -f image2 -i overlay.png
-c:v libx264 -c:a aac -shortest -crf 23 -pix_fmt yuv420p
-maxrate 2500k -bufsize 2500k -preset ultrafast -r 30 -g 60 -b:v 2000k -b:a 192k -ar 44100
-filter_complex "[1:v][2:v] overlay=0:0" -map 0:a -strict -2
-f flv rtmp://a.rtmp.youtube.com/live2/{key}
</code>```

Als tried using -framerate 1 instead of -r 1

THE ISSUE

So the issue is that the image doesn't always update. Sometimes it does update every couple seconds at the start but it stops updating after 10-20 seconds without any difference in log output and sometimes it just doesn't update.

I can however confirm that the image is being updated by the Python script but FFmpeg is just not picking this up.

I read setting the input format of the image to image2 should allow it to update so I am not sure what is wrong or what I can do to improve it.

答:
I'm working on the same task, and finally, I think, I found the answer.
Because streams different from each other we must reset their timestamps with setpts=PTS-STARTPTS to have them begin in the same zero timestamp . And, also, try to use image2pipe instead of image2.

This is your code with timestamp reset:

```<code>ffmpeg -re -i music.mp3 -f concat -i videoincludes.txt
-r 1 -loop 1 -f image2pipe -i overlay.png
-c:v libx264 -c:a aac -shortest -crf 23 -pix_fmt yuv420p
-maxrate 2500k -bufsize 2500k -preset ultrafast -r 30 -g 60 -b:v 2000k -b:a 192k -ar 44100
-filter_complex "[1:v]setpts=PTS-STARTPTS[out_main]; [2:v]setpts=PTS-STARTPTS[out_overlay]; [out_main][out_overlay]overlay=0:0" -map 0:a -strict -2
-f flv rtmp://a.rtmp.youtube.com/live2/{key}
</code>```

p.s and I think, there is no need in -r or -framerate anymore

Title: FFMPEG image not updating

Body:
THE INPUT FILES

An overlay image that has is being updated every 5 seconds by a Python script

A small MP4 file that will be looped by a concat input

An MP3 file as audio source

THE COMMAND (UPDATED)

This is the command I'm currently using to combine and stream the inputs.

ffmpeg -re -i music.mp3 -f concat -i videoincludes.txt
-r 1 -loop 1 -f image2 -i overlay.png
-c:v libx264 -c:a aac -shortest -crf 23 -pix_fmt yuv420p
-maxrate 2500k -bufsize 2500k -preset ultrafast -r 30 -g 60 -b:v 2000k -b:a 192k -ar 44100
-filter_complex "[1:v][2:v] overlay=0:0" -map 0:a -strict -2
-f flv rtmp://a.rtmp.youtube.com/live2/{key}

Als tried using -framerate 1 instead of -r 1

THE ISSUE

So the issue is that the image doesn't always update. Sometimes it does update every couple seconds at the start but it stops updating after 10-20 seconds without any difference in log output and sometimes it just doesn't update.

I can however confirm that the image is being updated by the Python script but FFmpeg is just not picking this up.

I read setting the input format of the image to image2 should allow it to update so I am not sure what is wrong or what I can do to improve it.

Body:
I'm working on the same task, and finally, I think, I found the answer.
Because streams different from each other we must reset their timestamps with setpts=PTS-STARTPTS to have them begin in the same zero timestamp . And, also, try to use image2pipe instead of image2.

This is your code with timestamp reset:

ffmpeg -re -i music.mp3 -f concat -i videoincludes.txt
-r 1 -loop 1 -f image2pipe -i overlay.png
-c:v libx264 -c:a aac -shortest -crf 23 -pix_fmt yuv420p
-maxrate 2500k -bufsize 2500k -preset ultrafast -r 30 -g 60 -b:v 2000k -b:a 192k -ar 44100
-filter_complex "[1:v]setpts=PTS-STARTPTS[out_main]; [2:v]setpts=PTS-STARTPTS[out_overlay]; [out_main][out_overlay]overlay=0:0" -map 0:a -strict -2
-f flv rtmp://a.rtmp.youtube.com/live2/{key}

p.s and I think, there is no need in -r or -framerate anymore


问:
How to write the expression "img[markers == -1] = [255,0,0]" in C++ OpenCV?
I'm trying to convert the OpenCV Python example here to C++.
I'm stuck in this line:

```<code>img[markers == -1] = [255,0,0]
</code>```

where both img and markers are matrices.

What is the efficient way to write this in C++ OpenCV?

答:
Since I've already written some code to back my comments up, it would be a waste not to write it up.

NB: Testing it on an i7-4930k, with MSVC 2013, OpenCV 3.1, 64bit. Using a randomly generated input image and mask (~9% is set to -1).

As Miki stated, the simplest way to do this in C++ is to use:

cv::MatExpr operator== (const cv::Mat& a, double s) to create a mask

which you the use in cv::Mat::setTo(...)

For example:

```<code>void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    img.setTo(value, markers == target);
}
</code>```

Even though this creates an intermediate mask Mat, it's still efficient enough for vast majority of cases (roughly 2.9 ms per 2^20 pixels).

So what if you feel this is really not good enough and you want to have a shot at writing something faster?

Let's begin with something simple -- iterate rows and columns and use cv::Mat::at.

```<code>void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    for (int32_t r(0); r < img.rows; ++r) {
        for (int32_t c(0); c < img.cols; ++c) {
            if (markers.at<int32_t>(r, c) == target) {
                img.at<cv::Vec3b>(r, c) = value;
            }
        }
    }
}
</code>```

A little better, ~2.4 ms per iteration.

Let's try using Mat iterators instead.

```<code>void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    cv::Mat3b::iterator it_img(img.begin());
    cv::Mat1i::const_iterator it_mark(markers.begin());
    cv::Mat1i::const_iterator it_mark_end(markers.end());

    for (; it_mark != it_mark_end; ++it_mark, ++it_img) {
        if (*it_mark == target) {
            *it_img = value;
        }
    }
}
</code>```

This doesn't seem to help in my case, ~3.1 ms per iteration.

Time to drop the gloves -- let's use pointers to the pixel data. We've got to be careful and account for discontinuous Mats (e.g. when you have ROI from a larger Mat) -- let's do processing row at a time.

```<code>void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    for (int32_t r(0); r < img.rows; ++r) {
        uint8_t* it_img(img.ptr<uint8_t>(r));
        int32_t const* it_mark(markers.ptr<int32_t>(r));
        int32_t const* it_mark_end(it_mark + markers.cols);

        for (; it_mark != it_mark_end; ++it_mark, it_img += 3) {
            if (*it_mark == target) {
                it_img[0] = value[0];
                it_img[1] = value[1];
                it_img[2] = value[2];
            }
        }
    }
}
</code>```

This is a step forward, ~1.9 ms per iteration.

The next easiest step with OpenCV could be parallelizing this -- we can take advantage of cv::parallel_for_. Let's split the work by rows, so we can reuse the previous algorithm.

```<code>class ParallelSWMM : public cv::ParallelLoopBody
{
public:
    ParallelSWMM(cv::Mat3b& img
        , cv::Vec3b value
        , cv::Mat1i const& markers
        , int32_t target)
        : img_(img)
        , value_(value)
        , markers_(markers)
        , target_(target)
    {
        CV_Assert(img.size == markers.size);
    }

    virtual void operator()(cv::Range const& range) const
    {
        for (int32_t r(range.start); r < range.end; ++r) {
            uint8_t* it_img(img_.ptr<uint8_t>(r));
            int32_t const* it_mark(markers_.ptr<int32_t>(r));
            int32_t const* it_mark_end(it_mark + markers_.cols);

            for (; it_mark != it_mark_end; ++it_mark, it_img += 3) {
                if (*it_mark == target_) {
                    it_img[0] = value_[0];
                    it_img[1] = value_[1];
                    it_img[2] = value_[2];
                }
            }
        }
    }

    ParallelSWMM& operator=(ParallelSWMM const&)
    {
        return *this;
    };

private:
    cv::Mat3b& img_;
    cv::Vec3b value_;
    cv::Mat1i const& markers_;
    int32_t target_;
};

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    ParallelSWMM impl(img, value, markers, target);
    cv::parallel_for_(cv::Range(0, img.rows), impl);
}
</code>```

This one runs at 0.5 ms.

Let's take a step back -- the in my case the original approach runs single threaded. What if we parallelized that? We can just replace the operator() in the above code with the following:

```<code>    virtual void operator()(cv::Range const& range) const
    {
        img_.rowRange(range).setTo(value_, markers_.rowRange(range) == target_);
    }
</code>```

That runs at around 0.9 ms.

That seems about it for the reasonable implementations. We could have a shot at vectorizing this, but this is far from trivial (pixels are 3 bytes, we have to deal with alignment, etc.) -- let's not go into that, although it could be a nice excercise for the curious reader. However, since we're around 10 clock cycles per pixel even for the worst approach, there's not much potential for improvement.

Make your pick. In general I'd go with the first approach, and worry about it only once measurements identify this particular operation as a bottleneck.

Body:
I'm trying to convert the OpenCV Python example here to C++.
I'm stuck in this line:

img[markers == -1] = [255,0,0]

where both img and markers are matrices.

What is the efficient way to write this in C++ OpenCV?

Body:
Since I've already written some code to back my comments up, it would be a waste not to write it up.

NB: Testing it on an i7-4930k, with MSVC 2013, OpenCV 3.1, 64bit. Using a randomly generated input image and mask (~9% is set to -1).

As Miki stated, the simplest way to do this in C++ is to use:

cv::MatExpr operator== (const cv::Mat& a, double s) to create a mask

which you the use in cv::Mat::setTo(...)

For example:

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    img.setTo(value, markers == target);
}

Even though this creates an intermediate mask Mat, it's still efficient enough for vast majority of cases (roughly 2.9 ms per 2^20 pixels).

So what if you feel this is really not good enough and you want to have a shot at writing something faster?

Let's begin with something simple -- iterate rows and columns and use cv::Mat::at.

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    for (int32_t r(0); r < img.rows; ++r) {
        for (int32_t c(0); c < img.cols; ++c) {
            if (markers.at<int32_t>(r, c) == target) {
                img.at<cv::Vec3b>(r, c) = value;
            }
        }
    }
}

A little better, ~2.4 ms per iteration.

Let's try using Mat iterators instead.

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    cv::Mat3b::iterator it_img(img.begin());
    cv::Mat1i::const_iterator it_mark(markers.begin());
    cv::Mat1i::const_iterator it_mark_end(markers.end());

    for (; it_mark != it_mark_end; ++it_mark, ++it_img) {
        if (*it_mark == target) {
            *it_img = value;
        }
    }
}

This doesn't seem to help in my case, ~3.1 ms per iteration.

Time to drop the gloves -- let's use pointers to the pixel data. We've got to be careful and account for discontinuous Mats (e.g. when you have ROI from a larger Mat) -- let's do processing row at a time.

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    CV_Assert(img.size == markers.size);

    for (int32_t r(0); r < img.rows; ++r) {
        uint8_t* it_img(img.ptr<uint8_t>(r));
        int32_t const* it_mark(markers.ptr<int32_t>(r));
        int32_t const* it_mark_end(it_mark + markers.cols);

        for (; it_mark != it_mark_end; ++it_mark, it_img += 3) {
            if (*it_mark == target) {
                it_img[0] = value[0];
                it_img[1] = value[1];
                it_img[2] = value[2];
            }
        }
    }
}

This is a step forward, ~1.9 ms per iteration.

The next easiest step with OpenCV could be parallelizing this -- we can take advantage of cv::parallel_for_. Let's split the work by rows, so we can reuse the previous algorithm.

class ParallelSWMM : public cv::ParallelLoopBody
{
public:
    ParallelSWMM(cv::Mat3b& img
        , cv::Vec3b value
        , cv::Mat1i const& markers
        , int32_t target)
        : img_(img)
        , value_(value)
        , markers_(markers)
        , target_(target)
    {
        CV_Assert(img.size == markers.size);
    }

    virtual void operator()(cv::Range const& range) const
    {
        for (int32_t r(range.start); r < range.end; ++r) {
            uint8_t* it_img(img_.ptr<uint8_t>(r));
            int32_t const* it_mark(markers_.ptr<int32_t>(r));
            int32_t const* it_mark_end(it_mark + markers_.cols);

            for (; it_mark != it_mark_end; ++it_mark, it_img += 3) {
                if (*it_mark == target_) {
                    it_img[0] = value_[0];
                    it_img[1] = value_[1];
                    it_img[2] = value_[2];
                }
            }
        }
    }

    ParallelSWMM& operator=(ParallelSWMM const&)
    {
        return *this;
    };

private:
    cv::Mat3b& img_;
    cv::Vec3b value_;
    cv::Mat1i const& markers_;
    int32_t target_;
};

void set_where_markers_match(cv::Mat3b img
    , cv::Vec3b value
    , cv::Mat1i markers
    , int32_t target)
{
    ParallelSWMM impl(img, value, markers, target);
    cv::parallel_for_(cv::Range(0, img.rows), impl);
}

This one runs at 0.5 ms.

Let's take a step back -- the in my case the original approach runs single threaded. What if we parallelized that? We can just replace the operator() in the above code with the following:

    virtual void operator()(cv::Range const& range) const
    {
        img_.rowRange(range).setTo(value_, markers_.rowRange(range) == target_);
    }

That runs at around 0.9 ms.

That seems about it for the reasonable implementations. We could have a shot at vectorizing this, but this is far from trivial (pixels are 3 bytes, we have to deal with alignment, etc.) -- let's not go into that, although it could be a nice excercise for the curious reader. However, since we're around 10 clock cycles per pixel even for the worst approach, there's not much potential for improvement.

Make your pick. In general I'd go with the first approach, and worry about it only once measurements identify this particular operation as a bottleneck.


问:
Google Console Search API giving incorrect data
I am extracting Search Analytics data for some Property using search console API v3.
I am using googleapiclient library(Python) for making API call.
Python script making API request:

```<code>from googleapiclient import sample_tools

service, flags = sample_tools.init(['https://example.com/'], 'webmasters', 'v3', __doc__, __file__,
                                             # parents=[argparser],
                                              scope='https://www.googleapis.com/auth/webmasters.readonly')

rowlimit = 5000      #initialised variable to pass values of rowLimit and startRow
startrow = 0

request = {
               'startDate': '2017-05-10',
               'endDate': '2017-05-10',
               'dimensions': ['date','query'],
               'rowLimit': rowlimit,
               'aggregationType': 'byProperty',
               'startRow': startrow
}

response = execute_request(service, 'https://example.com/', request)
</code>```

We are getting response. Now there is one limitation that we can not give
rowLimit > 5000.

Now with each request we often don't get 5000 records. So for next iteration I am setting startRow value by record beyond what I got in first request.

i.e. startrow = startrow+record_count_in_first_request
So, second iteration will have
startRow:startrow

rowLimit:5000

Using this approach I can get all the result data for certain date range.

But now I am facing another issue. The metrics values that I extracted using API are not matching with console platform(UI) values.

                   I checked the sum of clicks, impression over a certain date range, it is not matching with UI values for same date range.
Why do you think that happens?

Again this is the case when I use
'dimensions': ['date', 'query']
on the other hand when I use
'dimensions': ['date', 'page'] then I am getting correct result. I have checked the results with console UI. This behaviour of console search API is quite confusing. Does anybody faced similar issue before. Is there any sampling of data?
Let me know if you need more information regarding the issue I am facing.
Thanks for you time.

答:
In short, when you use page in dimensions and you didn't specify aggregationType in your API call, then the aggregation type will be determined by the API service.

aggregationType determines how clicks and impressions are aggregated. When you use dimensions: date, query, the API will use byProperty aggregation type by default while date, page automatically choose byPage type. It is documented here.

Please have a read on this documentation for the difference between byProperty (or site) and byPage.

Body:
I am extracting Search Analytics data for some Property using search console API v3.
I am using googleapiclient library(Python) for making API call.
Python script making API request:

from googleapiclient import sample_tools

service, flags = sample_tools.init(['https://example.com/'], 'webmasters', 'v3', __doc__, __file__,
                                             # parents=[argparser],
                                              scope='https://www.googleapis.com/auth/webmasters.readonly')

rowlimit = 5000      #initialised variable to pass values of rowLimit and startRow
startrow = 0

request = {
               'startDate': '2017-05-10',
               'endDate': '2017-05-10',
               'dimensions': ['date','query'],
               'rowLimit': rowlimit,
               'aggregationType': 'byProperty',
               'startRow': startrow
}

response = execute_request(service, 'https://example.com/', request)

We are getting response. Now there is one limitation that we can not give
rowLimit > 5000.

Now with each request we often don't get 5000 records. So for next iteration I am setting startRow value by record beyond what I got in first request.

i.e. startrow = startrow+record_count_in_first_request
So, second iteration will have
startRow:startrow

rowLimit:5000

Using this approach I can get all the result data for certain date range.

But now I am facing another issue. The metrics values that I extracted using API are not matching with console platform(UI) values.

                   I checked the sum of clicks, impression over a certain date range, it is not matching with UI values for same date range.
Why do you think that happens?

Again this is the case when I use
'dimensions': ['date', 'query']
on the other hand when I use
'dimensions': ['date', 'page'] then I am getting correct result. I have checked the results with console UI. This behaviour of console search API is quite confusing. Does anybody faced similar issue before. Is there any sampling of data?
Let me know if you need more information regarding the issue I am facing.
Thanks for you time.


问:
Want to get session values when client sends new request
I want to get server's session value when client creates a new request.

But, server returns nil always.

I don't know what is the problem in this case.

Client

```<code>package main

import (
    "io/ioutil"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "client"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", cIndex)
    router.HandleFunc("/test", cTest)
    http.ListenAndServe(":7000", router)
}

func cIndex(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("cIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = "bar"
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:8080?foo=bar")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)

}

func cTest(w http.ResponseWriter, r *http.Request) {
    req, err := http.NewRequest("GET", "http://localhost:8080/test", nil)
    if err != nil {
        log.Println("cTest Request Error : ", err.Error())
        return
    }
    req.SetBasicAuth("sample_id", "sample_secret")
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    c := &http.Client{
        Transport: &http.Transport{},
    }
    resp, err := c.Do(req)
    if err != nil {
        log.Println("cTest Response Error : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("cTest Body Error : ", err.Error())
        return
    }
    log.Println(string(body))
}
</code>```

Server

```<code>package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "server"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", sIndex)
    router.HandleFunc("/test", sTest)
    http.ListenAndServe(":8080", router)
}

func sIndex(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    v := r.FormValue("foo")
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = v
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:7000/test")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)
}

func sTest(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sTest Session Error : ", err.Error())
        return
    }
    v, ok := session.Values["foo"].(string)
    if !ok {
        log.Printf("foo = %v\n", v)
    }
    data := struct {
        Foo string
    }{
        v, // I expected v is bar,but v was nil.
    }

    bytes, err := json.Marshal(data)
    if err != nil {
        log.Println("sTest JSON Error : ", err.Error())
        return
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(bytes)
}
</code>```

Details

Client sends request to server with query foo=bar.

Server receives the request and parsing.

Server saves query parameter in session.(I used gorilla/session)

Client makes *http.Client and send new Request to server.

Server receives request, and loads value in session, and set the value at response.

Client receives value bar

In 5, I expected that server can load the value bar from session, but session value was nil.

答:
I wrote some codes and it moves.
Is it correct way?

Client

```<code>func cTest(w http.ResponseWrite, r *http.Request) {
    serverURL := "http://localhost:8080/test"
    r.Method = http.MethodGet
    r.Host = serverURL  // server
    v, err := url.Parse(serverURL)
    if err != nil {
        log.Println("url parsing error occurred : ", err.Error())
        return
    }
    c := &http.Client{Transport: &http.Transport{}}
    resp, err := c.Transport.RoundTrip(r)
    if err != nil {
        log.Println("client roundtrip error occurred : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("response body reading error occurred : ", err.Error())
        return
    }
    w.Write(body)
}
</code>```

Body:
I want to get server's session value when client creates a new request.

But, server returns nil always.

I don't know what is the problem in this case.

Client

package main

import (
    "io/ioutil"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "client"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", cIndex)
    router.HandleFunc("/test", cTest)
    http.ListenAndServe(":7000", router)
}

func cIndex(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("cIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = "bar"
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:8080?foo=bar")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)

}

func cTest(w http.ResponseWriter, r *http.Request) {
    req, err := http.NewRequest("GET", "http://localhost:8080/test", nil)
    if err != nil {
        log.Println("cTest Request Error : ", err.Error())
        return
    }
    req.SetBasicAuth("sample_id", "sample_secret")
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    c := &http.Client{
        Transport: &http.Transport{},
    }
    resp, err := c.Do(req)
    if err != nil {
        log.Println("cTest Response Error : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("cTest Body Error : ", err.Error())
        return
    }
    log.Println(string(body))
}

Server

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var (
    store       *sessions.CookieStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
    session     *sessions.Session
    SessionName = "server"
)

func main() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   60 * 15,
        Secure:   false,
        HttpOnly: true,
    }
    router := mux.NewRouter()
    router.HandleFunc("/", sIndex)
    router.HandleFunc("/test", sTest)
    http.ListenAndServe(":8080", router)
}

func sIndex(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    v := r.FormValue("foo")
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sIndex Session Error : ", err.Error())
        return
    }
    session.Values["foo"] = v
    session.Save(r, w)
    w.Header().Set("Location", "http://localhost:7000/test")
    w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
    w.WriteHeader(http.StatusFound)
}

func sTest(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, SessionName)
    if err != nil {
        log.Println("sTest Session Error : ", err.Error())
        return
    }
    v, ok := session.Values["foo"].(string)
    if !ok {
        log.Printf("foo = %v\n", v)
    }
    data := struct {
        Foo string
    }{
        v, // I expected v is bar,but v was nil.
    }

    bytes, err := json.Marshal(data)
    if err != nil {
        log.Println("sTest JSON Error : ", err.Error())
        return
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(bytes)
}

Details

Client sends request to server with query foo=bar.

Server receives the request and parsing.

Server saves query parameter in session.(I used gorilla/session)

Client makes *http.Client and send new Request to server.

Server receives request, and loads value in session, and set the value at response.

Client receives value bar

In 5, I expected that server can load the value bar from session, but session value was nil.

Body:
I wrote some codes and it moves.
Is it correct way?

Client

func cTest(w http.ResponseWrite, r *http.Request) {
    serverURL := "http://localhost:8080/test"
    r.Method = http.MethodGet
    r.Host = serverURL  // server
    v, err := url.Parse(serverURL)
    if err != nil {
        log.Println("url parsing error occurred : ", err.Error())
        return
    }
    c := &http.Client{Transport: &http.Transport{}}
    resp, err := c.Transport.RoundTrip(r)
    if err != nil {
        log.Println("client roundtrip error occurred : ", err.Error())
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("response body reading error occurred : ", err.Error())
        return
    }
    w.Write(body)
}


问:
Codename One SQL database storing wrong values
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.

Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.

The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.

I like the interface and any kind help would be appreciated.

```<code>Database db = Display.getInstance().openOrCreate("MyDB.db");

db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");

String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);

// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input

String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);

//keeps adding "John" to the database, even though value has been changed to "James"

Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);

while (cur.next()) {
             System.out.println(dataText);
        }
</code>```

答:
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.

It should be:

```<code>Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
    Row currentRow = cur.getRow();
    String dataText = currentRow.getString("Date");
    System.out.println(dataText);
}
</code>```

If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.

I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.

Body:
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.

Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.

The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.

I like the interface and any kind help would be appreciated.

Database db = Display.getInstance().openOrCreate("MyDB.db");

db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");

String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);

// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input

String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);

//keeps adding "John" to the database, even though value has been changed to "James"

Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);

while (cur.next()) {
             System.out.println(dataText);
        }

Body:
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.

It should be:

Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
    Row currentRow = cur.getRow();
    String dataText = currentRow.getString("Date");
    System.out.println(dataText);
}

If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.

I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.


问:
Which AWS service to use to deploy Backend?
I have a website (static sitting in s3), content is served from s3. I am planning to write a rest api (node or open to suggestions). When the front end makes angular $http call, example  if my site is called example.com, then the call will be something like relative url (/Update) should be resolved.

I am not sure exactly, what type of aws service I should use to deploy my backend code.

Updated

I am using Codestar, using Express web service. Here is my template.yml. and routes. The code star build goes fine, but deployment fails.

template.yml

```<code>    AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar

Parameters:
  ProjectId:
    Type: String
    Description: AWS CodeStar projectID used to associate new resources to team members

Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
        PostEvent:
          Type: Api
          Properties:
            Path: /
            Method: post
  GetItemsBylId:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /api/getItemsBylId/:id
            Method: get
</code>```

Here is my app.js

```<code>var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send({
    "Output": "Hello World!"
  });
});

app.get('/api/GetItemsBylId/:id', function (req, res) {
    res.send({
      "Output": "I am up!"
    });
});
</code>```

Here is the error from deployment at GetItemsBylId

```<code>   Failed to set tags on AWS::Lambda::Function. IAM permissions lambda:ListTags, lambda:TagResource and lambda:UntagResource are required to tag AWS::Lambda::Function resources and to propagate stack level tags.
</code>```

I am pretty sure it's because of the id param.

Update

solved the tag issue using query params. Rather than using, resouce:id, I am now using ?id="".

答:
You should check out AWS Codestar.  </p>

<p>Single button push and you will have a fully running CI/CD pipeline and publicly available endpoint for you develop against. </p>

Body:
I have a website (static sitting in s3), content is served from s3. I am planning to write a rest api (node or open to suggestions). When the front end makes angular $http call, example  if my site is called example.com, then the call will be something like relative url (/Update) should be resolved.

I am not sure exactly, what type of aws service I should use to deploy my backend code.

Updated

I am using Codestar, using Express web service. Here is my template.yml. and routes. The code star build goes fine, but deployment fails.

template.yml

    AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar

Parameters:
  ProjectId:
    Type: String
    Description: AWS CodeStar projectID used to associate new resources to team members

Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
        PostEvent:
          Type: Api
          Properties:
            Path: /
            Method: post
  GetItemsBylId:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /api/getItemsBylId/:id
            Method: get

Here is my app.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send({
    "Output": "Hello World!"
  });
});

app.get('/api/GetItemsBylId/:id', function (req, res) {
    res.send({
      "Output": "I am up!"
    });
});

Here is the error from deployment at GetItemsBylId

   Failed to set tags on AWS::Lambda::Function. IAM permissions lambda:ListTags, lambda:TagResource and lambda:UntagResource are required to tag AWS::Lambda::Function resources and to propagate stack level tags.

I am pretty sure it's because of the id param.

Update

solved the tag issue using query params. Rather than using, resouce:id, I am now using ?id="".

Body:
You should check out AWS Codestar.

Single button push and you will have a fully running CI/CD pipeline and publicly available endpoint for you develop against.