Programs & Examples On #Jbutton

A JButton is a common button in Java Swing.

Creating a custom JButton in Java

You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:

try {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    Class aClass = MainFrame.class;
    InputStream stream = aClass.getResourceAsStream("\\default.xml");

    if (stream == null) {
        System.err.println("Missing configuration file");
        System.exit(-1);                
    }

    synth.load(stream, aClass);

    UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
    System.err.println("Bad configuration file");
    pe.printStackTrace();
    System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
    System.err.println("Old JRE in use. Get a new one");
    System.exit(-3);
}

From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.

The xml file might look like this:

<synth>
    <style id="button">
        <font name="DIALOG" size="12" style="BOLD"/>
        <state value="MOUSE_OVER">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
        <state value="ENABLED">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
    </style>
    <bind style="button" type="name" key="dirt"/>
</synth>

The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").

And a couple of useful links:

http://javadesktop.org/articles/synth/

http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

How to set background color of a button in Java GUI?

Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in here to get a better result:

enter image description here

How to place a JButton at a desired location in a JFrame using Java

I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)

How do I add an image to a JButton

public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }

How to add action listener that listens to multiple buttons

The problem is that button1 is a local variable. You could do it by just change the way you add the actionListener.

button.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e)
            {
                //button is pressed
                System.out.println("You clicked the button");
            }});

Or you make button1 a global variable.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to Disable GUI Button in Java

Once you've created the frame the part of the code with your conditional isn't going to get entered. To put it another way, at the time you execute the test if (btn1Clicked == true) , the button has not only not been clicked yet, it hasn't even been displayed to the user.

Lose the booleans and move the line with the btnConvertDocuments.setEnabled(false) into your actionListener. Make the buttons instance variables, do not make them static variables. (Alternatively you could keep the buttons as local variables and assign each of them their own anonymous inner class listener.)

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

Java - Check if JTextField is empty or not

you can use isEmpty() or isBlank() methods regarding what you need.


Returns true if, and only if, length() is 0.

this.name.getText().isEmpty();

Returns true if the string is empty or contains only white space codepoints, otherwise false

this.name.getText().isBlank();

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

Swing/Java: How to use the getText and setText string properly

the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

Getting key with maximum value in dictionary?

Here is another one:

stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iterkeys(), key=lambda k: stats[k])

The function key simply returns the value that should be used for ranking and max() returns the demanded element right away.

How to set a cookie for another domain

In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.

Disable scrolling in all mobile devices

use this in style

body
{
overflow:hidden;
width:100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

How to read lines of a file in Ruby

Your first file has Mac Classic line endings (that’s "\r" instead of the usual "\n"). Open it with

File.open('foo').each(sep="\r") do |line|

to specify the line endings.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

How do I copy SQL Azure database to my local development server?

In SQL Server Management Studio

Right click on the database you want to import, click Tasks > Export data-tier application, and export your database to a local .dacpac file.

In your local target SQL server instance, you can right click Databases > Import data-tier application, and once it's local, you can do things like backup and restore the database.

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
    return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window and document aren't built-in, they're defined by the browser and most likely enumerable by design.

From ECMA-262 Edition 3:

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum } attribute set on them.


Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum } to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in loop.

Convert object string to JSON

This will also work

let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));

Angular 2: 404 error occur when I refresh through the browser

If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

jquery get all form elements: input, textarea & select

var $form_elements = $("#form_id").find(":input");

All the elements including the submit-button are now in the variable $form_elements.

How to convert answer into two decimal point

Call me lazy but:

 lblTellBMI.Text = "Your BMI is: " & Math.Round(sngBMI, 2)

I.e.: Label lblTellBMI will display Your BMI is: and then append the value from a Single type variable (sngBMI) as 2 decimal points, simply by using the Math.Round method.

The Math.Round method rounds a value to the nearest integer or to the specified number of fractional digits.

Source: https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx

Easy way to dismiss keyboard?

Add A Tap Gesture Recognizer to your view.And define it ibaction

your .m file will be like

    - (IBAction)hideKeyboardGesture:(id)sender {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in windows) [window endEditing:true];
    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

It's worked for me

HTML anchor link - href and onclick both?

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

Failure during conversion to COFF: file invalid or corrupt

Do you have Visual Studio 2012 installed as well? If so, 2012 stomps your 2010 IDE, possibly because of compatibility issues with .NET 4.5 and .NET 4.0.

See http://social.msdn.microsoft.com/Forums/da-DK/vssetup/thread/d10adba0-e082-494a-bb16-2bfc039faa80

Bootstrap carousel width and height

Are you trying to make it responsive? If you are then I would just recommend the following:

.tales {
  width: 100%;
}
.carousel-inner{
  width:100%;
  max-height: 200px !important;
}

However, the best way to handle this responsively would be thru the use of media queries like such:

/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {}

/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {}

/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {}

/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {}

/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {}

Remove blank values from array using C#

I prefer to use two options, white spaces and empty:

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

How to check if a variable is null or empty string or all whitespace in JavaScript?

Try this out

