问:
JS Bitwise Operator to Java
I'm trying to convert a js function to Java but i don't know how to work with JS Bitwise operator in java.

I need to translate this:

var r = '0x' + a.substring(j, 2) | 0     and
('0x' + a.substr(j, 2) ^ r)

Has anyone ever done that?

Thanks!

答:
First, separate the the string parsing and the bitwise operators into separate steps.

(Bjorn pointed out above; bitwise operators don't auto-cast in Java like they do in Javascript!)

So

```<code>'0x' + a.substring(j, 2)
</code>```

Becomes :

```<code> String foo = '0x' + a.substring(j, 2);
 int value = Integer.parseInt(foo, 16);
</code>```

Which should take a base-16 number represented in a string, and move it to an int.   Once you've got it as an int, you can use Java bitwise operators just fine.

Title: JS Bitwise Operator to Java

Body:
First, separate the the string parsing and the bitwise operators into separate steps.

(Bjorn pointed out above; bitwise operators don't auto-cast in Java like they do in Javascript!)

So

'0x' + a.substring(j, 2)

Becomes :

 String foo = '0x' + a.substring(j, 2);
 int value = Integer.parseInt(foo, 16);

Which should take a base-16 number represented in a string, and move it to an int.   Once you've got it as an int, you can use Java bitwise operators just fine.


来源: stackexchange

问:
Create Custom Switch button as shown in image
Is it possible to create the custom switch as shown in image below
(Specifically switch button and not the toggle button). I have referred this link and it creates toggle button http://www.mokasocial.com/2011/07/sexily-styled-toggle-buttons-for-android/

答:
Firstly, you must create two drawables for thumb and track property of Switch.

Thumb is back and forth of Switch,
Track is slide of Switch.

```<code><Switch
        android:id="@+id/sWidgetSwitchBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:thumb="@drawable/custom_switch_thumb"
        android:track="@drawable/custom_switch_track"/>
</code>```

Thumb :

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape
            android:dither="true"
            android:shape="rectangle"
            android:useLevel="false"
            android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/switch_thumb_on"
                android:startColor="@color/switch_thumb_on"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="47dp"
                android:height="47dp"/>
            <stroke
                android:width="4dp"
                android:color="#0000ffff"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape
            android:dither="true"
            android:shape="rectangle"
            android:useLevel="false"
            android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/actionbutton_bg_darkblue"
                android:startColor="@color/actionbutton_bg_darkblue"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="47dp"
                android:height="47dp"/>
            <stroke
                android:width="4dp"
                android:color="#0000ffff"/>
        </shape>
    </item>
</code>```

Track:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:dither="true"
               android:shape="rectangle"
               android:useLevel="false"
               android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/switch_track_bg"
                android:startColor="@color/switch_track_bg"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="100dp"
                android:height="50dp"/>
        </shape>

    </item>

    <item android:state_checked="false">
        <shape android:dither="true"
               android:shape="rectangle"
               android:useLevel="false"
               android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/black"
                android:startColor="@color/black"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="100dp"
                android:height="50dp"/>
        </shape>

    </item>
</selector>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Firstly, you must create two drawables for thumb and track property of Switch.

Thumb is back and forth of Switch,
Track is slide of Switch.

<Switch
        android:id="@+id/sWidgetSwitchBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:thumb="@drawable/custom_switch_thumb"
        android:track="@drawable/custom_switch_track"/>

Thumb :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape
            android:dither="true"
            android:shape="rectangle"
            android:useLevel="false"
            android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/switch_thumb_on"
                android:startColor="@color/switch_thumb_on"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="47dp"
                android:height="47dp"/>
            <stroke
                android:width="4dp"
                android:color="#0000ffff"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape
            android:dither="true"
            android:shape="rectangle"
            android:useLevel="false"
            android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/actionbutton_bg_darkblue"
                android:startColor="@color/actionbutton_bg_darkblue"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="47dp"
                android:height="47dp"/>
            <stroke
                android:width="4dp"
                android:color="#0000ffff"/>
        </shape>
    </item>

Track:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:dither="true"
               android:shape="rectangle"
               android:useLevel="false"
               android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/switch_track_bg"
                android:startColor="@color/switch_track_bg"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="100dp"
                android:height="50dp"/>
        </shape>

    </item>

    <item android:state_checked="false">
        <shape android:dither="true"
               android:shape="rectangle"
               android:useLevel="false"
               android:visible="true">
            <gradient
                android:angle="270"
                android:endColor="@color/black"
                android:startColor="@color/black"/>
            <corners
                android:radius="5dp"/>
            <size
                android:width="100dp"
                android:height="50dp"/>
        </shape>

    </item>
</selector>


问:
My class doesn't seem to map correctly with an API's JSON response, not binding
I am having issues with deserializing a JSON response.

```<code>userResponse = JsonConvert.DeserializeObject<UserResponse>(result);
</code>```

The json response looks like:

```<code>{
    "Results" : [
        {
            "Id" :  1,
            "Name" : "John",
            "Age"  : 50
        }
    ],
    "Paging" : {
        "TotalPages" : 5,
        "CurrentPage" : 1
    }
}
</code>```

My UserResponse class that is suppose to bind to the JSON above looks like:

```<code>[DataContract]
public class UserResponse
{
    [DateMember(Name = "Results" )]
    public List<User> Results {get;set;}

    [DateMember(Name = "Paging" )]
    public Paging Paging {get;set;}

}

[DataContract]
public class User
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Age {get;set;}
}

[DataContract]
public class Paging
{
    public int TotalPages {get;set;}
    public int CurrentPage {get;set;}
}
</code>```

Does the current UserResponse look have any issues with it?
I'm not sure why it isn't binding correctly.

The userResponse object is coming back not null, but the values of the properties are null.

答:
Because you are using DataContract you need to include the DataMember attribute on the other classes as well. Using DataContract is all or nothing.

If you look at Json.Net documentation about DataContract and DataMember Attributes

```<code>[DataContract]
public class File
{
    // excluded from serialization
    // does not have DataMemberAttribute
    public Guid Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Size { get; set; }
}
</code>```

Note the comment in the example.

So to solve your problem, either remove all DataContract and DataMember attributes

```<code>public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Paging
{
    public int TotalPages { get; set; }
    public int CurrentPage { get; set; }
}

public class UserResponse
{
    public List<User> Results { get; set; }
    public Paging Paging { get; set; }
}
</code>```

or have everything properly adorned with their respective attributes.

```<code>[DataContract]
public class User {
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Age { get; set; }
}

[DataContract]
public class Paging {
    [DataMember]
    public int TotalPages { get; set; }

    [DataMember]
    public int CurrentPage { get; set; }
}

[DataContract]
public class UserResponse {
    [DataMember]
    public List<User> Results { get; set; }

    [DataMember]
    public Paging Paging { get; set; }
}
</code>```

Body:
I am having issues with deserializing a JSON response.

userResponse = JsonConvert.DeserializeObject<UserResponse>(result);

The json response looks like:

{
    "Results" : [
        {
            "Id" :  1,
            "Name" : "John",
            "Age"  : 50
        }
    ],
    "Paging" : {
        "TotalPages" : 5,
        "CurrentPage" : 1
    }
}

My UserResponse class that is suppose to bind to the JSON above looks like:

[DataContract]
public class UserResponse
{
    [DateMember(Name = "Results" )]
    public List<User> Results {get;set;}

    [DateMember(Name = "Paging" )]
    public Paging Paging {get;set;}

}

[DataContract]
public class User
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Age {get;set;}
}

[DataContract]
public class Paging
{
    public int TotalPages {get;set;}
    public int CurrentPage {get;set;}
}

Does the current UserResponse look have any issues with it?
I'm not sure why it isn't binding correctly.

The userResponse object is coming back not null, but the values of the properties are null.

Body:
Because you are using DataContract you need to include the DataMember attribute on the other classes as well. Using DataContract is all or nothing.

If you look at Json.Net documentation about DataContract and DataMember Attributes

[DataContract]
public class File
{
    // excluded from serialization
    // does not have DataMemberAttribute
    public Guid Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Size { get; set; }
}

Note the comment in the example.

So to solve your problem, either remove all DataContract and DataMember attributes

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Paging
{
    public int TotalPages { get; set; }
    public int CurrentPage { get; set; }
}

public class UserResponse
{
    public List<User> Results { get; set; }
    public Paging Paging { get; set; }
}

or have everything properly adorned with their respective attributes.

[DataContract]
public class User {
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Age { get; set; }
}

[DataContract]
public class Paging {
    [DataMember]
    public int TotalPages { get; set; }

    [DataMember]
    public int CurrentPage { get; set; }
}

[DataContract]
public class UserResponse {
    [DataMember]
    public List<User> Results { get; set; }

    [DataMember]
    public Paging Paging { get; set; }
}


问:
Swing: easiest way to align width of [dynamic][static][dynamic] components?
What is the easiest way in standard Java Swing to align three components in such a way that:

the dynamic widths of Component1 and Component3 are adjusted to be equal,

while Component2 (which is in between) has constant width?

Imagine we have some resizable JPanel (such as inside a JFrame).

Small width should look like this:

```<code>[----------------whole JPanel----------------]
[--Component1--] [Component2] [--Component3--]
</code>```

Big width should look like this:

```<code>[------------------------whole JPanel------------------------]
[------Component1------] [Component2] [------Component3------]
</code>```

Note: I just "trialed-and-errored" with GroupLayout for too long.

答:
One option is using a GridBagLayout.  A quick and dirty snippet to get you started:

```<code>GridBagConstraints gbc;
final int A_CENTER = GridBagConstraints.CENTER;  // anchor: center
final int F_NONE = GridBagConstraints.NONE;  // fill: none
final int F_DX = GridBagConstraints.HORIZONTAL;  // fill: dx only
final Insets IN_0 = new Insets(0, 0, 0, 0);  // empty insets

setLayout(new GridBagLayout() );
gbc = new GridBagConstraints(0, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);
gbc = new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, A_CENTER, F_NONE, IN_0, 0, 0);
add(new JButton("test2"), gbc);
gbc = new GridBagConstraints(2, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);
</code>```

Obviously there's a lot more you can do with a GridBag, and you'll need to do some polishing to get exactly what you want to see, but this should get you started.

The fifth parameter in the GBC constructor is a weight for stretching in the x direction.  Setting them equal, and forcing the center component not to stretch (F_NONE) does the dirty work.

ContentLicense: CC BY-SA 2.5

Body:
What is the easiest way in standard Java Swing to align three components in such a way that:

the dynamic widths of Component1 and Component3 are adjusted to be equal,

while Component2 (which is in between) has constant width?

Imagine we have some resizable JPanel (such as inside a JFrame).

Small width should look like this:

[----------------whole JPanel----------------]
[--Component1--] [Component2] [--Component3--]

Big width should look like this:

[------------------------whole JPanel------------------------]
[------Component1------] [Component2] [------Component3------]

Note: I just "trialed-and-errored" with GroupLayout for too long.

Body:
One option is using a GridBagLayout.  A quick and dirty snippet to get you started:

GridBagConstraints gbc;
final int A_CENTER = GridBagConstraints.CENTER;  // anchor: center
final int F_NONE = GridBagConstraints.NONE;  // fill: none
final int F_DX = GridBagConstraints.HORIZONTAL;  // fill: dx only
final Insets IN_0 = new Insets(0, 0, 0, 0);  // empty insets

setLayout(new GridBagLayout() );
gbc = new GridBagConstraints(0, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);
gbc = new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, A_CENTER, F_NONE, IN_0, 0, 0);
add(new JButton("test2"), gbc);
gbc = new GridBagConstraints(2, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);

Obviously there's a lot more you can do with a GridBag, and you'll need to do some polishing to get exactly what you want to see, but this should get you started.

The fifth parameter in the GBC constructor is a weight for stretching in the x direction.  Setting them equal, and forcing the center component not to stretch (F_NONE) does the dirty work.


问:
Working with two databases from different domains within a same server
I have two domains.

In domain A, I have a PHP web site and in domain B, I have Java Website.

Now I want to use both database from both site.

How can I do that? I am using MySql 5.7.17

答:
You could set up a third server dedicated to mySQL and share that database with the 2 web servers, or you can just run a mySQL database on each of those computers and use the IP address or domain name of them to connect to each other's server

Explanation:

You currently have a java website running and a php website running on one machine if i understand correctly.

What you need to do is download mySQL, and go through the tutorial to get the server up and running https://dev.mysql.com/doc/mysql-getting-started/en/

Then you need to download the mysql Java driver, and the mysql PHP driver

Then you need to use the drivers to connect to the same mySQL server from the code, which would be on localhost if you are doing it all on one machine.

MySQL is a server. It is its own thing, not a database like SQLite that you create in the java code or php code. You create and set it up separately as it's own server, and then any other server can connect to it


问:
Google Maps API google.maps.event is undefined
I'm attempting to use the Google Maps API to get a location provided by the user. To do this I'm setting a marker that moves based on 'click' events. The code is as such:

```<code>function initialize_google_map(div_id) {
    var map = new GMap2(document.getElementById(div_id));

    map.setCenter(new GLatLng(45, -105), 2);

    map.setUIToDefault();

    return map;
}

