问:
Searching for commands to replace a panel with another
I am making a graphic program with swing that involves placing various panels with components on the frame. One of them is a panel with buttons that, when an option in an options menu is chosen, is entirely replaced with a different one that has different buttons. We've been thinking and it seems that the best way to do this would be to, each time the option is selected, to rebuild the frame from scratch.

This is the snippet of code in which I'm building the main panels:

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.nacher.calc.Main;
import com.nacher.calc.controller.Controller;

import net.miginfocom.swing.MigLayout;

/**
 *
 * @author chema && Sergio
 * This Panel contains buttons and textbox to perform the calculator actions
 */
public class PanelCalculator extends JPanel implements PropertyChangeListener {
    private static final long serialVersionUID = -8377215712645516042L;

    private PanelNumbers panelNumbers;
    private PanelScreen panelScreen;
    private PanelOptions panelOptions;
    private PanelScientific panelScientific;

    public Controller controller;

    public PanelCalculator(Controller controller) {
        this.controller = controller;

        //Initialize JTattoo Library
        try{
            UIManager.setLookAndFeel(new GraphiteLookAndFeel());
        }catch(UnsupportedLookAndFeelException ulafe){
            System.out.println("JTattoo Graphite failed to set");
        }
        this.setLayout(new MigLayout("wrap"));
        buildComponents();
        situateComponents();

        //controller = new Controller();
        controller.addPropertyChangeListener(panelScreen);//panelScreen escucha al controller
        panelOptions.addPropertyChangeListener(controller);//controller escucha al panelOptions
        panelNumbers.addPropertyChangeListener(controller);//controller escucha al panelNumbers
        panelScreen.addPropertyChangeListener(controller);//controller escucha al panelScreen
    }

    private void buildComponents(){
        this.setPreferredSize(new Dimension(210, 280));
        this.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions = new PanelOptions();
        panelOptions.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions.setPreferredSize(new Dimension(200, 50));

        panelScreen = new PanelScreen();
        panelScreen.setBorder(BorderFactory.createEtchedBorder());
        panelScreen.setPreferredSize(new Dimension(200, 40));
        panelScreen.setBackground(new Color(255, 255, 255));

        panelNumbers = new PanelNumbers();
        panelNumbers.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelNumbers.setPreferredSize(new Dimension(200, 185));

        panelOptions.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelOptions
        panelNumbers.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelNumbers
    }

    private void situateComponents(){
        this.add(panelOptions, "span");
        this.add(panelScreen, "span");
        this.add(panelNumbers, "span" );
    }

    /**
     * To build the Scientific Calculator
     */
    private void buildScientific() {
        //Instantiate the panelScientific
        panelScientific = new PanelScientific();
        panelScientific.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelScientific.setPreferredSize(new Dimension(200, 185));
        //Reordering the Panel Calculator
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String c = evt.getPropertyName();
        if (c.equals(Constants.SET_CALC_SCIENTIFIC)) {
            System.out.println("Set the Scientific Calculator");
            buildScientific();
        }
    }

}
</code>```

And this is the main class where we build the frame:

```<code>import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.jtattoo.plaf.bernstein.BernsteinLookAndFeel;
import com.jtattoo.plaf.fast.FastLookAndFeel;
import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.jtattoo.plaf.hifi.HiFiLookAndFeel;
import com.jtattoo.plaf.luna.LunaLookAndFeel;
import com.nacher.calc.controller.Controller;
import com.nacher.calc.ui.Constants;
import com.nacher.calc.ui.ImageConstants;
import com.nacher.calc.ui.PanelCalculator;

public class Main extends JFrame implements PropertyChangeListener {

    private static final long serialVersionUID = -4136829057174783241L;

    private static Main mySelf;
    private static PanelCalculator panelCalc;

    public static Controller controller;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {

        controller = new Controller();
        panelCalc = new PanelCalculator(controller);
        controller.addPropertyChangeListener(panelCalc);
        mySelf = new Main();
        try {
            mySelf.setTitle("Calculator");
            mySelf.setLocationRelativeTo(null);
            mySelf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mySelf.setIconImage(new ImageIcon(mySelf.getClass().getResource(ImageConstants.CALC_IMAGE_THREE)).getImage());
            mySelf.getContentPane().add(panelCalc);
            mySelf.setResizable(false);
            mySelf.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.out.println("Quitting the application.");
                }
            });
            mySelf.pack();
            mySelf.setVisible(true);
            controller.addPropertyChangeListener(mySelf);
        }catch(Exception ex) {
            System.out.println("The application could not run.");
            System.out.println(ex.getMessage());
            System.exit(-1);
        }
    }
</code>```

What commands should I use to 'unbuild' the frame, then rebuild it from scratch? Is there a more efficient way to replace one panel with another?

答:
The Card Layout was designed for this type of functionality. It allows you to define multiple panels to share the same space of the frame. You then just specify which panel is currently displayed.

Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.

Body:
I am making a graphic program with swing that involves placing various panels with components on the frame. One of them is a panel with buttons that, when an option in an options menu is chosen, is entirely replaced with a different one that has different buttons. We've been thinking and it seems that the best way to do this would be to, each time the option is selected, to rebuild the frame from scratch.

This is the snippet of code in which I'm building the main panels:

import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.nacher.calc.Main;
import com.nacher.calc.controller.Controller;

import net.miginfocom.swing.MigLayout;

/**
 *
 * @author chema && Sergio
 * This Panel contains buttons and textbox to perform the calculator actions
 */
public class PanelCalculator extends JPanel implements PropertyChangeListener {
    private static final long serialVersionUID = -8377215712645516042L;

    private PanelNumbers panelNumbers;
    private PanelScreen panelScreen;
    private PanelOptions panelOptions;
    private PanelScientific panelScientific;

    public Controller controller;

    public PanelCalculator(Controller controller) {
        this.controller = controller;

        //Initialize JTattoo Library
        try{
            UIManager.setLookAndFeel(new GraphiteLookAndFeel());
        }catch(UnsupportedLookAndFeelException ulafe){
            System.out.println("JTattoo Graphite failed to set");
        }
        this.setLayout(new MigLayout("wrap"));
        buildComponents();
        situateComponents();

        //controller = new Controller();
        controller.addPropertyChangeListener(panelScreen);//panelScreen escucha al controller
        panelOptions.addPropertyChangeListener(controller);//controller escucha al panelOptions
        panelNumbers.addPropertyChangeListener(controller);//controller escucha al panelNumbers
        panelScreen.addPropertyChangeListener(controller);//controller escucha al panelScreen
    }

    private void buildComponents(){
        this.setPreferredSize(new Dimension(210, 280));
        this.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions = new PanelOptions();
        panelOptions.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelOptions.setPreferredSize(new Dimension(200, 50));

        panelScreen = new PanelScreen();
        panelScreen.setBorder(BorderFactory.createEtchedBorder());
        panelScreen.setPreferredSize(new Dimension(200, 40));
        panelScreen.setBackground(new Color(255, 255, 255));

        panelNumbers = new PanelNumbers();
        panelNumbers.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelNumbers.setPreferredSize(new Dimension(200, 185));

        panelOptions.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelOptions
        panelNumbers.addPropertyChangeListener(panelScreen);//panelScreen escucha al panelNumbers
    }

    private void situateComponents(){
        this.add(panelOptions, "span");
        this.add(panelScreen, "span");
        this.add(panelNumbers, "span" );
    }

    /**
     * To build the Scientific Calculator
     */
    private void buildScientific() {
        //Instantiate the panelScientific
        panelScientific = new PanelScientific();
        panelScientific.setBorder(new EmptyBorder(0, 0, 0, 0));
        panelScientific.setPreferredSize(new Dimension(200, 185));
        //Reordering the Panel Calculator
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        String c = evt.getPropertyName();
        if (c.equals(Constants.SET_CALC_SCIENTIFIC)) {
            System.out.println("Set the Scientific Calculator");
            buildScientific();
        }
    }

}

And this is the main class where we build the frame:

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.jtattoo.plaf.bernstein.BernsteinLookAndFeel;
import com.jtattoo.plaf.fast.FastLookAndFeel;
import com.jtattoo.plaf.graphite.GraphiteLookAndFeel;
import com.jtattoo.plaf.hifi.HiFiLookAndFeel;
import com.jtattoo.plaf.luna.LunaLookAndFeel;
import com.nacher.calc.controller.Controller;
import com.nacher.calc.ui.Constants;
import com.nacher.calc.ui.ImageConstants;
import com.nacher.calc.ui.PanelCalculator;

public class Main extends JFrame implements PropertyChangeListener {

    private static final long serialVersionUID = -4136829057174783241L;

    private static Main mySelf;
    private static PanelCalculator panelCalc;

    public static Controller controller;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {

        controller = new Controller();
        panelCalc = new PanelCalculator(controller);
        controller.addPropertyChangeListener(panelCalc);
        mySelf = new Main();
        try {
            mySelf.setTitle("Calculator");
            mySelf.setLocationRelativeTo(null);
            mySelf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mySelf.setIconImage(new ImageIcon(mySelf.getClass().getResource(ImageConstants.CALC_IMAGE_THREE)).getImage());
            mySelf.getContentPane().add(panelCalc);
            mySelf.setResizable(false);
            mySelf.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.out.println("Quitting the application.");
                }
            });
            mySelf.pack();
            mySelf.setVisible(true);
            controller.addPropertyChangeListener(mySelf);
        }catch(Exception ex) {
            System.out.println("The application could not run.");
            System.out.println(ex.getMessage());
            System.exit(-1);
        }
    }

What commands should I use to 'unbuild' the frame, then rebuild it from scratch? Is there a more efficient way to replace one panel with another?


来源: stackexchange

问:
Jersey 2.0 Content-Length not set
I'm trying to post to a web service that requires the Content-Length header to be set using the following code:

```<code>// EDIT: added apache connector code
ClientConfig clientConfig = new ClientConfig();
ApacheConnector apache = new ApacheConnector(clientConfig);