/**
  * Checks the string if undefined, null, not typeof string, empty or space(s)
  * @param {any} str string to be evaluated
  * @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
    return str === undefined || str === null
                             || typeof str !== 'string'
                             || str.match(/^ *$/) !== null;
}

You can use it like this

isStringNullOrWhiteSpace('Your String');

Convert Month Number to Month Name Function in SQL

I think this is the best way to get the month name when you have the month number

Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )

Or

Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )

Add Keypair to existing EC2 instance

You can't apply a keypair to a running instance. You can only use the new keypair to launch a new instance.

For recovery, if it's an EBS boot AMI, you can stop it, make a snapshot of the volume. Create a new volume based on it. And be able to use it back to start the old instance, create a new image, or recover data.

Though data at ephemeral storage will be lost.


Due to the popularity of this question and answer, I wanted to capture the information in the link that Rodney posted on his comment.

Credit goes to Eric Hammond for this information.

Fixing Files on the Root EBS Volume of an EC2 Instance

You can examine and edit files on the root EBS volume on an EC2 instance even if you are in what you considered a disastrous situation like:

  • You lost your ssh key or forgot your password
  • You made a mistake editing the /etc/sudoers file and can no longer gain root access with sudo to fix it
  • Your long running instance is hung for some reason, cannot be contacted, and fails to boot properly
  • You need to recover files off of the instance but cannot get to it

On a physical computer sitting at your desk, you could simply boot the system with a CD or USB stick, mount the hard drive, check out and fix the files, then reboot the computer to be back in business.

A remote EC2 instance, however, seems distant and inaccessible when you are in one of these situations. Fortunately, AWS provides us with the power and flexibility to be able to recover a system like this, provided that we are running EBS boot instances and not instance-store.

The approach on EC2 is somewhat similar to the physical solution, but we’re going to move and mount the faulty “hard drive” (root EBS volume) to a different instance, fix it, then move it back.

In some situations, it might simply be easier to start a new EC2 instance and throw away the bad one, but if you really want to fix your files, here is the approach that has worked for many:

Setup

Identify the original instance (A) and volume that contains the broken root EBS volume with the files you want to view and edit.

instance_a=i-XXXXXXXX

volume=$(ec2-describe-instances $instance_a |
  egrep '^BLOCKDEVICE./dev/sda1' | cut -f3)

Identify the second EC2 instance (B) that you will use to fix the files on the original EBS volume. This instance must be running in the same availability zone as instance A so that it can have the EBS volume attached to it. If you don’t have an instance already running, start a temporary one.

instance_b=i-YYYYYYYY

Stop the broken instance A (waiting for it to come to a complete stop), detach the root EBS volume from the instance (waiting for it to be detached), then attach the volume to instance B on an unused device.

ec2-stop-instances $instance_a
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_b --device /dev/sdj $volume

ssh to instance B and mount the volume so that you can access its file system.

ssh ...instance b...

sudo mkdir -p 000 /vol-a
sudo mount /dev/sdj /vol-a

Fix It

At this point your entire root file system from instance A is available for viewing and editing under /vol-a on instance B. For example, you may want to:

  • Put the correct ssh keys in /vol-a/home/ubuntu/.ssh/authorized_keys
  • Edit and fix /vol-a/etc/sudoers
  • Look for error messages in /vol-a/var/log/syslog
  • Copy important files out of /vol-a/…

Note: The uids on the two instances may not be identical, so take care if you are creating, editing, or copying files that belong to non-root users. For example, your mysql user on instance A may have the same UID as your postfix user on instance B which could cause problems if you chown files with one name and then move the volume back to A.

Wrap Up

After you are done and you are happy with the files under /vol-a, unmount the file system (still on instance-B):

sudo umount /vol-a
sudo rmdir /vol-a

Now, back on your system with ec2-api-tools, continue moving the EBS volume back to it’s home on the original instance A and start the instance again:

ec2-detach-volume $volume
ec2-attach-volume --instance $instance_a --device /dev/sda1 $volume
ec2-start-instances $instance_a

Hopefully, you fixed the problem, instance A comes up just fine, and you can accomplish what you originally set out to do. If not, you may need to continue repeating these steps until you have it working.

Note: If you had an Elastic IP address assigned to instance A when you stopped it, you’ll need to reassociate it after starting it up again.

Remember! If your instance B was temporarily started just for this process, don’t forget to terminate it now.

Unable to import a module that is definitely installed

Most of the possible cases have been already covered in solutions, just sharing my case, it happened to me that I installed a package in one environment (e.g. X) and I was importing the package in another environment (e.g. Y). So, always make sure that you're importing the package from the environment in which you installed the package.

Disable automatic sorting on the first column when using jQuery DataTables

Set the aaSorting option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.

"aaSorting": []

The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').

How do I URl encode something in Node.js?

Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'

If you don't want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

Jquery each - Stop loop and return object

Because when you use a return statement inside an each loop, a "non-false" value will act as a continue, whereas false will act as a break. You will need to return false from the each function. Something like this:

function findXX(word) {
    var toReturn; 
    $.each(someArray, function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

What's the difference between ".equals" and "=="?

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

How can I make a list of lists in R?

The example creates a list of named lists in a loop.

  MyList <- list()
  for (aName in c("name1", "name2")){
    MyList[[aName]] <- list(aName)
  }
  MyList[["name1"]]
  MyList[["name2"]]

To add another list named "name3" do write:

  MyList$name3 <- list(1, 2, 3)

How to check if an element exists in the xml using xpath?

Normally when you try to select a node using xpath your xpath-engine will return null or equivalent if the node doesn't exists.

xpath: "/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml"

If your using xsl check out this question for an answer:

xpath find if node exists

Split a large dataframe into a list of data frames based on common value in column

You can just as easily access each element in the list using e.g. path[[1]]. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply functions to further operate on each element in the list. Example below.

#  For reproducibile data
set.seed(1)

#  Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )

#  Split on userid
out <- split( df , f = df$userid )
#$`1`
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

#$`2`
#  userid data1 data2
#2      2   xfv     4
#4      2   bfe    10
#6      2   mrx     2
#8      2   fqd     9

Access each element using the [[ operator like this:

out[[1]]
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

Or use an *apply function to do further operations on each list element. For instance, to take the mean of the data2 column you could use sapply like this:

sapply( out , function(x) mean( x$data2 ) )
#   1    2 
#3.75 6.25 

jQuery: Selecting by class and input type

Your selector is looking for any descendants of a checkbox element that have a class of .myClass.

Try this instead:

$("input.myClass:checkbox")

Check it out in action.

I also tested this:

$("input:checkbox.myClass")

And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect : style selectors to come last. As I said, though, either one will work.

How to pass data from Javascript to PHP and vice versa?

You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.

The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

SQL Server 2005 Using CHARINDEX() To split a string

    USE [master]
    GO
    /******  this function returns Pakistan where as if you want to get ireland simply replace (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING))) with
SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING, 0,CHARINDEX('$@$@$',@NEWSTRING)))******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[FN_RETURN_AFTER_SPLITER] 
    (  
     @SPLITER varchar(max))
    RETURNS VARCHAR(max)
    AS 
    BEGIN

    --declare @testString varchar(100),
    DECLARE @NEWSTRING VARCHAR(max) 
    -- set @teststring = '@ram?eez(ali)'
     SET @NEWSTRING = @SPLITER ; 

    SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING)))
    return @NEWSTRING 
    END
    --select [dbo].[FN_RETURN_AFTER_SPLITER]  ('Ireland$@$@$Pakistan')

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

var firstName = "John";
var id = 12;

ctx.Database.ExecuteSqlCommand(@"Update [User] SET FirstName = {0} WHERE Id = {1}"
, new object[]{ firstName, id });

This is so simple !!!

Image for knowing parameter reference

enter image description here

How can I get this ASP.NET MVC SelectList to work?

the value selected in the model takes advantage instead of the default item. (I agree I didn't read all posts)

How do I implement a progress bar in C#?

If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.

Suppress/ print without b' prefix for bytes in Python 3

you can use this code for showing or print :

<byte_object>.decode("utf-8")

and you can use this for encode or saving :

<str_object>.encode('utf-8')

How to apply CSS to iframe?

Expanding on the above jQuery solution to cope with any delays in loading the frame contents.

$('iframe').each(function(){
    function injectCSS(){
        $iframe.contents().find('head').append(
            $('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
        );
    }

    var $iframe = $(this);
    $iframe.on('load', injectCSS);
    injectCSS();
});

How to install JQ on Mac by command-line?

For most it is a breeze, however like you I had a difficult time installing jq

The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

What worked for me was removing all previous installs then pip install jq

Get to UIViewController from UIView?

The simplest do while loop for finding the viewController.

-(UIViewController*)viewController
{
    UIResponder *nextResponder =  self;

    do
    {
        nextResponder = [nextResponder nextResponder];

        if ([nextResponder isKindOfClass:[UIViewController class]])
            return (UIViewController*)nextResponder;

    } while (nextResponder != nil);

    return nil;
}

CardView Corner Radius

An easy way to achieve this would be:

1.Make a custom background resource (like a rectangle shape) with rounded corners.

2.set this custom background using the command -

cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);

this worked for me.

The XML layout I made with top left and bottom right radius.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>

In your case, you need to change only topLeftRadius as well as topRightRadius.

If you have a layout that overlaps with the corners of the card view and has a different color maybe, then you might need a different background resource file for the layout and in the xml set this background resource to your layout.

I tried and tested the above method. Hope this helps you.

How to merge two sorted arrays into a sorted array?

Any improvements that could be made would be micro-optimizations, the overall algorithm is correct.

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Official Notice: success and error have been deprecated, please use the standard then method instead.

Deprecation Notice: The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

link: https://code.angularjs.org/1.5.7/docs/api/ng/service/$http

screenshot: view the screenshot

How do I run a program with a different working directory from current, from Linux shell?

An option which doesn't require a subshell and is built in to bash

(pushd SOME_PATH && run_stuff; popd)

Demo:

$ pwd
/home/abhijit
$ pushd /tmp # directory changed
$ pwd
/tmp
$ popd
$ pwd
/home/abhijit

'module' object has no attribute 'DataFrame'

The most likely explanation is that either a file called 'pandas.py' is in the same directory as your script, or that another variable called 'pd' is used in your program.

An invalid XML character (Unicode: 0xc) was found

I faced a similar issue where XML was containing control characters. After looking into the code, I found that a deprecated class,StringBufferInputStream, was used for reading string content.

http://docs.oracle.com/javase/7/docs/api/java/io/StringBufferInputStream.html

This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.

I changed it to ByteArrayInputStream and it worked fine.

React - How to force a function component to render?

I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.

import useForceUpdate from 'use-force-update';

const MyButton = () => {

  const forceUpdate = useForceUpdate();

  const handleClick = () => {
    alert('I will re-render now.');
    forceUpdate();
  };

  return <button onClick={handleClick} />;
};

How do you uninstall a python package that was installed using distutils?

Another time stamp based hack:

  1. Create an anchor: touch /tmp/ts
  2. Reinstall the package to be removed: python setup.py install --prefix=<PREFIX>
  3. Remove files what are more recent than the anchor file: find <PREFIX> -cnewer /tmp/ts | xargs rm -r

How to move an entire div element up x pixels?

$('div').css({
    position: 'relative',
    top: '-15px'
});

how to convert from int to char*?

  • In C++17, use std::to_chars as:

    std::array<char, 10> str;
    std::to_chars(str.data(), str.data() + str.size(), 42);
    
  • In C++11, use std::to_string as:

    std::string s = std::to_string(number);
    char const *pchar = s.c_str();  //use char const* as target type
    
  • And in C++03, what you're doing is just fine, except use const as:

    char const* pchar = temp_str.c_str(); //dont use cast
    

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

The answer to the question how to convert a .cer file into a .crt file (they are encoded differently!) is:

openssl pkcs7 -print_certs -in certificate.cer -out certificate.crt

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

Can lambda functions be templated?

I am aware that this question is about C++11. However, for those who googled and landed on this page, templated lambdas are now supported in C++14 and go by the name Generic Lambdas.

[info] Most of the popular compilers support this feature now. Microsoft Visual Studio 2015 supports. Clang supports. GCC supports.

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

How to change RGB color to HSV?

This is the VB.net version which works fine for me ported from the C code in BlaM's post.

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.


Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
    Dim i As Integer
    Dim f, p, q, t As Double

    If (s = 0) Then
        ' achromatic (grey)
        r = v
        g = v
        b = v
        Exit Sub
    End If

    h /= 60 'sector 0 to 5
    i = Math.Floor(h)
    f = h - i 'factorial part of h
    p = v * (1 - s)
    q = v * (1 - s * f)
    t = v * (1 - s * (1 - f))

    Select Case (i)
        Case 0
            r = v
            g = t
            b = p
            Exit Select
        Case 1
            r = q
            g = v
            b = p
            Exit Select
        Case 2
            r = p
            g = v
            b = t
            Exit Select
        Case 3
            r = p
            g = q
            b = v
            Exit Select
        Case 4
            r = t
            g = p
            b = v
            Exit Select
        Case Else   'case 5:
            r = v
            g = p
            b = q
            Exit Select
    End Select
End Sub

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

How to plot a histogram using Matplotlib in Python with a list of data?

This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.

First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.

Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.

However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.

Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.

If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability) with maybe binning option, and use of x-labels already available is suspicious.

Then bar plot should not be used as histogram but rather simply

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
plt.hist(probability)
plt.show()

with the results

enter image description here

matplotlib in such case arrives by default with the following histogram values

(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
 array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
        0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
        0.42028986]),
 <a list of 10 Patch objects>)

the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.

One can check they they are equally spaced,

x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
  print(left, right, right-left)

enter image description here

Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram

plt.hist(probability, bins=3)

enter image description here

with the plot data "behind the bars" being

enter image description here

The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).

How to send multiple data fields via Ajax?

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';

after that you can do like:

var new_countries = countries.join(',')

after:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: new_countries,
    ...

This thing work as JSON string format.

How to log cron jobs?

By default cron logs to /var/log/syslog so you can see cron related entries by using:

grep CRON /var/log/syslog

https://askubuntu.com/questions/56683/where-is-the-cron-crontab-log

How many times a substring occurs

my_string = """Strings are amongst the most popular data types in Python. 
               We can create the strings by enclosing characters in quotes.
               Python treats single quotes the same as double quotes."""

Count = my_string.lower().strip("\n").split(" ").count("string")
Count = my_string.lower().strip("\n").split(" ").count("strings")
print("The number of occurance of word String is : " , Count)
print("The number of occurance of word Strings is : " , Count)

How to write some data to excel file(.xlsx)

It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb. Using OleDb, it behaves as if you were writing to a table using sql.

Here is the code I used to create and write to an new excel file. No extra references are needed

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

In MySQL, how to copy the content of one table to another table within the same database?

INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE;

EDIT: or if the tables have different structures you can also:

INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;

EDIT: to constrain this..

INSERT INTO TARGET_TABLE (`col1_`,`col2_`) SELECT `col1`,`col2` FROM SOURCE_TABLE WHERE `foo`=1

Clear the form field after successful submission of php form

Put the onClick function in the button submit:

<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />

In the <head>, define the function clearform(), and set the textbox value to "":

function clearform()
{
    document.getElementById("firstname").value=""; //don't forget to set the textbox id
    document.getElementById("lastname").value="";
}

This way the textbox will be cleared when you click the submit button.

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

How do I create delegates in Objective-C?

As a good practice recommended by Apple, it's good for the delegate (which is a protocol, by definition), to conform to NSObject protocol.

@protocol MyDelegate <NSObject>
    ...
@end

& to create optional methods within your delegate (i.e. methods which need not necessarily be implemented), you can use the @optional annotation like this :

@protocol MyDelegate <NSObject>
    ...
    ...
      // Declaration for Methods that 'must' be implemented'
    ...
    ...
    @optional
    ...
      // Declaration for Methods that 'need not necessarily' be implemented by the class conforming to your delegate
    ...
@end

So when using methods that you have specified as optional, you need to (in your class) check with respondsToSelector if the view (that is conforming to your delegate) has actually implemented your optional method(s) or not.

How do I get the information from a meta tag with JavaScript?

function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

Used in this way:

getMetaContentByName("video");

The example on this page:

getMetaContentByName("twitter:domain");

What is the copy-and-swap idiom?

Overview

Why do we need the copy-and-swap idiom?

Any class that manages a resource (a wrapper, like a smart pointer) needs to implement The Big Three. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls need to be avoided?

The copy-and-swap idiom is the solution, and elegantly assists the assignment operator in achieving two things: avoiding code duplication, and providing a strong exception guarantee.

How does it work?

Conceptually, it works by using the copy-constructor's functionality to create a local copy of the data, then takes the copied data with a swap function, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.

In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a swap function.

A swap function is a non-throwing function that swaps two objects of a class, member for member. We might be tempted to use std::swap instead of providing our own, but this would be impossible; std::swap uses the copy-constructor and copy-assignment operator within its implementation, and we'd ultimately be trying to define the assignment operator in terms of itself!

(Not only that, but unqualified calls to swap will use our custom swap operator, skipping over the unnecessary construction and destruction of our class that std::swap would entail.)


An in-depth explanation

The goal

Let's consider a concrete case. We want to manage, in an otherwise useless class, a dynamic array. We start with a working constructor, copy-constructor, and destructor:

#include <algorithm> // std::copy
#include <cstddef> // std::size_t

class dumb_array
{
public:
    // (default) constructor
    dumb_array(std::size_t size = 0)
        : mSize(size),
          mArray(mSize ? new int[mSize]() : nullptr)
    {
    }

    // copy-constructor
    dumb_array(const dumb_array& other)
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : nullptr),
    {
        // note that this is non-throwing, because of the data
        // types being used; more attention to detail with regards
        // to exceptions must be given in a more general case, however
        std::copy(other.mArray, other.mArray + mSize, mArray);
    }

    // destructor
    ~dumb_array()
    {
        delete [] mArray;
    }

private:
    std::size_t mSize;
    int* mArray;
};

This class almost manages the array successfully, but it needs operator= to work correctly.

A failed solution

Here's how a naive implementation might look:

// the hard part
dumb_array& operator=(const dumb_array& other)
{
    if (this != &other) // (1)
    {
        // get rid of the old data...
        delete [] mArray; // (2)
        mArray = nullptr; // (2) *(see footnote for rationale)

        // ...and put in the new
        mSize = other.mSize; // (3)
        mArray = mSize ? new int[mSize] : nullptr; // (3)
        std::copy(other.mArray, other.mArray + mSize, mArray); // (3)
    }

    return *this;
}

And we say we're finished; this now manages an array, without leaks. However, it suffers from three problems, marked sequentially in the code as (n).

  1. The first is the self-assignment test. This check serves two purposes: it's an easy way to prevent us from running needless code on self-assignment, and it protects us from subtle bugs (such as deleting the array only to try and copy it). But in all other cases it merely serves to slow the program down, and act as noise in the code; self-assignment rarely occurs, so most of the time this check is a waste. It would be better if the operator could work properly without it.

  2. The second is that it only provides a basic exception guarantee. If new int[mSize] fails, *this will have been modified. (Namely, the size is wrong and the data is gone!) For a strong exception guarantee, it would need to be something akin to:

    dumb_array& operator=(const dumb_array& other)
    {
        if (this != &other) // (1)
        {
            // get the new data ready before we replace the old
            std::size_t newSize = other.mSize;
            int* newArray = newSize ? new int[newSize]() : nullptr; // (3)
            std::copy(other.mArray, other.mArray + newSize, newArray); // (3)
    
            // replace the old data (all are non-throwing)
            delete [] mArray;
            mSize = newSize;
            mArray = newArray;
        }
    
        return *this;
    }
    
  3. The code has expanded! Which leads us to the third problem: code duplication. Our assignment operator effectively duplicates all the code we've already written elsewhere, and that's a terrible thing.

In our case, the core of it is only two lines (the allocation and the copy), but with more complex resources this code bloat can be quite a hassle. We should strive to never repeat ourselves.

(One might wonder: if this much code is needed to manage one resource correctly, what if my class manages more than one? While this may seem to be a valid concern, and indeed it requires non-trivial try/catch clauses, this is a non-issue. That's because a class should manage one resource only!)

A successful solution

As mentioned, the copy-and-swap idiom will fix all these issues. But right now, we have all the requirements except one: a swap function. While The Rule of Three successfully entails the existence of our copy-constructor, assignment operator, and destructor, it should really be called "The Big Three and A Half": any time your class manages a resource it also makes sense to provide a swap function.

We need to add swap functionality to our class, and we do that as follows†:

class dumb_array
{
public:
    // ...

    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        // enable ADL (not necessary in our case, but good practice)
        using std::swap;

        // by swapping the members of two objects,
        // the two objects are effectively swapped
        swap(first.mSize, second.mSize);
        swap(first.mArray, second.mArray);
    }

    // ...
};

(Here is the explanation why public friend swap.) Now not only can we swap our dumb_array's, but swaps in general can be more efficient; it merely swaps pointers and sizes, rather than allocating and copying entire arrays. Aside from this bonus in functionality and efficiency, we are now ready to implement the copy-and-swap idiom.

Without further ado, our assignment operator is:

dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}

And that's it! With one fell swoop, all three problems are elegantly tackled at once.

Why does it work?

We first notice an important choice: the parameter argument is taken by-value. While one could just as easily do the following (and indeed, many naive implementations of the idiom do):

dumb_array& operator=(const dumb_array& other)
{
    dumb_array temp(other);
    swap(*this, temp);

    return *this;
}

We lose an important optimization opportunity. Not only that, but this choice is critical in C++11, which is discussed later. (On a general note, a remarkably useful guideline is as follows: if you're going to make a copy of something in a function, let the compiler do it in the parameter list.‡)

Either way, this method of obtaining our resource is the key to eliminating code duplication: we get to use the code from the copy-constructor to make the copy, and never need to repeat any bit of it. Now that the copy is made, we are ready to swap.

Observe that upon entering the function that all the new data is already allocated, copied, and ready to be used. This is what gives us a strong exception guarantee for free: we won't even enter the function if construction of the copy fails, and it's therefore not possible to alter the state of *this. (What we did manually before for a strong exception guarantee, the compiler is doing for us now; how kind.)

At this point we are home-free, because swap is non-throwing. We swap our current data with the copied data, safely altering our state, and the old data gets put into the temporary. The old data is then released when the function returns. (Where upon the parameter's scope ends and its destructor is called.)

Because the idiom repeats no code, we cannot introduce bugs within the operator. Note that this means we are rid of the need for a self-assignment check, allowing a single uniform implementation of operator=. (Additionally, we no longer have a performance penalty on non-self-assignments.)

And that is the copy-and-swap idiom.

What about C++11?

The next version of C++, C++11, makes one very important change to how we manage resources: the Rule of Three is now The Rule of Four (and a half). Why? Because not only do we need to be able to copy-construct our resource, we need to move-construct it as well.

Luckily for us, this is easy:

class dumb_array
{
public:
    // ...

    // move constructor
    dumb_array(dumb_array&& other) noexcept ††
        : dumb_array() // initialize via default constructor, C++11 only
    {
        swap(*this, other);
    }

    // ...
};

What's going on here? Recall the goal of move-construction: to take the resources from another instance of the class, leaving it in a state guaranteed to be assignable and destructible.

So what we've done is simple: initialize via the default constructor (a C++11 feature), then swap with other; we know a default constructed instance of our class can safely be assigned and destructed, so we know other will be able to do the same, after swapping.

(Note that some compilers do not support constructor delegation; in this case, we have to manually default construct the class. This is an unfortunate but luckily trivial task.)

Why does that work?

That is the only change we need to make to our class, so why does it work? Remember the ever-important decision we made to make the parameter a value and not a reference:

dumb_array& operator=(dumb_array other); // (1)

Now, if other is being initialized with an rvalue, it will be move-constructed. Perfect. In the same way C++03 let us re-use our copy-constructor functionality by taking the argument by-value, C++11 will automatically pick the move-constructor when appropriate as well. (And, of course, as mentioned in previously linked article, the copying/moving of the value may simply be elided altogether.)

And so concludes the copy-and-swap idiom.


Footnotes

*Why do we set mArray to null? Because if any further code in the operator throws, the destructor of dumb_array might be called; and if that happens without setting it to null, we attempt to delete memory that's already been deleted! We avoid this by setting it to null, as deleting null is a no-operation.

†There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.

‡The reason is simple: once you have the resource to yourself, you may swap and/or move it (C++11) anywhere it needs to be. And by making the copy in the parameter list, you maximize optimization.

††The move constructor should generally be noexcept, otherwise some code (e.g. std::vector resizing logic) will use the copy constructor even when a move would make sense. Of course, only mark it noexcept if the code inside doesn't throw exceptions.

How to find numbers from a string?

Use the built-in VBA function Val, if the numbers are at the front end of the string:

Dim str as String
Dim lng as Long

str = "1 149 xyz"
lng = Val(str)

lng = 1149

Val Function, on MSDN

How can I get the image url in a Wordpress theme?

src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"
worked for me for wordpress 3.6 i used it to get header logo using as

<img src="<?php bloginfo('template_url'); ?>/images/logo.jpg">

Query to list number of records in each table in a database

If you use MySQL >4.x you can use this:

select TABLE_NAME, TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA="test";

Keep in mind that for some storage engines, TABLE_ROWS is an approximation.

Apache: The requested URL / was not found on this server. Apache

I had the same problem, but believe it or not is was a case of case sensitivity.

This on localhost: http://localhost/.../getdata.php?id=3

Did not behave the same as this on the server: http://server/.../getdata.php?id=3

Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Your secondNumber seems to be an ivar, so you have to use a local var to unwrap the optional. And careful. You don't test secondNumber for 0, which can lead into a division by zero. Technically you need another case to handle an impossible operation. For instance checkin if the number is 0 and do nothing in that case would at least not crash.

@IBAction func equals(sender: AnyObject) {

    guard let number = Screen.text?.toInt(), number > 0 else {
        return
    }

    secondNumber = number

    if operation == "+"{
        result = firstNumber + secondNumber
    }
    else if operation == "-" {
        result = firstNumber - secondNumber
    }
    else if operation == "x" {
        result = firstNumber * secondNumber
    }
    else {
        result = firstNumber / secondNumber
    }
    Screen.text = "\(result)"
}

How to send control+c from a bash script?

    pgrep -f process_name > any_file_name
    sed -i 's/^/kill /' any_file_name
    chmod 777 any_file_name
    ./any_file_name

for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.

Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).

Now, we can utilize Left Join to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:

SELECT child_table.* 
FROM child_table 
LEFT JOIN parent_table 
  ON parent_table.referenced_column = child_table.referencing_column 
WHERE parent_table.referenced_column IS NULL

Now, you can generally do one (or more) of the following steps to fix the data.

  1. Based on your "business logic", you will need to update/match these unmatching value(s), with the existing values in the parent table. You may sometimes need to set them null as well.
  2. Delete these rows having unmatching values.
  3. Add new rows in your parent table, corresponding to the unmatching values in the child table.

Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE syntax.

How do you check if a JavaScript Object is a DOM Object?

How about Lo-Dash's _.isElement?

$ npm install lodash.iselement

And in the code:

var isElement = require("lodash.iselement");
isElement(document.body);

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Try enabling openssl extension in your php.ini if it is disabled. This way I could access the web service without need of any extra arguments, i.e.,

$client = new SoapClient(url);

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

Liquibase lock - reasons?

Sometimes if the update application is abruptly stopped, then the lock remains stuck.

Then running

UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

against the database helps.

You may also need to replace LOCKED=0 with LOCKED=FALSE.

Or you can simply drop the DATABASECHANGELOGLOCK table, it will be recreated.

"Could not find a version that satisfies the requirement opencv-python"

I had the same error. The first time I used the 32-bit version of python but my computer is 64-bit. I then reinstalled the 64-bit version and succeeded.

How to check whether java is installed on the computer

type java -version in command prompt, it will give you the installed version of java on your system.

What is the difference between atomic / volatile / synchronized?

I know that two threads can not enter in Synchronize block at the same time

Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.

private Integer i = 0;

synchronized(i) {
   i++;
}

This will not behave as expected as it could be locking on a different object each time.

if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??

yes. It doesn't use locking to achieve thread safety.

If you want to know how they work in more detail, you can read the code for them.

And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??

Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.

i read in some article that thread has local copy of variables what is that ??

I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.

This is only an issue when memory is shared at least one thread updates it.

How can I change the version of npm using nvm?

NVM Installation & usage on Windows

Below are the steps for NVM Installation on Windows:

NVM stands for node version manager, which will help to switch the your node versions for specific use. It also allows the user to work with multiple npm and node versions.

Install nvm setup. Use command "nvm list" to check list ofinstalled node version. Type "nvm use version number[6.9.3]" to switch versions. For more info

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Adding values to a C# array

You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.

C++ code file extension? .cc vs .cpp

Other file extensions used include .cxx and .C (capital C). I believe Bjarne Stroustrup used .C originally. .cpp is the name of the C preprocessor so it's unfortunate that it was used for C++ as well.

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

How can I extract all values from a dictionary in Python?

If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].

Installing and Running MongoDB on OSX

mongo => mongo-db console
mongodb => mongo-db server

If you're on Mac and looking for a easier way to start/stop your mongo-db server, then MongoDB Preference Pane is something that you should look into. With it, you start/stop your mongo-db instance via UI. Hope it helps!

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Retrieve WordPress root directory path?

echo ABSPATH; // This shows the absolute path of WordPress

ABSPATH is a constant defined in the wp-config.php file.

How to get the first element of an array?

The previous examples work well when the array index begins at zero. thomax's answer did not rely on the index starting at zero, but relied on Array.prototype.find to which I did not have access. The following solution using jQuery $.each worked well in my case.

let haystack = {100: 'first', 150: 'second'},
    found = null;

$.each(haystack, function( index, value ) {
    found = value;  // Save the first array element for later.
    return false;  // Immediately stop the $.each loop after the first array element.
});

console.log(found); // Prints 'first'.

How to run multiple SQL commands in a single SQL connection?

Multiple Non-query example if anyone is interested.

using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
  DbConnection.Open();
  using (OdbcCommand DbCommand = DbConnection.CreateCommand())
  {
    DbCommand.CommandText = "INSERT...";
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name";
    DbCommand.ExecuteNonQuery();

    DbCommand.Parameters.Clear();
    DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name2";
    DbCommand.ExecuteNonQuery();
  }
}

MySQL 'Order By' - sorting alphanumeric correctly

I hate this, but this will work

order by lpad(name, 10, 0)  <-- assuming maximum string length is 10
                            <-- you can adjust to a bigger length if you want to

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

g++ undefined reference to typeinfo

This occurs when declared (non-pure) virtual functions are missing bodies. In your class definition, something like:

virtual void foo();

Should be defined (inline or in a linked source file):

virtual void foo() {}

Or declared pure virtual:

virtual void foo() = 0;

jQuery find element by data attribute value

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

_x000D_
_x000D_
$(function() {_x000D_
  $('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
  background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
_x000D_
_x000D_

How to update a single library with Composer?

Just use

composer require {package/packagename}

like

composer require phpmailer/phpmailer

if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

When you're working with strings in PHP you'll need to pay special attention to the formation, using " or '

$string = 'Hello, world!';
$string = "Hello, world!";

Both of these are valid, the following is not:

$string = "Hello, world';

You must also note that ' inside of a literal started with " will not end the string, and vice versa. So when you have a string which contains ', it is generally best practice to use double quotation marks.

$string = "It's ok here";

Escaping the string is also an option

$string = 'It\'s ok here too';

More information on this can be found within the documentation

How to make HTML input tag only accept numerical values?

I updated some answers posted to add the following:

  • Add the method as extension method
  • Allow only one point to be entered
  • Specify how many numbers after the decimal point is allowed.

    String.prototype.isDecimal = function isDecimal(evt,decimalPts) {
        debugger;
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
            return false;
    
        //Prevent more than one point
        if (charCode == 46 && this.includes("."))
            return false;
    
        // Restrict the needed decimal digits
        if (this.includes("."))
        {
            var number = [];
            number = this.split(".");
            if (number[1].length == decimalPts)
                 return false;
         }
    
         return true;
    };
    

How do I use System.getProperty("line.separator").toString()?

Try

rows = tabDelimitedTable.split("[" + newLine + "]");

This should solve the regex problem.

Also not that important but return type of

System.getProperty("line.separator")

is String so no need to call toString().

MySQL: #126 - Incorrect key file for table

Following these instructions allowed me to recreate my tmp directory and fix the issue:

Display all file systems and their disk usage in human readable form:

df -h

Find the processes that have files open in /tmp

sudo lsof /tmp/**/*