$(document).ready(function() {
    // configure the google maps api
    var map = initialize_google_map("map_canvas");
    var marker = google.maps.Marker({map: map, title:"Location"});
    google.maps.event.addListener(map, "click", function(evt) {
        alert("got click event");
        marker.setPosition(evt.latLng);
    });

    $(document).unload(function() {
    // unload the google map
    GUnload();
    });

});
</code>```

The "got click event" alert is never firing, and my Javascript console (Google Chrome) says this:

Uncaught TypeError: Cannot call method 'addListener' of undefined

The API is included like this:

答:
The problem here is that you are mixing Google Maps version two objects with Version 3.  In your initialize_google_map function you are creating and returning a GMap2 object (a version 2 object).  You are then passing this object into a google.maps.Marker object constructor (a version 3 object).

You just need to modify your initialize_google_map function to instantiate a google.maps.Map object.

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to use the Google Maps API to get a location provided by the user. To do this I'm setting a marker that moves based on 'click' events. The code is as such:

function initialize_google_map(div_id) {
    var map = new GMap2(document.getElementById(div_id));

    map.setCenter(new GLatLng(45, -105), 2);

    map.setUIToDefault();

    return map;
}

$(document).ready(function() {
    // configure the google maps api
    var map = initialize_google_map("map_canvas");
    var marker = google.maps.Marker({map: map, title:"Location"});
    google.maps.event.addListener(map, "click", function(evt) {
        alert("got click event");
        marker.setPosition(evt.latLng);
    });

    $(document).unload(function() {
    // unload the google map
    GUnload();
    });

});

The "got click event" alert is never firing, and my Javascript console (Google Chrome) says this:

Uncaught TypeError: Cannot call method 'addListener' of undefined

The API is included like this:


问:
Raw 2D arrays as function parameters in C++
Are raw arrays unsafe to use in C++ considering there are libraries such as std::array and std::vector? For embedded systems, using std::vector I believe may not be efficient particularly when there are several functions to implement and there's some heavy mathematical algorithms inside each function.
std::array isn't supported in the IDE I am working in. Is there any other way around raw arrays or they are fine to use? Or perhaps wrap arrays in a class?

Below is an example of how I am implementing this:

main.cpp

```<code>#include "file.hpp"
#include <stdio.h>

int main(void){

   funcClass func_class;

   func_class.divide();
   func_class.returnValue = func_class.multiply(func_class.vector);
</code>```

file.h

```<code>#ifndef file_hpp
#define file_hpp

 class funcClass{

   public:

   static const double a;
   static const double b;
   static const double c;

   double var1, var2, var3;

   void divide();

   double (*multiply(double answer[4][1]))[1];
   double vector[4][1];
   double (*returnValue)[1];

 };

#endif /* file_hpp */
</code>```

file.cpp

```<code>#include <stdio.h>
#include <cmath>
#include "file.hpp"

 const double funcClass::a = 5.5;    //constants
 const double funcClass::b = 4.4;
 const double funcClass::c = 14.4;

 funcClass::funcClass(){          //constructor for initializing variables

   var1 = 10.5;
   var2 = 20.5;
   var3 = 100.0;

 }

 void divide(){

    // some mathematical algorithms

 }

 double (*funcClass::multiply(double answer[4][1]))[1]{

 //.......

 answer[0][0] = 30.5;
 answer[1][0] = 31.6;
 answer[2][0] = 10.5;
 answer[3][0] = 21.6;

  return answer;
 }
</code>```

答:
2D arrays are allowed per C++ standard from the beginning of C++ to the last (and upcoming version), so you can use them. But that's not the nicer part of the language, and you must be prepared to control twice your code. If you can, std::array (fixed size) and std::vector (variable size) are much more programmer friendly. But at the very end, they are implemented through raw arrays and raw pointers...

My advice, is that it is legitimate to use raw arrays (including 2D arrays) if you know why in your use case they are better suited than standard containers, but it would certainly be better to wrap them in higher level classes if is makes sense, or simply typedefs if it is enough to keep the high program architecture clean.

Said differently: if in doubt, stick to standard containers, your life will be easier; but raw 2D arrays are not forbidden.

Body:
Are raw arrays unsafe to use in C++ considering there are libraries such as std::array and std::vector? For embedded systems, using std::vector I believe may not be efficient particularly when there are several functions to implement and there's some heavy mathematical algorithms inside each function.
std::array isn't supported in the IDE I am working in. Is there any other way around raw arrays or they are fine to use? Or perhaps wrap arrays in a class?

Below is an example of how I am implementing this:

main.cpp

#include "file.hpp"
#include <stdio.h>

int main(void){

   funcClass func_class;

   func_class.divide();
   func_class.returnValue = func_class.multiply(func_class.vector);

file.h

#ifndef file_hpp
#define file_hpp

 class funcClass{

   public:

   static const double a;
   static const double b;
   static const double c;

   double var1, var2, var3;

   void divide();

   double (*multiply(double answer[4][1]))[1];
   double vector[4][1];
   double (*returnValue)[1];

 };

#endif /* file_hpp */

file.cpp

#include <stdio.h>
#include <cmath>
#include "file.hpp"

 const double funcClass::a = 5.5;    //constants
 const double funcClass::b = 4.4;
 const double funcClass::c = 14.4;

 funcClass::funcClass(){          //constructor for initializing variables

   var1 = 10.5;
   var2 = 20.5;
   var3 = 100.0;

 }

 void divide(){

    // some mathematical algorithms

 }

 double (*funcClass::multiply(double answer[4][1]))[1]{

 //.......

 answer[0][0] = 30.5;
 answer[1][0] = 31.6;
 answer[2][0] = 10.5;
 answer[3][0] = 21.6;

  return answer;
 }


问:
Higlight text in JTextField but only when tabbing
I want to create a JDialog where the text in the textfields is selected but only if the focus is gained from keyboard (TAB, CTRL+TAB). I have found several topics on this matter but had problems with implementing it.

Here is one which I was trying.

And my code:

```<code>public class Dialogg extends JDialog implements FocusListener, MouseListener {

private boolean focusFromMouse = false;

public Dialogg() {
    JTextField tf1 = new JTextField("text1");
    JTextField tf2 = new JTextField("text2");

    tf1.addMouseListener(this);
    tf2.addMouseListener(this);
    tf1.addFocusListener(this);
    tf2.addFocusListener(this);
}

@Override
public void focusGained(FocusEvent e) {
    if (!focusFromMouse) {
        JTextField tf = (JTextField) e.getComponent();
        tf.selectAll();
        focusFromMouse = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    focusFromMouse = false;
}

@Override
public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}
</code>```

}

It does not work as intended, it does not matter what is focus source the text always highlights. When I run the code and follow it step by step it turns out that focusGained code happens before mouseClicked code so the flag is not reset when it should. Any hints?

EDIT:

As suggested by M. Prokhorov I have deleted less relevant (for the question) lines from the code.Thank you.

EDIT 2:

I am trying to wrap focus listener as suggested by camickr. It looks like this now:

```<code>tf1.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                        if (!focusFromMouse){
                        tf1.selectAll();
                        focusFromMouse=true;
                    }
                }
            });
        }
        public void focusLost(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    focusFromMouse=false;
                }
            });
        }
    });