// setup client to log requests and responses and their entities
client.register(new LoggingFilter(Logger.getLogger("com.example.app"), true));

Part part = new Part("123");
WebTarget target = client.target("https://api.thing.com/v1.0/thing/{thingId}");
Response jsonResponse = target.resolveTemplate("thingId", "abcdefg")
                .request(MediaType.APPLICATION_JSON)
                .header(HttpHeaders.AUTHORIZATION, "anauthcodehere")
                .post(Entity.json(part));
</code>```

From the release notes https://java.net/jira/browse/JERSEY-1617 and the Jersey 2.0 documentation https://jersey.java.net/documentation/latest/message-body-workers.html it implies that Content-Length is automatically set. However, I get a 411 response code back from the server indicating that Content-Length is not present in the request.

Does anyone know the best way to get the Content-Length header set?

I've verified through setting up a logger that the Content-Length header is not generated in the request.

Thanks.

答:
I've tested with Jersey 2.25.1 a simpler solution that consists in setting setChunkedEncodingEnabled(false) in the Jersey Client configuration. Instead of using a chunked encoding, the whole entity is serialised in memory and the Content-Length is set on the request.

For reference, here is an example of a configuration I've used:

```<code>private Client createJerseyClient(Environment environment) {
    Logger logger = Logger.getLogger(getClass().getName());
    JerseyClientConfiguration clientConfig = new JerseyClientConfiguration();
    clientConfig.setProxyConfiguration(new ProxyConfiguration("localhost", 3333));
    clientConfig.setGzipEnabled(false);
    clientConfig.setGzipEnabledForRequests(false);
    clientConfig.setChunkedEncodingEnabled(false);
    return new JerseyClientBuilder(environment)
            .using(clientConfig)
            .build("RestClient")
            .register(new LoggingFeature(logger, Level.INFO, null, null));
}
</code>```

I've used mitmproxy to verify the request headers and the Content-Length header was set correctly.

ContentLicense: CC BY-SA 3.0

Title: Jersey 2.0 Content-Length not set

Body:
I'm trying to post to a web service that requires the Content-Length header to be set using the following code:

// EDIT: added apache connector code
ClientConfig clientConfig = new ClientConfig();
ApacheConnector apache = new ApacheConnector(clientConfig);

// setup client to log requests and responses and their entities
client.register(new LoggingFilter(Logger.getLogger("com.example.app"), true));

Part part = new Part("123");
WebTarget target = client.target("https://api.thing.com/v1.0/thing/{thingId}");
Response jsonResponse = target.resolveTemplate("thingId", "abcdefg")
                .request(MediaType.APPLICATION_JSON)
                .header(HttpHeaders.AUTHORIZATION, "anauthcodehere")
                .post(Entity.json(part));

From the release notes https://java.net/jira/browse/JERSEY-1617 and the Jersey 2.0 documentation https://jersey.java.net/documentation/latest/message-body-workers.html it implies that Content-Length is automatically set. However, I get a 411 response code back from the server indicating that Content-Length is not present in the request.

Does anyone know the best way to get the Content-Length header set?

I've verified through setting up a logger that the Content-Length header is not generated in the request.

Thanks.

Body:
I've tested with Jersey 2.25.1 a simpler solution that consists in setting setChunkedEncodingEnabled(false) in the Jersey Client configuration. Instead of using a chunked encoding, the whole entity is serialised in memory and the Content-Length is set on the request.

For reference, here is an example of a configuration I've used:

private Client createJerseyClient(Environment environment) {
    Logger logger = Logger.getLogger(getClass().getName());
    JerseyClientConfiguration clientConfig = new JerseyClientConfiguration();
    clientConfig.setProxyConfiguration(new ProxyConfiguration("localhost", 3333));
    clientConfig.setGzipEnabled(false);
    clientConfig.setGzipEnabledForRequests(false);
    clientConfig.setChunkedEncodingEnabled(false);
    return new JerseyClientBuilder(environment)
            .using(clientConfig)
            .build("RestClient")
            .register(new LoggingFeature(logger, Level.INFO, null, null));
}

I've used mitmproxy to verify the request headers and the Content-Length header was set correctly.


问:
Introduction to Memory Addresses and Data Types
I was reading through some papers on Memory Addresses and Data Types in the C language and I've been grasping the content pretty well but I stumbled upon some maths and I can't seem to figure it out anywhere on the Internet.

Suppose I create two local variables

```<code>void foo(void){
    int i, j;
    printf("int i is stored in %p\n", &i);
    printf("int j is stored in %p\n", &j);
}
</code>```

The output I get is

```<code>int i is stored in 0x6ffc88
int j is stored in 0x6ffc84
</code>```

And in the text I'm reading, an integer is of size 4 bytes (same with my computer). So, int i is supposed to be allocated 4 bytes. But the difference between int i and int j's memory address is just 4 bits (0100).

Is the difference not meant to be something greater, like 4 bytes (0xffffffff)?

Please where am I making the confusion?

答:
j is located at at BYTE addresses 0x6ffc84,0x6ffc85,0x6ffc86,0x6ffc87, so, 32 bits.

i is located at at BYTE addresses 0x6ffc88,0x6ffc89,0x6ffc8a,0x6ffc8b, so, 32 bits.

Apart from microcontroller horrors like 8051, modern non-trivial processor architectures don't have bit addressable memory.

Body:
I was reading through some papers on Memory Addresses and Data Types in the C language and I've been grasping the content pretty well but I stumbled upon some maths and I can't seem to figure it out anywhere on the Internet.

Suppose I create two local variables

void foo(void){
    int i, j;
    printf("int i is stored in %p\n", &i);
    printf("int j is stored in %p\n", &j);
}

The output I get is

int i is stored in 0x6ffc88
int j is stored in 0x6ffc84

And in the text I'm reading, an integer is of size 4 bytes (same with my computer). So, int i is supposed to be allocated 4 bytes. But the difference between int i and int j's memory address is just 4 bits (0100).

Is the difference not meant to be something greater, like 4 bytes (0xffffffff)?

Please where am I making the confusion?


问:
how to give background color for button in android
i have three button which is arranged in table row .I gave background for the three button but it wraps the button .  </p>

答:
declare new a new xml in the drawable folder with the image/color you can specify image for each event state.
and you can you can set this xml as you background

if your xml is 'res/drawable/abc.xml' then set background as

```<code>android:background="@drawable/abc"
</code>```

You can also use ImageButton

```<code><ImageButton
----------------------
android:src="@drawable/youimage"
 />