Then umount /tmp and /var/tmp:

umount -l /tmp
umount -l /var/tmp

Then remove the corrupt partition file:

rm -fv /usr/tmpDSK

Then create a nice new one:

/scripts/securetmp

Note that by editing the securetmp Perl script you can manually set the size of the tmp directory yourself, however just running the script increased the size of the tmp directory on our server from roughly 450MB to 4.0GB.

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

How do I include a file over 2 directories back?

including over directories can be processed by proxy file

  • root
  • .....|__web
  • .....|.........|_requiredDbSettings.php
  • .....|
  • .....|___db
  • .....|.........|_dbsettings.php
  • .....|
  • .....|_proxy.php

    dbsettings.php:
    $host='localhost';
    $user='username':
    $pass='pass';
    
    proxy.php:
    include_once 'db/dbsettings.php
    
    requiredDbSettings.php:
    include_once './../proxy.php';
    

Two statements next to curly brace in an equation

To answer also to the comment by @MLT, there is an alternative to the standard cases environment, not too sophisticated really, with both lines numbered. This code:

\documentclass{article}
\usepackage{amsmath}
\usepackage{cases}

\begin{document}

\begin{numcases}{f(x)=}
  1, & if $x<0$\\
  0, & otherwise
\end{numcases}

\end{document}

