问:
How to make requestbody controller works?
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

```<code>function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }
</code>```

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

```<code>@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

```<code>@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}
</code>```

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

答:
```<code>@ResponseBody public void createUser(@RequestParam(value="inscrit") String inscrit) throws Exception {
//System.out.println(inscrit.getNom());
//System.out.println(inscrit.getPrenom());

Inscrit ins = JSON.parseObject(inscrit, Inscrit.class);
System.out.println(ins.getEmail());
try {
    user.adduser(ins);
} catch (Exception e) {
    e.printStackTrace();
}  }
</code>```

The class of inscrit.java is nonstandard.You should change it to Inscrit.java.

I hope this helps.

Body:
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

Body:
@ResponseBody public void createUser(@RequestParam(value="inscrit") String inscrit) throws Exception {
//System.out.println(inscrit.getNom());
//System.out.println(inscrit.getPrenom());

Inscrit ins = JSON.parseObject(inscrit, Inscrit.class);
System.out.println(ins.getEmail());
try {
    user.adduser(ins);
} catch (Exception e) {
    e.printStackTrace();
}  }

The class of inscrit.java is nonstandard.You should change it to Inscrit.java.

I hope this helps.


来源: stackexchange

问:
jersey unit test with parameters error 500
I want to test a method with this declaration:

```<code>@GET
@Path("/hello")
public Response myMethod(@Context HttpServletRequest requestContext,
                         @QueryParam("key") String value){...}

 Response output = target("/hello/myMethod")
                   .queryParam("key", "value")
                   .request().get();
</code>```

but I get 500, internal server error, I know that it is because of the first parameter of my method (@Context HttpServletRequest requestContext) but I do not know how to solve it.

答:
The problem is that the Jersey test is not running inside a servlet environment, which is something that is required to work with the servlet APIs. If you are not aware, Jersey does not need to run inside a servlet container. If the case of using the provider-grizzly2, if you don't set up the test container, it will default to running the GrizzlyTestContainerFactory, which only starts Grizzly and an HTTP server, not a servlet container.

In order to configure the JerseyTest as a servlet container, we need to override two other methods, configurDeployment and getTestContainerFactory. With the latter, we need to return the GrizzlyWebTestContainerFactory, which will set up the servlet container. In the configureDeployment method, we can configure the application, at the servlet level.

public class ServletTest extends JersyTest {

```<code>@Override
public ResourceConfig configure() {
    // configure Jersey
}

@Override
public TestContainerFactory getTestContainerFactory() {
    return new GrizzlyWebTestContainerFactory();
}

@Override
public DeploymentContext configureDeployment() {
    return ServletDeploymentContext
            .forServlet(new ServletContainer(configure()))
            .build();
}
</code>```

}

If you are using the provider-inmemory, it doesn't support servlet deployment, so you will need to switch over to the jetty provider or the grizzly provider.

ContentLicense: CC BY-SA 3.0

Body:
I want to test a method with this declaration:

@GET
@Path("/hello")
public Response myMethod(@Context HttpServletRequest requestContext,
                         @QueryParam("key") String value){...}

 Response output = target("/hello/myMethod")
                   .queryParam("key", "value")
                   .request().get();

but I get 500, internal server error, I know that it is because of the first parameter of my method (@Context HttpServletRequest requestContext) but I do not know how to solve it.

Body:
The problem is that the Jersey test is not running inside a servlet environment, which is something that is required to work with the servlet APIs. If you are not aware, Jersey does not need to run inside a servlet container. If the case of using the provider-grizzly2, if you don't set up the test container, it will default to running the GrizzlyTestContainerFactory, which only starts Grizzly and an HTTP server, not a servlet container.

In order to configure the JerseyTest as a servlet container, we need to override two other methods, configurDeployment and getTestContainerFactory. With the latter, we need to return the GrizzlyWebTestContainerFactory, which will set up the servlet container. In the configureDeployment method, we can configure the application, at the servlet level.

public class ServletTest extends JersyTest {

@Override
public ResourceConfig configure() {
    // configure Jersey
}

@Override
public TestContainerFactory getTestContainerFactory() {
    return new GrizzlyWebTestContainerFactory();
}

@Override
public DeploymentContext configureDeployment() {
    return ServletDeploymentContext
            .forServlet(new ServletContainer(configure()))
            .build();
}

}

If you are using the provider-inmemory, it doesn't support servlet deployment, so you will need to switch over to the jetty provider or the grizzly provider.


问:
javascript function doesn't responding
Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().

```<code>function checkJs()
{
   debugger;
   alert("your output!!!");
}
</code>```

My code:

```<code><div id="mydivid" style="background-color:lightblue;">
   STAGE