</code>```

The benefit for ImageButton is that, no need of different image/color for highlight.

ContentLicense: CC BY-SA 2.5

Body:
declare new a new xml in the drawable folder with the image/color you can specify image for each event state.
and you can you can set this xml as you background

if your xml is 'res/drawable/abc.xml' then set background as

android:background="@drawable/abc"

You can also use ImageButton

<ImageButton
----------------------
android:src="@drawable/youimage"
 />

The benefit for ImageButton is that, no need of different image/color for highlight.


问:
How to force JSF to resend a request?
I have a random bug in my JSF app that strips all my HTTP parameters. It happens randomly and I can't get any error messages (even when following BalusC's advice here and here).

I can't pinpoint the cause and fix it so I'm wondering if another solution is possile: forcing the request to be resent if all my parameters are empty. Is there a way to make the browser resend its request? For example, through a JSF or HTTP error code.

EDIT: Cleaned up unnecessary code.

答:
In the end, I followed @Xtreme Biker's advice and instead built a filter. It checks if parameters are present, otherwise it sends a redirect response (HTTP error code 307). Then the browser send back the same request which proceeds through.

Something like:

```<code>String formWebContainerWidth = httpRequest.getParameter("myParam");
if(formWebContainerWidth == null){

    // SC_TEMPORARY_REDIRECT = 307
    httpResponse.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
    httpResponse.setHeader("Location", httpRequest.getRequestURI());
} else {
   chain.doFilter(request, response);
}
</code>```

EDIT: Added the location, otherwise the browser sometimes displays a "page cannot be reached" error message.

Title: How to force JSF to resend a request?

Body:
In the end, I followed @Xtreme Biker's advice and instead built a filter. It checks if parameters are present, otherwise it sends a redirect response (HTTP error code 307). Then the browser send back the same request which proceeds through.

Something like:

String formWebContainerWidth = httpRequest.getParameter("myParam");
if(formWebContainerWidth == null){

    // SC_TEMPORARY_REDIRECT = 307
    httpResponse.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
    httpResponse.setHeader("Location", httpRequest.getRequestURI());
} else {
   chain.doFilter(request, response);
}

EDIT: Added the location, otherwise the browser sometimes displays a "page cannot be reached" error message.


问:
jQuery highlighting clicked list item
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

```<code>.active {
  background: #f00;
}
</code>```

HTML

```<code><ul id="orgCat">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus
    <ul>
    <li>abc</li>
    <li>sdf</li>
    <li>oupu
      <ul>
      <li>progf</li>
      <li>ghfhg</li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
  <li class="list-group-item">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>
</code>```

JQUERY

```<code>$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });
</code>```

Demo

答:
Try using an element around the text like below, here I've used span

$('#orgCat span').click(function(e) {
    e.preventDefault()
    $('.active').removeClass('active');
    $(this).addClass('active');
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  background: #f00;
}</code>```

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

```

ContentLicense: CC BY-SA 4.0

Title: jQuery highlighting clicked list item

Body:
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

.active {
  background: #f00;
}

HTML

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

JQUERY

$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });

Demo

Body:
Try using an element around the text like below, here I've used span

$('#orgCat span').click(function(e) {
    e.preventDefault()
    $('.active').removeClass('active');
    $(this).addClass('active');
  });

.active {
  background: #f00;
}

<script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<ul id="orgCat">
  <li class="list-group-item"><span class="active">Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span>
    <ul>
    <li><span>abc</span></li>
    <li><span>sdf</span></li>
    <li><span>oupu</span>
      <ul>
      <li><span>progf</span></li>
      <li><span>ghfhg</span></li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
  <li class="list-group-item"><span>Cras justo odio</span></li>
  <li class="list-group-item"><span>Dapibus ac facilisis in</span></li>
  <li class="list-group-item"><span>Morbi leo risus</span></li>
  <li class="list-group-item"><span>Porta ac consectetur ac</span></li>
  <li class="list-group-item"><span>Vestibulum at eros</span></li>
</ul>


问:
Python loop print change of state only once
I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar questions what was very helpful but if I execute the code it print the outside temp is higher, next I heat up the inside sensor and it prints that it is inside higher, all good except that it doesn’t continue, the loop works but it doesn’t recognize the next change of state.
. </p>

```<code>import RPi.GPIO as GPIO
import time
sensor_name_0 = "test"
printed_out = False
printed_in = False