produces

screenshot of output pdf

Notice that here, math must be delimited by \(...\) or $...$, at least on the right of & in each line (reference).

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

No Application Encryption Key Has Been Specified

I had to restart my queue worker using php artisan queue:restart after running php artisan key:generate to get jobs working.

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

How to see the values of a table variable at debug time in T-SQL?

I have come to the conclusion that this is not possible without any plugins.

Getting query parameters from react-router hash fragment

With stringquery Package:

import qs from "stringquery";

const obj = qs("?status=APPROVED&page=1limit=20");  
// > { limit: "10", page:"1", status:"APPROVED" }

With query-string Package:

import qs from "query-string";
const obj = qs.parse(this.props.location.search);
console.log(obj.param); // { limit: "10", page:"1", status:"APPROVED" } 

No Package:

const convertToObject = (url) => {
  const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
  let params = {};

  for(let i = 0; i < arr.length; i += 2){
    const key = arr[i], value = arr[i + 1];
    params[key] = value ; // build the object = { limit: "10", page:"1", status:"APPROVED" }
  }
  return params;
};


const uri = this.props.location.search; // "?status=APPROVED&page=1&limit=20"

const obj = convertToObject(uri);

console.log(obj); // { limit: "10", page:"1", status:"APPROVED" }


// obj.status
// obj.page
// obj.limit

