问:
Can't get correct icmpv6 checksum
Need to write a tool where i need to construct the whole ICMPv6 packet. I can't seem to get the code to generate correct ICMPv6 checksum. I have tried the checksum(void * buffer, int bytes) function from the following

Calculating checksum of ICMPv6 Packet in C

I have a wireshark capture that I am using to verify the checksum. The original packet content looks like

0000   33 33 00 00 00 01 38 ea a7 89 be 59 86 dd 60 00
0010   00 00 00 20 3a ff fe 80 00 00 00 00 00 00 88 c5
0020   75 41 aa 0c 58 ee ff 02 00 00 00 00 00 00 00 00
0030   00 00 00 00 00 01 88 00 b8 cc 20 00 00 00 fe 80
0040   00 00 00 00 00 00 88 c5 75 41 aa 0c 58 ee 02 01
0050   38 ea a7 89 be 59

The correct checksum ofcourse from the packet is 0xb8cc. The packet above is the whole IPv6 packet but the relevant content of the packet starts from source address which is fe 80 00 00 00 00 00 00 88 c5 75 41 aa 0c 58 ee
. ICMPv6 header starts at 88 00.

I think the checksum function from the link above might be correct but the buffer I am constructing to calculate checksum on is probably incorrect. Following the RFCs, I constructed the buffer by concatenating source addr, dest addr, packet length (32 = 00 20), Next header (58 = 3a), rest of ICMPv6 packet which gives me the final buffer of

uint8_t packet[] = {
                0xfe , 0x80 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00 ,
                0x88 , 0xc5 ,0x75 , 0x41 ,0xaa , 0x0c ,0x58 , 0xee,
                0xff , 0x02 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00,
                0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x01,
                0x00 , 0x20 ,0x3a , 0x88 ,0x00 , 0x00 ,0x00 ,
                0x20 , 0x00 ,0x00 , 0x00 ,0xfe , 0x80 ,0x00 , 0x00 ,
                0x00 , 0x00 ,0x00 , 0x00 ,0x88 , 0xc5 ,0x75 , 0x41 ,
                0xaa , 0x0c ,0x58 , 0xee ,0x02 , 0x01 ,0x38 , 0xea ,
                0xa7 , 0x89 ,0xbe , 0x59
                };

I call the checksum function as

fprintf(stdout, "%x\n", ~checksum(packet, sizeof(packet)));

but checksum value I get is ffffd174. Neglecting the first 2 bytes, I am getting 7510.

Any ideas what I am doing wrong? I think that there might be an endian problem in the checksum function but also I might have constructed the psuedo-header incorrectly.

答:
Figured out the problem, so posting the correction in case someone else is looking for it.

Problem was in how I added nextheader to the input data to checksum function. I needed to prefix Nextheader with one 0x00 byte. Last 32 bits in pseudo header part are supposed to be zeros followed by next header. Since first 16 bits only add to 0, it was sufficient to add only one zero byte before next header. So the input data to checksum function ended up being

```<code>    uint8_t packet[] = {
            0xfe , 0x80 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00, // src
            0x88 , 0xc5 ,0x75 , 0x41 ,0xaa , 0x0c ,0x58 , 0xee,
            0xff , 0x02 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00, // dst
            0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x01,
            0x00 , 0x20 , // length 32
            0x00 , 0x3a , // next header 58
            0x88 , // type
            0x00 , // code
            0x00 , 0x00 , // checksum
            0x20 , 0x00 ,0x00 , 0x00 ,0xfe , 0x80 ,0x00 , 0x00 , // body
            0x00 , 0x00 ,0x00 , 0x00 ,0x88 , 0xc5 ,0x75 , 0x41 ,
            0xaa , 0x0c ,0x58 , 0xee ,0x02 , 0x01 ,0x38 , 0xea ,
            0xa7 , 0x89 ,0xbe , 0x59
    };
</code>```

Title: Can't get correct icmpv6 checksum

Body:
Figured out the problem, so posting the correction in case someone else is looking for it.

Problem was in how I added nextheader to the input data to checksum function. I needed to prefix Nextheader with one 0x00 byte. Last 32 bits in pseudo header part are supposed to be zeros followed by next header. Since first 16 bits only add to 0, it was sufficient to add only one zero byte before next header. So the input data to checksum function ended up being

    uint8_t packet[] = {
            0xfe , 0x80 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00, // src
            0x88 , 0xc5 ,0x75 , 0x41 ,0xaa , 0x0c ,0x58 , 0xee,
            0xff , 0x02 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00, // dst
            0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x00 ,0x00 , 0x01,
            0x00 , 0x20 , // length 32
            0x00 , 0x3a , // next header 58
            0x88 , // type
            0x00 , // code
            0x00 , 0x00 , // checksum
            0x20 , 0x00 ,0x00 , 0x00 ,0xfe , 0x80 ,0x00 , 0x00 , // body
            0x00 , 0x00 ,0x00 , 0x00 ,0x88 , 0xc5 ,0x75 , 0x41 ,
            0xaa , 0x0c ,0x58 , 0xee ,0x02 , 0x01 ,0x38 , 0xea ,
            0xa7 , 0x89 ,0xbe , 0x59
    };


来源: stackexchange

问:
Selecting content to feature
in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.

This is what I'm using to select posts at the moment:

posts_controller.rb

```<code>favorite_post_ids = [8,2,5]
@favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.find(new_post_ids)
</code>```

and then in the view I loop over them to display the posts.

However, once a post is deleted and the controller can no longer find it, I get an error that says

```<code>Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)
</code>```

What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.

UPDATE :

I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.

答:
I dont encourage hardcoding. But still if that is your requirement, try </p>

```<code>favorite_post_ids = [8,2,5]
@favorite_posts = Post.where(:id => favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.where(:id => new_post_ids)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Selecting content to feature

Body:
in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.

This is what I'm using to select posts at the moment:

posts_controller.rb

favorite_post_ids = [8,2,5]
@favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.find(new_post_ids)

and then in the view I loop over them to display the posts.

However, once a post is deleted and the controller can no longer find it, I get an error that says

Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)

What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.

UPDATE :

I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.

Body:
I dont encourage hardcoding. But still if that is your requirement, try

favorite_post_ids = [8,2,5]
@favorite_posts = Post.where(:id => favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.where(:id => new_post_ids)


问:
How to get java file path deployed on web server?
I have abc.jar deployed on web server http://localhost:8080/test/scripts folder.

In that abc.jar file I have Path.java class where I have to write the code to get the URL of the server where the abc.jar file is present. The output should be http://localhost:8080/test/.

How to get the path?

答:
If I understand your question correctly you wanna get contextPath of your deployed .war file in the servlet class Path.java [I am assuming you are using servlets here],

```<code>public static String getURLWithContextPath(HttpServletRequest request) {
   return request.getContextPath(); // this method will provide you desired path.
}
</code>```

for more detail about the contextPath,

https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequest.html#getContextPath()

Body:
If I understand your question correctly you wanna get contextPath of your deployed .war file in the servlet class Path.java [I am assuming you are using servlets here],

public static String getURLWithContextPath(HttpServletRequest request) {
   return request.getContextPath(); // this method will provide you desired path.
}

for more detail about the contextPath,

https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequest.html#getContextPath()


问:
Integrate Testfairy SDK into my xamarin project
Can anyone please tell me how to integrate testfairty SDK into my xanmarin project.

Thanks in advance.

答:
There are 3 ways of using the TestFairy SDK with Xamarin:

Downloading the .dlls from github.

Downloading bindings using nuget

Downloading using the Xamarin Component Store (Recommended.)

You can find documentation at:

https://docs.testfairy.com/Platforms/Xamarin_Component.html

https://docs.testfairy.com/Platforms/Xamarin.html


问:
Singleton CDI @Inject null pointer exception
I need to fire events from some ejb (Stateless and Singleton) using dependency injection. I do not use Spring, Guice etc.
The problem is that I get NPE in one of beans when calling its method through getInstance(). Here is the code snippet:

```<code>@Stateless
@LocalBean
public class ControllerStartStop {
    @Inject
    private Event<SomeWebMessage> webEvent;

    public String startCircle(String passwordP, String passwordH) {
    .........
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));   // this works fine
    MainDay.getInstance().startDay();      // NullPointerException
</code>```

Here is MainDay singleton:

```<code>@Singleton
public class MainDay {
    private static final MainDay mDay = new MainDay();
    public static MainDay getInstance() {   return mDay ;   }

    @Inject
    private Event<SomeWebMessage> webEvent;