try:
    while True:
    if sensor_name_0:
        sensor_0 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[0]
        sensor_1 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[1]

        sensorpath = "/sys/bus/w1/devices/"
        sensorfile = "/w1_slave"

    def callsensor_0(sensor_0):
        f = open(sensorpath + sensor_0 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    def callsensor_1(sensor_1):
        f = open(sensorpath + sensor_1 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    outside = (str('%.1f' % float(callsensor_0(sensor_0))).rstrip('0').rstrip('.'))
    inside = (str('%.1f' % float(callsensor_1(sensor_1))).rstrip('0').rstrip('.'))
    print "loop"

    if outside > inside and not printed_out:
        printed_out = True
        print "outside is higher then inside"
        print  outside

    if outside < inside and not printed_in:
        printed_in = True
        print "inside is higher then outside"
        print  inside

    time.sleep(5)

except KeyboardInterrupt:
print('interrupted!')
</code>```

答:
```<code>    if outside > inside and not printed_out:
        printed_out = True
        print "outside is higher then inside"
        print  outside
        printed_in = False

    if outside < inside and not printed_in:
        printed_in = True
        print "inside is higher then outside"
        print  inside
        printed_out = False
    time.sleep(5)
</code>```

Body:
I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar questions what was very helpful but if I execute the code it print the outside temp is higher, next I heat up the inside sensor and it prints that it is inside higher, all good except that it doesn’t continue, the loop works but it doesn’t recognize the next change of state.
.

import RPi.GPIO as GPIO
import time
sensor_name_0 = "test"
printed_out = False
printed_in = False

try:
    while True:
    if sensor_name_0:
        sensor_0 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[0]
        sensor_1 = open('/sys/devices/w1_bus_master1/w1_master_slaves','r').read().split('\n')[1]

        sensorpath = "/sys/bus/w1/devices/"
        sensorfile = "/w1_slave"

    def callsensor_0(sensor_0):
        f = open(sensorpath + sensor_0 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    def callsensor_1(sensor_1):
        f = open(sensorpath + sensor_1 + sensorfile, 'r')
        lines = f.readlines()
        f.close()
        temp_line = lines[1].find('t=')
        temp_output = lines[1].strip() [temp_line+2:]
        temp_celsius = float(temp_output) / 1000
        return temp_celsius

    outside = (str('%.1f' % float(callsensor_0(sensor_0))).rstrip('0').rstrip('.'))
    inside = (str('%.1f' % float(callsensor_1(sensor_1))).rstrip('0').rstrip('.'))
    print "loop"

    if outside > inside and not printed_out:
        printed_out = True
        print "outside is higher then inside"
        print  outside

    if outside < inside and not printed_in:
        printed_in = True
        print "inside is higher then outside"
        print  inside

    time.sleep(5)

except KeyboardInterrupt:
print('interrupted!')


问:
PhP regex, remove white spaces and all special characters from string
I have a variable $name which can sometimes contain spaces and special characters like '%' '&' etc.how can I remove all of those using regex or in any other way?</p>

```<code> */
public function handle()
{
    $urls = Business::pluck('ical');
    $names = Business::pluck('name');
    foreach ($urls as $url) {
        foreach ($names as $name) {
            $test= explode("\n", $name);
            dd($test);
        $response = Curl::to($url)
            ->download('ical/'.$name.'.ics');
    }
</code>```

答:
Use the preg_replace() function of PHP.

```<code>$name = preg_replace('/[^\w\d]+/', '', $name);
</code>```

The regex /[^\w\d]+/ matches all white space and special characters.

https://www.tinywebhut.com/regex/2

Body:
I have a variable $name which can sometimes contain spaces and special characters like '%' '&' etc.how can I remove all of those using regex or in any other way?

 */
public function handle()
{
    $urls = Business::pluck('ical');
    $names = Business::pluck('name');
    foreach ($urls as $url) {
        foreach ($names as $name) {
            $test= explode("\n", $name);
            dd($test);
        $response = Curl::to($url)
            ->download('ical/'.$name.'.ics');
    }

Body:
Use the preg_replace() function of PHP.

$name = preg_replace('/[^\w\d]+/', '', $name);

The regex /[^\w\d]+/ matches all white space and special characters.

https://www.tinywebhut.com/regex/2


问:
Issues with a button not working when SQL is being used to get data from a table
This is some code I got off the internet because I'm quite new to SQL and had no intentions of using it until I came across this login feature I wanted to add into my desktop application. Here's the code.

```<code>    SqlConnection connection = new SqlConnection(@"Data Source=JOASH;Initial Catalog=Logins;Integrated Security=True");
        SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username='" + flatTextBox1.Text + "' AND Password='" + flatTextBox2 + "'", connection);
        DataTable dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
        if (dataTable.Rows[0][0].ToString() == "1")
        {
            this.Hide();
            Dashboard dashboard_form = new Dashboard();
            dashboard_form.Show();
        }
        else
        {
            MessageBox.Show("Authentication failed!");
        }
</code>```

That is the part where the SQL stuff is taking place for the Button. Basically, on clicking a button, the code is executed. But, for some reason, when I click the button, either the code isn't executing, or it isn't working. (I'm guessing it isn't executing.) I really hope that someone can help me with this. The button just won't work.

EDIT: As requested by Nirman, here's the Form Designer code.

```<code>    namespace subTerraApplication
    {
partial class WelcomePage
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.formSkin1 = new FlatUI.FormSkin();
        this.flatTextBox2 = new FlatUI.FlatTextBox();
        this.flatLabel2 = new FlatUI.FlatLabel();
        this.flatTextBox1 = new FlatUI.FlatTextBox();
        this.flatLabel1 = new FlatUI.FlatLabel();
        this.flatMini1 = new FlatUI.FlatMini();
        this.flatMax1 = new FlatUI.FlatMax();
        this.flatClose1 = new FlatUI.FlatClose();
        this.flatButton1 = new FlatUI.FlatButton();
        this.formSkin1.SuspendLayout();
        this.SuspendLayout();
        //
        // formSkin1
        //
        this.formSkin1.BackColor = System.Drawing.Color.White;
        this.formSkin1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(70)))), ((int)(((byte)(73)))));
        this.formSkin1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(53)))), ((int)(((byte)(58)))), ((int)(((byte)(60)))));
        this.formSkin1.Controls.Add(this.flatButton1);
        this.formSkin1.Controls.Add(this.flatTextBox2);
        this.formSkin1.Controls.Add(this.flatLabel2);
        this.formSkin1.Controls.Add(this.flatTextBox1);
        this.formSkin1.Controls.Add(this.flatLabel1);
        this.formSkin1.Controls.Add(this.flatMini1);
        this.formSkin1.Controls.Add(this.flatMax1);
        this.formSkin1.Controls.Add(this.flatClose1);
        this.formSkin1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.formSkin1.FlatColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.formSkin1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.formSkin1.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.formSkin1.HeaderMaximize = false;
        this.formSkin1.Location = new System.Drawing.Point(0, 0);
        this.formSkin1.Name = "formSkin1";
        this.formSkin1.Size = new System.Drawing.Size(256, 349);
        this.formSkin1.TabIndex = 0;
        this.formSkin1.Text = "subTerra Build 1";
        //
        // flatTextBox2
        //
        this.flatTextBox2.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox2.FocusOnHover = false;
        this.flatTextBox2.Location = new System.Drawing.Point(125, 135);
        this.flatTextBox2.MaxLength = 32767;
        this.flatTextBox2.Multiline = false;
        this.flatTextBox2.Name = "flatTextBox2";
        this.flatTextBox2.ReadOnly = false;
        this.flatTextBox2.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox2.TabIndex = 10;
        this.flatTextBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox2.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox2.UseSystemPasswordChar = true;
        //
        // flatLabel2
        //
        this.flatLabel2.AutoSize = true;
        this.flatLabel2.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel2.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel2.ForeColor = System.Drawing.Color.White;
        this.flatLabel2.Location = new System.Drawing.Point(13, 135);
        this.flatLabel2.Name = "flatLabel2";
        this.flatLabel2.Size = new System.Drawing.Size(99, 30);
        this.flatLabel2.TabIndex = 9;
        this.flatLabel2.Text = "Password";
        //
        // flatTextBox1
        //
        this.flatTextBox1.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox1.FocusOnHover = false;
        this.flatTextBox1.Location = new System.Drawing.Point(125, 81);
        this.flatTextBox1.MaxLength = 32767;
        this.flatTextBox1.Multiline = false;
        this.flatTextBox1.Name = "flatTextBox1";
        this.flatTextBox1.ReadOnly = false;
        this.flatTextBox1.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox1.TabIndex = 8;
        this.flatTextBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox1.UseSystemPasswordChar = false;
        //
        // flatLabel1
        //
        this.flatLabel1.AutoSize = true;
        this.flatLabel1.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel1.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel1.ForeColor = System.Drawing.Color.White;
        this.flatLabel1.Location = new System.Drawing.Point(13, 81);
        this.flatLabel1.Name = "flatLabel1";
        this.flatLabel1.Size = new System.Drawing.Size(106, 30);
        this.flatLabel1.TabIndex = 7;
        this.flatLabel1.Text = "Username";
        //
        // flatMini1
        //
        this.flatMini1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMini1.BackColor = System.Drawing.Color.White;
        this.flatMini1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMini1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMini1.Location = new System.Drawing.Point(189, -1);
        this.flatMini1.Name = "flatMini1";
        this.flatMini1.Size = new System.Drawing.Size(18, 18);
        this.flatMini1.TabIndex = 6;
        this.flatMini1.Text = "flatMini1";
        this.flatMini1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatMax1
        //
        this.flatMax1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMax1.BackColor = System.Drawing.Color.White;
        this.flatMax1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMax1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMax1.Location = new System.Drawing.Point(213, -1);
        this.flatMax1.Name = "flatMax1";
        this.flatMax1.Size = new System.Drawing.Size(18, 18);
        this.flatMax1.TabIndex = 5;
        this.flatMax1.Text = "flatMax1";
        this.flatMax1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatClose1
        //
        this.flatClose1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatClose1.BackColor = System.Drawing.Color.White;
        this.flatClose1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(35)))), ((int)(((byte)(35)))));
        this.flatClose1.Font = new System.Drawing.Font("Marlett", 10F);
        this.flatClose1.Location = new System.Drawing.Point(237, 0);
        this.flatClose1.Name = "flatClose1";
        this.flatClose1.Size = new System.Drawing.Size(18, 18);
        this.flatClose1.TabIndex = 4;
        this.flatClose1.Text = "flatClose1";
        this.flatClose1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatButton1
        //
        this.flatButton1.BackColor = System.Drawing.Color.Transparent;
        this.flatButton1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.flatButton1.Cursor = System.Windows.Forms.Cursors.Hand;
        this.flatButton1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.flatButton1.Location = new System.Drawing.Point(74, 209);
        this.flatButton1.Name = "flatButton1";
        this.flatButton1.Rounded = false;
        this.flatButton1.Size = new System.Drawing.Size(106, 32);
        this.flatButton1.TabIndex = 11;
        this.flatButton1.Text = "Login";
        this.flatButton1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // WelcomePage
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(256, 349);
        this.Controls.Add(this.formSkin1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.Name = "WelcomePage";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.TransparencyKey = System.Drawing.Color.Fuchsia;
        this.formSkin1.ResumeLayout(false);
        this.formSkin1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private FlatUI.FormSkin formSkin1;
    private FlatUI.FlatMini flatMini1;
    private FlatUI.FlatMax flatMax1;
    private FlatUI.FlatClose flatClose1;
    private FlatUI.FlatTextBox flatTextBox2;
    private FlatUI.FlatLabel flatLabel2;
    private FlatUI.FlatTextBox flatTextBox1;
    private FlatUI.FlatLabel flatLabel1;
    private FlatUI.FlatButton flatButton1;
}
</code>```

}

PROBLEM HAS BEEN SOLVED! The code for the click detection was missing!

答:
I do not see any event handler attached to the designer code of the button there should be:

```<code>this.flatButton1.Click += new System.EventHandler(this.flatButton1_Click);
</code>```

You have to define a event handler and put the code inside it

```<code>    private void flatButton1_Click(object sender, EventArgs e)
    {
        //Your code here
    }