Hope that helps :)

Happy coding!

What is the default access modifier in Java?

Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).

Extract images from PDF without resampling, in python?

I did this for my own program, and found that the best library to use was PyMuPDF. It lets you find out the "xref" numbers of each image on each page, and use them to extract the raw image data from the PDF.

import fitz
from PIL import Image
import io

filePath = "path/to/file.pdf"
#opens doc using PyMuPDF
doc = fitz.Document(filePath)

#loads the first page
page = doc.loadPage(0)

#[First image on page described thru a list][First attribute on image list: xref n], check PyMuPDF docs under getImageList()
xref = page.getImageList()[0][0]

#gets the image as a dict, check docs under extractImage 
baseImage = doc.extractImage(xref)

#gets the raw string image data from the dictionary and wraps it in a BytesIO object before using PIL to open it
image = Image.open(io.BytesIO(baseImage['image']))

#Displays image for good measure
image.show()

Definitely check out the docs, though.

Pandas DataFrame to List of Dictionaries

Use df.to_dict('records') -- gives the output without having to transpose externally.

In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

What's the proper way to compare a String to an enum value?

Define enum:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enum content:

private boolean enumContainsValue(String value)
{
    for (Gesture gesture : Gesture.values())
    {
        if (gesture.name().equals(value))
        {
            return true;
        }
    }

    return false;
}

And use it:

String gestureString = "PAPER";

if (enumContainsValue(gestureString))
{
    Gesture gestureId = Gesture.valueOf(gestureString);

    switch (gestureId)
    {
        case ROCK:
            Log.i("TAG", "ROCK");
            break;

        case PAPER:
            Log.i("TAG", "PAPER");
            break;

        case SCISSORS:
            Log.i("TAG", "SCISSORS");
            break;
    }
}

What are Keycloak's OAuth2 / OpenID Connect endpoints?

FQDN/auth/realms/{realm_name}/.well-known/openid-configuration

you will see everything here, plus if the identity provider is also Keycloak then feeding this URL will setup everything also true with other identity providers if they support and they already handled it

Python: Adding element to list while iterating

You can use an index and a while loop instead of a for loop if you want the loop to also loop over the elements that is added to the list during the loop:

i = 0
while i < len(myarr):
    a = myarr[i];
    i = i + 1;
    if somecond(a):
        myarr.append(newObj())

How to shrink temp tablespace in oracle?

I don't bother with dropping the alternate temp in case i need to reclaim storage again in the future...

  1. from temp group set default to stand-alone temp
  2. wait awhile, then resize members of temp group
  3. set default back to temp group
  4. wait awhile, resize stand alone temp. there's no rush to do the last step

Removing duplicate rows in Notepad++

In version 7.8, you can accomplish this without any plugins - Edit -> Line Operations -> Remove Consecutive Duplicate Lines. You will have to sort the file to place duplicate lines in consecutive order before this works, but it does work like a charm.

Sorting options are available under Edit -> Line Operations -> Sort By ...

What is Activity.finish() method doing exactly?

onDestroy() is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.

on the other hand, finish() just lets the system know that the programmer wants the current Activity to be finished. And hence, it calls up onDestroy() after that.

Something to note:

it isn't necessary that only a call to finish() triggers a call to onDestroy(). No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activity that are needed to be freed.

How can I right-align text in a DataGridView column?

I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

In this case e is from:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

How can I get a JavaScript stack trace when I throw an exception?

Edit 2 (2017):

In all modern browsers you can simply call: console.trace(); (MDN Reference)

Edit 1 (2013):

A better (and simpler) solution as pointed out in the comments on the original question is to use the stack property of an Error object like so:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

This will generate output like this:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

Giving the name of the calling function along with the URL, its calling function, and so on.

Original (2009):

A modified version of this snippet may somewhat help:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}

Is JavaScript object-oriented?

Objects in JavaScript inherit directly from objects. What can be more object oriented?

Count the number of all words in a string

You can remove double spaces and count the number of " " in the string to get the count of words. Use stringr and rm_white {qdapRegex}

str_count(rm_white(s), " ") +1

How can I view the source code for a function?

View(function_name) - eg. View(mean) Make sure to use uppercase [V]. The read-only code will open in the editor.

Django template how to look up a dictionary value with a variable

For me creating a python file named template_filters.py in my App with below content did the job

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

usage is like what culebrón said :

{{ mydict|get_item:item.NAME }}

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

Font Awesome icon inside text input element

My Solution to add a font-awesome icon inside the input element. Here is a simple code to add icon inside the input element. Just copy the code below and put where you want to add. or if you want to change the icon then just put your icon code in <i> tag.