public void mouseClicked(MouseEvent e) {
        focusFromMouse=true;
</code>```

I am printing line after each event to see the action order and still mouseClicked happens last. What am I doing wrong?

EDIT 3:

OK, I have found a solution which fulfils requirements of my simple Dialog.
I could not find a way of doing this with use of invokeLater or EventQueue. Vladislav's method works but as I understand it restricts the user to only use the keyboard.
I have used the initial approach but I have added an auxiliary variable and few conditions which allow to pass the flag "unharmed" trough Events that should not change the flag at given moment. It may not be subtle or universal but works for my app. Here is the code:

```<code>public void focusGained(FocusEvent e) {
    if(!focusFromMouse){
        if (higlight){
           JTextField tf = (JTextField) e.getComponent();
           tf.selectAll();
           focusFromMouse=false;
        }
    }
}

public void focusLost(FocusEvent e) {
    if (focusFromMouse){
        higlight=false;
        focusFromMouse=false;
    }else{
        higlight=true;
    }
}

public void mousePressed(MouseEvent e) {
    focusFromMouse=true;
}
</code>```

答:
At the first, by default, focus on JTextField is requested by mouse-press event, not by mouse-click.

So, this method:

```<code>public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}
</code>```

is useless because the mouse-click event is triggered after the mouse-press event.

One way to solve your problem is to remove all native MouseListeners from JTextField:

```<code>...
for( MouseListener ml : tf1.getMouseListeners() ){
    tf1.removeMouseListener(ml);
}