    public void startDay() {
        String s = new String("MainDay");
        webEvent.fire(new SomeWebMessage(s,0));   // NullPointerException
</code>```

beans.xml is in META-INF:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">

</beans>
</code>```

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*.
I have no idea what is the reason

答:
NPE 1:

Shouldn't the targetted EJB MainDay "observe" the event and call its startDay() method?

```<code>public void onEvent(@Observes SomeWebMessage event) {
    // if (...)
        startDay();
}
</code>```

So there is no need for a static getInstance() method.

NPE 2:

```<code>@Inject Event<SomeWebMessage> webEvent;
</code>```

Dependency injection (DI) only works, if you do not manually call the constructor new MainDay() but inject instances of the wanted bean and let the DI container handle construction.

But with @Observes (javax.enterprise.event.Observes) you should be able to remove all the smelly static stuff anyway.

Body:
I need to fire events from some ejb (Stateless and Singleton) using dependency injection. I do not use Spring, Guice etc.
The problem is that I get NPE in one of beans when calling its method through getInstance(). Here is the code snippet:

@Stateless
@LocalBean
public class ControllerStartStop {
    @Inject
    private Event<SomeWebMessage> webEvent;

    public String startCircle(String passwordP, String passwordH) {
    .........
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));   // this works fine
    MainDay.getInstance().startDay();      // NullPointerException

Here is MainDay singleton:

@Singleton
public class MainDay {
    private static final MainDay mDay = new MainDay();
    public static MainDay getInstance() {   return mDay ;   }

    @Inject
    private Event<SomeWebMessage> webEvent;

    public void startDay() {
        String s = new String("MainDay");
        webEvent.fire(new SomeWebMessage(s,0));   // NullPointerException

beans.xml is in META-INF:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">

</beans>

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*.
I have no idea what is the reason

Body:
NPE 1:

Shouldn't the targetted EJB MainDay "observe" the event and call its startDay() method?

public void onEvent(@Observes SomeWebMessage event) {
    // if (...)
        startDay();
}

So there is no need for a static getInstance() method.

NPE 2:

@Inject Event<SomeWebMessage> webEvent;

Dependency injection (DI) only works, if you do not manually call the constructor new MainDay() but inject instances of the wanted bean and let the DI container handle construction.

But with @Observes (javax.enterprise.event.Observes) you should be able to remove all the smelly static stuff anyway.


问:
Is there a way to export the PowerPoint?
I wanna export GoJs diagrams to Microsoft Office PowerPoint. so examined it, but I couldn't get a good result.

Is there a good way to do it?

答:
I found the best way.

Gojs can't export to PowerPoint, but I can get diagram objects.

Using that object, write an intermediate json file.

We grasp the state of diagram from that json and create a PowerPoint using apache poi.

apache poi https://poi.apache.org/

thanks.


问:
Cannot connect to hive using beeline, user root cannot impersonate anonymous
I'm trying to connect to hive using beeline !connect jdbc:hive2://localhost:10000 and I'm being asked for a username and password

Connecting to jdbc:hive2://localhost:10000'
Enter username for jdbc:hive2://localhost:10000:
Enter password for jdbc:hive2://localhost:10000:

As I don't know what username or password I'm supposed to type in I'm leaving it empty which causes the error: Error: Failed to open new session: java.lang.RuntimeException: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.authorize.AuthorizationException): User: root is not allowed to impersonate anonymous (state=,code=0)

My setup is a single node hadoop cluster in ubuntu.
I can confirm that the services are up and running, both hadoop and hiveserver2

The question is , what are these username and password I'm being asked, where can I find them or set them?

Thanks in advance

答:
You should provide a valid username and password that has privileges to access the HDFS and Hive Services (user running HiveServer2). For your setup, the user in which Hadoop and Hive are installed would be the superuser.

These credentials will be used by beeline to initiate a connection with HiveServer2.

And, add these properties in core-site.xml

```<code><property>
  <name>hadoop.proxyuser.username.groups</name>
  <value>*</value>
</property>
<property>
  <name>hadoop.proxyuser.username.hosts</name>
  <value>*</value>
</property>
</code>```

Restart services after adding these properties.

Then run beeline with the specified user name username as below:

beeline -u jdbc:hive2://localhost:10000 -u username
```

ref: https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-Impersonation

Alternatively, you can also set the parameter hive.server2.enable.doAs to false to disable user impersonation.

Body:
You should provide a valid username and password that has privileges to access the HDFS and Hive Services (user running HiveServer2). For your setup, the user in which Hadoop and Hive are installed would be the superuser.

These credentials will be used by beeline to initiate a connection with HiveServer2.

And, add these properties in core-site.xml

<property>
  <name>hadoop.proxyuser.username.groups</name>
  <value>*</value>
</property>
<property>
  <name>hadoop.proxyuser.username.hosts</name>
  <value>*</value>
</property>

Restart services after adding these properties.

Then run beeline with the specified user name username as below:

beeline -u jdbc:hive2://localhost:10000 -u username

ref: https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-Impersonation

Alternatively, you can also set the parameter hive.server2.enable.doAs to false to disable user impersonation.

ContentLicense: CC BY-SA 4.0


问:
select parent for the property 'of' in the postion widget jquery ui
I want to select parent for the property of in the position widget jquery UI.
i use the bellow code

```<code>jQuery("#modalLink4").position({
  my: "center",
  at: "center",
  of: jQuery("#modalLink4").parent()
});
</code>```

but it doesn't work correctly and its have error.
I can I select parent an element for the position I?!

答:
Your of declaration needs to be string name not the jQuery object. Try this:

```<code>of: "#" + $("#modalLink4").parent().attr('id')
</code>```

or (avoiding $)

```<code>of: "#" + jQuery("#modalLink4").parent().attr('id')
</code>```

See here
https://api.jqueryui.com/position/

Body:
I want to select parent for the property of in the position widget jquery UI.
i use the bellow code

jQuery("#modalLink4").position({
  my: "center",
  at: "center",
  of: jQuery("#modalLink4").parent()
});

but it doesn't work correctly and its have error.
I can I select parent an element for the position I?!

Body:
Your of declaration needs to be string name not the jQuery object. Try this:

of: "#" + $("#modalLink4").parent().attr('id')

or (avoiding $)

of: "#" + jQuery("#modalLink4").parent().attr('id')

See here
https://api.jqueryui.com/position/


问:
looping function javascript
saveEmail() (NOT page.saveEmail()) isn't being executed in a 3 second loop...

```<code>            $('input[name="email"]').bind('blur', function () {
                if (timer) clearTimeout(timer);
                page.saveEmail();
            }).bind('focus', function(e){
                  timer = setTimeout(function () {
                      function saveEmail () {
                          setTimeout(page.saveEmail, 3000);
                      }
                      saveEmail();
                  }, 3000);
            });
</code>```

答: setTimeout only fires once. If you want it to be executed repeatedly, you either need to set the timer again when it fires, or use setInterval.

ContentLicense: CC BY-SA 2.5

Title: looping function javascript

Body:
saveEmail() (NOT page.saveEmail()) isn't being executed in a 3 second loop...

            $('input[name="email"]').bind('blur', function () {
                if (timer) clearTimeout(timer);
                page.saveEmail();
            }).bind('focus', function(e){
                  timer = setTimeout(function () {
                      function saveEmail () {
                          setTimeout(page.saveEmail, 3000);
                      }
                      saveEmail();
                  }, 3000);
            });


问:
How to set PyCharm not to open all last projects?
I have a question when it comes to PyCharm IDE. It seems that it is set by default to open all last projects when started, and I would like to start with no projects opened. For instance, I have worked on two projects until now and when I start PyCharm it opens both of them.</p>

答:
This option is located in Settings:

Appearance & Behavior > System Settings > Startup/Shutdown > Reopen last project on startup

Also, you can use search with "last project".


答:
If you open the preferences and search for "Start" you will find this:

You can untick this and it will start at the project selection screen.

Title: How to set PyCharm not to open all last projects?

Body: I have a question when it comes to PyCharm IDE. It seems that it is set by default to open all last projects when started, and I would like to start with no projects opened. For instance, I have worked on two projects until now and when I start PyCharm it opens both of them.


问:
Can't access Javascript object
I am creating an app in ionic. In that I need to store a value of an object into another variable; the name of the array of objects is username.

This is username[0] :

```<code>Object {username: "user1"}
</code>```

Here I want to store the value of username into another $scope variable. So I did as follows:

```<code>$scope.username=$scope.username[0].username;
</code>```

But, it returned error. Why? and how to solve it.

答:
You have an object but you are trying to access it as an array with [0] and thus will return you undefined

You can either access your object with the dot notation

```<code>obj.username
</code>```

or with the brackets notation

```<code>obj["username"]
</code>```

let username = {
  username: "user1"
};

console.log(username.username);
console.log(username['username']);```

Title: Can't access Javascript object

Body:
I am creating an app in ionic. In that I need to store a value of an object into another variable; the name of the array of objects is username.

This is username[0] :

Object {username: "user1"}

Here I want to store the value of username into another $scope variable. So I did as follows:

$scope.username=$scope.username[0].username;

But, it returned error. Why? and how to solve it.

Body:
You have an object but you are trying to access it as an array with [0] and thus will return you undefined

You can either access your object with the dot notation

obj.username

or with the brackets notation

obj["username"]

let username = {
  username: "user1"
};

console.log(username.username);
console.log(username['username']);


问:
XSD desigener error Visual Studio 2017
I get the following error if I try to open a .xsd file or create a new one in Visual Studio 2017 its a .net 3.5 project and was working fine before I reinstalled windows and upgraded to visual studio 2017 pro.

This seems to be .net 3.5 specific as I opened another project that's 4.0 and its .xsd opened in designer fine.

To prevent possible data loss before loading the designer, the
  following errors must be resolved:

Value cannot be null. Parameter
  name: instance

```<code> Instances of this error (1)
</code>```

Hide Call Stack    at System.ComponentModel.TypeDescriptor.AddAttributes(Object instance,
  Attribute[] attributes) at
  Microsoft.VisualStudio.Design.VSDesignSurface.CreateDesigner(IComponent
  component, Boolean rootDesigner) at
  System.ComponentModel.Design.DesignerHost.AddToContainerPostProcess(IComponent
  component, String name, IContainer containerToAddTo) at
  System.ComponentModel.Design.DesignerHost.PerformAdd(IComponent
  component, String name) at
  System.ComponentModel.Design.DesignerHost.Add(IComponent component,
  String name) at System.ComponentModel.Container.Add(IComponent
  component) at
  Microsoft.VSDesigner.DataSource.Designer.DataSourceDesignerLoader.HandleLoad(IDesignerSerializationManager
  serializationManager) at
  Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.PerformLoad(IDesignerSerializationManager
  serializationManager) at
  Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32
  fReload)

Link to error screen shot

答:
Hy!
Set your project Target Framework: 4.6
(Right Click the ProjectName/Property Pages/Build/Target Framework--->4.6)
I try it, and it's work.</p>

Title: XSD desigener error Visual Studio 2017

Body:
I get the following error if I try to open a .xsd file or create a new one in Visual Studio 2017 its a .net 3.5 project and was working fine before I reinstalled windows and upgraded to visual studio 2017 pro.

This seems to be .net 3.5 specific as I opened another project that's 4.0 and its .xsd opened in designer fine.

To prevent possible data loss before loading the designer, the
  following errors must be resolved:

Value cannot be null. Parameter
  name: instance

 Instances of this error (1)

Hide Call Stack    at System.ComponentModel.TypeDescriptor.AddAttributes(Object instance,
  Attribute[] attributes) at
  Microsoft.VisualStudio.Design.VSDesignSurface.CreateDesigner(IComponent
  component, Boolean rootDesigner) at
  System.ComponentModel.Design.DesignerHost.AddToContainerPostProcess(IComponent
  component, String name, IContainer containerToAddTo) at
  System.ComponentModel.Design.DesignerHost.PerformAdd(IComponent
  component, String name) at
  System.ComponentModel.Design.DesignerHost.Add(IComponent component,
  String name) at System.ComponentModel.Container.Add(IComponent
  component) at
  Microsoft.VSDesigner.DataSource.Designer.DataSourceDesignerLoader.HandleLoad(IDesignerSerializationManager
  serializationManager) at
  Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.PerformLoad(IDesignerSerializationManager
  serializationManager) at
  Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32
  fReload)

Link to error screen shot


问:
Storing historical data with Java and Hibernate
This is a problem about historical data handling.
Suppose you have a class MyClass like the following one:

```<code>class MyClass {
    String field1;
    Integer field2;
    Long field3;

    getField1() {...}
    setField1(String ...) {...}

    ...
}
</code>```

Now, suppose I need to make MyClass able to store and retrieve old data, what's the best way to do this?

The requirements are to persist the classes through Hibernate, too. And to have at most two tables per "entity": only one table or one table for the "continuity" class (the one which represents the entity which evolves over the time) and another table for the historical data (as it's suggested here)

Please note that I have to be able to assign an arbitrary valid time to the values of the fields.

The class should have an interface like:

```<code>class MyClass {
    // how to store the fields????

    getField1At(Instant i) {...}
    setField1At(Instant i, String ...) {...}

    ...
}
</code>```

I'm currently using the JTemporal library, and it has a TemporalAttribute<T> class, which is like a map: you can do things like T myAttr.get(Instant i) to get the version of myAttr at Instant i. I know how to persist a TemporalAttribute in a table with Hibernate (it's simple: I persist the SortedMap used by the TemporalAttribute and you get a table with start and end valid time and the value of the attribute).

The real problem is that here we have multiple attributes.

I have a solution in mind but it's not clear, and I'd like to hear your ideas.

答:
Your project reminds me of Hibernate Envers.

The Envers project aims to enable easy
  auditing of persistent classes. All
  that you have to do is annotate your
  persistent class or some of its
  properties, that you want to audit,
  with @Audited. For each audited
  entity, a table will be created, which
  will hold the history of changes made
  to the entity. You can then retrieve
  and query historical data without much
  effort.

choose what you want to audit (on a per attribute basis)

make your own Revision Entity (that stores informations such as revision number, author, timestamp...)

Using Hibernate Envers for this decouples entities and revision data (in database and in your code).

Body:
This is a problem about historical data handling.
Suppose you have a class MyClass like the following one:

class MyClass {
    String field1;
    Integer field2;
    Long field3;

    getField1() {...}
    setField1(String ...) {...}

    ...
}

Now, suppose I need to make MyClass able to store and retrieve old data, what's the best way to do this?

The requirements are to persist the classes through Hibernate, too. And to have at most two tables per "entity": only one table or one table for the "continuity" class (the one which represents the entity which evolves over the time) and another table for the historical data (as it's suggested here)

Please note that I have to be able to assign an arbitrary valid time to the values of the fields.

The class should have an interface like:

class MyClass {
    // how to store the fields????

    getField1At(Instant i) {...}
    setField1At(Instant i, String ...) {...}

    ...
}

I'm currently using the JTemporal library, and it has a TemporalAttribute<T> class, which is like a map: you can do things like T myAttr.get(Instant i) to get the version of myAttr at Instant i. I know how to persist a TemporalAttribute in a table with Hibernate (it's simple: I persist the SortedMap used by the TemporalAttribute and you get a table with start and end valid time and the value of the attribute).

The real problem is that here we have multiple attributes.

I have a solution in mind but it's not clear, and I'd like to hear your ideas.


问:
Access methods outside companion object - Kotlin
I'm pretty new to kotlin and I was wondering if it's possible, and if it's against best practice to access methods and variables that are outside a companion object, from within the companion object.

For example

```<code>class A {
    fun doStuff(): Boolean = return true

    companion object{
        public fun stuffDone(): Boolean = return doStuff()
    }
}
</code>```

or something like that

Thank you

答:
doStuff() is an instance method of a class; calling it requires a class instance. Members of a companion object, just like static methods in Java, do not have a class instance in scope. Therefore, to call an instance method from a companion object method, you need to provide an instance explicitly:

```<code>class A {
    fun doStuff() = true

    companion object {
        fun stuffDone(a: A) = a.doStuff()
    }
}
</code>```

Body:
I'm pretty new to kotlin and I was wondering if it's possible, and if it's against best practice to access methods and variables that are outside a companion object, from within the companion object.

For example

class A {
    fun doStuff(): Boolean = return true

    companion object{
        public fun stuffDone(): Boolean = return doStuff()
    }
}

or something like that

Thank you

Body:
doStuff() is an instance method of a class; calling it requires a class instance. Members of a companion object, just like static methods in Java, do not have a class instance in scope. Therefore, to call an instance method from a companion object method, you need to provide an instance explicitly:

class A {
    fun doStuff() = true

    companion object {
        fun stuffDone(a: A) = a.doStuff()
    }
}


问:
WebApi2 how to pass Json with an array
I have the following Json with array that I am sending it from AngularJS

```<code>{id_fleet: 4177, id_fleetfeature: Array[2]}

var dataFeatures = {
    id_fleet: $scope.id,
    id_fleetfeature: $scope.selectedFeatures
}
$http.put(myUrl + "Fleets/Insert", JSON.stringify(dataFeatures)).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});
</code>```

Web API Model

```<code>public class modelFleetFeatures {
    public int id_fleet { get; set; }
    public int[] id_fleetfeature { get; set; }
}
</code>```

Web API Function

```<code>[HttpPut]
[Route("api/Fleets/FleetFeature/Update")]
public HttpResponseMessage updateFleetFeature(List<modelFleetFeatures> data)
{
    var cnt = 0;

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesDelete(item.id_fleet);
        db.SaveChanges();
    }

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesInsert(item.id_fleet, item.id_fleetfeature[cnt]);
        db.SaveChanges();
        cnt +=1;
    }

    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
</code>```

In the Web API the value of data always gets null

答:
You are sending single object in JSON, so why expecting list of object in API action?
Just expect single object in api Action , you will get that object model in call like :

```<code>public HttpResponseMessage updateFleetFeature(modelFleetFeatures data)
{
    //do stuff
}
</code>```

And no need to stringify json object in put request.

```<code>$http.put(myUrl + "Fleets/Insert", dataFeatures).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});
</code>```

Title: WebApi2 how to pass Json with an array

Body:
I have the following Json with array that I am sending it from AngularJS

{id_fleet: 4177, id_fleetfeature: Array[2]}

var dataFeatures = {
    id_fleet: $scope.id,
    id_fleetfeature: $scope.selectedFeatures
}
$http.put(myUrl + "Fleets/Insert", JSON.stringify(dataFeatures)).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});