</code>```

Body:
This is some code I got off the internet because I'm quite new to SQL and had no intentions of using it until I came across this login feature I wanted to add into my desktop application. Here's the code.

    SqlConnection connection = new SqlConnection(@"Data Source=JOASH;Initial Catalog=Logins;Integrated Security=True");
        SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username='" + flatTextBox1.Text + "' AND Password='" + flatTextBox2 + "'", connection);
        DataTable dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
        if (dataTable.Rows[0][0].ToString() == "1")
        {
            this.Hide();
            Dashboard dashboard_form = new Dashboard();
            dashboard_form.Show();
        }
        else
        {
            MessageBox.Show("Authentication failed!");
        }

That is the part where the SQL stuff is taking place for the Button. Basically, on clicking a button, the code is executed. But, for some reason, when I click the button, either the code isn't executing, or it isn't working. (I'm guessing it isn't executing.) I really hope that someone can help me with this. The button just won't work.

EDIT: As requested by Nirman, here's the Form Designer code.

    namespace subTerraApplication
    {
partial class WelcomePage
{
    ///
    /// Required designer variable.
    ///
    private System.ComponentModel.IContainer components = null;

    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        this.formSkin1 = new FlatUI.FormSkin();
        this.flatTextBox2 = new FlatUI.FlatTextBox();
        this.flatLabel2 = new FlatUI.FlatLabel();
        this.flatTextBox1 = new FlatUI.FlatTextBox();
        this.flatLabel1 = new FlatUI.FlatLabel();
        this.flatMini1 = new FlatUI.FlatMini();
        this.flatMax1 = new FlatUI.FlatMax();
        this.flatClose1 = new FlatUI.FlatClose();
        this.flatButton1 = new FlatUI.FlatButton();
        this.formSkin1.SuspendLayout();
        this.SuspendLayout();
        //
        // formSkin1
        //
        this.formSkin1.BackColor = System.Drawing.Color.White;
        this.formSkin1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(70)))), ((int)(((byte)(73)))));
        this.formSkin1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(53)))), ((int)(((byte)(58)))), ((int)(((byte)(60)))));
        this.formSkin1.Controls.Add(this.flatButton1);
        this.formSkin1.Controls.Add(this.flatTextBox2);
        this.formSkin1.Controls.Add(this.flatLabel2);
        this.formSkin1.Controls.Add(this.flatTextBox1);
        this.formSkin1.Controls.Add(this.flatLabel1);
        this.formSkin1.Controls.Add(this.flatMini1);
        this.formSkin1.Controls.Add(this.flatMax1);
        this.formSkin1.Controls.Add(this.flatClose1);
        this.formSkin1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.formSkin1.FlatColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.formSkin1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.formSkin1.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.formSkin1.HeaderMaximize = false;
        this.formSkin1.Location = new System.Drawing.Point(0, 0);
        this.formSkin1.Name = "formSkin1";
        this.formSkin1.Size = new System.Drawing.Size(256, 349);
        this.formSkin1.TabIndex = 0;
        this.formSkin1.Text = "subTerra Build 1";
        //
        // flatTextBox2
        //
        this.flatTextBox2.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox2.FocusOnHover = false;
        this.flatTextBox2.Location = new System.Drawing.Point(125, 135);
        this.flatTextBox2.MaxLength = 32767;
        this.flatTextBox2.Multiline = false;
        this.flatTextBox2.Name = "flatTextBox2";
        this.flatTextBox2.ReadOnly = false;
        this.flatTextBox2.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox2.TabIndex = 10;
        this.flatTextBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox2.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox2.UseSystemPasswordChar = true;
        //
        // flatLabel2
        //
        this.flatLabel2.AutoSize = true;
        this.flatLabel2.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel2.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel2.ForeColor = System.Drawing.Color.White;
        this.flatLabel2.Location = new System.Drawing.Point(13, 135);
        this.flatLabel2.Name = "flatLabel2";
        this.flatLabel2.Size = new System.Drawing.Size(99, 30);
        this.flatLabel2.TabIndex = 9;
        this.flatLabel2.Text = "Password";
        //
        // flatTextBox1
        //
        this.flatTextBox1.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox1.FocusOnHover = false;
        this.flatTextBox1.Location = new System.Drawing.Point(125, 81);
        this.flatTextBox1.MaxLength = 32767;
        this.flatTextBox1.Multiline = false;
        this.flatTextBox1.Name = "flatTextBox1";
        this.flatTextBox1.ReadOnly = false;
        this.flatTextBox1.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox1.TabIndex = 8;
        this.flatTextBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox1.UseSystemPasswordChar = false;
        //
        // flatLabel1
        //
        this.flatLabel1.AutoSize = true;
        this.flatLabel1.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel1.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel1.ForeColor = System.Drawing.Color.White;
        this.flatLabel1.Location = new System.Drawing.Point(13, 81);
        this.flatLabel1.Name = "flatLabel1";
        this.flatLabel1.Size = new System.Drawing.Size(106, 30);
        this.flatLabel1.TabIndex = 7;
        this.flatLabel1.Text = "Username";
        //
        // flatMini1
        //
        this.flatMini1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMini1.BackColor = System.Drawing.Color.White;
        this.flatMini1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMini1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMini1.Location = new System.Drawing.Point(189, -1);
        this.flatMini1.Name = "flatMini1";
        this.flatMini1.Size = new System.Drawing.Size(18, 18);
        this.flatMini1.TabIndex = 6;
        this.flatMini1.Text = "flatMini1";
        this.flatMini1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatMax1
        //
        this.flatMax1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMax1.BackColor = System.Drawing.Color.White;
        this.flatMax1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMax1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMax1.Location = new System.Drawing.Point(213, -1);
        this.flatMax1.Name = "flatMax1";
        this.flatMax1.Size = new System.Drawing.Size(18, 18);
        this.flatMax1.TabIndex = 5;
        this.flatMax1.Text = "flatMax1";
        this.flatMax1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatClose1
        //
        this.flatClose1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatClose1.BackColor = System.Drawing.Color.White;
        this.flatClose1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(35)))), ((int)(((byte)(35)))));
        this.flatClose1.Font = new System.Drawing.Font("Marlett", 10F);
        this.flatClose1.Location = new System.Drawing.Point(237, 0);
        this.flatClose1.Name = "flatClose1";
        this.flatClose1.Size = new System.Drawing.Size(18, 18);
        this.flatClose1.TabIndex = 4;
        this.flatClose1.Text = "flatClose1";
        this.flatClose1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatButton1
        //
        this.flatButton1.BackColor = System.Drawing.Color.Transparent;
        this.flatButton1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.flatButton1.Cursor = System.Windows.Forms.Cursors.Hand;
        this.flatButton1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.flatButton1.Location = new System.Drawing.Point(74, 209);
        this.flatButton1.Name = "flatButton1";
        this.flatButton1.Rounded = false;
        this.flatButton1.Size = new System.Drawing.Size(106, 32);
        this.flatButton1.TabIndex = 11;
        this.flatButton1.Text = "Login";
        this.flatButton1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // WelcomePage
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(256, 349);
        this.Controls.Add(this.formSkin1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.Name = "WelcomePage";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.TransparencyKey = System.Drawing.Color.Fuchsia;
        this.formSkin1.ResumeLayout(false);
        this.formSkin1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private FlatUI.FormSkin formSkin1;
    private FlatUI.FlatMini flatMini1;
    private FlatUI.FlatMax flatMax1;
    private FlatUI.FlatClose flatClose1;
    private FlatUI.FlatTextBox flatTextBox2;
    private FlatUI.FlatLabel flatLabel2;
    private FlatUI.FlatTextBox flatTextBox1;
    private FlatUI.FlatLabel flatLabel1;
    private FlatUI.FlatButton flatButton1;
}

}

PROBLEM HAS BEEN SOLVED! The code for the click detection was missing!

Body:
I do not see any event handler attached to the designer code of the button there should be:

this.flatButton1.Click += new System.EventHandler(this.flatButton1_Click);

You have to define a event handler and put the code inside it

    private void flatButton1_Click(object sender, EventArgs e)
    {
        //Your code here
    }


问:
How to using group by function in Xquery
I am using XQuery and I need to convert the (,) sepereated format or using group by in Xquery.

```<code>Final Output
grp|A|#A
grp|A4|#A
grp|A2|#A
grp|A1|#A

Expected Output

grp|A,A4,A2,A1|#A
</code>```

My Xquery:

```<code>let $root := 'grp'
let $uri := for $i in fn:collection('collection')
 return fn:document-uri($i)