for( MouseMotionListener mml : tf1.getMouseMotionListeners() ){
    tf1.removeMouseMotionListener(mml);
}
...
</code>```

Another way is to handle all mouse events and consume those of them, which are triggered by JTextField:

```<code>Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
  @Override
  public void eventDispatched(AWTEvent event) {
    if( event.getSource() == tf1 ){
      ((MouseEvent)event).consume();
    }
  }
}, AWTEvent.MOUSE_EVENT_MASK);
</code>```

Body:
I want to create a JDialog where the text in the textfields is selected but only if the focus is gained from keyboard (TAB, CTRL+TAB). I have found several topics on this matter but had problems with implementing it.

Here is one which I was trying.

And my code:

public class Dialogg extends JDialog implements FocusListener, MouseListener {

private boolean focusFromMouse = false;

public Dialogg() {
    JTextField tf1 = new JTextField("text1");
    JTextField tf2 = new JTextField("text2");

    tf1.addMouseListener(this);
    tf2.addMouseListener(this);
    tf1.addFocusListener(this);
    tf2.addFocusListener(this);
}

@Override
public void focusGained(FocusEvent e) {
    if (!focusFromMouse) {
        JTextField tf = (JTextField) e.getComponent();
        tf.selectAll();
        focusFromMouse = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    focusFromMouse = false;
}

@Override
public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}

}

It does not work as intended, it does not matter what is focus source the text always highlights. When I run the code and follow it step by step it turns out that focusGained code happens before mouseClicked code so the flag is not reset when it should. Any hints?

EDIT:

As suggested by M. Prokhorov I have deleted less relevant (for the question) lines from the code.Thank you.

EDIT 2:

I am trying to wrap focus listener as suggested by camickr. It looks like this now:

tf1.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                        if (!focusFromMouse){
                        tf1.selectAll();
                        focusFromMouse=true;
                    }
                }
            });
        }
        public void focusLost(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    focusFromMouse=false;
                }
            });
        }
    });
public void mouseClicked(MouseEvent e) {
        focusFromMouse=true;

I am printing line after each event to see the action order and still mouseClicked happens last. What am I doing wrong?

EDIT 3:

OK, I have found a solution which fulfils requirements of my simple Dialog.
I could not find a way of doing this with use of invokeLater or EventQueue. Vladislav's method works but as I understand it restricts the user to only use the keyboard.
I have used the initial approach but I have added an auxiliary variable and few conditions which allow to pass the flag "unharmed" trough Events that should not change the flag at given moment. It may not be subtle or universal but works for my app. Here is the code:

public void focusGained(FocusEvent e) {
    if(!focusFromMouse){
        if (higlight){
           JTextField tf = (JTextField) e.getComponent();
           tf.selectAll();
           focusFromMouse=false;
        }
    }
}

public void focusLost(FocusEvent e) {
    if (focusFromMouse){
        higlight=false;
        focusFromMouse=false;
    }else{
        higlight=true;
    }
}

public void mousePressed(MouseEvent e) {
    focusFromMouse=true;
}

Body:
At the first, by default, focus on JTextField is requested by mouse-press event, not by mouse-click.

So, this method:

public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}

is useless because the mouse-click event is triggered after the mouse-press event.

One way to solve your problem is to remove all native MouseListeners from JTextField:

...
for( MouseListener ml : tf1.getMouseListeners() ){
    tf1.removeMouseListener(ml);
}

for( MouseMotionListener mml : tf1.getMouseMotionListeners() ){
    tf1.removeMouseMotionListener(mml);
}
...

Another way is to handle all mouse events and consume those of them, which are triggered by JTextField:

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
  @Override
  public void eventDispatched(AWTEvent event) {
    if( event.getSource() == tf1 ){
      ((MouseEvent)event).consume();
    }
  }
}, AWTEvent.MOUSE_EVENT_MASK);


问:
UICollectionView inside UIScrollView cells disappear
I have a strange behaviour of collectionView when I change contentInset of scrollView when the keyboard is appear. And sometimes the cells just disappears, I don't know how this happens.

self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardRect.height, right: 0)

Here is a test project. in google drive. I have tested XCode 8.3, iOS 10, Simulator iPhone SE

automaticallyAdjustsScrollViewInsets = false doesn't work

答:
Well, that is rather odd. When the scrollView.contentInset is changed, or when the scrollView size is changed, the .contentSize.height of the embedded UICollectionView changes to 32. I can't figure out why. It doesn't seem to be related to anything else...

I tried loading it as a Child VC and adding it as a subview instead of using "embedded in Container View" method -- same result.

Couple workarounds though (or, if it sounds better, alternate approaches)...

It does not appear to happen if the embedded Child VC in the ContainerView is a regular UIViewController with a UICollectionView added as a subview.

It does not appear to happen if you add a Collection View directly to the View Controller, and skip the whole Container View thing.


问:
How to transform employee attendence from rows to columns
I have two tables, lets say, tblEmployees and tblAttendence. Employees table only contains employee codes and names, and attendence tables contains entry for each day for each employee if it is absent or not.

I post my test script with this question with 5 dummy records for employee and 30 rows in attendence table for each employee for a month (june 2017), so attendence table will have total 150(5x30) rows. I need the output in a tabular form showing employee names in each row but each day will appear in separate column. In my test script I did this for only 7 days with using left outer joins to same table with different day condition.

Here is the script:

```<code>----create dummy tables for 'Employee', and 'Attendence'
declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = '1 jun 2017'
declare @DateLast date = '30 jun 2017'

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = ('E00' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = ('Emp_Name_' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end

-------at this points, we have 2 tables,
-------tblEmployee contains 5 dummy records

----this query will do the actual job
----i.e, tranform attendence data against each employee for each day

select
e.*
,t1.Absence as Day1
,t2.Absence as Day2
,t3.Absence as Day3
,t4.Absence as Day4
,t5.Absence as Day5
,t6.Absence as Day6
,t7.Absence as Day7

from @tblEmployee e
left outer join @tblAttendence t1 on t1.EmployeeID = e.EmployeeID and t1.AttendenceDay = 1
left outer join @tblAttendence t2 on t2.EmployeeID = e.EmployeeID and t2.AttendenceDay = 2
left outer join @tblAttendence t3 on t3.EmployeeID = e.EmployeeID and t3.AttendenceDay = 3
left outer join @tblAttendence t4 on t4.EmployeeID = e.EmployeeID and t4.AttendenceDay = 4
left outer join @tblAttendence t5 on t5.EmployeeID = e.EmployeeID and t5.AttendenceDay = 5
left outer join @tblAttendence t6 on t6.EmployeeID = e.EmployeeID and t6.AttendenceDay = 6
left outer join @tblAttendence t7 on t7.EmployeeID = e.EmployeeID and t7.AttendenceDay = 7
</code>```

Now I have to do same work with full month days, means 30 columns required against employee record and using this technique I have to copy paste same code.

Is it a right approach for solving this problem or is there any better solution?

答:
Just Run this cte and we will get Query in message Then copy and run the code along with your you will get you expected out put

```<code>DECLARE @SQL nvarchar(max)
;With cte
AS
(
SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno
FROM master..spt_values

)
,Ct2 AS
(
SELECT Rno FROM cte WHERE Rno <=30
)
SELECT DISTINCT  @SQL=CONCAT('SELECT e.*,',
STUFF((SELECT ', '+' t'+CAST(Rno AS VARCHAR(10))+'.Absence AS [Day'+CAST(Rno AS VARCHAR(10))+']' FROM Ct2 i
  FOR XML PATH ('')),1,1,''),'  FROM @tblEmployee e',
  STUFF((SELECT '  '+' LEFT OUTER JOIN @tblAttendence t'+CAST(Rno AS VARCHAR(10))+' ON t'+CAST(Rno AS VARCHAR(10))+'.EmployeeID = e.EmployeeID AND t'+CAST(Rno AS VARCHAR(10))+'.AttendenceDay ='+CAST(Rno AS VARCHAR(10)) FROM Ct2 i
  FOR XML PATH ('')),1,1,''))
FROM Ct2 o

PRINT @SQL
</code>```

Here one more method is Dynamic sql process

```<code>SET NOCOUNT ON
DECLARE @RunCommand TABLE(RunCommand nvarchar(max))
DECLARE @SQL nvarchar(max),
        @SQL2 nvarchar(max),
        @FullSql nvarchar(max)
SET @SQL='
---create dummy tables for ''Employee'', and ''Attendence''

declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = ''1 july 2017''
declare @DateLast date = ''31 july 2017''

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = (''E00'' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = (''Emp_Name_'' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end
'
SET @SQL2='
;With cte
AS
(
SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno
FROM master..spt_values

)
,Ct2 AS
(
SELECT Rno FROM cte WHERE Rno <=31
)
SELECT DISTINCT  CONCAT(''SELECT e.*,'',
STUFF((SELECT '', ''+'' t''+CAST(Rno AS VARCHAR(10))+''.Absence AS [Day''+CAST(Rno AS VARCHAR(10))+'']'' FROM Ct2 i
  FOR XML PATH ('''')),1,1,''''),''  FROM @tblEmployee e'',
  STUFF((SELECT ''  ''+'' LEFT OUTER JOIN @tblAttendence t''+CAST(Rno AS VARCHAR(10))+'' ON t''+CAST(Rno AS VARCHAR(10))+''.EmployeeID = e.EmployeeID AND t''+CAST(Rno AS VARCHAR(10))+''.AttendenceDay =''+CAST(Rno AS VARCHAR(10)) FROM Ct2 i
  FOR XML PATH ('''')),1,1,''''))
FROM Ct2 o
'
INSERT INTO @RunCommand
EXEC( @SQl2)

SELECT @SQL2=RunCommand FROM @RunCommand

SET @FullSql=@SQL+@SQL2

PRINT @FullSql

EXEC(@FullSql)

SET NOCOUNT OFF
</code>```

Body:
I have two tables, lets say, tblEmployees and tblAttendence. Employees table only contains employee codes and names, and attendence tables contains entry for each day for each employee if it is absent or not.

I post my test script with this question with 5 dummy records for employee and 30 rows in attendence table for each employee for a month (june 2017), so attendence table will have total 150(5x30) rows. I need the output in a tabular form showing employee names in each row but each day will appear in separate column. In my test script I did this for only 7 days with using left outer joins to same table with different day condition.

Here is the script:

----create dummy tables for 'Employee', and 'Attendence'
declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = '1 jun 2017'
declare @DateLast date = '30 jun 2017'

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = ('E00' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = ('Emp_Name_' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end

-------at this points, we have 2 tables,
-------tblEmployee contains 5 dummy records

----this query will do the actual job
----i.e, tranform attendence data against each employee for each day

select
e.*
,t1.Absence as Day1
,t2.Absence as Day2
,t3.Absence as Day3
,t4.Absence as Day4
,t5.Absence as Day5
,t6.Absence as Day6
,t7.Absence as Day7

from @tblEmployee e
left outer join @tblAttendence t1 on t1.EmployeeID = e.EmployeeID and t1.AttendenceDay = 1
left outer join @tblAttendence t2 on t2.EmployeeID = e.EmployeeID and t2.AttendenceDay = 2
left outer join @tblAttendence t3 on t3.EmployeeID = e.EmployeeID and t3.AttendenceDay = 3
left outer join @tblAttendence t4 on t4.EmployeeID = e.EmployeeID and t4.AttendenceDay = 4
left outer join @tblAttendence t5 on t5.EmployeeID = e.EmployeeID and t5.AttendenceDay = 5
left outer join @tblAttendence t6 on t6.EmployeeID = e.EmployeeID and t6.AttendenceDay = 6
left outer join @tblAttendence t7 on t7.EmployeeID = e.EmployeeID and t7.AttendenceDay = 7

Now I have to do same work with full month days, means 30 columns required against employee record and using this technique I have to copy paste same code.

Is it a right approach for solving this problem or is there any better solution?

Body:
Just Run this cte and we will get Query in message Then copy and run the code along with your you will get you expected out put

DECLARE @SQL nvarchar(max)
;With cte
AS
(
SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno
FROM master..spt_values

)
,Ct2 AS
(
SELECT Rno FROM cte WHERE Rno <=30
)
SELECT DISTINCT  @SQL=CONCAT('SELECT e.*,',
STUFF((SELECT ', '+' t'+CAST(Rno AS VARCHAR(10))+'.Absence AS [Day'+CAST(Rno AS VARCHAR(10))+']' FROM Ct2 i
  FOR XML PATH ('')),1,1,''),'  FROM @tblEmployee e',
  STUFF((SELECT '  '+' LEFT OUTER JOIN @tblAttendence t'+CAST(Rno AS VARCHAR(10))+' ON t'+CAST(Rno AS VARCHAR(10))+'.EmployeeID = e.EmployeeID AND t'+CAST(Rno AS VARCHAR(10))+'.AttendenceDay ='+CAST(Rno AS VARCHAR(10)) FROM Ct2 i
  FOR XML PATH ('')),1,1,''))
FROM Ct2 o

PRINT @SQL

Here one more method is Dynamic sql process

SET NOCOUNT ON
DECLARE @RunCommand TABLE(RunCommand nvarchar(max))
DECLARE @SQL nvarchar(max),
        @SQL2 nvarchar(max),
        @FullSql nvarchar(max)
SET @SQL='
---create dummy tables for ''Employee'', and ''Attendence''

declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = ''1 july 2017''
declare @DateLast date = ''31 july 2017''

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = (''E00'' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = (''Emp_Name_'' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end
'
SET @SQL2='
;With cte
AS
(
SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno
FROM master..spt_values

)
,Ct2 AS
(
SELECT Rno FROM cte WHERE Rno <=31
)
SELECT DISTINCT  CONCAT(''SELECT e.*,'',
STUFF((SELECT '', ''+'' t''+CAST(Rno AS VARCHAR(10))+''.Absence AS [Day''+CAST(Rno AS VARCHAR(10))+'']'' FROM Ct2 i
  FOR XML PATH ('''')),1,1,''''),''  FROM @tblEmployee e'',
  STUFF((SELECT ''  ''+'' LEFT OUTER JOIN @tblAttendence t''+CAST(Rno AS VARCHAR(10))+'' ON t''+CAST(Rno AS VARCHAR(10))+''.EmployeeID = e.EmployeeID AND t''+CAST(Rno AS VARCHAR(10))+''.AttendenceDay =''+CAST(Rno AS VARCHAR(10)) FROM Ct2 i
  FOR XML PATH ('''')),1,1,''''))
FROM Ct2 o
'
INSERT INTO @RunCommand
EXEC( @SQl2)

SELECT @SQL2=RunCommand FROM @RunCommand

SET @FullSql=@SQL+@SQL2

PRINT @FullSql

EXEC(@FullSql)

SET NOCOUNT OFF


问:
show img with url in laravel 5.4
I have a image that want show in slide show I use html tag ,
I'm new in laravel and I don't Know How to show image in my blade.
How I can use  tag in laravel?

答:
If you have stored images inside laravel public directory then, you can use asset which refers to public/ directory.

If you have image at public/images/abc.png then, you can add image in view like this:

```<code> <img src="{{ asset('images/abc.png') }}">
</code>```

Title: show img with url in laravel 5.4

Body:
If you have stored images inside laravel public directory then, you can use asset which refers to public/ directory.

If you have image at public/images/abc.png then, you can add image in view like this:

 <img src="{{ asset('images/abc.png') }}">


问:
Does Vim or SciTE has syntax highlight support for T4 template .tt files?
Does Vim or SciTE has syntax highlight support for T4 template .tt files?</p>

答:
There is a vim bundle here for T4 syntax highlighting:

https://github.com/sillyotter/t4-vim


问:
Inheriting UIView - Losing instance variables
Bit of an Objective-C rookie, I've looked around for an answer but haven't been able to find one so forgive me if this is an obvious question.

Basically, I need to draw on the screen segments of a circle (for instance, a 90 degree segment, where a horizontal and vertical line meet at the bottom left and an arc connects the end points). I've managed to achieve this in a custom class called CircleSegment that inherits UIView and overrides drawRect.

My issue is achieving this programatically; I need some way of creating my CircleSegment class and storing in it the desired angle before it draws the segment itself.

Here's what I have so far:

CircleSegment.h

```<code>#import <UIKit/UIKit.h>

@interface CircleSegment : UIView {
    float angleSize;
    UIColor *backColor;
}

-(float)convertDegToRad:(float)degrees;
-(float)convertRadToDeg:(float)radians;

@property (nonatomic) float angleSize;
@property (nonatomic, retain) UIColor *backColor;

@end
</code>```

CircleSegment.m

```<code>#import "CircleSegment.h"

@implementation CircleSegment

@synthesize angleSize;
@synthesize backColor;

// INITIALISATION OVERRIDES
// ------------------------

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)newBGColor
{
    // Ignore.
}
- (void)setOpaque:(BOOL)newIsOpaque
{
    // Ignore.
}

// MATH FUNCTIONS
// --------------

// Converts degrees to radians.
-(float)convertDegToRad:(float)degrees {
    return degrees * M_PI / 180;
}

// Converts radians to degrees.
-(float)convertRadToDeg:(float)radians {
    return radians * 180 / M_PI;
}

// DRAWING CODE
// ------------

- (void)drawRect:(CGRect)rect {

    float endAngle = 360 - angleSize;

    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100)
                                                         radius:100
                                                     startAngle:[self convertDegToRad:270]
                                                       endAngle:[self convertDegToRad:endAngle]
                                                      clockwise:YES];

    [aPath addLineToPoint:CGPointMake(100.0, 100.0)];

    [aPath closePath];

    CGContextRef aRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(aRef, backColor.CGColor);

    CGContextSaveGState(aRef);

    aPath.lineWidth = 1;

    [aPath fill];
    [aPath stroke];

    //CGContextRestoreGState(aRef);

}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

Note that the .m file is a bit messy with various bits of test code...

So essentially I want to create an instance of CircleSegment, store an angle in the angleSize property, draw a segment based on that angle and then add that view to the main app view to display it...

To try and achieve that, I've add the following test code to viewDidLoad on my ViewController:

```<code>CircleSegment *seg1 = [[CircleSegment alloc] init];
seg1.backColor = [UIColor greenColor];
seg1.angleSize = 10;

[self.view addSubview:seg1];
</code>```

It seems to store the UIColor and angleSize fine when I breakpoint those places, however if I place a breakpoint in drawRect which I overrode on CircleSegment.m, the values have reverted back to nil values (or whatever the correct term would be, feel free to correct me).

I'd really appreciate it if someone could point me in the right direction!

Thanks

答:
It seems to store the UIColor and
  angleSize fine when I breakpoint those
  places, however if I place a
  breakpoint in drawRect which I
  overrode on CircleSegment.m, the
  values have reverted back to nil
  values (or whatever the correct term
  would be, feel free to correct me).

Are you sure you are working with the same instance?

Drop in something like NSLog(@"%@ %p", NSStringFromSelector(_cmd), self); in viewDidLoad and in drawRect and make sure you are actually dealing with the same instance.

(I've seen cases where a developer will alloc/initWithFrame: a view and then use the instance that was created during NIB loading, wondering why that instance wasn't properly initialized.)

Body:
Bit of an Objective-C rookie, I've looked around for an answer but haven't been able to find one so forgive me if this is an obvious question.

Basically, I need to draw on the screen segments of a circle (for instance, a 90 degree segment, where a horizontal and vertical line meet at the bottom left and an arc connects the end points). I've managed to achieve this in a custom class called CircleSegment that inherits UIView and overrides drawRect.

My issue is achieving this programatically; I need some way of creating my CircleSegment class and storing in it the desired angle before it draws the segment itself.

Here's what I have so far:

CircleSegment.h

#import <UIKit/UIKit.h>

@interface CircleSegment : UIView {
    float angleSize;
    UIColor *backColor;
}

-(float)convertDegToRad:(float)degrees;
-(float)convertRadToDeg:(float)radians;

@property (nonatomic) float angleSize;
@property (nonatomic, retain) UIColor *backColor;

@end

CircleSegment.m

#import "CircleSegment.h"

@implementation CircleSegment

@synthesize angleSize;
@synthesize backColor;

// INITIALISATION OVERRIDES
// ------------------------

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)newBGColor
{
    // Ignore.
}
- (void)setOpaque:(BOOL)newIsOpaque
{
    // Ignore.
}

// MATH FUNCTIONS
// --------------

// Converts degrees to radians.
-(float)convertDegToRad:(float)degrees {
    return degrees * M_PI / 180;
}

// Converts radians to degrees.
-(float)convertRadToDeg:(float)radians {
    return radians * 180 / M_PI;
}

// DRAWING CODE
// ------------

- (void)drawRect:(CGRect)rect {

    float endAngle = 360 - angleSize;

    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100)
                                                         radius:100
                                                     startAngle:[self convertDegToRad:270]
                                                       endAngle:[self convertDegToRad:endAngle]
                                                      clockwise:YES];

    [aPath addLineToPoint:CGPointMake(100.0, 100.0)];

    [aPath closePath];

    CGContextRef aRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(aRef, backColor.CGColor);

    CGContextSaveGState(aRef);

    aPath.lineWidth = 1;

    [aPath fill];
    [aPath stroke];

    //CGContextRestoreGState(aRef);

}

- (void)dealloc {
    [super dealloc];
}

@end

Note that the .m file is a bit messy with various bits of test code...

So essentially I want to create an instance of CircleSegment, store an angle in the angleSize property, draw a segment based on that angle and then add that view to the main app view to display it...

To try and achieve that, I've add the following test code to viewDidLoad on my ViewController:

CircleSegment *seg1 = [[CircleSegment alloc] init];
seg1.backColor = [UIColor greenColor];
seg1.angleSize = 10;

[self.view addSubview:seg1];

It seems to store the UIColor and angleSize fine when I breakpoint those places, however if I place a breakpoint in drawRect which I overrode on CircleSegment.m, the values have reverted back to nil values (or whatever the correct term would be, feel free to correct me).

I'd really appreciate it if someone could point me in the right direction!

Thanks


问:
Find filepath to public_html directory or it's equivalent using PHP
I'm creating a .php file that will be uploaded to the root directory of a server. I need that .php file to then figure out the path to the public_html folder or it's equivalent.

I need to do this because I want my .php file to be able to be uploaded to the root and used on any hosting account. Because many hosting companies use different file paths to the public_html folder or even call it something different, I'm trying to figure out how to detect it.

Preferable there is a server variable or easy test to do this. If not, the public_html folder will always contain a particular file so maybe I could search for this particular file and get the path that way. I'm just worried about a filename search being heavy on memory.

The .php file that is being executed is located inside the ROOT directory and needs to locate the public_html folder.

Like this: /home/user/file.php

needs to detect

/home/user/public_html/ or /home/user/var/www/ or /home/user/website.com/html/ etc.

答:
I found this website which provided me with the only good solution I have found after scouring the web...

```<code>$root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']);
</code>```

The way this works is by getting the full path of the file and then removing the relative path of the file from the full path.

Body:
I found this website which provided me with the only good solution I have found after scouring the web...

$root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']);

The way this works is by getting the full path of the file and then removing the relative path of the file from the full path.


问:
pgAdmin 4 not starting on Windows 10 64bit
After a fresh install of postgres 9.6.0.1 for Windows 10 64bit I am not able to get pgAdmin 4 starting.

First it throws an fatal error message:

After OK, that message appears:

Is there anything wrong? because after OK - the program won't start.

What can I do to get pgadmin 4 running? What should I enter in Python Path and what in Application Path?

答: Try to install pgamin 4.5.1, it works for me (w10 x64) pgadmin 4.1.5</p>


问:
Assign multiple feature group in edit control in leaflet draw
How can i assign multiple the feature groups in edit control,

Assume we have two feature groups(It can be multiple),and we want to assign edit control to both groups.

This is groups,

```<code>var attLayerGroup = new L.FeatureGroup();
var photoLayerGroup = new L.FeatureGroup();
</code>```

And this is, How i assign control to groups,

```<code>    var drawControl = map.addControl(new L.Control.Draw({
    edit: {
        featureGroup: photoLayerGroup,attLayerGroup,
        poly: {
            allowIntersection: true
        }
    },
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        }

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

Is it right way to assigning Edit control to FeatureGroup ?
  If not,How can we do it?

答:
Leaflet.Draw featureGroup does not accept multiple feature groups.

You can have two instances of Leaflet.Draw set up, one for each feature group. However, I predict you will have issues with the buttons Leaflet.Draw sets up and possibly the events thrown by each instance.

The second option is to have a single instances of Leaflet.Draw and you swap the feature group with a toggle.

Body:
How can i assign multiple the feature groups in edit control,

Assume we have two feature groups(It can be multiple),and we want to assign edit control to both groups.

This is groups,

var attLayerGroup = new L.FeatureGroup();
var photoLayerGroup = new L.FeatureGroup();

And this is, How i assign control to groups,

    var drawControl = map.addControl(new L.Control.Draw({
    edit: {
        featureGroup: photoLayerGroup,attLayerGroup,
        poly: {
            allowIntersection: true
        }
    },
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        }

    }
}));

Is it right way to assigning Edit control to FeatureGroup ?
  If not,How can we do it?


问:
What does the "Unexpected end of input" error mean?
I am currently building an application in R to calculate the QR matrix decomposition, the QR non negative matrix decomposition and computing ICA. At the moment I am working on the first task. I am getting the following error:

```<code>source("trial.R")

Error in source("trial.R") : trial.R:153:0: unexpected end of input
151:
152:
    ^
</code>```

Code:

```<code>library(rworldmap)

install.packages("plotrix")
library(plotrix)

install.packages("fastICA")
library(fastICA)
install.packages("Matrix")
source("utils.R")
library("corpcor")

twophase.cx <- function(A, k, fudge=5) {

    SVD=svd(normalised)
    V=SVD$v

    vk<-array(0,dim=c(nrow(V),k))
    cols_v=ncol(V)
    for(cl in 1:k){
     for(r in 1:nrow(V)){
      vk[r,cl]<-V[r,cl+k]
      }}

   probs=rep(0,k)

   prod=A%*%vk%*%t(vk)
    for(j in 1:k){

    subA=A[nrow(A)-j,ncol(A)-j]

    subV=vk[nrow(subV)-j,ncol(vk)-j]

    subprod=prod[nrow(prod)-j,ncol(prod)-j]

    normv<-norm(subV,"2")
    normA<-norm(subA,"2")
    normProd<-norm(subprod,"2")
    add1<-(normv*normv)/(2*k)
    add2<-((normA*normA)-(normProd*normProd))/(2*((normA*normA)-           (normProd*normProd)))
    probs[j]<-add1+add2
  }

   const<-(k*log(k))

   keep<-sample(c(1:k),size=const,prob=probs,replace=FALSE)

   S1<-matrix(0,ncol(A),const)
   for(i in 1:ncol(A)){
    for(j in 1:const){
     if(is.element(j,keep)){
      S1[i,j]<-1}}}

  D1<-matrix(0,const,const)
 for(i in 1:const){
   if(is.element(i,keep)){
    prd<-const*probs[i]
   if(prd<1){D[i,i]<-prd}
   if(prd>=1){D[i,i]<-1}
  }

 toSample<-t(vk)%*%S1%*%D1
 S2<-qr(toSample)$pivot[1:k]
 C<-A %*% S1 %*% S2
cols<-C
X<-pseudoinverse(C)%*%A
err<-norm(A-C %*% X, 'F')
list(cols=C,X=X,  err=err)

}

cx <- function(A, k, nreps=20, ...) {
best.res = list(cols=NA, X=NA, err=Inf)
for (rep in 1:nreps) {
    res <- twophase.cx(A, k, ...)
    if (res$err < best.res$err) {
        best.res <- res
    }
}
best.res
}

data <- as.matrix( read.csv("worldclim.csv") )
coord <- read.csv("coordinates.csv")

data.normal <-scale(data,center=TRUE,scale=TRUE)
k<-10

cx.res <- cx(t(data.normal), 5)

xLim <- c(min(coord["lon"]), max(coord["lon"]))
yLim <- c(min(coord["lat"]), max(coord["lat"]))
map <- getMap(resolution="low")
plot(map, xlim=xLim, ylim=yLim, asp=1)

points(coord[cx.res$cols,1], coord[cx.res$cols,2], col=2, pch=19, cex=1.5)
points(coord[cx.res$cols,1], coord[cx.res$cols,2], col=4, pch=65:127,    cex=.6)

x <- cx.res$X[1,]
plot(map, xlim=xLim, ylim=yLim, asp=1)
points(coord[,1], coord[,2], col=color.scale(x, c(0,1), 0.8, 1,     color.spec="hsv"), cex=.6, pch=19)
color.legend(xLim[1]+1, yLim[1]-5, xLim[2]-1, yLim[1]-3, c(round(min(x),    4), round(mean(x), 4), round(max(x), 4)), color.scale(sort(x), c(0,1), 0.8, 1,    color.spec="hsv"), gradient="x")

convex.cone <- function(A, k) {

}

house.price <- read.csv("us_housing_prices.csv", row.names=1)

rownames(house.price)

colnames(house.price)[1:18]
colnames(house.price)[seq(1, by=12, to=ncol(house.price))]

plot.time.series(house.price[1:5,])
plot.time.series(house.price[6:10,])
plot.time.series(house.price[11:15,])
plot.time.series(house.price[16:20,])

hp <- house.price
hp[is.na(house.price)] <- 0

hp <- scale(t(hp))

hp.ica <- fastICA(hp, 20, fun="logcosh", verbose=TRUE)

rownames(hp.ica$S) <- colnames(house.price)
with(hp.ica, plot.time.series(t(S[,1:5])) )

with(hp.ica, plot(S[,1:2], asp=1) )

with(hp.ica, identify(S[,1:2], labels=rownames(S)) )
</code>```

I am quite new to R. Please suggest which might be the issue.

答: You're missing a } for the twophase.cx function, I suspect at line 72.

Body:
I am currently building an application in R to calculate the QR matrix decomposition, the QR non negative matrix decomposition and computing ICA. At the moment I am working on the first task. I am getting the following error:

source("trial.R")

Error in source("trial.R") : trial.R:153:0: unexpected end of input
151:
152:
    ^

Code:

library(rworldmap)

install.packages("plotrix")
library(plotrix)

install.packages("fastICA")
library(fastICA)
install.packages("Matrix")
source("utils.R")
library("corpcor")

twophase.cx <- function(A, k, fudge=5) {

    SVD=svd(normalised)
    V=SVD$v

    vk<-array(0,dim=c(nrow(V),k))
    cols_v=ncol(V)
    for(cl in 1:k){
     for(r in 1:nrow(V)){
      vk[r,cl]<-V[r,cl+k]
      }}

   probs=rep(0,k)

   prod=A%*%vk%*%t(vk)
    for(j in 1:k){

    subA=A[nrow(A)-j,ncol(A)-j]

    subV=vk[nrow(subV)-j,ncol(vk)-j]

    subprod=prod[nrow(prod)-j,ncol(prod)-j]

    normv<-norm(subV,"2")
    normA<-norm(subA,"2")
    normProd<-norm(subprod,"2")
    add1<-(normv*normv)/(2*k)
    add2<-((normA*normA)-(normProd*normProd))/(2*((normA*normA)-           (normProd*normProd)))
    probs[j]<-add1+add2
  }

   const<-(k*log(k))

   keep<-sample(c(1:k),size=const,prob=probs,replace=FALSE)

   S1<-matrix(0,ncol(A),const)
   for(i in 1:ncol(A)){
    for(j in 1:const){
     if(is.element(j,keep)){
      S1[i,j]<-1}}}

  D1<-matrix(0,const,const)
 for(i in 1:const){
   if(is.element(i,keep)){
    prd<-const*probs[i]
   if(prd<1){D[i,i]<-prd}
   if(prd>=1){D[i,i]<-1}
  }

 toSample<-t(vk)%*%S1%*%D1
 S2<-qr(toSample)$pivot[1:k]
 C<-A %*% S1 %*% S2
cols<-C
X<-pseudoinverse(C)%*%A
err<-norm(A-C %*% X, 'F')
list(cols=C,X=X,  err=err)

}

cx <- function(A, k, nreps=20, ...) {
best.res = list(cols=NA, X=NA, err=Inf)
for (rep in 1:nreps) {
    res <- twophase.cx(A, k, ...)
    if (res$err < best.res$err) {
        best.res <- res
    }
}
best.res
}

data <- as.matrix( read.csv("worldclim.csv") )
coord <- read.csv("coordinates.csv")

data.normal <-scale(data,center=TRUE,scale=TRUE)
k<-10

cx.res <- cx(t(data.normal), 5)

xLim <- c(min(coord["lon"]), max(coord["lon"]))
yLim <- c(min(coord["lat"]), max(coord["lat"]))
map <- getMap(resolution="low")
plot(map, xlim=xLim, ylim=yLim, asp=1)

points(coord[cx.res$cols,1], coord[cx.res$cols,2], col=2, pch=19, cex=1.5)
points(coord[cx.res$cols,1], coord[cx.res$cols,2], col=4, pch=65:127,    cex=.6)

x <- cx.res$X[1,]
plot(map, xlim=xLim, ylim=yLim, asp=1)
points(coord[,1], coord[,2], col=color.scale(x, c(0,1), 0.8, 1,     color.spec="hsv"), cex=.6, pch=19)
color.legend(xLim[1]+1, yLim[1]-5, xLim[2]-1, yLim[1]-3, c(round(min(x),    4), round(mean(x), 4), round(max(x), 4)), color.scale(sort(x), c(0,1), 0.8, 1,    color.spec="hsv"), gradient="x")

convex.cone <- function(A, k) {

}

house.price <- read.csv("us_housing_prices.csv", row.names=1)

rownames(house.price)

colnames(house.price)[1:18]
colnames(house.price)[seq(1, by=12, to=ncol(house.price))]

plot.time.series(house.price[1:5,])
plot.time.series(house.price[6:10,])
plot.time.series(house.price[11:15,])
plot.time.series(house.price[16:20,])

hp <- house.price
hp[is.na(house.price)] <- 0

hp <- scale(t(hp))

hp.ica <- fastICA(hp, 20, fun="logcosh", verbose=TRUE)

rownames(hp.ica$S) <- colnames(house.price)
with(hp.ica, plot.time.series(t(S[,1:5])) )

with(hp.ica, plot(S[,1:2], asp=1) )

with(hp.ica, identify(S[,1:2], labels=rownames(S)) )

I am quite new to R. Please suggest which might be the issue.


问:
Null reference exception when trying to delete a "MeetingRequest" message in Outlook REST API
I am trying to move a message to the DeletedItems folder. My request looks like this

POST
  https://outlook.office.com/api/v2.0/me/messages/AAMkADNjZDVkNTljLTMwNmEtNDM1Yi1iZjgyLTAwNTgzYzBmNDc4NQBGAAAAAADwJW0rZtALTZ4Uu7_1UsU3BwBGSE8dc8m8SYGboVROeF8MAAAAAAEKAABGSE8dc8m8SYGboVROeF8MAACUQ60PAAA=/move

{"DestinationId":"DeletedItems"}

And the response is

{
      "error": {
          "code": "ErrorInternalServerError",
          "message": "Object reference not set to an instance of an object."
      } }

A get request to the message returns the message. I think the problem might be that it is a meeting request message created by me ("MeetingMessageType": "MeetingRequest"). Is it the case that I can delete meeting request messages from other people but not my own?

here is how the message looks like:

{
    "Id": "AAMkADNjZDVkNTljLTMwNmEtNDM1Yi1iZjgyLTAwNTgzYzBmNDc4NQBGAAAAAADwJW0rZtALTZ4Uu7_1UsU3BwBGSE8dc8m8SYGboVROeF8MAAAAAAEKAABGSE8dc8m8SYGboVROeF8MAACUQ60PAAA=",
    "CreatedDateTime": "2017-07-06T12:01:37Z",
    "LastModifiedDateTime": "2017-07-06T12:06:34Z",
    "ChangeKey": "CwAAABYAAABGSE8dc8m8SYGboVROeF8MAACUVif6",
    "Categories": [],
    "ReceivedDateTime": "2017-07-06T12:01:38Z",
    "SentDateTime": "2017-07-06T12:01:38Z",
    "HasAttachments": false,
    "InternetMessageId": "",
    "Subject": "test test",
    "BodyPreview": "",
    "Importance": "Normal",
    "ParentFolderId": "AQMkADNjZDVkNTljLTMwNmEtNDM1Yi1iZjgyLTAwADU4M2MwZjQ3ODUALgAAA-AlbStm0AtNnhS7v7VSxTcBAEZITx1zybxJgZuhVE54XwwAAAIBCgAAAA==",
    "ConversationId": "AAQkADNjZDVkNTljLTMwNmEtNDM1Yi1iZjgyLTAwNTgzYzBmNDc4NQAQADZTzPctHtlCvZkjxZlRlYM=",
    "IsDeliveryReceiptRequested": null,
    "IsReadReceiptRequested": false,
    "IsRead": true,
    "IsDraft": false,
    "WebLink": "https://outlook.office365.com/owa/?ItemID=AAMkADNjZDVkNTljLTMwNmEtNDM1Yi1iZjgyLTAwNTgzYzBmNDc4NQBGAAAAAADwJW0rZtALTZ4Uu7%2B1UsU3BwBGSE8dc8m8SYGboVROeF8MAAAAAAEKAABGSE8dc8m8SYGboVROeF8MAACUQ60PAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
    "InferenceClassification": "Focused",
    "MeetingMessageType": "MeetingRequest",
...

答:
Without looking at your server side logs, this appears to be a known issue that was just fixed last night.  We will be backporting and rolling out the fix over the next few days.

It has nothing to do with the fact that it is a meeting request and/or created by you. From the Exchange store's point of view, an item is an item is an item :)


问:
How to limit the number of test threads in Cargo.toml?
I have tests which share a common resource and can't be executed concurrently. These tests fail with cargo test, but work with RUST_TEST_THREADS=1 cargo test.

I can modify the tests to wait on a global mutex, but I don't want to clutter them if there is any simpler way to force cargo set this environment variable for me.

答:
As of Rust 1.18, there is no such thing. In fact, there is not even a simpler option to disable parallel testing.

Source

However, what might help you is cargo test -- --test-threads=1, which is the recommended way of doing what you are doing over the RUST_TEST_THREADS envvar.  Keep in mind that this only sets the number of threads used for testing in addition to the main thread.


问:
JSX Unexpected token - Webpack and babel-loader
I'm getting JSX parse error after upgrading webpack from ^1.14.0 to "^3.0.0"

```<code>ERROR in ./shared/Application.js
Module parse failed: /Users/arjunkumar/Documents/Work/test/web/shared/Application.js Unexpected token (25:2)
You may need an appropriate loader to handle this file type.
</code>```

The related code in Application.js looks like this

```<code>ReactDOM.render(
  <Provider store={store}>
    <Router routes={Routes(store)} history={history} />
  </Provider>,
  document.getElementById('app-shell')
);
</code>```

Relevant part of webpack.config.js file looks as follows (all the required plugins are imported properly to webpack config file, not present in the following code).

```<code>module.exports = {
  entry: {
    app:['./shared/Application.js'],
    vendors:[// vendors like react and other libs ]
  },
  output: {
    path: __dirname + '/public/build',
    filename: 'app.[chunkhash].js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'autoprefixer-loader',
            'sass-loader'
          ],
          exclude: /node_modules/
        }),
      },
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015', {modules: false}],
              'react'
            ],
            babelrc: false
          }
        }]
      },
      {
        test: /\.jsx$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              'es2015',
              'react'
            ],
            babelrc: false
          }
        }]
      },
    ]
  },
  devtool: ( process.env.NODE_ENV === 'production' ) ? false : 'eval',
  plugins: [
    new ExtractTextPlugin(
      'app.[chunkhash].css',
      {
        allChunks: true
      }
    ),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['utilities','vendors'],
      filename: '[name].[chunkhash].js',
      minChunks: Infinity
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      },
      output: {
        comments:false
      },
      comments: false
    }),
    new AssetsPlugin({
      filename: 'assets.json',
      fullPath: false,
      path: __dirname + '/public/build',
      prettyPrint: true
    })
  ]

};
</code>```

Relevant dependencies for the issue from package.json file is as follows.

```<code>{
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-object-assign": "^6.8.0",
    "babel-plugin-transform-react-constant-elements": "^6.9.1",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.9",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-loose": "^8.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "extract-text-webpack-plugin": "^2.1.2",
    "html-webpack-plugin": "^2.21.0",
    "husky": "^0.13.1",
    "lodash-webpack-plugin": "^0.10.6",
    "node-sass": "^3.13.1",
    "postcss-loader": "^2.0.6",
    "purifycss-webpack": "^0.4.2",
    "sass-loader": "^4.1.1",
    "webpack": "^3.0.0",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-server": "^2.5.0"
  },
  "dependencies": {
    "react": "^15.1.0"
  }
}
</code>```

Just in case anyone wants to check .babelrc file ( I think babel-loader respects babelrc: false flag in webpack.config.js).

```<code>{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-inline-elements",
        "transform-react-remove-prop-types"
      ]
    }
  },
  "comments": false,
  "compact": false
}
</code>```

Any thoughts or leads on what might be wrong?

Another important thing I noticed is even though my webpack project and global dependency is at 3.0.0, when I run the webpack in the project it shows Version: webpack 1.15.0 at the top. Screenshot below.

答:
You're running webpack from the command line, which means that you're running the globally installed unless you have ./node_modules/.bin/ in your PATH. Even though you say your globally installed version should be 3.0.0, it is a much better idea to always run the locally installed one. If you want to run it from the command line you can do it by running:

```<code>./node_modules/.bin/webpack --progress
</code>```

A more elegant way to run it, is by creating an npm script in your package.json.

```<code>"scripts": {
  "build": "webpack --progress"
}
</code>```

npm will automatically look into ./node_modules/.bin/ for an executable. And then you can run that script with:

```<code>npm run build
</code>```

Your config looks okay, except for resolve.extensions, which no longer allows/requires an empty string.

```<code>resolve: {
  extensions: ['.js', '.jsx']
},
</code>```

I don't really see why you're using two different rules for .js and .jsx. You can have a regular expression that matches both with /\.jsx?$/. But the two rules are not identical. The difference is that you use modules: false only for .js, but you should let webpack handle the ES modules. If you don't have a reason to do it differently, you should combine the two rules.

Body:
I'm getting JSX parse error after upgrading webpack from ^1.14.0 to "^3.0.0"

ERROR in ./shared/Application.js
Module parse failed: /Users/arjunkumar/Documents/Work/test/web/shared/Application.js Unexpected token (25:2)
You may need an appropriate loader to handle this file type.

The related code in Application.js looks like this

ReactDOM.render(
  <Provider store={store}>
    <Router routes={Routes(store)} history={history} />
  </Provider>,
  document.getElementById('app-shell')
);

Relevant part of webpack.config.js file looks as follows (all the required plugins are imported properly to webpack config file, not present in the following code).

module.exports = {
  entry: {
    app:['./shared/Application.js'],
    vendors:[// vendors like react and other libs ]
  },
  output: {
    path: __dirname + '/public/build',
    filename: 'app.[chunkhash].js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'autoprefixer-loader',
            'sass-loader'
          ],
          exclude: /node_modules/
        }),
      },
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015', {modules: false}],
              'react'
            ],
            babelrc: false
          }
        }]
      },
      {
        test: /\.jsx$/,
        exclude: [/node_modules/],
        use:[{
          loader: 'babel-loader',
          options: {
            presets: [
              'es2015',
              'react'
            ],
            babelrc: false
          }
        }]
      },
    ]
  },
  devtool: ( process.env.NODE_ENV === 'production' ) ? false : 'eval',
  plugins: [
    new ExtractTextPlugin(
      'app.[chunkhash].css',
      {
        allChunks: true
      }
    ),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['utilities','vendors'],
      filename: '[name].[chunkhash].js',
      minChunks: Infinity
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      },
      output: {
        comments:false
      },
      comments: false
    }),
    new AssetsPlugin({
      filename: 'assets.json',
      fullPath: false,
      path: __dirname + '/public/build',
      prettyPrint: true
    })
  ]

};

Relevant dependencies for the issue from package.json file is as follows.

{
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-object-assign": "^6.8.0",
    "babel-plugin-transform-react-constant-elements": "^6.9.1",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.9",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-loose": "^8.0.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "extract-text-webpack-plugin": "^2.1.2",
    "html-webpack-plugin": "^2.21.0",
    "husky": "^0.13.1",
    "lodash-webpack-plugin": "^0.10.6",
    "node-sass": "^3.13.1",
    "postcss-loader": "^2.0.6",
    "purifycss-webpack": "^0.4.2",
    "sass-loader": "^4.1.1",
    "webpack": "^3.0.0",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-server": "^2.5.0"
  },
  "dependencies": {
    "react": "^15.1.0"
  }
}

Just in case anyone wants to check .babelrc file ( I think babel-loader respects babelrc: false flag in webpack.config.js).

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-inline-elements",
        "transform-react-remove-prop-types"
      ]
    }
  },
  "comments": false,
  "compact": false
}

Any thoughts or leads on what might be wrong?

Another important thing I noticed is even though my webpack project and global dependency is at 3.0.0, when I run the webpack in the project it shows Version: webpack 1.15.0 at the top. Screenshot below.

Body:
You're running webpack from the command line, which means that you're running the globally installed unless you have ./node_modules/.bin/ in your PATH. Even though you say your globally installed version should be 3.0.0, it is a much better idea to always run the locally installed one. If you want to run it from the command line you can do it by running:

./node_modules/.bin/webpack --progress

A more elegant way to run it, is by creating an npm script in your package.json.

"scripts": {
  "build": "webpack --progress"
}

npm will automatically look into ./node_modules/.bin/ for an executable. And then you can run that script with:

npm run build

Your config looks okay, except for resolve.extensions, which no longer allows/requires an empty string.

resolve: {
  extensions: ['.js', '.jsx']
},

I don't really see why you're using two different rules for .js and .jsx. You can have a regular expression that matches both with /\.jsx?$/. But the two rules are not identical. The difference is that you use modules: false only for .js, but you should let webpack handle the ES modules. If you don't have a reason to do it differently, you should combine the two rules.


问:
Can my browser / computer / mobile run Archilogic?
Which browsers are supported?

On which mobile phones can I use the application?

On which devices does it run best or how do I get the best results?

Which VR devices can I use?

答:
Archilogic runs entirely within your Browser. So all you need is a modern Browser that supports webGl.

Here you can test your browser:

The following browsers currently support WebGL – the technology the application is based on:
Microsoft Internet Explorer 11+, Microsoft Edge, Google Chrome, Mozilla Firefox, Apple Safari 8+

If you run Internet Explorer 10 or older, you need to update to version 11 or use a different browser like Chrome or Firefox.
If you run Safari 7 or older on Mac OSX, you can enable WebGl following these instructions:

Open the Safari menu and select Preferences Click the Advanced tab in
  the Preferences window Then, at the bottom of the window, check the
  Show Develop menu in menu bar checkbox Then, open the Develop menu in
  the menu bar and select Enable WebGL or use a different browser like
  Chrome or Firefox.

On mobile devices iOS 8 + and Android 4.4 + are supported.

The best results you get on a device with a strong GPU component (a good graphics card). however the application is designed to be very user and mobile friendly - this means that you get a mobile-friendly version for your model - the files are smaller to download and less heavy on your mobile's graphics card and processor.


问:
How do you send NumPad keys using SendKeys?
I want to send the keystroke of NumPad keys (1-9).

I tried to use:

```<code>SendKeys.SendWait("{NUMPAD1}");
</code>```

but it says

System.ArgumentException: The keyword NUMPAD1 is invalid (translated)

So i don't know the right keycode for the NumPad.

答:
You should be able to pass in a number in the same manner as passing in a letter.  For example:</p>

```<code>SendKeys.SendWait("{A}");  //sends the letter 'A'
SendKeys.SendWait("{5}");  //sends the number '5'
</code>```

Body:
I want to send the keystroke of NumPad keys (1-9).

I tried to use:

SendKeys.SendWait("{NUMPAD1}");

but it says

System.ArgumentException: The keyword NUMPAD1 is invalid (translated)

So i don't know the right keycode for the NumPad.

Body:
You should be able to pass in a number in the same manner as passing in a letter.  For example:

SendKeys.SendWait("{A}");  //sends the letter 'A'
SendKeys.SendWait("{5}");  //sends the number '5'


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
If you must pass the tests then you're going to have to write inefficient code, because you must return a copy of a string. This implies you must use dynamic allocation, possibly multiple times because of the copy.

So change the tests and change the signature.

```<code>template<class Out>
Out first_last_n(const std::string::size_type& n, const std::string& s, Out r)
{
    r = copy_n(s.begin(), n, r);
    std::string::const_iterator pos(s.end());
    std::advance(pos, -n);
    return copy_n(pos, n, r);
}
</code>```

Then call it like so:

```<code>std::string s("Hello world!");
char r[5];
r[4] = 0;
first_last_n(2, s, r);
</code>```

This allows you to use dynamic programming, and it eliminates the need of dynamic allocation in the function.

I like my algorithms minimalistic, and I purposely eliminated the check for n being smaller or equal to the size of the string. I replace the check with a pre-condition for the function. Preconditions are faster than checks: they have zero overhead.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}

Body:
If you must pass the tests then you're going to have to write inefficient code, because you must return a copy of a string. This implies you must use dynamic allocation, possibly multiple times because of the copy.

So change the tests and change the signature.

template<class Out>
Out first_last_n(const std::string::size_type& n, const std::string& s, Out r)
{
    r = copy_n(s.begin(), n, r);
    std::string::const_iterator pos(s.end());
    std::advance(pos, -n);
    return copy_n(pos, n, r);
}

Then call it like so:

std::string s("Hello world!");
char r[5];
r[4] = 0;
first_last_n(2, s, r);

This allows you to use dynamic programming, and it eliminates the need of dynamic allocation in the function.

I like my algorithms minimalistic, and I purposely eliminated the check for n being smaller or equal to the size of the string. I replace the check with a pre-condition for the function. Preconditions are faster than checks: they have zero overhead.


问:
How do I retrieve the data in the name list attribute (html) using jQuery?
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

```<code>Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator
</code>```

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

```<code><div id="wrapper">
<div id="form_div">
 <form method="post" action="store_employee.php">
  <table id="employee_table" align=center>
   <tr id="row1">
    <td><input type="text" name="name[]" placeholder="Enter Name"></td>
    <td><input type="text" name="age[]" placeholder="Enter Age"></td>
    <td><input type="text" name="job[]" placeholder="Enter Job"></td>
   </tr>
  </table>
  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>