</div>
<input type="button" id="btnid" value="Load Data" />
</code>```

When i click a button , Its just call the jQuery click function

```<code>$(document).ready(function () {
   $("#btnid").click(function (event) {
      debugger;
      $.getScript('mydata.js', function() {
         // debugger;
          checkJs();
      });

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

I used initialy 1.12.4.js library file in the head tag

and i added my external js file in head tag.

what is the problem in my code. why the button click did not reached the external method.

答:
1.Make sure that jQuery library added before your external java-script file.

When you ensure the first point do like below:-

```<code>$(document).ready(function () {
    $("#btnid").click(function (event) {
       checkJs();
    });
});
</code>```

2.If you want to use $.getScript() then do like below:-

```<code>$(document).ready(function () {
    $("#btnid").click(function (event) {
      $.getScript('mydata.js').done(function(data, textStatus) { // check the file path of mydata.js is correct or not?
         checkJs();
      });
    });
});
</code>```

The above code will work only when you have jQuery library added before this code and you remove the external JavaScript file path from your head.

Note:-

data:- returned data from external script

textStatus:- status of the call to external script (plain-text like "Success")

For more knowledge check this link:- jQuery.getScript()

Title: javascript function doesn't responding

Body:
Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().

function checkJs()
{
   debugger;
   alert("your output!!!");
}

My code:

   STAGE

<input type="button" id="btnid" value="Load Data" />

When i click a button , Its just call the jQuery click function

$(document).ready(function () {
   $("#btnid").click(function (event) {
      debugger;
      $.getScript('mydata.js', function() {
         // debugger;
          checkJs();
      });

   });
});

I used initialy 1.12.4.js library file in the head tag

and i added my external js file in head tag.

what is the problem in my code. why the button click did not reached the external method.

Body:
1.Make sure that jQuery library added before your external java-script file.

When you ensure the first point do like below:-

$(document).ready(function () {
    $("#btnid").click(function (event) {
       checkJs();
    });
});

2.If you want to use $.getScript() then do like below:-

$(document).ready(function () {
    $("#btnid").click(function (event) {
      $.getScript('mydata.js').done(function(data, textStatus) { // check the file path of mydata.js is correct or not?
         checkJs();
      });
    });
});

The above code will work only when you have jQuery library added before this code and you remove the external JavaScript file path from your head.

Note:-

data:- returned data from external script

textStatus:- status of the call to external script (plain-text like "Success")

For more knowledge check this link:- jQuery.getScript()


问:
Improving the readability of the scatterplot in ggpairs, ggplot
I am using the Auto dataset from the ISLR library and the function ggpairs() from gpairs library to create a scatterplot of all possible combinations of variables.  My code is the following:

```<code>data(Auto)
setDT(Auto)
ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
                    diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
     theme(axis.text.x = element_text(angle = 90, hjust = 1))
</code>```

The plot is the one below:

There are some issues with this plot:

The axes tick labels are not readable.  How could I remove the numbers and possibly rotate the tick lables to be vertical to the axes?

How could I enforce different colors for the combo pairs (categorical - continuous)

Your advice will be appreciated.

答:
Maybe the proposed solution is not a perfect match with your wishes, but I hope it helps.

You need to invoke more libraries to get the code to work.

You will need to have factors to "force" the categorical variables to be known as such.

The following code may do the trick:

```<code>library(ISLR)
library(data.table)
library(GGally)
library(ggplot2)
data(Auto, package = "ISLR")

# remove unwanted column and make categorical variables
Auto2 <- Auto[, -9]
Auto2$cylinders <- factor(Auto2$cylinders)
Auto2$origin <- factor(Auto2$origin)

ggpairs(Auto2 ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
        diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))
</code>```

This yields the following picture:

Please let me know whether this is what you want.

Body:
I am using the Auto dataset from the ISLR library and the function ggpairs() from gpairs library to create a scatterplot of all possible combinations of variables.  My code is the following:

data(Auto)
setDT(Auto)
ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
                    diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
     theme(axis.text.x = element_text(angle = 90, hjust = 1))

The plot is the one below:

There are some issues with this plot:

The axes tick labels are not readable.  How could I remove the numbers and possibly rotate the tick lables to be vertical to the axes?

How could I enforce different colors for the combo pairs (categorical - continuous)

Your advice will be appreciated.

Body:
Maybe the proposed solution is not a perfect match with your wishes, but I hope it helps.

You need to invoke more libraries to get the code to work.

You will need to have factors to "force" the categorical variables to be known as such.

The following code may do the trick:

library(ISLR)
library(data.table)
library(GGally)
library(ggplot2)
data(Auto, package = "ISLR")

# remove unwanted column and make categorical variables
Auto2 <- Auto[, -9]
Auto2$cylinders <- factor(Auto2$cylinders)
Auto2$origin <- factor(Auto2$origin)

ggpairs(Auto2 ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
        diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))

This yields the following picture:

Please let me know whether this is what you want.


问:
Image resizer with azure blob storage. Returns "403 forbidden" when going through the resizer
We have been using image resizer with azurereader2 for quite a while with no problem. After a small release (that really shouldnt have anything to do with this) we suddenly get errors when we try to access the images through the resizer.

This is only a problem on our test environment, the new release and image resizer etc. works just fine in production.
Both production and test is hosted in azure, and both use their own azure blob storage.

example url:
test.mysite.com/images/pim/b6ffa894-bc8f-4f1b-a1e8-ef115b78a56f.jpg?width=250&height=312&format=jpg&scale=both&mode=pad

returns the following error

```
Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase`1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.c__DisplayClass13.b__12(RESTCommand`1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobClient.cs:line 788
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
   --- End of inner exception stack trace ---
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.EndGetBlobReferenceFromServer(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobClient.cs:line 630
   at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.c__DisplayClass1`1.b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ImageResizer.Plugins.AzureReader2.AzureReader2Plugin.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ImageResizer.Util.AsyncUtils.RunSync[TResult](Func`1 func)
   at ImageResizer.Storage.Blob.Open() in C:\projects\resizer\Plugins\ImageResizer.Storage\Blob.cs:line 41
   at ImageResizer.ImageBuilder.GetStreamFromSource(Object source, ResizeSettings settings, Boolean& disposeStream, String& path, Boolean& restoreStreamPosition)
   at ImageResizer.ImageBuilder.LoadImage(Object source, ResizeSettings settings, Boolean restoreStreamPos)
   at ImageResizer.ImageBuilder.BuildJob(ImageJob job)
   at ImageResizer.ImageBuilder.Build(ImageJob job)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource, Boolean addFileExtension)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings)
   at ImageResizer.InterceptModule.c__DisplayClass5_0.b__1(Stream stream)
   at ImageResizer.Plugins.DiskCache.CustomDiskCache.c__DisplayClass28_0.b__0()
   at ImageResizer.Plugins.DiskCache.LockProvider.TryExecute(String key, Int32 timeoutMs, LockCallback success)
   at ImageResizer.Plugins.DiskCache.CustomDiskCache.GetCachedFile(String keyBasis, String extension, ResizeImageDelegate writeCallback, Int32 timeoutMs, Boolean asynchronous)
   at ImageResizer.Plugins.DiskCache.DiskCache.Process(IResponseArgs e)
   at ImageResizer.Plugins.DiskCache.DiskCache.Process(HttpContext context, IResponseArgs e)
   at ImageResizer.InterceptModule.HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf)
   at XXX.Web.Modules.CustomImageResizingInterceptModule.HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf) in E:\TeamCity\buildAgent\work\4773e55a378b97a1\src\Portal\Portal\Infrastructure\Web\Modules\CustomImageResizingInterceptModule.cs:line 15
   at ImageResizer.InterceptModule.CheckRequest_PostAuthorizeRequest(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request Information
RequestID:e8c13071-0001-00c2-437e-d8b9c7000000
RequestDate:Mon, 29 May 2017 13:19:16 GMT
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

```

the url
test.mysite.com/images/pim/b6ffa894-bc8f-4f1b-a1e8-ef115b78a56f.jpg  correctly redirects to the image in the azure blob.

I have tried regenerating the access key for the blob storage, without any luck.

I have tried pointing to another blob storage from our test env, that does not work either.

I can access the test blob storage just fine from my local environment.

/resizer.debug reports 0 issues detected.

Any help is greatly appreciated, let me know if i can provide additional info.

答: This is purely a azure blob storage connection problem, image resizer is not the culprit.</p>

Body:
We have been using image resizer with azurereader2 for quite a while with no problem. After a small release (that really shouldnt have anything to do with this) we suddenly get errors when we try to access the images through the resizer.

This is only a problem on our test environment, the new release and image resizer etc. works just fine in production.
Both production and test is hosted in azure, and both use their own azure blob storage.

example url:
test.mysite.com/images/pim/b6ffa894-bc8f-4f1b-a1e8-ef115b78a56f.jpg?width=250&height=312&format=jpg&scale=both&mode=pad

returns the following error

Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase`1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.c__DisplayClass13.b__12(RESTCommand`1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobClient.cs:line 788
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
   --- End of inner exception stack trace ---
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient.EndGetBlobReferenceFromServer(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobClient.cs:line 630
   at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.c__DisplayClass1`1.b__0(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 66
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ImageResizer.Plugins.AzureReader2.AzureReader2Plugin.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ImageResizer.Util.AsyncUtils.RunSync[TResult](Func`1 func)
   at ImageResizer.Storage.Blob.Open() in C:\projects\resizer\Plugins\ImageResizer.Storage\Blob.cs:line 41
   at ImageResizer.ImageBuilder.GetStreamFromSource(Object source, ResizeSettings settings, Boolean& disposeStream, String& path, Boolean& restoreStreamPosition)
   at ImageResizer.ImageBuilder.LoadImage(Object source, ResizeSettings settings, Boolean restoreStreamPos)
   at ImageResizer.ImageBuilder.BuildJob(ImageJob job)
   at ImageResizer.ImageBuilder.Build(ImageJob job)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource, Boolean addFileExtension)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource)
   at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings)
   at ImageResizer.InterceptModule.c__DisplayClass5_0.b__1(Stream stream)
   at ImageResizer.Plugins.DiskCache.CustomDiskCache.c__DisplayClass28_0.b__0()
   at ImageResizer.Plugins.DiskCache.LockProvider.TryExecute(String key, Int32 timeoutMs, LockCallback success)
   at ImageResizer.Plugins.DiskCache.CustomDiskCache.GetCachedFile(String keyBasis, String extension, ResizeImageDelegate writeCallback, Int32 timeoutMs, Boolean asynchronous)
   at ImageResizer.Plugins.DiskCache.DiskCache.Process(IResponseArgs e)
   at ImageResizer.Plugins.DiskCache.DiskCache.Process(HttpContext context, IResponseArgs e)
   at ImageResizer.InterceptModule.HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf)
   at XXX.Web.Modules.CustomImageResizingInterceptModule.HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFile vf) in E:\TeamCity\buildAgent\work\4773e55a378b97a1\src\Portal\Portal\Infrastructure\Web\Modules\CustomImageResizingInterceptModule.cs:line 15
   at ImageResizer.InterceptModule.CheckRequest_PostAuthorizeRequest(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request Information
RequestID:e8c13071-0001-00c2-437e-d8b9c7000000
RequestDate:Mon, 29 May 2017 13:19:16 GMT
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

the url
test.mysite.com/images/pim/b6ffa894-bc8f-4f1b-a1e8-ef115b78a56f.jpg  correctly redirects to the image in the azure blob.

I have tried regenerating the access key for the blob storage, without any luck.

I have tried pointing to another blob storage from our test env, that does not work either.

I can access the test blob storage just fine from my local environment.

/resizer.debug reports 0 issues detected.

Any help is greatly appreciated, let me know if i can provide additional info.


问:
Getting list of my manager's directs except few of them using my employee id
I have an employee table with EmployeeId, ReportsToEmployeeId column, which gives list of employees in an org and whom the employee reports to.

```<code>EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP3        EMP1
EMP4        EMP1
EMP5        EMP1
EMP6        EMP1
EMP7        EMP1
</code>```

I also have one more table - AssistantManager. This table specified under a manager, few of the directs act as assistant manager (team lead). This table contains two column, AssistantManagerEmployeeId, ReportsToEmployeeId.

```<code>AssistantManagerEmployeeId, ReportsToEmployeeId
EMP3                        EMP1
EMP6                        EMP1
</code>```

Consider I am one of the Assistant Manager (EMP3) of a Manager (EMP1). I need to query list of my manager's (EMP1) directs except AssistantManagers (EMP3, EMP6). So the result should contains -

```<code>EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP4        EMP1
EMP5        EMP1
EMP7        EMP1
</code>```

I am writing the query as below

```<code>SELECT *
FROM Employee
JOIN AssistantManager ON AssistantManager.ReportsToEmployeeId = Employee.ReportsToEmployeeId
WHERE AssistantManager.AssistantManagerEmployeeId = @MyEmployeeId
AND Employee.EmployeeId NOT IN
(
-- Gives list of Assistant Managers who as under my manager
SELECT OtherRec.AssistantManagerEmployeeId
FROM AssistantManager myRec
JOIN AssistantManager OtherRec ON OtherRec.ReportsToEmployeeId = myRec.ReportsToEmployeeId
Where myRec.AssistantManagerEmployeeId = @MyEmployeeId
)
</code>```

Please let me know a query that more efficient. I am actually looking if possible to write without a sub query.

Many Thanks, Thirumalai M

答:
Your query should be like below for better efficiency

```<code>SELECT
  E.*--- everything from Employee table
FROM Employee E
  JOIN
  AssistantManager AM
        ON  E.ReportsToEmployeeId =AM.ReportsToEmployeeId  AND AM.AssistantManagerEmployeeId=@MyEmployeeId -- check to include your manager's directs
  WHERE NOT EXISTS -- check to exclude all AMs under your manager
    (
        SELECT 1
        FROM AssistantManager AM2
        WHERE
            AM2.ReportsToEmployeeId=AM.ReportsToEmployeeId AND
            E.EmployeeID= AM2.AssistantManagerEmployeeId
    )
</code>```

Sample output:

Body:
I have an employee table with EmployeeId, ReportsToEmployeeId column, which gives list of employees in an org and whom the employee reports to.

EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP3        EMP1
EMP4        EMP1
EMP5        EMP1
EMP6        EMP1
EMP7        EMP1

I also have one more table - AssistantManager. This table specified under a manager, few of the directs act as assistant manager (team lead). This table contains two column, AssistantManagerEmployeeId, ReportsToEmployeeId.

AssistantManagerEmployeeId, ReportsToEmployeeId
EMP3                        EMP1
EMP6                        EMP1

Consider I am one of the Assistant Manager (EMP3) of a Manager (EMP1). I need to query list of my manager's (EMP1) directs except AssistantManagers (EMP3, EMP6). So the result should contains -

EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP4        EMP1
EMP5        EMP1
EMP7        EMP1

I am writing the query as below

SELECT *
FROM Employee
JOIN AssistantManager ON AssistantManager.ReportsToEmployeeId = Employee.ReportsToEmployeeId
WHERE AssistantManager.AssistantManagerEmployeeId = @MyEmployeeId
AND Employee.EmployeeId NOT IN
(
-- Gives list of Assistant Managers who as under my manager
SELECT OtherRec.AssistantManagerEmployeeId
FROM AssistantManager myRec
JOIN AssistantManager OtherRec ON OtherRec.ReportsToEmployeeId = myRec.ReportsToEmployeeId
Where myRec.AssistantManagerEmployeeId = @MyEmployeeId
)

Please let me know a query that more efficient. I am actually looking if possible to write without a sub query.

Many Thanks, Thirumalai M

Body:
Your query should be like below for better efficiency

SELECT
  E.*--- everything from Employee table
FROM Employee E
  JOIN
  AssistantManager AM
        ON  E.ReportsToEmployeeId =AM.ReportsToEmployeeId  AND AM.AssistantManagerEmployeeId=@MyEmployeeId -- check to include your manager's directs
  WHERE NOT EXISTS -- check to exclude all AMs under your manager
    (
        SELECT 1
        FROM AssistantManager AM2
        WHERE
            AM2.ReportsToEmployeeId=AM.ReportsToEmployeeId AND
            E.EmployeeID= AM2.AssistantManagerEmployeeId
    )

Sample output:


问:
Tensorflow Attempting to use uninitialized value AUC/AUC/auc/false_positives
I'm training a CNN using for image classification. Due to the limited size of my data set I'm using transfer learning. Basically, I'm using the pre-trained network Google is proving in its retrain example (https://www.tensorflow.org/tutorials/image_retraining).

The model works great and gives a very good accuracy. But my dataset is highly imbalance which mean accuracy is not the best metric to judge the performance of the model.

By looking into different solutions, some suggested changing the sampling method or the performance metric used. I'm choosing to go with the later.

Tensorflow provides a good verity of metrics including, AUC, precision, recall, etc.

Now, here is the code of the retraing model:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py

I'm adding the following to add_evaluation_step(result_tensor, ground_truth_tensor) function:

```<code>  with tf.name_scope('AUC'):
    with tf.name_scope('prediction'):
        prediction = tf.argmax(result_tensor, 1)
    with tf.name_scope('AUC'):
        auc_value = tf.metrics.auc(tf.argmax(ground_truth_tensor, 1), prediction, curve='ROC')

  tf.summary.scalar('accuracy', evaluation_step)
  tf.summary.scalar('AUC', auc_value)
</code>```

But I'm getting this error:

Traceback (most recent call last):   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 1135, in
      tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/platform/app.py",
  line 44, in run
      _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 911, in main
      ground_truth_input: train_ground_truth})   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 767, in run
      run_metadata_ptr)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 965, in _run
      feed_dict_string, options, run_metadata)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 1015, in _do_run
      target_list, options, run_metadata)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 1035, in _do_call
      raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError:
  Attempting to use uninitialized value AUC/AUC/auc/false_positives

  [[Node: AUC/AUC/auc/false_positives/read = IdentityT=DT_FLOAT,
  _class=["loc:@AUC/AUC/auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Caused by op u'AUC/AUC/auc/false_positives/read', defined at:   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 1135, in
      tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/platform/app.py",
  line 44, in run
      _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 874, in main
      final_tensor, ground_truth_input)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 806, in add_evaluation_step
      auc_value, update_op = tf.metrics.auc(tf.argmax(ground_truth_tensor, 1), prediction,
  curve='ROC')   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 555, in auc
      labels, predictions, thresholds, weights)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 473, in _confusion_matrix_at_thresholds
      false_p = _create_local('false_positives', shape=[num_thresholds])   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 177, in _create_local
      validate_shape=validate_shape)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/variables.py",
  line 226, in init
      expected_shape=expected_shape)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/variables.py",
  line 344, in _init_from_args
      self._snapshot = array_ops.identity(self._variable, name="read")   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/gen_array_ops.py",
  line 1490, in identity
      result = _op_def_lib.apply_op("Identity", input=input, name=name)   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/op_def_library.py",
  line 768, in apply_op
      op_def=op_def)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/ops.py",
  line 2402, in create_op
      original_op=self._default_original_op, op_def=op_def)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/ops.py",
  line 1264, in init
      self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use
  uninitialized value AUC/AUC/auc/false_positives    [[Node:
  AUC/AUC/auc/false_positives/read = IdentityT=DT_FLOAT,
  _class=["loc:@AUC/AUC/auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

But I don't understand why is this because in the main I have this:

```<code>init = tf.global_variables_initializer()
sess.run(init)
</code>```

答:
try this:</p>

```<code>init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init)
</code>```

Body:
I'm training a CNN using for image classification. Due to the limited size of my data set I'm using transfer learning. Basically, I'm using the pre-trained network Google is proving in its retrain example (https://www.tensorflow.org/tutorials/image_retraining).

The model works great and gives a very good accuracy. But my dataset is highly imbalance which mean accuracy is not the best metric to judge the performance of the model.

By looking into different solutions, some suggested changing the sampling method or the performance metric used. I'm choosing to go with the later.

Tensorflow provides a good verity of metrics including, AUC, precision, recall, etc.

Now, here is the code of the retraing model:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py

I'm adding the following to add_evaluation_step(result_tensor, ground_truth_tensor) function:

  with tf.name_scope('AUC'):
    with tf.name_scope('prediction'):
        prediction = tf.argmax(result_tensor, 1)
    with tf.name_scope('AUC'):
        auc_value = tf.metrics.auc(tf.argmax(ground_truth_tensor, 1), prediction, curve='ROC')

  tf.summary.scalar('accuracy', evaluation_step)
  tf.summary.scalar('AUC', auc_value)

But I'm getting this error:

Traceback (most recent call last):   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 1135, in
      tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/platform/app.py",
  line 44, in run
      _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 911, in main
      ground_truth_input: train_ground_truth})   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 767, in run
      run_metadata_ptr)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 965, in _run
      feed_dict_string, options, run_metadata)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 1015, in _do_run
      target_list, options, run_metadata)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/client/session.py",
  line 1035, in _do_call
      raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError:
  Attempting to use uninitialized value AUC/AUC/auc/false_positives

  [[Node: AUC/AUC/auc/false_positives/read = IdentityT=DT_FLOAT,
  _class=["loc:@AUC/AUC/auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Caused by op u'AUC/AUC/auc/false_positives/read', defined at:   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 1135, in
      tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/platform/app.py",
  line 44, in run
      _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 874, in main
      final_tensor, ground_truth_input)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/examples/image_retraining/retrain.py",
  line 806, in add_evaluation_step
      auc_value, update_op = tf.metrics.auc(tf.argmax(ground_truth_tensor, 1), prediction,
  curve='ROC')   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 555, in auc
      labels, predictions, thresholds, weights)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 473, in _confusion_matrix_at_thresholds
      false_p = _create_local('false_positives', shape=[num_thresholds])   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/metrics_impl.py",
  line 177, in _create_local
      validate_shape=validate_shape)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/variables.py",
  line 226, in init
      expected_shape=expected_shape)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/variables.py",
  line 344, in _init_from_args
      self._snapshot = array_ops.identity(self._variable, name="read")   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/ops/gen_array_ops.py",
  line 1490, in identity
      result = _op_def_lib.apply_op("Identity", input=input, name=name)   File
  "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/op_def_library.py",
  line 768, in apply_op
      op_def=op_def)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/ops.py",
  line 2402, in create_op
      original_op=self._default_original_op, op_def=op_def)   File "/home/user_2/tensorflow/bazel-bin/tensorflow/examples/image_retraining/retrain.runfiles/org_tensorflow/tensorflow/python/framework/ops.py",
  line 1264, in init
      self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use
  uninitialized value AUC/AUC/auc/false_positives    [[Node:
  AUC/AUC/auc/false_positives/read = IdentityT=DT_FLOAT,
  _class=["loc:@AUC/AUC/auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

But I don't understand why is this because in the main I have this:

init = tf.global_variables_initializer()
sess.run(init)

Body:
try this:

init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init)


问:
Logical breakdown for dot net namespace hierarchy
I am looking for a reference/links that give good high level logical breakdown of the dot net namespace.

And if it has some indicators to individual frameworks like what's specific to asp.net, wcf, wpf, wwf etc.

Any links/references/diagrams are highly appreciated.

Update

I found one poster for .net 4.0.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
How to modify only one element in a react .map function?
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case? </p>

```<code>changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>
        <div className="commentHolder" key={i}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}
</code>```

答:
I suggest breaking this into two components. The CommentList and the Comment component.

comment-list.js

```<code>import Comment from './comment';

class CommentList extends Component{
    render(){
    return(
        <div>
        <ul className="list-group">
                {Object.values(this.props.commentInfo).map((data) =>
                data.map((secondData, i) =>
                    <Comment text={secondData.text} category={secondData.category} organization={secondData.organization} key={secondData.key} />
      )
        </ul>
      </div>
    )
  }
}
</code>```

comment.js

```<code>class Comment extends Component {
    constructor(props){
    super(props);
    this.state = {
        isReply: false
    }
  }
  changeIsReply = () => {
    this.setState(
      {isReply: !this.state.isReply,}
    );
  }
    render(){
    const {text, category, organization, key} = this.props;
    return(
      <div className="commentHolder" key={i}>
        <p>{text}</p>
        <p>{category}</p>
        <p>{organization}</p>
        <button> UpButton </button> <br />
        <button> DownButton </button>
        <button onClick = {this.changeIsReply} > Reply </button>
        {this.state.isReply ? <SetComment id={key} /> : null}
      </div>
    )
  }
}

export default Comment;
</code>```

This way each comment has control over its own state and whether or not to show the SetComment component.

Try to make more components instead of putting all markup in a single render method. This also helps organize your code so that you are mapping each set of values to a component which I feel makes it a little easier to wrap your head around.

Body:
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case?

changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (

    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>

{secondData.text}

{secondData.category}

{secondData.organization}

            <button> UpButton </button>

            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}

      )
    )}

  )
}