_x000D_
_x000D_
<style>_x000D_
body {font-family: Arial, Helvetica, sans-serif;}_x000D_
* {box-sizing: border-box;}_x000D_
.soft-codeon {_x000D_
  display: -ms-flexbox; /* IE10 */_x000D_
  display: flex;_x000D_
  width: 50%;_x000D_
  margin-bottom: 15px;_x000D_
}_x000D_
_x000D_
.icon {_x000D_
  padding: 10px;_x000D_
  background: linear-gradient(to right, #ec008c, #fc6767); _x000D_
  color: white;_x000D_
  min-width: 20px;_x000D_
  text-align: center;_x000D_
}_x000D_
.soft-field {_x000D_
  width: 100%;_x000D_
  padding: 10px;_x000D_
  outline: none;_x000D_
  border:2px solid #fc6767;_x000D_
}_x000D_
.soft-field:focus {_x000D_
  border: 2px solid #ec008c;_x000D_
}_x000D_
</style>
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
  <div class="soft-codeon">_x000D_
    <i class="fa fa-user icon"></i>_x000D_
    <input class="soft-field" type="text" placeholder="Username" name="usrnm">_x000D_
  </div>_x000D_
  <div class="soft-codeon">_x000D_
    <i class="fa fa-envelope icon"></i>_x000D_
    <input class="soft-field" type="text" placeholder="Email" name="email">_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to set Linux environment variables with Ansible

There are multiple ways to do this and from your question it's nor clear what you need.

1. If you need environment variable to be defined PER TASK ONLY, you do this:

- hosts: dev
  tasks:
    - name: Echo my_env_var
      shell: "echo $MY_ENV_VARIABLE"
      environment:
        MY_ENV_VARIABLE: whatever_value

    - name: Echo my_env_var again
      shell: "echo $MY_ENV_VARIABLE"

Note that MY_ENV_VARIABLE is available ONLY for the first task, environment does not set it permanently on your system.

TASK: [Echo my_env_var] ******************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}

TASK: [Echo my_env_var again] ************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}

Hopefully soon using environment will also be possible on play level, not only task level as above. There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651

UPDATE: It's now merged as of Jan 2, 2015.

2. If you want permanent environment variable + system wide / only for certain user

You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:

  • ~/.profile
  • /etc/environment
  • /etc/profile.d directory
  • ...

You will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables

After all for setting environment variable in ex. Ubuntu you can just use lineinfile module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.

FloatingActionButton example with Support Library

FloatingActionButton extends ImageView. So, it's simple as like introducing an ImageView in your layout. Here is an XML sample.

<android.support.design.widget.FloatingActionButton   xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/somedrawable"
    android:layout_gravity="right|bottom"
    app:borderWidth="0dp"
    app:rippleColor="#ffffff"/>

app:borderWidth="0dp" is added as a workaround for elevation issues.

Any implementation of Ordered Set in Java?

Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.

You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.

Also, you can't insert at a certain position.

Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.

How to do join on multiple criteria, returning all combinations of both criteria

create table a1
(weddingTable INT(3),
 tableSeat INT(3),
 tableSeatID INT(6),
 Name varchar(10));

insert into a1
 (weddingTable, tableSeat, tableSeatID, Name)
 values (001,001,001001,'Bob'),
 (001,002,001002,'Joe'),
 (001,003,001003,'Dan'),
 (002,001,002001,'Mark');

create table a2
 (weddingTable int(3),
 tableSeat int(3),
 Meal varchar(10));

insert into a2
(weddingTable, tableSeat, Meal)
values 
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');

select x.*, y.Meal

from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);

Using braces with dynamic variable names in PHP

Try using {} instead of ():

${"file".$i} = file($filelist[$i]);

Change background color of selected item on a ListView

It's very simple. In the constructor of the "OnItemClick" use the parameter "view" which is the second one that represents the listView or GridView's items's view and it becomes the new item's view made by the adapterView it self. So to set new color ONLY to the SELECTED ITEM itself do as the following:

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){ //view is instead of the view like textView , ImageView, or whatever view.setBackgroundColor(Color.green); }

If you do any different codes to set new color, you will face awkward behaviours like the green color will be applied to the unclicked item.

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

The system cannot find the file specified. in Visual Studio

The code should be :

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World";
    return 0;
}

Or maybe :

#include <iostream>

int main() {
    std::cout << "Hello World";
    return 0;
}

Just a quick note: I have deleted the system command, because I heard it's not a good practice to use it. (but of course, you can add it for this kind of program)

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

How to determine if binary tree is balanced?

    static boolean isBalanced(Node root) {
    //check in the depth of left and right subtree
    int diff = depth(root.getLeft()) - depth(root.getRight());
    if (diff < 0) {
        diff = diff * -1;
    }
    if (diff > 1) {
        return false;
    }
    //go to child nodes
    else {
        if (root.getLeft() == null && root.getRight() == null) {
            return true;
        } else if (root.getLeft() == null) {
            if (depth(root.getRight()) > 1) {
                return false;
            } else {
                return true;
            }
        } else if (root.getRight() == null) {
            if (depth(root.getLeft()) > 1) {
                return false;
            } else {
                return true;
            }
        } else if (root.getLeft() != null && root.getRight() != null && isBalanced(root.getLeft()) && isBalanced(root.getRight())) {
            return true;
        } else {
            return false;
        }
    }
}

Match linebreaks - \n or \r\n?

In Python:

# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M) 

or more rigorous:

# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

If you've just killed a big query, it will take time to rollback. If you issue another query before the killed query is done rolling back, you might get a lock timeout error. That's what happened to me. The solution was just to wait a bit.

Details:

I had issued a DELETE query to remove about 900,000 out of about 1 million rows.

I ran this by mistake (removes only 10% of the rows): DELETE FROM table WHERE MOD(id,10) = 0

Instead of this (removes 90% of the rows): DELETE FROM table WHERE MOD(id,10) != 0

I wanted to remove 90% of the rows, not 10%. So I killed the process in the MySQL command line, knowing that it would roll back all the rows it had deleted so far.

Then I ran the correct command immediately, and got a lock timeout exceeded error soon after. I realized that the lock might actually be the rollback of the killed query still happening in the background. So I waited a few seconds and re-ran the query.

How can I center <ul> <li> into div

Try

div#divID ul {margin:0 auto;}

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

I believe this has been answered in some sections already, just test with gmail for your "MAIL_HOST" instead and don't forget to clear cache. Setup like below: Firstly, you need to setup 2 step verification here google security. An App Password link will appear and you can get your App Password to insert into below "MAIL_PASSWORD". More info on getting App Password here

MAIL_DRIVER=smtp
[email protected]
MAIL_FROM_NAME=DomainName
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=YOUR_GMAIL_CREATED_APP_PASSWORD
MAIL_ENCRYPTION=tls

Clear cache with:

php artisan config:cache

What is git tag, How to create tags & How to checkout git remote tag(s)

(This answer took a while to write, and codeWizard's answer is correct in aim and essence, but not entirely complete, so I'll post this anyway.)