let $result := for $each-uri in $uri

             let $title := (doc($each-uri)//grp/title/text())[1]
             let $id  := (doc($each-uri)//grp/@id)[1]
             let $root :=  'grp'
             return fn:concat($root,'|',$id,'|',$title)

         return fn:distinct-values($result)
</code>```

答:
I think only a group-by clause and a string-join call were missing.

```<code>let $root := 'grp'
let $uri := for $i in fn:collection('collection')
            return fn:document-uri($i)
let $result := for $each-uri in $uri
               let $title := (doc($each-uri)//grp/title/text())[1]
               let $id  := (doc($each-uri)//grp/@id)[1]
               let $root :=  'grp'
               group by $root, $title
               return fn:concat($root,'|',string-join($id, ","),'|',$title)
return fn:distinct-values($result)
</code>```

Although distinct-values may need to be moved to the IDs, and concat can be replaced with string-join as well, like so:

```<code>let $root := 'grp'
let $uri := for $i in fn:collection('collection')
            return fn:document-uri($i)
let $result := for $each-uri in $uri
               let $title := (doc($each-uri)//grp/title/text())[1]
               let $id  := (doc($each-uri)//grp/@id)[1]
               let $root :=  'grp'
               group by $root, $title
               return string-join(
                 ($root, string-join(distinct-values($id), ","), $title),
                 '|'
               )
return $result
</code>```

Body:
I am using XQuery and I need to convert the (,) sepereated format or using group by in Xquery.

Final Output
grp|A|#A
grp|A4|#A
grp|A2|#A
grp|A1|#A

Expected Output

grp|A,A4,A2,A1|#A

My Xquery:

let $root := 'grp'
let $uri := for $i in fn:collection('collection')
 return fn:document-uri($i)
let $result := for $each-uri in $uri

             let $title := (doc($each-uri)//grp/title/text())[1]
             let $id  := (doc($each-uri)//grp/@id)[1]
             let $root :=  'grp'
             return fn:concat($root,'|',$id,'|',$title)

         return fn:distinct-values($result)

Body:
I think only a group-by clause and a string-join call were missing.

let $root := 'grp'
let $uri := for $i in fn:collection('collection')
            return fn:document-uri($i)
let $result := for $each-uri in $uri
               let $title := (doc($each-uri)//grp/title/text())[1]
               let $id  := (doc($each-uri)//grp/@id)[1]
               let $root :=  'grp'
               group by $root, $title
               return fn:concat($root,'|',string-join($id, ","),'|',$title)
return fn:distinct-values($result)

Although distinct-values may need to be moved to the IDs, and concat can be replaced with string-join as well, like so:

let $root := 'grp'
let $uri := for $i in fn:collection('collection')
            return fn:document-uri($i)
let $result := for $each-uri in $uri
               let $title := (doc($each-uri)//grp/title/text())[1]
               let $id  := (doc($each-uri)//grp/@id)[1]
               let $root :=  'grp'
               group by $root, $title
               return string-join(
                 ($root, string-join(distinct-values($id), ","), $title),
                 '|'
               )
return $result


问:
Various errors while scanning for folders
Please do not mark as duplicate as I have looked at the other questions with this error and I still can't figure it out.

I am making a basic scanner that scans a directory given to it and it deletes all sub directories that are older than 90 days. Here is the code:

```<code>import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'
</code>```

Here is the full traceback:

```<code>Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found
</code>```

Edit: When I use my program on a folder with multiple sub folders such as the desktop folder, it gives me the following error: WindowsError: [Error 2] The system cannot find the file specified and the name of the first folder.

I am using python 2.7.13. Can anyone please help? Any help is widely appreciated.

答:
Works for me:

```<code>import os, sys
import time
import shutil
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'
</code>```

I adapted the os.walk(path) output as Moses said, changed the while to if and added (os.path.join(path,folders), so os.stat(...) can find the folder in question.

```<code>for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400:
</code>```

Body:
Please do not mark as duplicate as I have looked at the other questions with this error and I still can't figure it out.

I am making a basic scanner that scans a directory given to it and it deletes all sub directories that are older than 90 days. Here is the code:

import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'

Here is the full traceback:

Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found

Edit: When I use my program on a folder with multiple sub folders such as the desktop folder, it gives me the following error: WindowsError: [Error 2] The system cannot find the file specified and the name of the first folder.

I am using python 2.7.13. Can anyone please help? Any help is widely appreciated.

Body:
Works for me:

import os, sys
import time
import shutil
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'

I adapted the os.walk(path) output as Moses said, changed the while to if and added (os.path.join(path,folders), so os.stat(...) can find the folder in question.

for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400:


问:
Is there a way to make my background iPhone app to go foreground?
Is there a way to make my background iPhone app to go foreground?

Tnx.

答:
Nope. But you can do something when you feel must do. For example, use remote Apple Push Notification Service (APNS) to notify your user that you want her to bring your app back to the foreground.

Or, as JustSid put it, use local notification to notify your user that you want her attention.


问:
How to use AndroidAnnotation @SharedPref with Kotlin
I'm trying to use AndroidAnnotations @SharefPref within kotlin, but Iget following error

```<code>org.androidannotations.annotations.sharedpreferences.Pref can only be used on an element that extends org.androidannotations.api.sharedpreferences.SharedPreferencesHelper
</code>```

What am I doing wrong?

```<code>//Interface
@SharedPref(SharedPref.Scope.APPLICATION_DEFAULT)
open interface MyPreferences {
    @DefaultInt(-1)
    fun someIntValue():Int
}

//Fragment
@Pref
lateinit open var sharedPref:CongressPreferences_

//usage within fragment
val get: Int = sharedPref.selectedEventId().get()
</code>```

答:
This is due to a bug in the Kotlin annotation processor.

To fix this, you must add correctErrorTypes = true to your kapt block.

```<code>kapt {
  correctErrorTypes = true
}
</code>```

Also make sure you are using the latest Kotlin version (as of this moment: 1.1.3).

Body:
I'm trying to use AndroidAnnotations @SharefPref within kotlin, but Iget following error

org.androidannotations.annotations.sharedpreferences.Pref can only be used on an element that extends org.androidannotations.api.sharedpreferences.SharedPreferencesHelper

What am I doing wrong?

//Interface
@SharedPref(SharedPref.Scope.APPLICATION_DEFAULT)
open interface MyPreferences {
    @DefaultInt(-1)
    fun someIntValue():Int
}

//Fragment
@Pref
lateinit open var sharedPref:CongressPreferences_

//usage within fragment
val get: Int = sharedPref.selectedEventId().get()

Body:
This is due to a bug in the Kotlin annotation processor.

To fix this, you must add correctErrorTypes = true to your kapt block.

kapt {
  correctErrorTypes = true
}

Also make sure you are using the latest Kotlin version (as of this moment: 1.1.3).


问:
Nested loops with depth parameter in python
How do I make a number of nested loops where depth is a parameter.
I am thinking of a function which takes depth as a parameter

```<code>def make_nested_loops(depth):
    ...
</code>```

And, the result for depth=3 is the following

```<code>for i1 in range(10):
    for i2 in range(i1 + 1, 10):
        for i3 in range(i2 + 1, 10):
            # do stuff
</code>```

So far I've been able to do this using strings building and exec command. But I think there is better and more efficient way to do it.

答:
An inefficient but simple approach would be to use itertools.product and filter unwanted tuples:

```<code>def make_tuples(depth, n):
    for i in itertools.product(range(n), repeat=depth):
        if sorted(i) < i:
            continue
        yield i
</code>```

More efficient would be a recursive generator:

```<code>def make_tuples(depth, n, start=0):
    if depth == 0:
        yield ()
    else:
        for x in range(start, n):
            for t in make_tuples(depth - 1, n, x + 1):
                yield (x,) + t
</code>```

Using it would look like

```<code>for (i1, i2, i3) in make_tuples(3, 10):
    # do stuff with i1, i2, i3
</code>```

If the depth is really dynamic, you can't of course unpack the tuples coming from make_tuples. The body will have to know what to do with tuples
of fixed but unknown length.

```<code>for tpl in make_tuples(n, 10):
    # Do stuff with tpl
</code>```

Body:
How do I make a number of nested loops where depth is a parameter.
I am thinking of a function which takes depth as a parameter

def make_nested_loops(depth):
    ...

And, the result for depth=3 is the following

for i1 in range(10):
    for i2 in range(i1 + 1, 10):
        for i3 in range(i2 + 1, 10):
            # do stuff

So far I've been able to do this using strings building and exec command. But I think there is better and more efficient way to do it.

Body:
An inefficient but simple approach would be to use itertools.product and filter unwanted tuples:

def make_tuples(depth, n):
    for i in itertools.product(range(n), repeat=depth):
        if sorted(i) < i:
            continue
        yield i

More efficient would be a recursive generator:

def make_tuples(depth, n, start=0):
    if depth == 0:
        yield ()
    else:
        for x in range(start, n):
            for t in make_tuples(depth - 1, n, x + 1):
                yield (x,) + t

Using it would look like

for (i1, i2, i3) in make_tuples(3, 10):
    # do stuff with i1, i2, i3

If the depth is really dynamic, you can't of course unpack the tuples coming from make_tuples. The body will have to know what to do with tuples
of fixed but unknown length.

for tpl in make_tuples(n, 10):
    # Do stuff with tpl


问:
Graph Partitioning
Consider I have a graph containing 10,000 nodes. Now I want to look for a certain number of nodes in the graph. I want to achieve this with graph partition technique so that if a reasonable number of desired nodes is found in some partition I can stop searching. So how to do the partitioning? What are the suitable algorithms or tools to use?

My graph is in matrix format. where mat[i][j] gives the value of the edge weight between two nodes 'i' and 'j'.

After finding a partition, I want to have a list of all the nodes present in that partition.

答:
If I understand you correctly, you want to search for a set of nodes that match some objective -- while parallelizing this search on the partition level. In this case, a good partitioning strategy would be to balance the number of "matching nodes" across partitions.

The reason is that if those matching nodes are balanced, all parallel workers working independently on a partition have the same chance of finding/matching the vertices.

In my experience, you can achieve a very solid balancing with respect to different objectives when using random assignment of vertices to partitions -- even if the edge-cut size is not optimal.

However, it is difficult to answer your question without knowing more about your objective, so maybe you can update your question with more details.

Title: Graph Partitioning


问:
Ignore whitespace in HTML
Is there anything in HTML/CSS that tells the browser to ignore whitespace completely?

So many times when you want to put, say, two images next to each other - you try desperately to keep the HTML readable, but the browser puts a space between them.

So instead of something like this:

```<code><img src="images/minithing.jpg" alt="my mini thing" />
<img src="images/minithing.jpg" alt="my mini thing" />
<img src="images/minithing.jpg" alt="my mini thing" />
<img src="images/minithing.jpg" alt="my mini thing" />
</code>```

you end up with this

```<code><img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" /><img src="images/minithing.jpg" alt="my mini thing" />
</code>```

Which is just so horrible!

答:
This is a simple question and the answer is not so simple.

One can try to avoid the spaces in the source code which is not always achievable in CMS, because there they are automatically inserted by the system. If you want to change this you have to dig deep inte the CMS's core code.

Then you can try to use left floated images. But this is dangerous. At first you don't really have a control over vertical-alignment by definition. And secondly, you run into total chaos if you have so many floated elements, that they stretch over more than one line. And if you have a layout that relies on left floated elements (most of them do so today) you can even break some outer floating styles, if you clear floating after the images. This can be overridden, if you float any surrounding element. Rather not to be recommended.

So the only solution would be a CSS declaration that handles the process of whitespace handling. This is not part of any standard (as CSS 3 is not yet finished).

I prefer the no whitespace in HTML variant. With using drupal as CMS this can be achieved rather easy in your template.php and theming files. Then I choose inline-block.

P.S.:
inline-block is rather complicated to get in the different browsers.
For FF 2 you need display: -moz-inline-box.
The rest and IE8 can have display: inline-block right after.
And for lte IE 7 you need display: inline in a following separate declaration (preferrably via conditional comments).

edit

What I use for making a element inline-block

```<code>elem.inline {
  display: -moz-inline-box; /* FF2 */
  display: inline-block; /* gives hasLayout in IE 6+7*/
}
/* * html hack for IE 6 */
* html elem.inline {
  display: inline; /* elements with hasLayout and display inline behave like inline-block */
}
/* * +  html hack for IE 7 */
* + html elem.inline {
  display: inline; /* elements with hasLayout and display inline behave like inline-block */
}
</code>```

Title: Ignore whitespace in HTML

Body:
Is there anything in HTML/CSS that tells the browser to ignore whitespace completely?

So many times when you want to put, say, two images next to each other - you try desperately to keep the HTML readable, but the browser puts a space between them.

So instead of something like this:

you end up with this

Which is just so horrible!

Body:
This is a simple question and the answer is not so simple.

One can try to avoid the spaces in the source code which is not always achievable in CMS, because there they are automatically inserted by the system. If you want to change this you have to dig deep inte the CMS's core code.

Then you can try to use left floated images. But this is dangerous. At first you don't really have a control over vertical-alignment by definition. And secondly, you run into total chaos if you have so many floated elements, that they stretch over more than one line. And if you have a layout that relies on left floated elements (most of them do so today) you can even break some outer floating styles, if you clear floating after the images. This can be overridden, if you float any surrounding element. Rather not to be recommended.

So the only solution would be a CSS declaration that handles the process of whitespace handling. This is not part of any standard (as CSS 3 is not yet finished).

I prefer the no whitespace in HTML variant. With using drupal as CMS this can be achieved rather easy in your template.php and theming files. Then I choose inline-block.

P.S.:
inline-block is rather complicated to get in the different browsers.
For FF 2 you need display: -moz-inline-box.
The rest and IE8 can have display: inline-block right after.
And for lte IE 7 you need display: inline in a following separate declaration (preferrably via conditional comments).

edit

What I use for making a element inline-block

elem.inline {
  display: -moz-inline-box; /* FF2 */
  display: inline-block; /* gives hasLayout in IE 6+7*/
}
/* * html hack for IE 6 */
* html elem.inline {
  display: inline; /* elements with hasLayout and display inline behave like inline-block */
}
/* * +  html hack for IE 7 */
* + html elem.inline {
  display: inline; /* elements with hasLayout and display inline behave like inline-block */
}


问:
$.post is not send data to web form
Function:

```<code>$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});
</code>```

ServerSide of :

```<code> protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }
</code>```

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

答:
You are currently not posting form encoded data but a json string. If you want to keep the aspx as the end point and access the variables using the Form collection then you will have to change your ajax call to post form encoded data and specify that in the header of the http call.

```<code>$.post({
    url: "/SurveyResult.aspx",
    data: $.param({test: 'testing'}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).done(function (data) {
  alert("Data Updated");
});
</code>```

See also param which makes passing / transforming objects as a part of the request data a little easier to write. You could also replace it with this hard coded string.

```<code>data: "test=testing",
</code>```

Title: $.post is not send data to web form

Body:
Function:

$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});

ServerSide of :

 protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

Body:
You are currently not posting form encoded data but a json string. If you want to keep the aspx as the end point and access the variables using the Form collection then you will have to change your ajax call to post form encoded data and specify that in the header of the http call.

$.post({
    url: "/SurveyResult.aspx",
    data: $.param({test: 'testing'}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).done(function (data) {
  alert("Data Updated");
});

See also param which makes passing / transforming objects as a part of the request data a little easier to write. You could also replace it with this hard coded string.

data: "test=testing",


问:
django-import-export to export subset of fields
I'm using django-import-export to export users from the django user admin interface.

I want to limit the number of fields present in the export.

Looking at the docs, I tried the following:

```<code>class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class UserAdmin(ExportMixin, UserAdmin):
    pass

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
</code>```

From the python shell, this appears to work fine, the following code

```<code>export = UserResource().export()
print export.csv
</code>```

produces output that contains only the 3 fields I requested.

However, exports from the admin interface still contain all User fields.

How can I limit the number of fields exported through the admin interface?

答:
You can use

```<code>exclude = ('abc','def', 'ijk')
</code>```

Assume you want to export only 'first_name' & 'last_name'. Then,

```<code>class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')
        exclude = ('email')
</code>```

Body:
I'm using django-import-export to export users from the django user admin interface.

I want to limit the number of fields present in the export.

Looking at the docs, I tried the following:

class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class UserAdmin(ExportMixin, UserAdmin):
    pass

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

From the python shell, this appears to work fine, the following code

export = UserResource().export()
print export.csv

produces output that contains only the 3 fields I requested.

However, exports from the admin interface still contain all User fields.

How can I limit the number of fields exported through the admin interface?

Body:
You can use

exclude = ('abc','def', 'ijk')

Assume you want to export only 'first_name' & 'last_name'. Then,

class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')
        exclude = ('email')


问:
Tango Asus Zenfone AR
I developed an app base on tango using java api. The app is working without problems in the Tango development kit and Lenovo phab 2 pro. Since a couple of days I tried to run on the new Asus Zenfone AR but I am getting this error.

```<code>I/TangoClientLibLoader: basePath: /data/data/com.google.tango/libfiles/
E/TangoJNINative: ERROR! Unable to load libtango_client_api.so!

java.lang.UnsatisfiedLinkError: No implementation found for int com.google.atap.tango.TangoJNINative.SetBinder(android.os.IBinder) (tried Java_com_google_atap_tango_TangoJNINative_SetBinder and Java_com_google_atap_tango_TangoJNINative_SetBinder__Landroid_os_IBinder_2)
                                                                   at com.google.atap.tango.TangoJNINative.SetBinder(Native Method)
                                                                   at com.google.atap.tangoservice.Tango$2.onServiceConnected(Tango.java:329)
                                                                   at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1468)
                                                                   at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1496)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:159)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6097)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

By the way,I used the Java Hello Video Example and I got this issue, maybe is related to my problem.

Any help would be great.

答:
Set the target SDK in android build settings as 23.

There are some internal dependencies in libtango_client_api.so that require the target sdk to be set to 23. I believe they are working on fixing this issue in the near future.

Title: Tango Asus Zenfone AR

Body:
I developed an app base on tango using java api. The app is working without problems in the Tango development kit and Lenovo phab 2 pro. Since a couple of days I tried to run on the new Asus Zenfone AR but I am getting this error.

I/TangoClientLibLoader: basePath: /data/data/com.google.tango/libfiles/
E/TangoJNINative: ERROR! Unable to load libtango_client_api.so!

java.lang.UnsatisfiedLinkError: No implementation found for int com.google.atap.tango.TangoJNINative.SetBinder(android.os.IBinder) (tried Java_com_google_atap_tango_TangoJNINative_SetBinder and Java_com_google_atap_tango_TangoJNINative_SetBinder__Landroid_os_IBinder_2)
                                                                   at com.google.atap.tango.TangoJNINative.SetBinder(Native Method)
                                                                   at com.google.atap.tangoservice.Tango$2.onServiceConnected(Tango.java:329)
                                                                   at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1468)
                                                                   at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1496)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:159)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6097)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