Web API Model

public class modelFleetFeatures {
    public int id_fleet { get; set; }
    public int[] id_fleetfeature { get; set; }
}

Web API Function

[HttpPut]
[Route("api/Fleets/FleetFeature/Update")]
public HttpResponseMessage updateFleetFeature(List<modelFleetFeatures> data)
{
    var cnt = 0;

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesDelete(item.id_fleet);
        db.SaveChanges();
    }

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesInsert(item.id_fleet, item.id_fleetfeature[cnt]);
        db.SaveChanges();
        cnt +=1;
    }

    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

In the Web API the value of data always gets null

Body:
You are sending single object in JSON, so why expecting list of object in API action?
Just expect single object in api Action , you will get that object model in call like :

public HttpResponseMessage updateFleetFeature(modelFleetFeatures data)
{
    //do stuff
}

And no need to stringify json object in put request.

$http.put(myUrl + "Fleets/Insert", dataFeatures).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});


问:
Swipe effect in TabHost inside a fragment
I have a NavigationDrawer that opens fragments if a button is clicked. But now, i need to make a Tabhost in one of these fragments. I never worked with TabHost and i can't find any topic explaining how to implement the Swipe effect in one TabHost inside a fragment. Until then, i have the Tabhost configured but don't have any effect. I'll be thankful if you can explain me how to do it.