There is no such thing as a "remote Git tag". There are only "tags". I point all this out not to be pedantic,1 but because there is a great deal of confusion about this with casual Git users, and the Git documentation is not very helpful2 to beginners. (It's not clear if the confusion comes because of poor documentation, or the poor documentation comes because this is inherently somewhat confusing, or what.)

There are "remote branches", more properly called "remote-tracking branches", but it's worth noting that these are actually local entities. There are no remote tags, though (unless you (re)invent them). There are only local tags, so you need to get the tag locally in order to use it.

The general form for names for specific commits—which Git calls references—is any string starting with refs/. A string that starts with refs/heads/ names a branch; a string starting with refs/remotes/ names a remote-tracking branch; and a string starting with refs/tags/ names a tag. The name refs/stash is the stash reference (as used by git stash; note the lack of a trailing slash).

There are some unusual special-case names that do not begin with refs/: HEAD, ORIG_HEAD, MERGE_HEAD, and CHERRY_PICK_HEAD in particular are all also names that may refer to specific commits (though HEAD normally contains the name of a branch, i.e., contains ref: refs/heads/branch). But in general, references start with refs/.

One thing Git does to make this confusing is that it allows you to omit the refs/, and often the word after refs/. For instance, you can omit refs/heads/ or refs/tags/ when referring to a local branch or tag—and in fact you must omit refs/heads/ when checking out a local branch! You can do this whenever the result is unambiguous, or—as we just noted—when you must do it (for git checkout branch).

It's true that references exist not only in your own repository, but also in remote repositories. However, Git gives you access to a remote repository's references only at very specific times: namely, during fetch and push operations. You can also use git ls-remote or git remote show to see them, but fetch and push are the more interesting points of contact.

Refspecs

During fetch and push, Git uses strings it calls refspecs to transfer references between the local and remote repository. Thus, it is at these times, and via refspecs, that two Git repositories can get into sync with each other. Once your names are in sync, you can use the same name that someone with the remote uses. There is some special magic here on fetch, though, and it affects both branch names and tag names.

You should think of git fetch as directing your Git to call up (or perhaps text-message) another Git—the "remote"—and have a conversation with it. Early in this conversation, the remote lists all of its references: everything in refs/heads/ and everything in refs/tags/, along with any other references it has. Your Git scans through these and (based on the usual fetch refspec) renames their branches.

Let's take a look at the normal refspec for the remote named origin:

$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
$ 

This refspec instructs your Git to take every name matching refs/heads/*—i.e., every branch on the remote—and change its name to refs/remotes/origin/*, i.e., keep the matched part the same, changing the branch name (refs/heads/) to a remote-tracking branch name (refs/remotes/, specifically, refs/remotes/origin/).

It is through this refspec that origin's branches become your remote-tracking branches for remote origin. Branch name becomes remote-tracking branch name, with the name of the remote, in this case origin, included. The plus sign + at the front of the refspec sets the "force" flag, i.e., your remote-tracking branch will be updated to match the remote's branch name, regardless of what it takes to make it match. (Without the +, branch updates are limited to "fast forward" changes, and tag updates are simply ignored since Git version 1.8.2 or so—before then the same fast-forward rules applied.)

Tags

But what about tags? There's no refspec for them—at least, not by default. You can set one, in which case the form of the refspec is up to you; or you can run git fetch --tags. Using --tags has the effect of adding refs/tags/*:refs/tags/* to the refspec, i.e., it brings over all tags (but does not update your tag if you already have a tag with that name, regardless of what the remote's tag says Edit, Jan 2017: as of Git 2.10, testing shows that --tags forcibly updates your tags from the remote's tags, as if the refspec read +refs/tags/*:refs/tags/*; this may be a difference in behavior from an earlier version of Git).

Note that there is no renaming here: if remote origin has tag xyzzy, and you don't, and you git fetch origin "refs/tags/*:refs/tags/*", you get refs/tags/xyzzy added to your repository (pointing to the same commit as on the remote). If you use +refs/tags/*:refs/tags/* then your tag xyzzy, if you have one, is replaced by the one from origin. That is, the + force flag on a refspec means "replace my reference's value with the one my Git gets from their Git".

Automagic tags during fetch

For historical reasons,3 if you use neither the --tags option nor the --no-tags option, git fetch takes special action. Remember that we said above that the remote starts by displaying to your local Git all of its references, whether your local Git wants to see them or not.4 Your Git takes note of all the tags it sees at this point. Then, as it begins downloading any commit objects it needs to handle whatever it's fetching, if one of those commits has the same ID as any of those tags, git will add that tag—or those tags, if multiple tags have that ID—to your repository.

Edit, Jan 2017: testing shows that the behavior in Git 2.10 is now: If their Git provides a tag named T, and you do not have a tag named T, and the commit ID associated with T is an ancestor of one of their branches that your git fetch is examining, your Git adds T to your tags with or without --tags. Adding --tags causes your Git to obtain all their tags, and also force update.

Bottom line

You may have to use git fetch --tags to get their tags. If their tag names conflict with your existing tag names, you may (depending on Git version) even have to delete (or rename) some of your tags, and then run git fetch --tags, to get their tags. Since tags—unlike remote branches—do not have automatic renaming, your tag names must match their tag names, which is why you can have issues with conflicts.

In most normal cases, though, a simple git fetch will do the job, bringing over their commits and their matching tags, and since they—whoever they are—will tag commits at the time they publish those commits, you will keep up with their tags. If you don't make your own tags, nor mix their repository and other repositories (via multiple remotes), you won't have any tag name collisions either, so you won't have to fuss with deleting or renaming tags in order to obtain their tags.

When you need qualified names

I mentioned above that you can omit refs/ almost always, and refs/heads/ and refs/tags/ and so on most of the time. But when can't you?

The complete (or near-complete anyway) answer is in the gitrevisions documentation. Git will resolve a name to a commit ID using the six-step sequence given in the link. Curiously, tags override branches: if there is a tag xyzzy and a branch xyzzy, and they point to different commits, then:

git rev-parse xyzzy

will give you the ID to which the tag points. However—and this is what's missing from gitrevisionsgit checkout prefers branch names, so git checkout xyzzy will put you on the branch, disregarding the tag.

In case of ambiguity, you can almost always spell out the ref name using its full name, refs/heads/xyzzy or refs/tags/xyzzy. (Note that this does work with git checkout, but in a perhaps unexpected manner: git checkout refs/heads/xyzzy causes a detached-HEAD checkout rather than a branch checkout. This is why you just have to note that git checkout will use the short name as a branch name first: that's how you check out the branch xyzzy even if the tag xyzzy exists. If you want to check out the tag, you can use refs/tags/xyzzy.)

Because (as gitrevisions notes) Git will try refs/name, you can also simply write tags/xyzzy to identify the commit tagged xyzzy. (If someone has managed to write a valid reference named xyzzy into $GIT_DIR, however, this will resolve as $GIT_DIR/xyzzy. But normally only the various *HEAD names should be in $GIT_DIR.)


1Okay, okay, "not just to be pedantic". :-)

2Some would say "very not-helpful", and I would tend to agree, actually.

3Basically, git fetch, and the whole concept of remotes and refspecs, was a bit of a late addition to Git, happening around the time of Git 1.5. Before then there were just some ad-hoc special cases, and tag-fetching was one of them, so it got grandfathered in via special code.

4If it helps, think of the remote Git as a flasher, in the slang meaning.

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Linux supports capabilities to support more fine-grained permissions than just "this application is run as root". One of those capabilities is CAP_NET_BIND_SERVICE which is about binding to a privileged port (<1024).

Unfortunately I don't know how to exploit that to run an application as non-root while still giving it CAP_NET_BIND_SERVICE (probably using setcap, but there's bound to be an existing solution for this).

How do I call a dynamically-named method in Javascript?

Within a ServiceWorker or Worker, replace window with self:

self[method_prefix + method_name](arg1, arg2);

Workers have no access to the DOM, therefore window is an invalid reference. The equivalent global scope identifier for this purpose is self.

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

jQuery: Get height of hidden element in jQuery

One workaround is to create a parent div outside the element you want to get the height of, apply a height of '0' and hide any overflow. Next, take the height of the child element and remove the overflow property of the parent.

_x000D_
_x000D_
var height = $("#child").height();_x000D_
// Do something here_x000D_
$("#parent").append(height).removeClass("overflow-y-hidden");
_x000D_
.overflow-y-hidden {_x000D_
  height: 0px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="parent" class="overflow-y-hidden">_x000D_
  <div id="child">_x000D_
    This is some content I would like to get the height of!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

Unable to auto-detect email address

Ran the sample of these commands:

git config --global user.email "[email protected]"

git config --global user.name "focus1"

Footnote:

[email protected] === email address used to login to your github account.

focus === your github username

Making a Windows shortcut start relative to where the folder is?

  1. Right click on your /bat/ folder and click Create Shortcut.

    • On Windows 7 you will get bat - Shortcut in the current directory.
    • On Windows XP you will get Shortcut to bat.
  2. Right click on the shortcut you just created and click Properties.

  3. Change Target (under the Shortcut tab on Windows 7) to the following:

    %windir%\system32\cmd.exe /c start "" "%CD%\bat\bat\run.bat"
    
  4. Make sure Start in is blank. That causes it to start in the current directory.

  5. Click OK. On Windows 7, the shortcut icon will change to the cmd.exe icon.
  6. That's probably acceptable in the case of shortcutting to a .bat but if you want to change the icon, open the shortcut's properties again and click Change Icon... (again, under the Shortcut tab on Windows 7). At this point you can Browse... for an icon or bring up a list of default system icons by entering

    %SystemRoot%\system32\SHELL32.dll
    

    to the left of the Browse... button and hitting Enter. This works on Windows 7 and Windows XP but the icons are different due to style updates (but are recognizably similar). Depending on the version of Windows the shortcut resides, the icon will will sometimes change accordingly.

More Info:

See Using the "start" command with parameters passed to the started program to better understand the empty double-quotes at the beginning of the first Target command.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

You can use git log with the pathnames of the respective folders:

git log A B

The log will only show commits made in A and B. I usually throw in --stat to make things a little prettier, which helps for quick commit reviews.

One time page refresh after first page load

Try with this

var element = document.getElementById('position');        
element.scrollIntoView(true);`

Test whether string is a valid integer

For laughs I roughly just quickly worked out a set of functions to do this (is_string, is_int, is_float, is alpha string, or other) but there are more efficient (less code) ways to do this:

#!/bin/bash

function strindex() {
    x="${1%%$2*}"
    if [[ "$x" = "$1" ]] ;then
        true
    else
        if [ "${#x}" -gt 0 ] ;then
            false
        else
            true
        fi
    fi
}

function is_int() {
    if is_empty "${1}" ;then
        false
        return
    fi
    tmp=$(echo "${1}" | sed 's/[^0-9]*//g')
    if [[ $tmp == "${1}" ]] || [[ "-${tmp}" == "${1}" ]] ; then
        #echo "INT (${1}) tmp=$tmp"
        true
    else
        #echo "NOT INT (${1}) tmp=$tmp"
        false
    fi
}

function is_float() {
    if is_empty "${1}" ;then
        false
        return
    fi
    if ! strindex "${1}" "-" ; then
        false
        return
    fi
    tmp=$(echo "${1}" | sed 's/[^a-z. ]*//g')
    if [[ $tmp =~ "." ]] ; then
        #echo "FLOAT  (${1}) tmp=$tmp"
        true
    else
        #echo "NOT FLOAT  (${1}) tmp=$tmp"
        false
    fi
}