By the way,I used the Java Hello Video Example and I got this issue, maybe is related to my problem.

Any help would be great.


问:
Macro to fill blank selected row from in main workbook from open workbook form
I have one main workbook I use as a schedule. I have a different "request" excel workbook form that customers send to me filled out. I want to have a macro that copies one row from the customer form into my main workbook. In my main workbook, I want to manually enter a new row, have that row selected, and then the data from the customer workbook would fill into the selected row. I have many of the customer forms and would prefer the macro to pull the data from whatever customer form I have open at that time. I do not want the macro to automatically insert a new row because of the way I have my schedule workbook formatted. Does anyone know how to accomplish this?

Thank you!

EDIT: I tried to run an initial macro and here is the code:

```<code>    Sub Macro1()
'
' Macro1 Macro
'

'
    Windows("TEST - Tool Move Request Form.xlsx").Activate
    Range("B12:K12").Select
    Selection.Copy
    Windows("TEST - Ocotillo Site Tool Move Schedule.xlsx").Activate
    Range("A26").Select
    ActiveSheet.Paste
    Range("E32").Select
End Sub
</code>```

答:
```<code>Private Sub Macro1()
Dim x As Workbook
Dim y As Workbook
Dim PrevRow As Long

'Workbook From - Take the path
Set x = Workbooks.Open("C:\TEST - Tool Move Request Form.xlsx")
'Workbook To - Take the path
Set y = Workbooks.Open("C:\TEST - Ocotillo Site Tool Move Schedule.xlsx")
'Find the last row and move to the next row
PrevRow = y.Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row + 1

'Take the sheet you're going to, and add corresponding value
y.Sheets("Sheet1").Range("A" & PrevRow).Value = x.Sheets("Sheet1").Range("B12")
y.Sheets("Sheet1").Range("B" & PrevRow).Value = x.Sheets("Sheet1").Range("C12")
y.Sheets("Sheet1").Range("C" & PrevRow).Value = x.Sheets("Sheet1").Range("D12")
y.Sheets("Sheet1").Range("D" & PrevRow).Value = x.Sheets("Sheet1").Range("E12")
y.Sheets("Sheet1").Range("E" & PrevRow).Value = x.Sheets("Sheet1").Range("F12")
y.Sheets("Sheet1").Range("F" & PrevRow).Value = x.Sheets("Sheet1").Range("G12")
End Sub
</code>```