PacksFragment.java

```<code>package studio.com.archeagemanager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */

public class PacksFragment extends Fragment {

    TabHost tabHost;

    public PacksFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_packs, container, false);

        TabHost host = (TabHost) view.findViewById(R.id.tabhost);
        host.setup();

        //Tab 1
        TabHost.TabSpec spec = host.newTabSpec("Tab One");
        spec.setContent(R.id.nuia);
        spec.setIndicator("NUIA");
        host.addTab(spec);

        //Tab 2
        spec = host.newTabSpec("Tab two");
        spec.setContent(R.id.haranya);
        spec.setIndicator("HARANYA");
        host.addTab(spec);

        //Tab 3
        spec = host.newTabSpec("Tab three");
        spec.setContent(R.id.oceanic);
        spec.setIndicator("OCEANIC");
        host.addTab(spec);

        //Tab 4
        spec = host.newTabSpec("Tab four");
        spec.setContent(R.id.auroria);
        spec.setIndicator("AURORIA");
        host.addTab(spec);

        for (int i=0; i<4; i++) {
            View tabView = host.getTabWidget().getChildTabViewAt(i);
            tabView.setPadding(0, 0, 0, 0);
            TextView tv = (TextView)tabView.findViewById(android.R.id.title);
            tv.setSingleLine();
            tv.setTextSize(14);
        }

        return view;
    }

}
</code>```

答:
In Your Layout file fragments_pack Just add Tab Host with Horizontal Scroll View as per your requirement similar to this

```<code><TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/horizontalScrollView"
        android:fillViewport="true"
        android:scrollbars="none">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </HorizontalScrollView>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />
</LinearLayout>
</code>```

Body:
I have a NavigationDrawer that opens fragments if a button is clicked. But now, i need to make a Tabhost in one of these fragments. I never worked with TabHost and i can't find any topic explaining how to implement the Swipe effect in one TabHost inside a fragment. Until then, i have the Tabhost configured but don't have any effect. I'll be thankful if you can explain me how to do it.

PacksFragment.java

package studio.com.archeagemanager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */

public class PacksFragment extends Fragment {

    TabHost tabHost;

    public PacksFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_packs, container, false);

        TabHost host = (TabHost) view.findViewById(R.id.tabhost);
        host.setup();

        //Tab 1
        TabHost.TabSpec spec = host.newTabSpec("Tab One");
        spec.setContent(R.id.nuia);
        spec.setIndicator("NUIA");
        host.addTab(spec);

        //Tab 2
        spec = host.newTabSpec("Tab two");
        spec.setContent(R.id.haranya);
        spec.setIndicator("HARANYA");
        host.addTab(spec);

        //Tab 3
        spec = host.newTabSpec("Tab three");
        spec.setContent(R.id.oceanic);
        spec.setIndicator("OCEANIC");
        host.addTab(spec);

        //Tab 4
        spec = host.newTabSpec("Tab four");
        spec.setContent(R.id.auroria);
        spec.setIndicator("AURORIA");
        host.addTab(spec);

        for (int i=0; i<4; i++) {
            View tabView = host.getTabWidget().getChildTabViewAt(i);
            tabView.setPadding(0, 0, 0, 0);
            TextView tv = (TextView)tabView.findViewById(android.R.id.title);
            tv.setSingleLine();
            tv.setTextSize(14);
        }

        return view;
    }

}

Body:
In Your Layout file fragments_pack Just add Tab Host with Horizontal Scroll View as per your requirement similar to this

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/horizontalScrollView"
        android:fillViewport="true"
        android:scrollbars="none">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </HorizontalScrollView>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />
</LinearLayout>


问:
How to acces a model attribute from another model
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

```<code>from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)
</code>```

答:
Like other answers, you use backwards relation in Django.

See example: Many-to-one relationships

And Examples of model relationship API

Body:
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)


问:
Effect of removal "static" keyword for function
Recently, I have learned the existence of "backtrace" function.
This function allow one to retrieve, at some conditions, the callstack of an ELF running program compiled without debugging information.

It's perfect for me (I can't insert debugging symbol in production program), but for "backtrace" to work, there is (roughly) two condition :

Tell the linker to add extra information (by passing -rdynamic option).

Convert all "static" function to "non-static" function.

My worries is that if I fullfill this two condition, my program will be slower (because compiler can't optimise non-static function as he optimize static function ?).
As far as I know, adding extra information with -rdynamic doesn't impact program's performance : it's just add a little weight to the ELF binary.

So here's my question :

What is the effect in term of running performance when all static function become non-static function ?

答:
Yes, your worries are correct: Declaring a function as static provides a good hint to the compiler, which it can turn into better optimization. The amount of speedup that you receive from static depends on your precise situation, though, so there's only truth in measurement (as always when it comes to performance).

The point about declaring a function as static is, that the compiler knows definitely, that it sees all the calling sites of a function. And if it sees, that the function is only called from one single place, it will generally always inline it, no matter how long it is. And the inlining may unlock further opportunities for optimization. This avoids the function call overhead, both in terms of size and speed. In this, static is actually a stronger hint than inline.

Of course, the effect on the performance depends on the frequency of calls to the static function. So, as I said, you need measurement to assess how much performance you gain from the static keyword.


问:
How do I insert a space after a character in a textbox, depending on the total characters entered, JQuery?
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

```<code>$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});
</code>```

答:
You can use a RegExp to replace the last 3 characters with a space plus the same 3 characters:

```<code>$('#postcode').blur(function(){
  $(this).val($(this).val().replace(/...$/, ' $&'));
});
</code>```

Try it: http://jsfiddle.net/PJMDp/1/

If you really must count 3 characters, you should use slice, not substring:

```<code>$('#postcode').blur(function(){
  var postcode = $(this), val = postcode.val();
  if(val.length > 3)
    postcode.val(val.slice(0, -3)+' '+val.slice(-3));
});
</code>```

Try it: http://jsfiddle.net/PJMDp/2/

Body:
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});

Body:
You can use a RegExp to replace the last 3 characters with a space plus the same 3 characters:

$('#postcode').blur(function(){
  $(this).val($(this).val().replace(/...$/, ' $&'));
});

Try it: http://jsfiddle.net/PJMDp/1/

If you really must count 3 characters, you should use slice, not substring:

$('#postcode').blur(function(){
  var postcode = $(this), val = postcode.val();
  if(val.length > 3)
    postcode.val(val.slice(0, -3)+' '+val.slice(-3));
});