function is_strict_string() {
    if is_empty "${1}" ;then
        false
        return
    fi
    if [[ "${1}" =~ ^[A-Za-z]+$ ]]; then
        #echo "STRICT STRING (${1})"
        true
    else
        #echo "NOT STRICT STRING (${1})"
        false
    fi
}

function is_string() {
    if is_empty "${1}" || is_int "${1}" || is_float "${1}" || is_strict_string "${1}" ;then
        false
        return
    fi
    if [ ! -z "${1}" ] ;then
        true
        return
    fi
    false
}
function is_empty() {
    if [ -z "${1// }" ] ;then
        true
    else
        false
    fi
}

Run through some tests here, I defined that -44 is an int but 44- isn't etc.. :

for num in "44" "-44" "44-" "4-4" "a4" "4a" ".4" "4.4" "-4.4" "09" "hello" "h3llo!" "!!" " " "" ; do
    if is_int "$num" ;then
        echo "INT = $num"

    elif is_float "$num" ;then
        echo "FLOAT = $num"

    elif is_string "$num" ; then
        echo "STRING = $num"

    elif is_strict_string "$num" ; then
        echo "STRICT STRING = $num"
    else
        echo "OTHER = $num"
    fi
done

Output:

INT = 44
INT = -44
STRING = 44-
STRING = 4-4
STRING = a4
STRING = 4a
FLOAT = .4
FLOAT = 4.4
FLOAT = -4.4
INT = 09
STRICT STRING = hello
STRING = h3llo!
STRING = !!
OTHER =  
OTHER = 

NOTE: Leading 0's could infer something else when adding numbers such as octal so it would be better to strip them if you intend on treating '09' as an int (which I'm doing) (eg expr 09 + 0 or strip with sed)

Close Bootstrap Modal

My five cents on this one is that I don't want to have to target the bootstrap modal with an id and seeing as there should be only one modal at a time the following should be quite sufficient to remove the modal as toggle could be dangerous:

$('.modal').removeClass('show');

How can I remove specific rules from iptables?

Assume that, if you want to remove NAT rules,

List the appended IPtables using the command below,

# sudo iptables -L -t nat -v

Chain PREROUTING (policy ACCEPT 18 packets, 1382 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    7   420 DNAT       tcp  --  any    any     anywhere             saltmaster           tcp dpt:http to:172.31.5.207:80
    0     0 DNAT       tcp  --  eth0   any     anywhere             anywhere             tcp dpt:http to:172.31.5.207:8080

If you would like to remove the nat rule from the IPtables, just execute the command,

# sudo iptables -F -t nat -v

Flushing chain `PREROUTING'
Flushing chain `INPUT'
Flushing chain `OUTPUT'
Flushing chain `POSTROUTING'

Then, you can verify that,

# sudo iptables -L -t nat -v

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

What is the best way to test for an empty string with jquery-out-of-the-box?

if((a.trim()=="")||(a=="")||(a==null))
{
    //empty condition
}
else
{
    //working condition
}

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

How to assign execute permission to a .sh file in windows to be executed in linux

This is possible using the Info-Zip open-source Zip utilities. If unzip is run with the -X parameter, it will attempt to preserve the original permissions. If the source filesystem was NTFS and the destination is a Unix one, it will attempt to translate from one to the other. I do not have a Windows system available right now to test the translation, so you will have to experiment with which group needs to be awarded execute permissions. It'll be something like "Users" or "Any user"

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

Math functions in AngularJS bindings

Either bind the global Math object onto the scope (remember to use $window not window)

$scope.abs = $window.Math.abs;

Use the binding in your HTML:

<p>Distance from zero: {{abs(distance)}}</p>

Or create a filter for the specific Math function you're after:

module.filter('abs', ['$window', function($window) {
  return function(n) {
    return $window.Math.abs($window.parseInt(n));
  };
});

Use the filter in your HTML:

<p>Distance from zero: {{distance | abs}}</p>

How to use pip with python 3.4 on windows?

"py -m pip install requests" works fine with Windows and its up gradation. Just change the path after installing Python 3.4 in the command prompt and type in "py -m pip install requests"command prompt. pip install

How can I find the number of years between two dates?

Try this:

int getYear(Date date1,Date date2){ 
      SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
      Integer.parseInt(simpleDateformat.format(date1));

      return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));

    }

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

This process is quite simple in correcting the the error. What is happening is a failure to connect to phpMyAdmin. In order to fix the problem you simply need to provide the correct password to the system phpMyAdmin configuration file located in apps\phpMyadmin\config.ini.php 1. the root should already be set as user 2. Insert the password between ' ' and that it.

If you still have problems then this means that the user name and /or the password need to be updated or inserted into the DB. to do this use the command line tool and do an update.

UPDATE mysql.user SET Password=PASSWORD('Johnny59 or whatever you want to use') WHERE User='root';

How to set the text color of TextView in code?

In Adapter you can set the text color by using this code:

holder.my_text_view = (TextView) convertView.findViewById(R.id.my_text_view);
holder.my_text_view.setTextColor(Color.parseColor("#FFFFFF"));

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

Auto select file in Solution Explorer from its open tab

This isn't exactly what you're looking for, but it would automatically select the "active" file in the Solution Explorer:

Tools-->Options-->Projects and Solutions-->Track Active Item in Solution Explorer.

jQuery map vs. each

i understood it by this:

function fun1() {
    return this + 1;
}
function fun2(el) {
    return el + 1;
}

var item = [5,4,3,2,1];

var newitem1 = $.each(item, fun1);
var newitem2 = $.map(item, fun2);

console.log(newitem1); // [5, 4, 3, 2, 1] 
console.log(newitem2); // [6, 5, 4, 3, 2] 

so, "each" function returns the original array while "map" function returns a new array

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Go to project properties-> configuration properties -> Librarian Set Target Machine to MachineX64 (/MACHINE:X64)

Google Maps API v2: How to make markers clickable?

Step 1
public class TopAttractions extends Fragment implements OnMapReadyCallback, 
GoogleMap.OnMarkerClickListener

Step 2
gMap.setOnMarkerClickListener(this);

Step 3
@Override
public boolean onMarkerClick(Marker marker) {
    if(marker.getTitle().equals("sharm el-shek"))
        Toast.makeText(getActivity().getApplicationContext(), "Hamdy", Toast.LENGTH_SHORT).show();
    return false;
}

C# Checking if button was clicked

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

Using jquery to delete all elements with a given id

You should be using a class for multiple elements as an id is meant to be only a single element. To answer your question on the .each() syntax though, this is what it would look like:

$('#myID').each(function() {
    $(this).remove();
});

Official JQuery documentation here.

POST Content-Length exceeds the limit

I disagree, but the solution to increase the file size in php.ini or .htaccess won't work if the user sends a file larger than allowed by the server application.

I suggest validating this on the front end. For example:

_x000D_
_x000D_
$(document).ready(function() {
    $ ('#your_input_file_id').bind('change', function() {
        var fileSize = this.files[0].size/1024/1024;
        if (fileSize > 2) { // 2M
            alert('Your custom message for max file size exceeded');
            $('#your_input_file_id').val('');
        }
    });
});
_x000D_
_x000D_
_x000D_

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

Android: how to refresh ListView contents?

I think refilling the same adapter with different data would be more or most better technique. Put this method in your Adapter class with right argument (the data list you want to display as names in my case) Call this where u update the data of list with updated list (names in my case)

public void refill(ArrayList<BeanDatabase> names) {
    list.clear();
    list.addAll(names);
    list.notifyDataSetChanged();
}

If you change the adapter or set the adapter again and again on when the list updates, then force close error would surely cause problems at some point. (Error:List data been updated but adapter doesn't notify the List View)

System has not been booted with systemd as init system (PID 1). Can't operate

I encountered the same problem! ps --no-headers -o comm 1 After running this in the terminal, the system will return either systemd or init

if it returns 'init', then the 'systemctl' command won't work for your system

What's in an Eclipse .classpath/.project file?

Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.

The .project file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)

The .classpath file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings directory inside the project); the .classpath file is just one of them. Specifically, the .classpath file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).

Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath file portability.

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

How can I disable the default console handler, while using the java logging API?

Do a reset of the configuration and set the root level to OFF

LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);

Change bundle identifier in Xcode when submitting my first app in IOS

A very simple solution to that is to open the file:

YOURPROJECT.xcodeproj/project.pbxproj

And find for this variable:

PRODUCT_BUNDLE_IDENTIFIER

You'll see something like that:

PRODUCT_BUNDLE_IDENTIFIER = com.YOUR_APP_NAME.SOMETHING;

So, the name on the right is your Bundle Identifier. In my case it works perfectly.

What's the C# equivalent to the With statement in VB?

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0:

    var bar = Stuff.Elements.Foo
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

How to check date of last change in stored procedure or function in SQL server

This is the correct solution for finding a function:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'fn'
AND name = 'fn_NAME'

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Database rebuild fixed it for me as well. Also had to restore the old database from backup as it got corrupted during power outage... The copy master.mdf procedure did not work for me.

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);