Body:
I have one main workbook I use as a schedule. I have a different "request" excel workbook form that customers send to me filled out. I want to have a macro that copies one row from the customer form into my main workbook. In my main workbook, I want to manually enter a new row, have that row selected, and then the data from the customer workbook would fill into the selected row. I have many of the customer forms and would prefer the macro to pull the data from whatever customer form I have open at that time. I do not want the macro to automatically insert a new row because of the way I have my schedule workbook formatted. Does anyone know how to accomplish this?

Thank you!

EDIT: I tried to run an initial macro and here is the code:

    Sub Macro1()
'
' Macro1 Macro
'

'
    Windows("TEST - Tool Move Request Form.xlsx").Activate
    Range("B12:K12").Select
    Selection.Copy
    Windows("TEST - Ocotillo Site Tool Move Schedule.xlsx").Activate
    Range("A26").Select
    ActiveSheet.Paste
    Range("E32").Select
End Sub


问:
When to call findViewById in an Activity
I am encountering the following issue.
I have the following lines of code :

```<code>Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibility(View.VISIBLE);
</code>```

These get executed after the user clicks on menu item in the UI. So I am pretty sure the UI is drawn on the screen. The spinner should be on the screen, and already filled with data.
The menu item is to change the language of the screen. The spinner should than fill up with items in the newly selected language.

In GooglePlay I sometimes get an error report where the stackTrace gives a NullPointerException in the 2nd line. So it must be that domainSpinner is null.

I have never experienced this issue myself. Also we use a beta version of the app for our own use, and none of my collegues has ever had this issue.

I have no idea why the findViewById should sometimes return null. I have tried going back and forward, rotating, .... But I never have this problem.

Note that the item R.id.domain can have a visibility of GONE setted programmatically. But I also played with this but could not reproduce the problem.

Code of the menu item action :

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item)
{
   int id = item.getItemId();
   if (id == R.id.action_nl)
   {
      changeLanguage("nl", true);
      return true;
   }
   else if (id == R.id.action_fr)
   {
      changeLanguage("fr", true);
      return true;
   }
   else if (id == R.id.action_en)
   {
      changeLanguage("en", true);
      return true;
   }
   else if (id == R.id.action_de)
   {
      changeLanguage("de", true);
      return true;
   }

   return super.onOptionsItemSelected(item);
</code>```

}

答:
You can try this. Make sure the domainSpinner is initialized on the Main Thread. Also add a condition for setting visibility only when domainSpinner is not equal to null.</p>

```<code>Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(new Runnable() {

    @Override
    public void run() {
        Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
        if(domainSpinner!=null) {
           domainSpinner.setVisibility(View.VISIBLE);
        }
    }
});
</code>```

Body:
I am encountering the following issue.
I have the following lines of code :

Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibility(View.VISIBLE);

These get executed after the user clicks on menu item in the UI. So I am pretty sure the UI is drawn on the screen. The spinner should be on the screen, and already filled with data.
The menu item is to change the language of the screen. The spinner should than fill up with items in the newly selected language.

In GooglePlay I sometimes get an error report where the stackTrace gives a NullPointerException in the 2nd line. So it must be that domainSpinner is null.

I have never experienced this issue myself. Also we use a beta version of the app for our own use, and none of my collegues has ever had this issue.

I have no idea why the findViewById should sometimes return null. I have tried going back and forward, rotating, .... But I never have this problem.

Note that the item R.id.domain can have a visibility of GONE setted programmatically. But I also played with this but could not reproduce the problem.

Code of the menu item action :

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
   int id = item.getItemId();
   if (id == R.id.action_nl)
   {
      changeLanguage("nl", true);
      return true;
   }
   else if (id == R.id.action_fr)
   {
      changeLanguage("fr", true);
      return true;
   }
   else if (id == R.id.action_en)
   {
      changeLanguage("en", true);
      return true;
   }
   else if (id == R.id.action_de)
   {
      changeLanguage("de", true);
      return true;
   }

   return super.onOptionsItemSelected(item);

}

Body:
You can try this. Make sure the domainSpinner is initialized on the Main Thread. Also add a condition for setting visibility only when domainSpinner is not equal to null.

Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(new Runnable() {

    @Override
    public void run() {
        Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
        if(domainSpinner!=null) {
           domainSpinner.setVisibility(View.VISIBLE);
        }
    }
});


问:
Slim trailing slash route
I have this route in a Slim application:

```<code>$app->get('/fasi/:id/',function ($id) use ($app) {
        $app->render("fasi.html");
});
</code>```

This answers to

```<code>http://test/fasi/1/
</code>```

but also to

```<code>http://test/fasi/1
</code>```

Is there any way to force Slim to answer only to the url with the trailing slash (first one) or, to redirect the client adding the trailing slash?

答:
You can make optional the slash and the parameter also, like this:

```<code>$app->get('/fasi/[:id[/]]',function ($id) use ($app) {
    $app->render("fasi.html");
});
</code>```

This works with:

http://test/fasi/1

or:

http://test/fasi/1/

Title: Slim trailing slash route

Body:
I have this route in a Slim application:

$app->get('/fasi/:id/',function ($id) use ($app) {
        $app->render("fasi.html");
});

This answers to

http://test/fasi/1/

but also to

http://test/fasi/1

Is there any way to force Slim to answer only to the url with the trailing slash (first one) or, to redirect the client adding the trailing slash?

Body:
You can make optional the slash and the parameter also, like this:

$app->get('/fasi/[:id[/]]',function ($id) use ($app) {
    $app->render("fasi.html");
});

This works with:

http://test/fasi/1

or:

http://test/fasi/1/