Try it: http://jsfiddle.net/PJMDp/2/


问:
Select data from database via AJAX (ASP.NET MVC)
I have database with tables Companies, Vacancies, Interview and QuestionBlocks.

Here is scheme of it

So Vacancy is connected to Company, Interview connected to Vacancy and Question blocks connected to Interview.

I realize DropdownLists for Company and when I select company Vacancy dropdown list updates.

Here is code for View

```<code><div style="width: 100%; margin-left: 20px;height: 15%;padding-top: 20px;">
    @Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting", @style = "width:30%; margin-left:20px;" })
    <select class="greeting" id="vacancy" name="id"  style="width:30%; margin-left:150px;" data-url="@Url.Action("Vacancies","Questions")">
        <option value="" disabled selected>Вакансия</option>
    </select>
</div>
</code>```

And Ajax call

```<code><script>
    $(function () {
        $("#Company").change(function (e) {
            var $vacancy = $("#vacancy");
            var url = $vacancy.data("url") + '?companyId=' + $(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });
    });
</script>
</code>```

I have View like this

So what I need.

I need to make request to controller and find QuestionBlock  that related to VacancyId.

So as I understood I need to pass VacancyId from dropdownlist to controller make some sql operations and return JSON?

Or how I can do this?

UPDATE

Thank's for answer @CuriousDev, It works well for select item.

I need one more thing, I need to display Question1-Question10 like this.

Here is my Action method

```<code>public ActionResult QuestionBlocks(int vacancyId)
{
    var items = db.QuestionBlocks
        .Where(x => x.Interview.VacancyId == vacancyId)
        .Select(x => new
        {
            ID = x.Block_ID.ToString(),
            Question1 = x.Question1,
            Question2 = x.Question2,
            Question3 = x.Question3,
            Question4 = x.Question4,
            Question5 = x.Question5,
            Question6 = x.Question6,
            Question7 = x.Question7,
            Question8 = x.Question8,
            Question9 = x.Question9,
            Question10 = x.Question10,
        })
        .ToList();
    return Json(items, JsonRequestBehavior.AllowGet);
}
</code>```

How I need to write ajax call to back -end and display data in div?

答:
Hi I am not sure whats failing your requirement, you have understanding for the logic its just the implementation which you need.

```<code>$("#Company").change(function (e) {
    var companyId = $(this).val();
    var model = {
        companyId:companyId
    };

    $.ajax({
        url: '@Url.Action("Vacancies","Questions")',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        type: 'POST',
        dataType: 'json',
        processData: false
    })
    .success(function (result) {
        console.log(result);
        console.log(result.Vacancies);

    })
    .error(function (xhr, status) {
    alert("error");
});

});
</code>```

For Controller

```<code>public ActionResult Vacancies(int companyId)
{
    // Logic to get the vacancies data
    var result = "abc";
    return Json(new { Vacancies = result }, JsonRequestBehavior.AllowGet);
}
</code>```

I hope the above implementation helps you.
Thanks

Body:
I have database with tables Companies, Vacancies, Interview and QuestionBlocks.

Here is scheme of it

So Vacancy is connected to Company, Interview connected to Vacancy and Question blocks connected to Interview.

I realize DropdownLists for Company and when I select company Vacancy dropdown list updates.

Here is code for View

    @Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting", @style = "width:30%; margin-left:20px;" })
    <select class="greeting" id="vacancy" name="id"  style="width:30%; margin-left:150px;" data-url="@Url.Action("Vacancies","Questions")">
        <option value="" disabled selected>Вакансия</option>
    </select>

And Ajax call

I have View like this

So what I need.

I need to make request to controller and find QuestionBlock  that related to VacancyId.

So as I understood I need to pass VacancyId from dropdownlist to controller make some sql operations and return JSON?

Or how I can do this?

UPDATE

Thank's for answer @CuriousDev, It works well for select item.

I need one more thing, I need to display Question1-Question10 like this.

Here is my Action method

public ActionResult QuestionBlocks(int vacancyId)
{
    var items = db.QuestionBlocks
        .Where(x => x.Interview.VacancyId == vacancyId)
        .Select(x => new
        {
            ID = x.Block_ID.ToString(),
            Question1 = x.Question1,
            Question2 = x.Question2,
            Question3 = x.Question3,
            Question4 = x.Question4,
            Question5 = x.Question5,
            Question6 = x.Question6,
            Question7 = x.Question7,
            Question8 = x.Question8,
            Question9 = x.Question9,
            Question10 = x.Question10,
        })
        .ToList();
    return Json(items, JsonRequestBehavior.AllowGet);
}

How I need to write ajax call to back -end and display data in div?

Body:
Hi I am not sure whats failing your requirement, you have understanding for the logic its just the implementation which you need.

$("#Company").change(function (e) {
    var companyId = $(this).val();
    var model = {
        companyId:companyId
    };

    $.ajax({
        url: '@Url.Action("Vacancies","Questions")',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        type: 'POST',
        dataType: 'json',
        processData: false
    })
    .success(function (result) {
        console.log(result);
        console.log(result.Vacancies);

    })
    .error(function (xhr, status) {
    alert("error");
});

});

For Controller

public ActionResult Vacancies(int companyId)
{
    // Logic to get the vacancies data
    var result = "abc";
    return Json(new { Vacancies = result }, JsonRequestBehavior.AllowGet);
}

I hope the above implementation helps you.
Thanks


问:
How to create dynamic routes in sh-service framework
Please help me, how to create a custom routes in php sh-service framework.</p>

答:
Thank you so much it is working for me.

Try this format:

```<code>$app->get('/name/:firstname',function($app,$req,$res){

   echo $req->firstname;
}
</code>```

Don't try this format:

```<code>$app->get('/name/{firstname}',function($app,$req,$res){

   $res->json($req->firstname);
}
</code>```

Body:
Thank you so much it is working for me.

Try this format:

$app->get('/name/:firstname',function($app,$req,$res){

   echo $req->firstname;
}

Don't try this format:

$app->get('/name/{firstname}',function($app,$req,$res){

   $res->json($req->firstname);
}


问:
How to make SQL query text parameter accept sentence containing an apostrophe
How I am performing a SQL query to insert data into the database. Note that the field PlanDetails in the table dbo.Plans is a text field. However, when a user tries to input a sentence which contains an apostrophe (e.g. I'll go to sleep). via the HTML form . The database returns an error "Incorect syntax near ll), which refers to the apostrophe problem. In this case, how should I modify the code below to make it accept sentences with apostrophe? It is told that I can use parameterized queries. In this node js example, how can I do that?</p>

```<code>CreatePlan : function (newPlan , UserID, DisplayName, Email, callback) {
    var sql = require('mssql');
    var config = require('./configuration/sqlconfig');
    var conn = new sql.Connection(config);
    var req = new sql.Request(conn);
    conn.connect(function (err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Attempting to Insert new learning plan...');
        req.query('INSERT INTO dbo.Plans (PlanTitle, PlanTopic, OwnerID, OwnerName, PlanDetails, TargetLearners, OwnerContact) VALUES ("' + newPlan.PlanTitle + '", "' + newPlan.PlanTopic + '", "' + UserID + '", "' + DisplayName + '", "' + newPlan.PlanDetails + '", "' + newPlan.TargetLearners + '", "' +Email+ '");', function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log("Added one new learning plan");
                console.log("The new plan title is " + newPlan.PlanTitle);
                callback();
            }
            conn.close();
        });
    });
},
</code>```

答:
In SQL (and in many other languages), you have to escape special characters to avoid any ambiguity in the code. There is a lot of documentation about how to escape and which character are concerned all other internet.

Here is the wikipedia article about escape character: https://en.wikipedia.org/wiki/Escape_character

Here is a stackoverflow post that answer your question: How do I escape special characters in MySQL?

However I should warn you about SQL injection, the code you are using will not be safe and you should probably take a look at the good practice in this matter.

Body:
How I am performing a SQL query to insert data into the database. Note that the field PlanDetails in the table dbo.Plans is a text field. However, when a user tries to input a sentence which contains an apostrophe (e.g. I'll go to sleep). via the HTML form . The database returns an error "Incorect syntax near ll), which refers to the apostrophe problem. In this case, how should I modify the code below to make it accept sentences with apostrophe? It is told that I can use parameterized queries. In this node js example, how can I do that?

CreatePlan : function (newPlan , UserID, DisplayName, Email, callback) {
    var sql = require('mssql');
    var config = require('./configuration/sqlconfig');
    var conn = new sql.Connection(config);
    var req = new sql.Request(conn);
    conn.connect(function (err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Attempting to Insert new learning plan...');
        req.query('INSERT INTO dbo.Plans (PlanTitle, PlanTopic, OwnerID, OwnerName, PlanDetails, TargetLearners, OwnerContact) VALUES ("' + newPlan.PlanTitle + '", "' + newPlan.PlanTopic + '", "' + UserID + '", "' + DisplayName + '", "' + newPlan.PlanDetails + '", "' + newPlan.TargetLearners + '", "' +Email+ '");', function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log("Added one new learning plan");
                console.log("The new plan title is " + newPlan.PlanTitle);
                callback();
            }
            conn.close();
        });
    });
},


问:
Different Output while having same input
```<code>groceries = {'fruits', 'milk', 'sweet', 'egg'}

print(groceries)
</code>```

When I runs the code, it shows following different output randomly.

I want to know that why it shows different output of same input ?

Different Output

Sometime output is this:

```<code>{'milk', 'sweet', 'fruits', 'egg'}
</code>```

Sometime output is this:

```<code>{'sweet', 'fruits', 'milk', 'egg'}
</code>```

Sometime output is this:

```<code>{'egg', 'sweet', 'fruits', 'milk'}
</code>```

Sometime Output is this:

```<code>{'fruits', 'milk', 'sweet', 'egg'}
</code>```

I want to know what is the reason, why it shows different output and randomly?

How we can show single output each time?

答:
You defined a set, which is unordered. You might use tuple or lists instead:

```<code>groceries = ['fruits', 'milk', 'sweet', 'egg'] # list
groceries = ('fruits', 'milk', 'sweet', 'egg') # tuple
</code>```

Also there is an ordered version of the dictionary.

Body:
groceries = {'fruits', 'milk', 'sweet', 'egg'}

print(groceries)

When I runs the code, it shows following different output randomly.

I want to know that why it shows different output of same input ?

Different Output

Sometime output is this:

{'milk', 'sweet', 'fruits', 'egg'}

Sometime output is this:

{'sweet', 'fruits', 'milk', 'egg'}

Sometime output is this:

{'egg', 'sweet', 'fruits', 'milk'}

Sometime Output is this:

{'fruits', 'milk', 'sweet', 'egg'}

I want to know what is the reason, why it shows different output and randomly?

How we can show single output each time?

Body:
You defined a set, which is unordered. You might use tuple or lists instead:

groceries = ['fruits', 'milk', 'sweet', 'egg'] # list
groceries = ('fruits', 'milk', 'sweet', 'egg') # tuple

Also there is an ordered version of the dictionary.


答:
Ok, if username was an array in the first place in your code, and you write:

```<code>$scope.username=$scope.username[0].username;
</code>```

So you are overwriting your existing username array with an object, then the next time you will call $scope.username[0].username it will fail and throw an error :Can't read property username of undefinedbecause username[0] is undefined here.

So you need to use different variables in the scope to refer users and username.

Title: Can't access Javascript object

Body:
I am creating an app in ionic. In that I need to store a value of an object into another variable; the name of the array of objects is username.

This is username[0] :

Object {username: "user1"}

Here I want to store the value of username into another $scope variable. So I did as follows:

$scope.username=$scope.username[0].username;

But, it returned error. Why? and how to solve it.

Body:
Ok, if username was an array in the first place in your code, and you write:

$scope.username=$scope.username[0].username;

So you are overwriting your existing username array with an object, then the next time you will call $scope.username[0].username it will fail and throw an error :Can't read property username of undefinedbecause username[0] is undefined here.

So you need to use different variables in the scope to refer users and username.


问:
What does <? php echo ("
"); ..... echo("
"); ?> mean?
The question is the tag ``` ```

I've seen one script I am working on, uses it:

echo ("```");</code></p>

<p>....
....</p>

<p><code>echo ("```");

What exactly does it do ?

Is it an Html tag or a PHP ?

I've searched on Google but nothing much comes out of it. When do we usually use that HTML tag?...or PHP tag?

答:
"```"</code> is an HTML tag. If you insert this line of code in your program</p>

<p><code>echo "```";

then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with
 you would be able to break the line and go to the next one.

For example,

the code below would be displayed on multiple lines, due to \n line ending specifier.

```<code><?php
    echo "```";
    printf("Hello\n", 65, 127, 245);
    printf("Goodbye");
?>
```

<p>However the following code, would be displayed in one line only (line endings are disregarded).</p>

```<?php
    printf("Hello\n", 65, 127, 245);
    printf("Goodbye");
?>
```

Title: What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

Body:
The question is the tag

I've seen one script I am working on, uses it:

echo ("
");

....
....

echo ("
");

What exactly does it do ?

Is it an Html tag or a PHP ?

I've searched on Google but nothing much comes out of it. When do we usually use that HTML tag?...or PHP tag?

Body:
"<pre>" is an HTML tag. If you insert this line of code in your program

echo "<pre>";

then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br> you would be able to break the line and go to the next one.

For example,

the code below would be displayed on multiple lines, due to \n line ending specifier.

<?php
    echo "<pre>";
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>

However the following code, would be displayed in one line only (line endings are disregarded).

<?php
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>


问:
How to set time like today, yesterday and date on particular item in ListView
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

```<code>public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }
</code>```

答:
you have compare two dates first one is position in getView & another one is previous item (position-1), please try this:</p>

```<code>       try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            Date date_ = format.parse("Item date time");
            java.text.DateFormat df = java.text.DateFormat.getTimeInstance();
            vh.chat_time_label_txt.setText(df.format(date_));

            SimpleDateFormat dateFormat_ = new SimpleDateFormat(
                "dd MMMM yyyy", Locale.ENGLISH);
            vh.top_date_label_txt.setText(dateFormat_.format(date_));
            vh.top_date_label_txt.setVisibility(View.VISIBLE);
            if (position > 0) {
                XmppChatModel temp = mChatConversationArrayList.get(mChatConversationArrayList.size() - 1);
                Date date__ = format.parse(temp.getTIMESTAMP());
                if (dateFormat_.format(date__)
                    .equals(dateFormat_.format(date_))) {
                    vh.top_date_label_txt.setVisibility(View.GONE);
                }
            }
      } catch (Exception e) {
           e.printStackTrace();
           vh.top_date_label_txt.setVisibility(View.GONE);
      }
</code>```

Body:
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }

Body:
you have compare two dates first one is position in getView & another one is previous item (position-1), please try this:

       try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            Date date_ = format.parse("Item date time");
            java.text.DateFormat df = java.text.DateFormat.getTimeInstance();
            vh.chat_time_label_txt.setText(df.format(date_));

            SimpleDateFormat dateFormat_ = new SimpleDateFormat(
                "dd MMMM yyyy", Locale.ENGLISH);
            vh.top_date_label_txt.setText(dateFormat_.format(date_));
            vh.top_date_label_txt.setVisibility(View.VISIBLE);
            if (position > 0) {
                XmppChatModel temp = mChatConversationArrayList.get(mChatConversationArrayList.size() - 1);
                Date date__ = format.parse(temp.getTIMESTAMP());
                if (dateFormat_.format(date__)
                    .equals(dateFormat_.format(date_))) {
                    vh.top_date_label_txt.setVisibility(View.GONE);
                }
            }
      } catch (Exception e) {
           e.printStackTrace();
           vh.top_date_label_txt.setVisibility(View.GONE);
      }


问:
Dropping mssql data records for records older than xx days
I'm trying to drop all the records from my DB where the records are OLDER than 3 days.

I've written something like this:

```<code>delete from Results WHERE [Date] > DATEADD(d, -3, getdate())
</code>```

I wanted to check whether this sql query is correct since I'm worried that I might make a mistake and delete more than I should...

this this query correct?

答:
Always check WHERE clause in SELECT clause before update or delete statement :

```<code>SELECT DATEADD(d, -3, getdate())
</code>```

First check your WHERE clause in SELECT statement.It gives your expected date means continue with same WHERE clause in DELETE.

Body:
I'm trying to drop all the records from my DB where the records are OLDER than 3 days.

I've written something like this:

delete from Results WHERE [Date] > DATEADD(d, -3, getdate())

I wanted to check whether this sql query is correct since I'm worried that I might make a mistake and delete more than I should...

this this query correct?

Body:
Always check WHERE clause in SELECT clause before update or delete statement :

SELECT DATEADD(d, -3, getdate())

First check your WHERE clause in SELECT statement.It gives your expected date means continue with same WHERE clause in DELETE.


问:
Extract
 tag from BeautifulSoup resultSet
I want to extract all the
tags from the html page. The needed content can be retrieved with result = soup.find('div', {'class':'column column_620 column_content'}). This returns the first class column_620. After that I get its siblings and want to extract the
 tags. But that result does not have the method findAll().
What can I do to extract the desired
 tag entry?

```<code>import re
import time
from datetime import datetime
import platform
import pandas as pd
from numpy import nan
from itertools import chain

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

timestampStart = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

sdCel = 'http://www.linguista.ch/sprachschule/san-diego-cel/'

#browser = webdriver.PhantomJS() # headless
browser = webdriver.Chrome() # run it with chrome browser appearing
browser.get(sdCel)
sellingPoints = soup.find('div', {'class':'column column_620 column_content'})
points_ul = sellingPoints.find_next_siblings()
#points_ul = sellingPoints.parent.find_next_sibling()

for item in points_ul.findAll('li'): #this gives error
    if isinstance(item, Tag):
        print item.text
</code>```

This gives the following error:
AttributeError: 'ResultSet' object has no attribute 'findAll'

This is the part of points_ul which I have to retrieve:

\n

Weshalb wir      College of English Language f\xfcr einen Sprachaufenthalt empfehlen:
\n

Beste Lage im Stadtzentrum von San Diego

Sprachschule mit famil\xe4rer Atmosph\xe4re

Von der Terrasse aus geniessen Sie einen tollen Blick \xfcber die Stadt

Kleine Klasen mit max. 10 Teilnehmern

Hervorragendes Preis- / Leistungsverh\xe4ltnis

\n

答:
That's because sellingPoints.find_next_siblings() is returning you a list, and lists don't have a findAll method.

First iterate the list, then use the findAll in its elements.

Title: Extract <li> tag from BeautifulSoup resultSet

Body:
I want to extract all the
tags from the html page. The needed content can be retrieved with result = soup.find('div', {'class':'column column_620 column_content'}). This returns the first class column_620. After that I get its siblings and want to extract the
 tags. But that result does not have the method findAll().
What can I do to extract the desired
 tag entry?

import re
import time
from datetime import datetime
import platform
import pandas as pd
from numpy import nan
from itertools import chain

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

timestampStart = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

sdCel = 'http://www.linguista.ch/sprachschule/san-diego-cel/'

#browser = webdriver.PhantomJS() # headless
browser = webdriver.Chrome() # run it with chrome browser appearing
browser.get(sdCel)
sellingPoints = soup.find('div', {'class':'column column_620 column_content'})
points_ul = sellingPoints.find_next_siblings()
#points_ul = sellingPoints.parent.find_next_sibling()

for item in points_ul.findAll('li'): #this gives error
    if isinstance(item, Tag):
        print item.text

This gives the following error:
AttributeError: 'ResultSet' object has no attribute 'findAll'

This is the part of points_ul which I have to retrieve:

\n

Weshalb wir      College of English Language f\xfcr einen Sprachaufenthalt empfehlen:
\n

Beste Lage im Stadtzentrum von San Diego

Sprachschule mit famil\xe4rer Atmosph\xe4re

Von der Terrasse aus geniessen Sie einen tollen Blick \xfcber die Stadt

Kleine Klasen mit max. 10 Teilnehmern

Hervorragendes Preis- / Leistungsverh\xe4ltnis

\n


问:
PHP PDO Segmentation fault error on null return value
Currently I am using freetds to connect to a MSSql server where I am pulling in a lot of accounting data. The data is pulling in fine until it hits a null value. At that point I am not receiving any PHP errors. Instead I am getting the following error in the apache error log.

[notice] child pid 10235 exit signal Segmentation fault (11)

I did some searching for this and found this page, but it does not really help. The query I am using looks something like this,

```<code>SELECT DISTINCT(t1.PEREND), t2.ERATE, t2.EEXTEND, t2.EARNDED, t1.ENTRYSEQ
       FROM UPCHKD as t1 LEFT JOIN
            (SELECT EARNDED, PEREND, ERATE, EEXTEND, ENTRYSEQ FROM UPCHKD
                    WHERE (EARNDED LIKE '401K%'AND EARNDED NOT LIKE '401KL%') AND
                          EMPLOYEE = ? AND PEREND >= ? AND PEREND <= ?) as t2 ON t1.PEREND = t2.PEREND
       WHERE t1.PEREND >= ? AND t1.PEREND <= ? AND t1.EMPLOYEE = ? ORDER BY PEREND
</code>```

And I am getting the data using a while loop like the following,

```<code>while($result = $sth->fetch(PDO::FETCH_ASSOC)) {
    //Deal with data here
}
</code>```

I can not tell if this is a problem with PDO, my database layer, MSSQL, or my query. Also, I would like to point out that if I take the query and run it manually using MSSQL studio, it runs fine, and shows the null values properly.

答:
One solution to this issue works by adding if null statements to all return columns like so,

```<code>ISNULL(t2.ERATE, 0) as ERATE, ISNULL(t2.EEXTEND, 0) as EEXTEND, ISNULL(t2.EARNDED, '') as EARNDED
</code>```

If nulls are found now, they are returned as zeros without error. It is not the prettiest, but it works.

Body:
Currently I am using freetds to connect to a MSSql server where I am pulling in a lot of accounting data. The data is pulling in fine until it hits a null value. At that point I am not receiving any PHP errors. Instead I am getting the following error in the apache error log.

[notice] child pid 10235 exit signal Segmentation fault (11)

I did some searching for this and found this page, but it does not really help. The query I am using looks something like this,

SELECT DISTINCT(t1.PEREND), t2.ERATE, t2.EEXTEND, t2.EARNDED, t1.ENTRYSEQ
       FROM UPCHKD as t1 LEFT JOIN
            (SELECT EARNDED, PEREND, ERATE, EEXTEND, ENTRYSEQ FROM UPCHKD
                    WHERE (EARNDED LIKE '401K%'AND EARNDED NOT LIKE '401KL%') AND
                          EMPLOYEE = ? AND PEREND >= ? AND PEREND <= ?) as t2 ON t1.PEREND = t2.PEREND
       WHERE t1.PEREND >= ? AND t1.PEREND <= ? AND t1.EMPLOYEE = ? ORDER BY PEREND

And I am getting the data using a while loop like the following,

while($result = $sth->fetch(PDO::FETCH_ASSOC)) {
    //Deal with data here
}

I can not tell if this is a problem with PDO, my database layer, MSSQL, or my query. Also, I would like to point out that if I take the query and run it manually using MSSQL studio, it runs fine, and shows the null values properly.

Body:
One solution to this issue works by adding if null statements to all return columns like so,

ISNULL(t2.ERATE, 0) as ERATE, ISNULL(t2.EEXTEND, 0) as EEXTEND, ISNULL(t2.EARNDED, '') as EARNDED

If nulls are found now, they are returned as zeros without error. It is not the prettiest, but it works.


问:
Display the result of a registration page on top of the registration form
I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance

Here my code:

```<code><?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    echo "Records added successfully.";
                } else{
                    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
                }

                // close connection
                mysqli_close($conn);
            } else {
                die('Email exists, Please use a different email');
            }
        }
        else {
            die('Passwords not matching, please try again');
        }
    }