</div>
</code>```

Javascript

```<code>    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "<tr id='row"+$rowno+"'>"+
            "<td><input type='text' name='name[]' placeholder='Enter Name'></td>"+
            "<td><input type='text' name='age[]' placeholder='Enter Age'></td>"+
            "<td><input type='text' name='job[]' placeholder='Enter Job'></td>"+
            "<td><input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')></td>"+
        "</tr>");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}
</code>```

答:
You can use map()

let res = $('tr').map((_, row) => {
  return [$(row).find('input').map((_, el) => el.value).get()]
}).get()

console.log(res)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="form_div">
    <form method="post" action="store_employee.php">
      <table id="employee_table" align=center>
        <tr id="row1">
          <td><input type="text" name="name[]" placeholder="Enter Name" value="Joe"></td>
          <td><input type="text" name="age[]" placeholder="Enter Age" value="34"></td>
          <td><input type="text" name="job[]" placeholder="Enter Job" value="President"></td>
        </tr>
        <tr id="row1">
          <td><input type="text" name="name[]" placeholder="Enter Name" value="Bill"></td>
          <td><input type="text" name="age[]" placeholder="Enter Age" value="77"></td>
          <td><input type="text" name="job[]" placeholder="Enter Job" value="Flunky"></td>
        </tr>
      </table>
      <input type="button" onclick="add_row();" value="ADD ROW">
      <input type="submit" name="submit_row" value="SUBMIT">
    </form>
  </div></code>```