Body:
I suggest breaking this into two components. The CommentList and the Comment component.

comment-list.js

import Comment from './comment';

class CommentList extends Component{
    render(){
    return(
        <div>
        <ul className="list-group">
                {Object.values(this.props.commentInfo).map((data) =>
                data.map((secondData, i) =>
                    <Comment text={secondData.text} category={secondData.category} organization={secondData.organization} key={secondData.key} />
      )
        </ul>
      </div>
    )
  }
}

comment.js

class Comment extends Component {
    constructor(props){
    super(props);
    this.state = {
        isReply: false
    }
  }
  changeIsReply = () => {
    this.setState(
      {isReply: !this.state.isReply,}
    );
  }
    render(){
    const {text, category, organization, key} = this.props;
    return(
      <div className="commentHolder" key={i}>
        <p>{text}</p>
        <p>{category}</p>
        <p>{organization}</p>
        <button> UpButton </button> <br />
        <button> DownButton </button>
        <button onClick = {this.changeIsReply} > Reply </button>
        {this.state.isReply ? <SetComment id={key} /> : null}
      </div>
    )
  }
}

export default Comment;

This way each comment has control over its own state and whether or not to show the SetComment component.

Try to make more components instead of putting all markup in a single render method. This also helps organize your code so that you are mapping each set of values to a component which I feel makes it a little easier to wrap your head around.


问:
Run Node.js using VBA
The overall goal is to run Node.js on a JavaScript file and scrape the output using MS Access VBA. Here's the JavaScript file I'm using to test:

```<code>// C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js

var fs = require("fs");
var outputFile = "testLog.txt";

fs.writeFile(outputFile, new Date());
</code>```

When I run this from the command prompt as follows, it generates a testLog.txt file with a timestamp in the Interview Prep folder.

```<code>C:\Users\micha\OneDrive\AppAcademy\Interview Prep>node tst.js
</code>```

Now I want to trigger the same thing using VBA from within an Access app. I've tried it two ways. The first is quick and dirty, but my understanding is that I can flesh it out with StdOut for the scraping bit. It uses WScript.Shell:

```<code>Private Sub runShellTest_Click()
    Dim objShell As Object, objExec As Object
    Set objShell = CreateObject("WScript.Shell")
    Set objExec = objShell.Exec("C:\Program Files\nodejs\node.exe C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js")
End Sub
</code>```

When I run it, a command prompt briefly flashes onscreen, but I don't get a new testLog.txt.

The other way I tried is even quicker and dirtier:

```<code>Private Sub runShellTest_Click()
    MsgBox (Shell("C:\Program Files\nodejs\node.exe C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js", vbNormalFocus))
End Sub
</code>```

Again, the command prompt flashes up briefly, and there's no new testLog.txt. However, the message box shows a task ID as expected, so I guess... something happened?

Any help is appreciated!

答: When you run it like this, the file will get generated at the Access executable's location. Please check where your Access is installed location, you should find the file there. In node code you will have to also pass the path where the file needs to be generated. </p>

Title: Run Node.js using VBA

Body:
The overall goal is to run Node.js on a JavaScript file and scrape the output using MS Access VBA. Here's the JavaScript file I'm using to test:

// C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js

var fs = require("fs");
var outputFile = "testLog.txt";

fs.writeFile(outputFile, new Date());

When I run this from the command prompt as follows, it generates a testLog.txt file with a timestamp in the Interview Prep folder.

C:\Users\micha\OneDrive\AppAcademy\Interview Prep>node tst.js

Now I want to trigger the same thing using VBA from within an Access app. I've tried it two ways. The first is quick and dirty, but my understanding is that I can flesh it out with StdOut for the scraping bit. It uses WScript.Shell:

Private Sub runShellTest_Click()
    Dim objShell As Object, objExec As Object
    Set objShell = CreateObject("WScript.Shell")
    Set objExec = objShell.Exec("C:\Program Files\nodejs\node.exe C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js")
End Sub

When I run it, a command prompt briefly flashes onscreen, but I don't get a new testLog.txt.

The other way I tried is even quicker and dirtier:

Private Sub runShellTest_Click()
    MsgBox (Shell("C:\Program Files\nodejs\node.exe C:\Users\micha\OneDrive\AppAcademy\Interview Prep\tst.js", vbNormalFocus))
End Sub

Again, the command prompt flashes up briefly, and there's no new testLog.txt. However, the message box shows a task ID as expected, so I guess... something happened?

Any help is appreciated!


问:
Splitting declaration and initialization using RASCAL
I'm new to Rascal and experimenting with its transformation/term rewriting abilities.

I want to write a script that splits declarations like:

int x = 5;

into declaration/initializations like:

int x;
x = 5;

How might I go about this? Let's say the language I'm trying to transform is Java.

Thanks for any help.

答:
I have some more code examples here, which use concrete syntax matching and substitution to arrive at what you want:

```<code>module JavaMatch

import lang::java::\syntax::Java15;

// this just replaces exactly these specific kinds of declarations, as the only statement in a block:
CompilationUnit splitInitializersSimple(CompilationUnit u) = visit(u) {
    case (Block) `{ int i = 0; }` => (Block) `{int i; i = 0;}`
};

// the next generalizes over any type, variable name or expression, but still one statement in a block:
CompilationUnit splitInitializersSingle(CompilationUnit u) = visit(u) {
    case (Block) `{ <Type t> <Id i> = <Expr e>; }`
      => (Block) `{<Type t> <Id i>; <Id i> = <Expr e>;}`
};

// Now we allow more statements around the declaration, and we simply leave them where they are
CompilationUnit splitInitializersInContext(CompilationUnit u) = visit(u) {
    case (Block) `{ <BlockStm* pre>
                 '  <Type t> <Id i> = <Expr e>;
                 '  <BlockStm* post>
                 '}`
      => (Block) `{ <BlockStm* pre>
                 '  <Type t> <Id i>;
                 '  <Id i> = <Expr e>;
                 '  <BlockStm* post>
                 '}`
};

// But there could be more initializers in the same decl as well, as in int i, j = 0, k; :
CompilationUnit splitInitializersInContext2(CompilationUnit u) = visit(u) {
case (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>= <Expr e>, <{VarDec ","}+ b>;
             '  <BlockStm* post>
             '}`
  => (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>, <{VarDec ","}+ b>;
             '  <Id i> = <Expr e>;
             '  <BlockStm* post>
             '}`
};

// and now we add `innermost` such that not only the first but all occurrences are replaced:
CompilationUnit splitInitializersInContext2(CompilationUnit u) = innermost visit(u) {
case (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>= <Expr e>, <{VarDec ","}+ b>;
             '  <BlockStm* post>
             '}`
  => (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>, <{VarDec ","}+ b>;
             '  <Id i> = <Expr e>;
             '  <BlockStm* post>
             '}`
};

void doIt(loc file) {
  start[CompilationUnit] unit = parse(#start[CompilationUnit], file);
  unit.top = splitInitializersInContext(unit.top);
  writeFile(file, "<unit>");
}
</code>```

Final remarks, because this is still not fully general:

taking care of modifiers and array types; this will just add more variables to match and carry to the right hand side

the initializers will now occur in reverse order as statements, and in case of data dependency between them this would break

note that the shape of the rule is dependent very much on the Java grammar, since we use concrete syntax matching here. It helps to browse the grammar while you create such code.

this code preserves comments in many places, but not all, in particular in between declarations which are rewritten and in between vardecs which are rewritten the comments will be lost using this code.

Body:
I have some more code examples here, which use concrete syntax matching and substitution to arrive at what you want:

module JavaMatch

import lang::java::\syntax::Java15;

// this just replaces exactly these specific kinds of declarations, as the only statement in a block:
CompilationUnit splitInitializersSimple(CompilationUnit u) = visit(u) {
    case (Block) `{ int i = 0; }` => (Block) `{int i; i = 0;}`
};

// the next generalizes over any type, variable name or expression, but still one statement in a block:
CompilationUnit splitInitializersSingle(CompilationUnit u) = visit(u) {
    case (Block) `{ <Type t> <Id i> = <Expr e>; }`
      => (Block) `{<Type t> <Id i>; <Id i> = <Expr e>;}`
};

// Now we allow more statements around the declaration, and we simply leave them where they are
CompilationUnit splitInitializersInContext(CompilationUnit u) = visit(u) {
    case (Block) `{ <BlockStm* pre>
                 '  <Type t> <Id i> = <Expr e>;
                 '  <BlockStm* post>
                 '}`
      => (Block) `{ <BlockStm* pre>
                 '  <Type t> <Id i>;
                 '  <Id i> = <Expr e>;
                 '  <BlockStm* post>
                 '}`
};

// But there could be more initializers in the same decl as well, as in int i, j = 0, k; :
CompilationUnit splitInitializersInContext2(CompilationUnit u) = visit(u) {
case (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>= <Expr e>, <{VarDec ","}+ b>;
             '  <BlockStm* post>
             '}`
  => (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>, <{VarDec ","}+ b>;
             '  <Id i> = <Expr e>;
             '  <BlockStm* post>
             '}`
};

// and now we add `innermost` such that not only the first but all occurrences are replaced:
CompilationUnit splitInitializersInContext2(CompilationUnit u) = innermost visit(u) {
case (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>= <Expr e>, <{VarDec ","}+ b>;
             '  <BlockStm* post>
             '}`
  => (Block) `{ <BlockStm* pre>
             '  <Type t> <{VarDec ","}+ a>, <Id i>, <{VarDec ","}+ b>;
             '  <Id i> = <Expr e>;
             '  <BlockStm* post>
             '}`
};

void doIt(loc file) {
  start[CompilationUnit] unit = parse(#start[CompilationUnit], file);
  unit.top = splitInitializersInContext(unit.top);
  writeFile(file, "<unit>");
}

Final remarks, because this is still not fully general:

taking care of modifiers and array types; this will just add more variables to match and carry to the right hand side

the initializers will now occur in reverse order as statements, and in case of data dependency between them this would break

note that the shape of the rule is dependent very much on the Java grammar, since we use concrete syntax matching here. It helps to browse the grammar while you create such code.

this code preserves comments in many places, but not all, in particular in between declarations which are rewritten and in between vardecs which are rewritten the comments will be lost using this code.


问:
Python logging, how to write info to 2 separate
I'm trying log to different StringIOs. I would've expected that each logger would write to each StringIO that was instantiated and given to. But that's not working, only the first StringIO stores the logged info.
Any suggestions on what I'm missing?

```<code>    import logging
    from StringIO import StringIO
    formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

    log_stream1 = StringIO()
    log1 = logging.getLogger('a')
    log1.setLevel(logging.DEBUG)
    stream_handler1 = logging.StreamHandler(log_stream1)
    stream_handler1.setLevel(logging.INFO)
    stream_handler1.setFormatter(formatter)
    log1.addHandler(stream_handler1)

    log_stream2 = StringIO()
    log2 = logging.getLogger('b')
    log2.setLevel(logging.DEBUG)
    stream_handler2 = logging.StreamHandler(log_stream2)
    stream_handler2.setLevel(logging.INFO)
    stream_handler2.setFormatter(formatter)
    log2.addHandler(stream_handler1)

    log1.info('log1')
    log2.info('log2')
</code>```

output:

```<code>    In [6]: log_stream1.getvalue()
    Out[6]: '2017-06-08 10:05:12,468 a   INFO log1\n2017-06-08 10:05:12,468 b   INFO log2\n'

    In [7]: log_stream2.getvalue()
    Out[7]: ''
</code>```

答:
You wrote log2.addHandler(stream_handler1).
You should write log2.addHandler(stream_handler2).

Body:
I'm trying log to different StringIOs. I would've expected that each logger would write to each StringIO that was instantiated and given to. But that's not working, only the first StringIO stores the logged info.
Any suggestions on what I'm missing?

    import logging
    from StringIO import StringIO
    formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

    log_stream1 = StringIO()
    log1 = logging.getLogger('a')
    log1.setLevel(logging.DEBUG)
    stream_handler1 = logging.StreamHandler(log_stream1)
    stream_handler1.setLevel(logging.INFO)
    stream_handler1.setFormatter(formatter)
    log1.addHandler(stream_handler1)

    log_stream2 = StringIO()
    log2 = logging.getLogger('b')
    log2.setLevel(logging.DEBUG)
    stream_handler2 = logging.StreamHandler(log_stream2)
    stream_handler2.setLevel(logging.INFO)
    stream_handler2.setFormatter(formatter)
    log2.addHandler(stream_handler1)

    log1.info('log1')
    log2.info('log2')

output:

    In [6]: log_stream1.getvalue()
    Out[6]: '2017-06-08 10:05:12,468 a   INFO log1\n2017-06-08 10:05:12,468 b   INFO log2\n'

    In [7]: log_stream2.getvalue()
    Out[7]: ''


问:
serialize a datetime as an integer timestamp
I would like for django rest to not convert my DateTime model field into a string date represtation when serializing it.

```<code>response_date = serializers.DateTimeField(source="updated_at")
</code>```

I would like this to come out as

1411880508

and not

"2014-09-28T05:01:48.123"

答:
Global Configuration:</p>

```<code>REST_FRAMEWORK = {
    'DATETIME_FORMAT': '%s.%f',
}
</code>```

Body:
I would like for django rest to not convert my DateTime model field into a string date represtation when serializing it.

response_date = serializers.DateTimeField(source="updated_at")

I would like this to come out as

1411880508

and not

"2014-09-28T05:01:48.123"

Body:
Global Configuration:

REST_FRAMEWORK = {
    'DATETIME_FORMAT': '%s.%f',
}


问:
NullPointerException while testing Spring boot camel application
```<code>public class MyRouteTest extends CamelSpringTestSupport {

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.scan("com.mypackage.routes");
        ctx.refresh();
        return ctx;
    }
    @Test
    public void testRouteRunning() throws Exception {
       assertTrue(context().getRouteStatus("direct:start").isStarted());
    }
}
</code>```

getRouteStatus is returning null I am following this to write my test cases

Any pointers on how to fix this will be very helpful.

答:
You need to use the id of the route, not the url, eg "direct:start" is the url of the route, the route has an id as well. If you do not specify an id, then an id is auto assigned such as route1, route2 etc.

Use .routeId("myNameHere") to specify the id of a route.

Body:
public class MyRouteTest extends CamelSpringTestSupport {

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.scan("com.mypackage.routes");
        ctx.refresh();
        return ctx;
    }
    @Test
    public void testRouteRunning() throws Exception {
       assertTrue(context().getRouteStatus("direct:start").isStarted());
    }
}

getRouteStatus is returning null I am following this to write my test cases

Any pointers on how to fix this will be very helpful.


问:
How to add a github library dependency with ASP.Net Core
I created an asp.net core project using just the command line program dotnet.

Is it possible to add dependencies for libraries found on github without downloading it manually and adding the library to the /bin folder?

I know there is a dotnet restore command, but not sure if that would be to pull down dependencies that I add to my project.

Is there a specific file to add dependencies?

答:
You can't add dependency libraries ("packages") directly from GitHub, they should be published on NuGet (most of them are there) or similar.

Usually, library authors put link to NuGet directly in their project description page ion GitHub.

When you known package name on NuGet, you can run this:

```<code>dotnet add package <packagename>
</code>```

And package will be added to your project (open projectname.csproj file in notepad - you will see all packages there).

Now you should run dotnet restore to actually download package to your machine.

More details about dotnet command is here

Body:
You can't add dependency libraries ("packages") directly from GitHub, they should be published on NuGet (most of them are there) or similar.

Usually, library authors put link to NuGet directly in their project description page ion GitHub.

When you known package name on NuGet, you can run this:

dotnet add package <packagename>

And package will be added to your project (open projectname.csproj file in notepad - you will see all packages there).

Now you should run dotnet restore to actually download package to your machine.

More details about dotnet command is here


问:
Store custom class in UserDefaults
I'm trying to store a custom class in user defaults but throughs an exception

terminating with uncaught exception of type NSException

My class is as follows: Transactions

```<code>import Foundation
import SwiftyJSON
class Transactions: NSObject,NSCoding {
    var transOBJ = [JSON]()
    init(transOBJ:[JSON]) {
        self.transOBJ = transOBJ
    }
    required convenience init(coder aDecoder:NSCoder) {
        let obj = aDecoder.decodeObject(forKey: "OBJ") as! [JSON]
        self.init(transOBJ: obj)
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(transOBJ, forKey: "OBJ")
    }
}
</code>```

The exception is throwing on aCoder.encode(transOBJ, forKey: "OBJ")

The code for saving in user defaults is:

```<code>let trans = [Transactions(transOBJ: self.transactionObjs)]
var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: trans)
userDefaults.set(encodedData, forKey: "transactions")
userDefaults.synchronize()
</code>```

Update 1

I am calling the user defaults inside the Alamofire request function. Then it is giving an error
But when I call it outside Alamofire request function, then it runs just fine. What should I do?
I want to save it inside the success of alamofire but can't do it

答:
Thank you Tj3n. JSON also need to conform NSCoding. Just Transactions isn't enough. I created different variables for string and integers in the Transactions NSObject, extracted data from JSON, stored extracted data in the variables declared and then encoded and decoded them accordingly. It worked.

If there is another way, I'm all ears.

Title: Store custom class in UserDefaults

Body:
I'm trying to store a custom class in user defaults but throughs an exception

terminating with uncaught exception of type NSException

My class is as follows: Transactions

import Foundation
import SwiftyJSON
class Transactions: NSObject,NSCoding {
    var transOBJ = [JSON]()
    init(transOBJ:[JSON]) {
        self.transOBJ = transOBJ
    }
    required convenience init(coder aDecoder:NSCoder) {
        let obj = aDecoder.decodeObject(forKey: "OBJ") as! [JSON]
        self.init(transOBJ: obj)
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(transOBJ, forKey: "OBJ")
    }
}

The exception is throwing on aCoder.encode(transOBJ, forKey: "OBJ")

The code for saving in user defaults is:

let trans = [Transactions(transOBJ: self.transactionObjs)]
var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: trans)
userDefaults.set(encodedData, forKey: "transactions")
userDefaults.synchronize()

Update 1

I am calling the user defaults inside the Alamofire request function. Then it is giving an error
But when I call it outside Alamofire request function, then it runs just fine. What should I do?
I want to save it inside the success of alamofire but can't do it


问:
Selecting unique lines based on two columns in mysql
I've been trying to figure out a way to select lines that are unique based on the values of two columns. For example, here is a sample/example of my file:

```<code>s      r
10    12
10    13
14    10
10    12
14    10
12    10
</code>```

And this is what I want my output to look like:

```<code>s      r
10    12
10    13
14    10
</code>```

I've tried to use this code

```<code>SELECT * FROM `message` WHERE (`s_id`=$b_id or 'r_id'=$b_id) GROUP BY
r_id
</code>```

However, it only select 10,12  10,11 and i also needed 14,10 i mean the third row

in this case $b_id is obtained from session and it may be s or r

答:
You can try to use DISTINCT
SELECT DISTINCT s_id,r_id FROMmessageWHERE (s_id=$b_id or 'r_id'=$b_id);
always try to specify which column needed instead of * (all) it improve the performance

Body:
I've been trying to figure out a way to select lines that are unique based on the values of two columns. For example, here is a sample/example of my file:

s      r
10    12
10    13
14    10
10    12
14    10
12    10

And this is what I want my output to look like:

s      r
10    12
10    13
14    10

I've tried to use this code

SELECT * FROM `message` WHERE (`s_id`=$b_id or 'r_id'=$b_id) GROUP BY
r_id

However, it only select 10,12  10,11 and i also needed 14,10 i mean the third row

in this case $b_id is obtained from session and it may be s or r


问:
Updating Ruby via RVM issue, seems to be a problem with libxml
I was about to start my first Rails 3 app and thought I would upgrade to the latest version of ruby before I did and the ruby fails to make correctly.

I'm using Snow leopard on the 32bit kernal at the moment and every time I try and run 1.9.2 whether it's through readline or ssl I still get the following error:

```<code>ld: warning: in ../../libruby.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
ld: in /Developer/SDKs/MacOSX10.6.sdk/usr/local/lib/libxml2.2.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
collect2: ld returned 1 exit status
make[1]: *** [../../.ext/i386-darwin10.5.0/tcltklib.bundle] Error 1
</code>```

I tried using the 64 kernal using this among other as a guide http://www.markhneedham.com/blog/2010/07/08/installing-ruby-1-9-2-with-rvm-on-snow-leopard/  but then I get a similar message saying libxml1.dylib is failing because it's not set up to 64bit.

Has anyone got any ideas? it's driving me nuts...

答:
Ok for anyone having the same issue as me I would suggest going to 64bit kernal - if your not sure how go here

I would then follow this excellent blog post

The only other thing I need to do above this post was as well as updating libxml I also had to update libxlst (which you can download from the same source).  Once I ran the install checked it was pointing to the the correct kernal then everything updated fine.

Hope that helps anyone having the same issue!

Body:
I was about to start my first Rails 3 app and thought I would upgrade to the latest version of ruby before I did and the ruby fails to make correctly.

I'm using Snow leopard on the 32bit kernal at the moment and every time I try and run 1.9.2 whether it's through readline or ssl I still get the following error:

ld: warning: in ../../libruby.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
ld: in /Developer/SDKs/MacOSX10.6.sdk/usr/local/lib/libxml2.2.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
collect2: ld returned 1 exit status
make[1]: *** [../../.ext/i386-darwin10.5.0/tcltklib.bundle] Error 1

I tried using the 64 kernal using this among other as a guide http://www.markhneedham.com/blog/2010/07/08/installing-ruby-1-9-2-with-rvm-on-snow-leopard/  but then I get a similar message saying libxml1.dylib is failing because it's not set up to 64bit.

Has anyone got any ideas? it's driving me nuts...


问:
Bottom navigation overlapping recycler view contents in android
I am using bottom navigation view and displaying three tabs,In one of the tab i have added recycler view, but the contents are overlapped by bottom navigation.Not able to scroll recycler view.Is there any way that i can  hide the bottom navigation when i scroll item on recycler view.

```<code><?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:sv="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".activity.patient.PatientsActivity">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <RelativeLayout
            android:id="@+id/asd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:orientation="vertical">

            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />

            <android.support.design.widget.BottomNavigationView
                android:id="@+id/bottom_navigation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                app:itemBackground="@color/white"
                app:layout_behavior=".BottomNavigationBehavior"
                app:menu="@menu/bottom_navigation_main" />
        </RelativeLayout>
    </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.DrawerLayout>
</code>```

image

答:
add NestedScrollView just before RecyclerView this may work like above</p>

```<code> <android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />
 </android.support.v4.widget.NestedScrollView>
</code>```

Body:
I am using bottom navigation view and displaying three tabs,In one of the tab i have added recycler view, but the contents are overlapped by bottom navigation.Not able to scroll recycler view.Is there any way that i can  hide the bottom navigation when i scroll item on recycler view.

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:sv="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".activity.patient.PatientsActivity">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <RelativeLayout
            android:id="@+id/asd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:orientation="vertical">

            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />

            <android.support.design.widget.BottomNavigationView
                android:id="@+id/bottom_navigation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                app:itemBackground="@color/white"
                app:layout_behavior=".BottomNavigationBehavior"
                app:menu="@menu/bottom_navigation_main" />
        </RelativeLayout>
    </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.DrawerLayout>

image

Body:
add NestedScrollView just before RecyclerView this may work like above

 <android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />
 </android.support.v4.widget.NestedScrollView>


问:
How to change the value of the drop-down on change event?
I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:

```<code>$("select#code").on("change", function () {
         getNameFunc($(this).val())
});

$("select#empName").on("change", function () {
         getCodeFunc($(this).val())
});

function getNameFunc(value) {
   $.ajax({
        url: '@Url.Action("getName", "Employees")',
        data: { id: value },
        cache: false,
        type: "GET",
        success: function (data) {
               $("#empName").val(data.Name);
        }
    });
}

function getCodeFunc(value) {
     $.ajax({
          url: '@Url.Action("getCode", "Employees")',
          data: { id: value },
          cache: false,
          type: "GET",
          success: function (data) {
               $("#code").val(data.Code);
          }
    });
}
</code>```

My drop-down list:

```<code>@Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
@Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })
</code>```

In alert function, I am getting expected value but the problem is displaying it in to drop-down list.

答:
Check this code. You might get help from this.
Note that I have not implemented ajax call in this code.

$("#emp_code").on("change",function(){
    $("#emp_name").val($("#emp_code").val());
});

$("#emp_name").on("change",function(){
    $("#emp_code").val($("#emp_name").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Emp Code:</label>
<select id="emp_code">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<br/>
<label>Emp Name:</label>
<select id="emp_name">
  <option value="1">ABC</option>
  <option value="2">XYZ</option>
  <option value="3">PQR</option>
  <option value="4">JKL</option>
</select></code>```

Body:
I have two drop-down lists which are from same table. One contains employee code and second one contains employee name. If I change the employee code then other drop-down should show the employee name relevant to code and if I change the employee name then it should show the code. I am able to successfully retrieve the values but I am unable to show value in the drop-down. Following is my code:

$("select#code").on("change", function () {
         getNameFunc($(this).val())
});

$("select#empName").on("change", function () {
         getCodeFunc($(this).val())
});

function getNameFunc(value) {
   $.ajax({
        url: '@Url.Action("getName", "Employees")',
        data: { id: value },
        cache: false,
        type: "GET",
        success: function (data) {
               $("#empName").val(data.Name);
        }
    });
}

function getCodeFunc(value) {
     $.ajax({
          url: '@Url.Action("getCode", "Employees")',
          data: { id: value },
          cache: false,
          type: "GET",
          success: function (data) {
               $("#code").val(data.Code);
          }
    });
}

My drop-down list:

@Html.DropDownList("EmpCode", null, htmlAttributes: new { id = "code" })
@Html.DropDownList("EmpName", null, htmlAttributes: new { id = "empName" })

In alert function, I am getting expected value but the problem is displaying it in to drop-down list.

Body:
Check this code. You might get help from this.
Note that I have not implemented ajax call in this code.

$("#emp_code").on("change",function(){
    $("#emp_name").val($("#emp_code").val());
});

$("#emp_name").on("change",function(){
    $("#emp_code").val($("#emp_name").val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Emp Code:</label>
<select id="emp_code">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<br/>
<label>Emp Name:</label>
<select id="emp_name">
  <option value="1">ABC</option>
  <option value="2">XYZ</option>
  <option value="3">PQR</option>
  <option value="4">JKL</option>
</select>


问:
PHP Pass variable to next page
It seems pretty simple but I can't find a good way to do it.

Say in the first page I create a variable

```<code>$myVariable = "Some text";
</code>```

And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).

How can I achieve this?

Thanks!

答:
try this code

using hidden field we can pass php varibale to another page

page1.php

```<code><?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>
</code>```

pass php variable to hidden field value so you can access this variable into another page

page2.php

```<code><?php
 $text=$_POST['text'];
 echo $text;
?>
</code>```

Title: PHP Pass variable to next page

Body:
It seems pretty simple but I can't find a good way to do it.

Say in the first page I create a variable

$myVariable = "Some text";

And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).

How can I achieve this?

Thanks!

Body:
try this code

using hidden field we can pass php varibale to another page

page1.php

<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>

pass php variable to hidden field value so you can access this variable into another page

page2.php

<?php
 $text=$_POST['text'];
 echo $text;
?>


问:
Angular2 - Set A Different Color to an element Depending On Value
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

```<code>.red {
    color: red;
}

.green {
    color: green;
}
</code>```

XXX.component.css

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>
</code>```

答:
You can use it like this:</p>

```<code> <div class="card template-card" [ngClass]="{'z-depth-3': template == selectedTemplate, 'not-selected': !(template == selectedTemplate) && selectedTemplate != null}">
</code>```

Body:
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

.red {
    color: red;
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">

hello {{proportion}}

Body:
You can use it like this:

 <div class="card template-card" [ngClass]="{'z-depth-3': template == selectedTemplate, 'not-selected': !(template == selectedTemplate) && selectedTemplate != null}">


问:
is there a way to read only new (unread) messages in kafka consumer?
in consumer when subscribed to a topic and start consuming messages it read the messages from the the beginning is there any way to read only unread messages ? this is the code i used for consuming the messages.</p>

```<code>  Properties props = new Properties();
  props.put("bootstrap.servers", "localhost:9092");
  props.put("group.id", "test");
  props.put("enable.auto.commit", "true");
  props.put("auto.commit.interval.ms", "1000");
  props.put("session.timeout.ms", "30000");
  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");

  KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

  //Kafka Consumer subscribes list of topics here.
  consumer.subscribe(Arrays.asList(topicName));

  while (true) {
      ConsumerRecords<String, String> records = consumer.poll(100);
      for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value= %s\n", record.offset(), record.key(), record.value());

  }
</code>```

答: i have try your code, and it read only unread messages. what's your client version and server version?</p>

Body:
in consumer when subscribed to a topic and start consuming messages it read the messages from the the beginning is there any way to read only unread messages ? this is the code i used for consuming the messages.

  Properties props = new Properties();
  props.put("bootstrap.servers", "localhost:9092");
  props.put("group.id", "test");
  props.put("enable.auto.commit", "true");
  props.put("auto.commit.interval.ms", "1000");
  props.put("session.timeout.ms", "30000");
  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");

  KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

  //Kafka Consumer subscribes list of topics here.
  consumer.subscribe(Arrays.asList(topicName));

  while (true) {
      ConsumerRecords<String, String> records = consumer.poll(100);
      for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value= %s\n", record.offset(), record.key(), record.value());

  }