</code>```

and here my html

```<code><div class="registration-container">
    <div class="registrationpage-heading">
        <h2>Kostenlos und ohne Installation testen</h2>
        <p>Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.</p>
    </div>

    <div class="user-login">
        <form class="login-form" action="user_login.php" method="post">
            <input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <select name="gender">
            <option>Herr</option>
            <option>Frau </option>
            </select><br><br>

            <input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>

            <input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
        </form>
    </div>

    <div class="register-terms">
        <p>Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.</p>
    </div>
</div>
</code>```

答:
In above scenario, submit the form page itself using

```<code><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
</code>```

But make registration html to php file

```<code><?php
   if(isset($_POST['submitbutton'])){
      //perform validation, display error if any
   }
?>
</code>```

If you want to go modular approach then use class having validate, register method after submit include class file and use methods

Body:
I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance

Here my code:

<?php

$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
mysqli_select_db($conn, 'registration');

    if(isset($_POST['submitbutton'])){

        if ($_POST['password'] == $_POST['confirm_password']) {
            $email = mysqli_real_escape_string($conn, $_POST['email']);
            $password = mysqli_real_escape_string($conn, $_POST['password']);
            $gender = mysqli_real_escape_string($conn, $_POST['gender']);
            $fname = mysqli_real_escape_string($conn, $_POST['fname']);
            $lname = mysqli_real_escape_string($conn, $_POST['lname']);
            $firm = mysqli_real_escape_string($conn, $_POST['firm']);

            $check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
            $count = mysqli_num_rows($check_email_exists);
            if ($count == 0) {
                $sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";

                if(mysqli_query($conn, $sql)){
                    echo "Records added successfully.";
                } else{
                    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
                }

                // close connection
                mysqli_close($conn);
            } else {
                die('Email exists, Please use a different email');
            }
        }
        else {
            die('Passwords not matching, please try again');
        }
    }

and here my html

Kostenlos und ohne Installation testen

Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.

        <form class="login-form" action="user_login.php" method="post">
            <input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <select name="gender">
            <option>Herr</option>
            <option>Frau </option>
            </select>

            <input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
            onfocus="if(this.value==this.defaultValue)this.value=''"
            onblur="if(this.value=='')this.value=this.defaultValue" >

            <input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
        </form>

Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.

Body:
In above scenario, submit the form page itself using

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

But make registration html to php file

<?php
   if(isset($_POST['submitbutton'])){
      //perform validation, display error if any
   }
?>

If you want to go modular approach then use class having validate, register method after submit include class file and use methods


问:
C++ variadic template with doubles
The following code

```<code>#include <initializer_list>
#include <vector>