Body:
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

 <form method="post" action="store_employee.php">

    <input type="text" name="name[]" placeholder="Enter Name">
    <input type="text" name="age[]" placeholder="Enter Age">
    <input type="text" name="job[]" placeholder="Enter Job">

  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>

Javascript

    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "
"+
            "<input type='text' name='name[]' placeholder='Enter Name'>	"+
            "<input type='text' name='age[]' placeholder='Enter Age'>	"+
            "<input type='text' name='job[]' placeholder='Enter Job'>	"+
            "<input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>	"+
        "
");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}

Body:
You can use map()

let res = $('tr').map((_, row) => {
  return [$(row).find('input').map((_, el) => el.value).get()]
}).get()

console.log(res)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="form_div">
    <form method="post" action="store_employee.php">
      <table id="employee_table" align=center>
        <tr id="row1">
          <td><input type="text" name="name[]" placeholder="Enter Name" value="Joe"></td>
          <td><input type="text" name="age[]" placeholder="Enter Age" value="34"></td>
          <td><input type="text" name="job[]" placeholder="Enter Job" value="President"></td>
        </tr>
        <tr id="row1">
          <td><input type="text" name="name[]" placeholder="Enter Name" value="Bill"></td>
          <td><input type="text" name="age[]" placeholder="Enter Age" value="77"></td>
          <td><input type="text" name="job[]" placeholder="Enter Job" value="Flunky"></td>
        </tr>
      </table>
      <input type="button" onclick="add_row();" value="ADD ROW">
      <input type="submit" name="submit_row" value="SUBMIT">
    </form>
  </div>


问:
Create Product Publish to Multiple Channels
I'm trying to determine if the bigcommerce API allows you to create a new product and have it display in multiple channels not just the web store. The API documentation doesn't seem to mention anything about channel management for products, is this possible?</p>

答: Channel management configuration and publishing isn't currently available in the BigCommerce API</p>