template<int ...>
const std::vector<int>*make_from_ints(int args...)
{ return new std::vector<int>(std::initializer_list<int>{args}); }
</code>```

is compiling (with GCC 6.3, on Debian/Sid/x86-64) correctly, and I expect it for a call like

```<code>auto vec = make_from_ints(1,2,3);
</code>```

to return a pointer to some vector of integers containing 1, 2, 3.

However, if I replace int by double, that is if I add the following (in the same basiletemplates.cc file ...) code:

```<code>template<double ...>
const std::vector<double>*make_from_doubles(double args...)
{ return new std::vector<double>(std::initializer_list<double>{args}); }
</code>```

I'm getting a compile error:

```<code>basiletemplates.cc:8:17: error: ‘double’ is not a valid type
                for a template non-type parameter
 template<double ...>
                 ^~~
</code>```

and I don't understand why. After all both int and double are scalar numerical POD types (predefined in the C++11 standard).

How to get a template variadic function to be able to code:

```<code>auto dvec = make_from_doubles(-1.0, 2.0, 4.0);
</code>```

and get a pointer to some vector of doubles containing -1.0, 2.0, 4.0 ?

BTW, compiling for C++14 (with g++ -Wall -std=c++14 -c basiletemplates.cc), and using clang++ (version 3.8.1) instead of g++ dont change anything.

答:
```<code>template<int ...>
const std::vector<int>*make_from_ints(int args...)
{ return new std::vector<int>(std::initializer_list<int>{args}); }
</code>```

The snippet above has a multitude of issues:

Returning a const std::vector<int>* instead of a std::vector<int> and unnecessarily using dynamic allocation.

Even if you wanted to use dynamic allocation, you should use std::make_unique instead of new.

You defined make_from_ints to be template function that takes any amount of int template parameters, but you're not giving those ints a name - you cannot ever use them!

Your signature is actually being parsed as make_from_ints(int args, ...) - this is a C va_args signature that has nothing to do with variadic templates.

The correct syntax for an argument pack is type... name.

If you want to accept any number of arguments of a specific type that works nicely with template argument deduction, the easiest way is to use a regular variadic template that accepts an arbitrary amount of types and static_asserts their type (or uses std::enable_if for SFINAE-friendliness). Here's an example:

```<code>template <typename... Ts>
auto make_from_ints(Ts... xs)
{
    static_assert((std::is_same<Ts, int>::value && ...));
    return std::vector<int>{xs...};
}

template <typename... Ts>
auto make_from_doubles(Ts... xs)
{
    static_assert((std::is_same<Ts, double>::value && ...));
    return std::vector<double>{xs...};
}
</code>```

Usage:

```<code>for(auto x : make_from_ints(1,2,3,4)) std::cout << x << " ";
std::cout << "\n";
for(auto x : make_from_doubles(1.0,1.5,2.0,2.5)) std::cout << x << " ";
</code>```

1 2 3 4

1 1.5 2 2.5

live example on wandbox

Note that I'm using a C++17 fold expression to check if all Ts... are of a particular type here:

```<code>static_assert((std::is_same<Ts, int>::value && ...));
</code>```

If you do not have access to C++17 features, this can be easily replaced with something like:

```<code>template <typename... Ts>
constexpr auto all_true(Ts... xs)
{
    for(auto x : std::initializer_list<bool>{xs...})
        if(!x) return false;

    return true;
}

// ...

static_assert(all_true(std::is_same<Ts, int>{}...));
</code>```

Title: C++ variadic template with doubles

Body:
The following code

#include <initializer_list>
#include <vector>

template<int ...>
const std::vector<int>*make_from_ints(int args...)
{ return new std::vector<int>(std::initializer_list<int>{args}); }

is compiling (with GCC 6.3, on Debian/Sid/x86-64) correctly, and I expect it for a call like

auto vec = make_from_ints(1,2,3);

to return a pointer to some vector of integers containing 1, 2, 3.

However, if I replace int by double, that is if I add the following (in the same basiletemplates.cc file ...) code:

template<double ...>
const std::vector<double>*make_from_doubles(double args...)
{ return new std::vector<double>(std::initializer_list<double>{args}); }

I'm getting a compile error:

basiletemplates.cc:8:17: error: ‘double’ is not a valid type
                for a template non-type parameter
 template<double ...>
                 ^~~

and I don't understand why. After all both int and double are scalar numerical POD types (predefined in the C++11 standard).

How to get a template variadic function to be able to code:

auto dvec = make_from_doubles(-1.0, 2.0, 4.0);

and get a pointer to some vector of doubles containing -1.0, 2.0, 4.0 ?

BTW, compiling for C++14 (with g++ -Wall -std=c++14 -c basiletemplates.cc), and using clang++ (version 3.8.1) instead of g++ dont change anything.

Body:
template<int ...>
const std::vector<int>*make_from_ints(int args...)
{ return new std::vector<int>(std::initializer_list<int>{args}); }

The snippet above has a multitude of issues:

Returning a const std::vector<int>* instead of a std::vector<int> and unnecessarily using dynamic allocation.

Even if you wanted to use dynamic allocation, you should use std::make_unique instead of new.

You defined make_from_ints to be template function that takes any amount of int template parameters, but you're not giving those ints a name - you cannot ever use them!

Your signature is actually being parsed as make_from_ints(int args, ...) - this is a C va_args signature that has nothing to do with variadic templates.

The correct syntax for an argument pack is type... name.

If you want to accept any number of arguments of a specific type that works nicely with template argument deduction, the easiest way is to use a regular variadic template that accepts an arbitrary amount of types and static_asserts their type (or uses std::enable_if for SFINAE-friendliness). Here's an example:

template <typename... Ts>
auto make_from_ints(Ts... xs)
{
    static_assert((std::is_same<Ts, int>::value && ...));
    return std::vector<int>{xs...};
}

template <typename... Ts>
auto make_from_doubles(Ts... xs)
{
    static_assert((std::is_same<Ts, double>::value && ...));
    return std::vector<double>{xs...};
}

Usage:

for(auto x : make_from_ints(1,2,3,4)) std::cout << x << " ";
std::cout << "\n";
for(auto x : make_from_doubles(1.0,1.5,2.0,2.5)) std::cout << x << " ";

1 2 3 4

1 1.5 2 2.5

live example on wandbox

Note that I'm using a C++17 fold expression to check if all Ts... are of a particular type here:

static_assert((std::is_same<Ts, int>::value && ...));

If you do not have access to C++17 features, this can be easily replaced with something like:

template <typename... Ts>
constexpr auto all_true(Ts... xs)
{
    for(auto x : std::initializer_list<bool>{xs...})
        if(!x) return false;

    return true;
}

// ...

static_assert(all_true(std::is_same<Ts, int>{}...));


答:
What is the effect in term of running performance when all static function become non-static function ?

The answer is "some", I think. The only way you can be sure what the performance issue is likely to be is to measure the performance of your program with and without static functions. The most obvious thing I can think of is that the optimiser might not be able to inline non static functions.

You actually don't need to make the static functions non static, the only issue will be the lack of symbolic names in the backtrace.

However, I think you have bigger problems. From your link to the man page:

Omission of the frame pointers (as implied by any of gcc(1)'s nonzero optimization levels) may cause these assumptions to be violated.

For backstrace to work reliably, it looks like you will have to compile without optimisation. That will certainly have a huge impact on performance. I think I'd manage without it.

Title: Effect of removal "static" keyword for function

Body:
Recently, I have learned the existence of "backtrace" function.
This function allow one to retrieve, at some conditions, the callstack of an ELF running program compiled without debugging information.

It's perfect for me (I can't insert debugging symbol in production program), but for "backtrace" to work, there is (roughly) two condition :

Tell the linker to add extra information (by passing -rdynamic option).

Convert all "static" function to "non-static" function.

My worries is that if I fullfill this two condition, my program will be slower (because compiler can't optimise non-static function as he optimize static function ?).
As far as I know, adding extra information with -rdynamic doesn't impact program's performance : it's just add a little weight to the ELF binary.

So here's my question :

What is the effect in term of running performance when all static function become non-static function ?