Programs & Examples On #Joptionpane

JOptionPane is a Java class that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.

How to present a simple alert message in java?

Even without importing swing, you can get the call in one, all be it long, string. Otherwise just use the swing import and simple call:

JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE);

Easy enough.

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

Java - How to create a custom dialog box?

Try this simple class for customizing a dialog to your liking:

import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;

public class CustomDialog
{
    private List<JComponent> components;

    private String title;
    private int messageType;
    private JRootPane rootPane;
    private String[] options;
    private int optionIndex;

    public CustomDialog()
    {
        components = new ArrayList<>();

        setTitle("Custom dialog");
        setMessageType(JOptionPane.PLAIN_MESSAGE);
        setRootPane(null);
        setOptions(new String[] { "OK", "Cancel" });
        setOptionSelection(0);
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public void setMessageType(int messageType)
    {
        this.messageType = messageType;
    }

    public void addComponent(JComponent component)
    {
        components.add(component);
    }

    public void addMessageText(String messageText)
    {
        JLabel label = new JLabel("<html>" + messageText + "</html>");

        components.add(label);
    }

    public void setRootPane(JRootPane rootPane)
    {
        this.rootPane = rootPane;
    }

    public void setOptions(String[] options)
    {
        this.options = options;
    }

    public void setOptionSelection(int optionIndex)
    {
        this.optionIndex = optionIndex;
    }

    public int show()
    {
        int optionType = JOptionPane.OK_CANCEL_OPTION;
        Object optionSelection = null;

        if(options.length != 0)
        {
            optionSelection = options[optionIndex];
        }

        int selection = JOptionPane.showOptionDialog(rootPane,
                components.toArray(), title, optionType, messageType, null,
                options, optionSelection);

        return selection;
    }

    public static String getLineBreak()
    {
        return "<br>";
    }
}

JOptionPane Yes or No window

You can do this a whole simpler:

int test = JOptionPane.showConfirmDialog(null, "Would you like green eggs and ham?", "An insane question!");
switch(test) {
    case 0: JOptionPane.showMessageDialog(null, "HELLO!"); //Yes option
    case 1: JOptionPane.showMessageDialog(null, "GOODBYE!"); //No option
    case 2: JOptionPane.showMessageDialog(null, "GOODBYE!"); //Cancel option
}

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Filtering collections in C#

To do it in place, you can use the RemoveAll method of the "List<>" class along with a custom "Predicate" class...but all that does is clean up the code... under the hood it's doing the same thing you are...but yes, it does it in place, so you do same the temp list.

Difference between setUp() and setUpBeforeClass()

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

Splitting a string into chunks of a certain size

How's this for a one-liner?

List<string> result = new List<string>(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));

With this regex it doesn't matter if the last chunk is less than four characters, because it only ever looks at the characters behind it.

I'm sure this isn't the most efficient solution, but I just had to toss it out there.

Dynamically converting java object of Object class to a given class when class name is known

you don't, declare an interface that declares the methods you would like to call:

public interface MyInterface
{
  void doStuff();
}

public class MyClass implements MyInterface
{
  public void doStuff()
  {
    System.Console.Writeln("done!");
  }
}

then you use

MyInterface mobj = (myInterface)obj;
mobj.doStuff();

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

Save plot to image file instead of displaying it using Matplotlib

If you don't like the concept of the "current" figure, do:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

Mongoose's find method with $or condition does not work properly

I implore everyone to use Mongoose's query builder language and promises instead of callbacks:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

Read more about Mongoose Queries.

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

<div> cannot appear as a descendant of <p>

I got this warning by using Material UI components, then I test the component="div" as prop to the below code and everything became correct:

import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';

<Typography component="span">
  <Grid component="span">
    Lorem Ipsum
  </Grid>
</Typography>

Actually, this warning happens because in the Material UI the default HTML tag of Grid component is div tag and the default Typography HTML tag is p tag, So now the warning happens,

Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>

Git's famous "ERROR: Permission to .git denied to user"

If problem is coming on windows then remove the Credentials from the Windows history.

  • Go to Credential Manager
  • Go to Windows Credentials
  • Delete the entries under Generic Credentials
  • Try connecting again.This time , it should prompt you for the correct username and password.

enter image description here enter image description here

remove credentials from git

SelectedValue vs SelectedItem.Value of DropDownList

Be careful using SelectedItem.Text... If there is no item selected, then SelectedItem will be null and SelectedItem.Text will generate a null-value exception.

.NET should have provided a SelectedText property like the SelectedValue property that returns String.Empty when there is no selected item.

Is there an easy way to strike through text in an app widget?

Another way to do it programmatically which looks a bit less like a hack than the Paint way:

Instead of doing:

tv.setText(s);

do:

private static final StrikethroughSpan STRIKE_THROUGH_SPAN = new StrikethroughSpan();
...
tv.setText(s, TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) tv.getText();
spannable.setSpan(STRIKE_THROUGH_SPAN, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

SCRIPT438: Object doesn't support property or method IE

Implement "use strict" in all script tags to find inconsistencies and fix potential unscoped variables!

Ideal way to cancel an executing AsyncTask

Our global AsyncTask class variable

LongOperation LongOperationOdeme = new LongOperation();

And KEYCODE_BACK action which interrupt AsyncTask

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LongOperationOdeme.cancel(true);
        }
        return super.onKeyDown(keyCode, event);
    }

It works for me.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

Is it possible to preview stash contents in git?

When this question was first asked, this may not have been an option, but, if you use PyCharm, you can use the UnStash Changes tool (VCS->Git->UnStash Changes...). This allows you to view the list of stashed changes, as well as pop, drop, clear, or apply (into a new branch if desired):

Unstash Changes Window

and view the changed files per stash:

Paths Affected Window

as well as diffs per file. In the diffs you can cherry-pick individual changes to apply from the stashed changes to the working branch (using the left-pointing chevron):

enter image description here

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

What is the default initialization of an array in Java?

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

So Java is initializing the array by running its constructor method while creating the object

How to remove gaps between subplots in matplotlib?

The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:

However, with aspect='equal', as in the following code:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:

Using LIKE in an Oracle IN clause

What would be useful here would be a LIKE ANY predicate as is available in PostgreSQL

SELECT * 
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])

Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR, however:

SELECT * 
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...

Or alternatively, create a semi join using an EXISTS predicate and an auxiliary array data structure (see this question for details):

SELECT *
FROM tbl t
WHERE EXISTS (
  SELECT 1
  -- Alternatively, store those values in a temp table:
  FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
  WHERE t.my_col LIKE column_value
)

For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:

  1. Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file.
  2. Removed the code which inserted the www-widgetapi.js script.
  3. Downloaded the www-widgetapi.js script (from https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl7VfO1r/www-widgetapi.js) to a local www-widgetapi.js file.
  4. Replaced the targetOrigin argument in the postMessage call which was causing the error in the console, with a "*" (indicating no preference - see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).
  5. Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.

Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Patched yt-api.js example

How can I use Helvetica Neue Condensed Bold in CSS?

In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.

  1. fonts.com: License the real font as a webfont from fonts.com. Free (with a badge), $10/month for 250k pageviews and $100/month for 2.5M pageviews. You can download the font to your desktop with the most expensive plan (but if you're on a Mac you already have it).
  2. myfonts.com / fontspring.com: Buy a pretty close alternative like Nimbus Sans Novus D from MyFont ($160 for unlimited pageviews), or Franklin Gothic FS Demi Condensed, from fontspring.com (about $21.95, flat one time fee with unlimited pageviews). In both cases you also get to download the font for your desktop so you can use it in Photoshop for comps.

A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.

h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}

Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.

UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.

What's the best way to add a drop shadow to my UIView

Try this:

UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;

First of all: The UIBezierPath used as shadowPath is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.

Regarding your issue specifically: The important line is view.layer.masksToBounds = NO. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.

For those wondering what the difference between masksToBounds (on the layer) and the view's own clipToBounds property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.


Swift 2.2:

override func layoutSubviews()
{
    super.layoutSubviews()

    let shadowPath = UIBezierPath(rect: bounds)
    layer.masksToBounds = false
    layer.shadowColor = UIColor.blackColor().CGColor
    layer.shadowOffset = CGSizeMake(0.0, 5.0)
    layer.shadowOpacity = 0.5
    layer.shadowPath = shadowPath.CGPath
}

Swift 3:

override func layoutSubviews()
{
    super.layoutSubviews()

    let shadowPath = UIBezierPath(rect: bounds)
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
    layer.shadowOpacity = 0.5
    layer.shadowPath = shadowPath.cgPath
}

When to use static classes in C#

For C# 3.0, extension methods may only exist in top-level static classes.

Why does the JFrame setSize() method not set the size correctly?

JFrame SetSize() contains the the Area + Border.

I think you have to set the size of ContentPane of that

jFrame.getContentPane().setSize(800,400);

So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

JFrame jf = new JFrame();
JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
jf.pack();

I am reading this from Javadoc

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child);

However using JFrame you need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(child);

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.

The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.

In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.

My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.

C# Error: Parent does not contain a constructor that takes 0 arguments

You can use a constructor with no parameters in your Parent class :

public parent() { } 

Update values from one column in same table to another in SQL Server

update TABLE_1 a set COLUMN_1 = (select COLUMN_2 from TABLE_1 b where a.ID = b.ID)

css overflow - only 1 line of text

I was able to achieve this by using the webkit-line-clamp and the following css:

div {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

cURL not working (Error #77) for SSL connections on CentOS for non-root users

I just had a similar problem with Error#77 on CentOS7. I was missing the softlink /etc/pki/tls/certs/ca-bundle.crt that is installed with the ca-certificates RPM.

'curl' was attempting to open this path to get the Certificate Authorities. I discovered with:

strace curl https://example.com

and saw clearly that the open failed on that link.

My fix was:

yum reinstall ca-certificates

That should setup everything again. If you have private CAs for Corporate or self-signed use make sure they are in /etc/pki/ca-trust/source/anchors so that they are re-added.

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

How to pretty print XML from the command line?

xmllint support formatting in-place:

for f in *.xml; do xmllint -o $f --format $f; done

As Daniel Veillard has written:

I think xmllint -o tst.xml --format tst.xml should be safe as the parser will fully load the input into a tree before opening the output to serialize it.

Indent level is controlled by XMLLINT_INDENT environment variable which is by default 2 spaces. Example how to change indent to 4 spaces:

XMLLINT_INDENT='    '  xmllint -o out.xml --format in.xml

You may have lack with --recover option when you XML documents are broken. Or try weak HTML parser with strict XML output:

xmllint --html --xmlout <in.xml >out.xml

--nsclean, --nonet, --nocdata, --noblanks etc may be useful. Read man page.

apt-get install libxml2-utils
apt-cyg install libxml2
brew install libxml2

how to calculate binary search complexity

Here is the solution using the master theorem, with readable LaTeX.

For each recurrence in the recurrence relation for binary search, we convert the problem into one subproblem, with runtime T(N/2). Therefore:

T(n) = T(n/2)+1

Substituting into the master theorem, we get:

T(n) = aT(n/b) + f(n)

Now, because logba is 0 and f(n) is 1, we can use the second case of the master theorem because:

f(n) = O(1) = O(n0) = O(nlogba)

This means that:

T(n)=O(nlogbalogn) = O(n0logn) = O(logn)

Return in Scala

This topic is actually a little more complicated as described in the answers so far. This blogpost by Rob Norris explains it in more detail and gives examples on when using return will actually break your code (or at least have non-obvious effects).

At this point let me just quote the essence of the post. The most important statement is right in the beginning. Print this as a poster and put it to your wall :-)

The return keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.

It gives one example, where it actually breaks something, when you inline a function

// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add

scala> sum(33, 42, 99)
res2: Int = 174 // alright

def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR

scala> sumR(33, 42, 99)
res3: Int = 33 // um.

because

A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.

This is only one of the examples given in the linked post and it's the easiest to understand. There're more and I highly encourage you, to go there, read and understand.

When you come from imperative languages like Java, this might seem odd at first, but once you get used to this style it will make sense. Let me close with another quote:

If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation.

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

Python, add items from txt file into a list

This should be a good case for map and lambda

with open ('names.txt','r') as f :
   Names = map (lambda x : x.strip(),f_in.readlines())

I stand corrected (or at least improved). List comprehensions is even more elegant

with open ('names.txt','r') as f :
    Names = [name.rstrip() for name in f]

Entity Framework change connection at runtime

I have two extension methods to convert the normal connection string to the Entity Framework format. This version working well with class library projects without copying the connection strings from app.config file to the primary project. This is VB.Net but easy to convert to C#.

Public Module Extensions

    <Extension>
    Public Function ToEntityConnectionString(ByRef sqlClientConnStr As String, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
        Dim sqlb As New SqlConnectionStringBuilder(sqlClientConnStr)
        Return ToEntityConnectionString(sqlb, modelFileName, multipleActiceResultSet)
    End Function

    <Extension>
    Public Function ToEntityConnectionString(ByRef sqlClientConnStrBldr As SqlConnectionStringBuilder, ByVal modelFileName As String, Optional ByVal multipleActiceResultSet As Boolean = True)
        sqlClientConnStrBldr.MultipleActiveResultSets = multipleActiceResultSet
        sqlClientConnStrBldr.ApplicationName = "EntityFramework"

        Dim metaData As String = "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string='{1}'"
        Return String.Format(metaData, modelFileName, sqlClientConnStrBldr.ConnectionString)
    End Function

End Module

After that I create a partial class for DbContext:

Partial Public Class DlmsDataContext

    Public Shared Property ModelFileName As String = "AvrEntities" ' (AvrEntities.edmx)

    Public Sub New(ByVal avrConnectionString As String)
        MyBase.New(CStr(avrConnectionString.ToEntityConnectionString(ModelFileName, True)))
    End Sub

End Class

Creating a query:

Dim newConnectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=DB;Persist Security Info=True;User ID=sa;Password=pass"

Using ctx As New DlmsDataContext(newConnectionString)
    ' ...
    ctx.SaveChanges()
End Using

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

How do I create a branch?

Normally you'd copy it to svn+ssh://host.example.com/repos/project/branches/mybranch so that you can keep several branches in the repository, but your syntax is valid.

Here's some advice on how to set up your repository layout.

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

Add floating point value to android resources/values

Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

I'm using Build Tools major version 29.

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

If the extended class has the issue then the above error message will gets displayed.

Example

class Example extends Example1 {

}

fix the issues in Example1

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

How to find EOF through fscanf?

If you have integers in your file fscanf returns 1 until integer occurs. For example:

FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
    counter = fscanf(in, "%d", &sequence);
    if ( counter == 1 ) {
        length += 1;
    }
}

To find out the end of the file with symbols you can use EOF. For example:

char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
    printf("%c", symbol); 
}

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

How can I display a list view in an Android Alert Dialog?

private void AlertDialogue(final List<Animals> animals) {
 final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AdminActivity.this);
 alertDialog.setTitle("Filter by tag");

 final String[] animalsArray = new String[animals.size()];

 for (int i = 0; i < tags.size(); i++) {
  animalsArray[i] = tags.get(i).getanimal();

 }

 final int checkedItem = 0;
 alertDialog.setSingleChoiceItems(animalsArray, checkedItem, new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {

   Log.e(TAG, "onClick: " + animalsArray[which]);

  }
 });


 AlertDialog alert = alertDialog.create();
 alert.setCanceledOnTouchOutside(false);
 alert.show();

}

How to align the text middle of BUTTON

I think you can use Padding like: Hope this one can help you.

.loginButton {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    <!--Using padding to align text in box or image-->
    padding: 3px 2px;
}

How to lose margin/padding in UITextView?

In case anyone looking for latest Swift version then below code is working fine with Xcode 10.2 and Swift 4.2

yourTextView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

How to add a new audio (not mixing) into a video using ffmpeg?

Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {



            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");




            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};


            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {


                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");


                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }


        }

In PHP, how do you change the key of an array element?

Easy stuff:

this function will accept the target $hash and $replacements is also a hash containing newkey=>oldkey associations.

This function will preserve original order, but could be problematic for very large (like above 10k records) arrays regarding performance & memory.

function keyRename(array $hash, array $replacements) {
    $new=array();
    foreach($hash as $k=>$v)
    {
        if($ok=array_search($k,$replacements))
            $k=$ok;
        $new[$k]=$v;
    }
    return $new;    
}

this alternative function would do the same, with far better performance & memory usage, at the cost of loosing original order (which should not be a problem since it is hashtable!)

function keyRename(array $hash, array $replacements) {

    foreach($hash as $k=>$v)
        if($ok=array_search($k,$replacements))
        {
          $hash[$ok]=$v;
          unset($hash[$k]);
        }

    return $hash;       
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

First you should learn about loops, in this case most suitable is for loop. For instance let's initialize whole table with increasing values starting with 0:

final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
    array[i] = i;
}

Now you can modify it to initialize your table with values as per your assignment. But what happen if you replace condition i < SIZE with i < 11? Well, you will get IndexOutOfBoundException, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.

In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

Extract the maximum value within each group in a dataframe

df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))

Just using base R

Get int from String, also containing letters, in Java

Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

I have been using iPhone Configuration Utility to read the UDIDs and install the Development app. Still works fine on iOS7

c# open file with default application and parameters

you can try with

Process process = new Process();
process.StartInfo.FileName = "yourProgram.exe";
process.StartInfo.Arguments = ..... //your parameters
process.Start();

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

clearInterval() not working

The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

How to move Docker containers between different hosts?

Alternatively, if you do not wish to push to a repository:

  1. Export the container to a tarball

    docker export <CONTAINER ID> > /home/export.tar
    
  2. Move your tarball to new machine

  3. Import it back

    cat /home/export.tar | docker import - some-name:latest
    

How do you loop in a Windows batch file?

Type:

for /?

and you will get several pages of help text.

How do I read an attribute on a class at runtime?

System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++)
{
    if (attributes[i] is DomainNameAttribute)
    {
        System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
    }   
}

How correctly produce JSON by RESTful web service?

Use this annotation

@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})

What parameters should I use in a Google Maps URL to go to a lat-lon?

yeah I had the same question for a long time and I found the perfect one. here are some parameters from it.

https://maps.google.com?parameter = value



q=

is used to specify the search query in Google maps search.
eg :

https://maps.google.com?q=newyork or
https://maps.google.com?q=51.03841,-114.01679

near=

is used to specify the location alternative to q=. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if query is a business or suchlike.

z=

Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

ll=

Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

sll=

Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

t=

Sets the kind of map shown. Can be set to:

m – normal  map,
k – satellite,
h – hybrid,
p – terrain

saddr=

Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

daddr=

Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

via=

Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

doflg=

Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

msa=

Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

dirflg=

can set miscellaneous values below:

h - Avoid highway
t - Avoid tolls

reference http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Get protocol + host name from URL

If it contains less than 3 slashes thus you've it got and if not then we can find the occurrence between it:

import re

link = http://forum.unisoftdev.com/something

slash_count = len(re.findall("/", link))
print slash_count # output: 3

if slash_count > 2:
   regex = r'\:\/\/(.*?)\/'
   pattern  = re.compile(regex)
   path = re.findall(pattern, url)

   print path

Add text to Existing PDF using Python

Leveraging David Dehghan's answer above, the following works in Python 2.7.13:

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger

import StringIO

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(290, 720, "Hello world")
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader("original.pdf")
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Extend a java class from one file in another java file

You don't.

If you want to extend Person with Student, just do:

public class Student extends Person
{
}

And make sure, when you compile both classes, one can find the other one.

What IDE are you using?

Git pushing to remote branch

git push --set-upstream origin <branch_name>_test

--set-upstream sets the association between your local branch and the remote. You only have to do it the first time. On subsequent pushes you can just do:

git push

If you don't have origin set yet, use:

git remote add origin <repository_url> then retry the above command.

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

Disable password authentication for SSH

Run

service ssh restart

instead of

/etc/init.d/ssh restart

This might work.

Is there a way to know your current username in mysql?

Use this query:

SELECT USER();

Or

SELECT CURRENT_USER;

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.

To check if a cell is empty, you can use cell(x,y) = "".
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks) or xlCellTypeConstants or xlCellTypeFormulas

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Had the same problem,

All i had to do whas set the oracle shell variable:

. /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

Sorterd!

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

Describe table structure

In DBTools for Sybase, it's sp_columns your_table_name.

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

How do I specify the platform for MSBuild?

If you want to build your solution for x86 and x64, your solution must be configured for both platforms. Actually you just have an Any CPU configuration.

How to check the available configuration for a project

To check the available configuration for a given project, open the project file (*.csproj for example) and look for a PropertyGroup with the right Condition.

If you want to build in Release mode for x86, you must have something like this in your project file:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
  ...
</PropertyGroup>

How to create and edit the configuration in Visual Studio

Configuration Manager panel
(source: microsoft.com)

New solution platform button
(source: msdn.com)

New solution platform panel
(source: msdn.com)

How to create and edit the configuration (on MSDN)

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

How to set True as default value for BooleanField on Django?

I am using django==1.11. The answer get the most vote is actually wrong. Checking the document from django, it says:

initial -- A value to use in this Field's initial display. This value is not used as a fallback if data isn't given.

And if you dig into the code of form validation process, you will find that, for each fields, form will call it's widget's value_from_datadict to get actual value, so this is the place where we can inject default value.

To do this for BooleanField, we can inherit from CheckboxInput, override default value_from_datadict and init function.

class CheckboxInput(forms.CheckboxInput):
    def __init__(self, default=False, *args, **kwargs):
        super(CheckboxInput, self).__init__(*args, **kwargs)
        self.default = default

    def value_from_datadict(self, data, files, name):
        if name not in data:
            return self.default
        return super(CheckboxInput, self).value_from_datadict(data, files, name)

Then use this widget when creating BooleanField.

class ExampleForm(forms.Form):
    bool_field = forms.BooleanField(widget=CheckboxInput(default=True), required=False)

ReflectionException: Class ClassName does not exist - Laravel

try to use following command

php artisan db:seed --class=DatabaseSeeder

Bootstrap navbar Active State not working

when use header.php for every page for the navbar code, the jquery does not work, the active is applied and then removed, a simple solution, is as follows

on every page set variable <?php $pageName = "index"; ?> on Index page and similarly <?php $pageName = "contact"; ?> on Contact us page

then call the header.php (ie the nav code is in header.php) <?php include('header.php'); >

in the header.php ensure that each nav-link is as follows

<a class="nav-link <?php if ($page_name == 'index') {echo "active";} ?> href="index.php">Home</a>

<a class="nav-link <?php if ($page_name == 'contact') {echo "active";} ?> href="contact.php">Contact Us</a>

hope this helps cause i have spent days to get the jquery to work but failed,

if someone would kindly explain what exactly is the issue when the header.php is included and then page loads... why the jquery fails to add the active class to the nav-link..??

Vertical Alignment of text in a table cell

I had the same issue but solved it by using !important. I forgot about the inheritance in CSS. Just a tip to check first.

Change output format for MySQL command line results to CSV

If you are using mysql client you can set up the resultFormat per session e.g.

mysql -h localhost -u root --resutl-format=json

or

mysql -h localhost -u root --vertical

Check out the full list of arguments here.

Android Reading from an Input stream efficiently

What about this. Seems to give better performance.

byte[] bytes = new byte[1000];

StringBuilder x = new StringBuilder();

int numRead = 0;
while ((numRead = is.read(bytes)) >= 0) {
    x.append(new String(bytes, 0, numRead));
}

Edit: Actually this sort of encompasses both steelbytes and Maurice Perry's

Select and display only duplicate records in MySQL

SELECT id, payer_email FROM paypal_ipn_orders
WHERE payer_email IN (
    SELECT payer_email FROM papypal_ipn_orders GROUP BY payer_email HAVING COUNT(*) > 1)

Generating a random & unique 8 character string using MySQL

If you're OK with "random" but entirely predictable license plates, you can use a linear-feedback shift register to choose the next plate number - it's guaranteed to go through every number before repeating. However, without some complex math, you won't be able to go through every 8 character alphanumeric string (you'll get 2^41 out of the 36^8 (78%) possible plates). To make this fill your space better, you could exclude a letter from the plates (maybe O), giving you 97%.

How to serve up a JSON response using Go?

You can set your content-type header so clients know to expect json

w.Header().Set("Content-Type", "application/json")

Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

Eclipse add Tomcat 7 blank server name

Deleting/Moving files org.eclipse.jst.server.tomcat.core.prefs and org.eclipse.wst.server.core.prefs worked for me.

What is the C# equivalent of friend?

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]

How can I add a username and password to Jenkins?

If installed as an admin, use:-

uname - admin
pw - the passkey that was generated during installation

Reporting Services Remove Time from DateTime in Expression

Something like this:

=FormatDateTime(Now, DateFormat.ShortDate) 

Where "Now" can be replaced by the name of the date/time field that you're trying to convert.)
For instance,

=FormatDateTime(Fields!StartDate.Value, DateFormat.ShortDate)

libstdc++-6.dll not found

Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.

I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#

What is the difference between 'protected' and 'protected internal'?

In practice, about methods:

protected - accessible for inherited classes, otherwise private.

internal - public only for classes inside the assembly, otherwise private.

protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.

Experimental decorators warning in TypeScript compilation

I've to add the following in the settings.json file of vscode to remove the warning.

"javascript.implicitProjectConfig.experimentalDecorators": true

VSCode -> Preferences -> Settings

enter image description here

UPDATE

As Clepsyd pointed out, this setting had been deprecated. You need to use now

"js/ts.implicitProjectConfig.experimentalDecorators":true

enter image description here

How to cancel a Task in await?

Or, in order to avoid modifying slowFunc (say you don't have access to the source code for instance):

var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code

//original code: await task;  
await Task.WhenAny(task, completionSource.Task); //New code

You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:

await Task.WhenAny(task, source.Token.AsTask());

How to easily import multiple sql files into a MySQL database?

The easiest solution is to copy/paste every sql files in one.

You can't add some sql markup for file importation (the imported files will be in your computer, not in the server, and I don't think MySQL manage some import markup for external sql files).

Reading binary file and looping over each byte

This generator yields bytes from a file, reading the file in chunks:

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

# example:
for b in bytes_from_file('filename'):
    do_stuff_with(b)

See the Python documentation for information on iterators and generators.

java collections - keyset() vs entrySet() in map

Every call to the Iterator.next() moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?

for (String key : map.keySet()) {
    System.out.println(key + ":" + map.get(key));
}

Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry implementations usually implement the toString() method, so you don't have to print the key-value pair manually.

for (Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry);
}

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

How to get VM arguments from inside of Java application?

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name");

to get that value

Program to find largest and smallest among 5 numbers without using array

void main()
{
int a,b,c,d,e,max;
    max=a;
    if(b/max)
        max=b;
    if(c/max)
        max=c;
    if(d/max)
        max=d;
    if(e/max)
        max=e;
    cout<<"Maximum is"<<max;
}

The most accurate way to check JS object's type?

I put together a little type check utility inspired by the above correct answers:

thetypeof = function(name) {
        let obj = {};
        obj.object = 'object Object'
        obj.array = 'object Array'
        obj.string = 'object String'
        obj.boolean = 'object Boolean'
        obj.number = 'object Number'
        obj.type = Object.prototype.toString.call(name).slice(1, -1)
        obj.name = Object.prototype.toString.call(name).slice(8, -1)
        obj.is = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type === obj[ofType])? true: false
        }
        obj.isnt = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type !== obj[ofType])? true: false
        }
        obj.error = (ofType) => {
            throw new TypeError(`The type of ${name} is ${obj.name}: `
            +`it should be of type ${ofType}`)
        }
        return obj;
    };

example:

if (thetypeof(prop).isnt('String')) thetypeof(prop).error('String')
if (thetypeof(prop).is('Number')) // do something

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

what is the use of fflush(stdin) in c programming

It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:

char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);

Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

However, note that this use of fflush() is unportable. I've tested right now on a Linux machine, and it does not work, for example.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

 // prepare json data
        let mapDict = [ "1":"First", "2":"Second"]

        let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
        let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData

        // create post request
        let url = NSURL(string: "http://httpbin.org/post")!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        // insert json data to the request
        request.httpBody = jsonData as Data


        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            if error != nil{
                return
            }
            do {
                let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

                print("Result",result!)

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()

Python class returning value

You are describing a function, not a class.

def Myclass():
    return []

How to create NSIndexPath for TableView

Obligatory answer in Swift : NSIndexPath(forRow:row, inSection: section)

You will notice that NSIndexPath.indexPathForRow(row, inSection: section) is not available in swift and you must use the first method to construct the indexPath.

How to properly upgrade node using nvm

if you have 4.2 and want to install 5.0.0 then

nvm install v5.0.0 --reinstall-packages-from=4.2

the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

source: sitepoint

git checkout tag, git pull fails in branch

Edit: For newer versions of Git, --set-upstream master has been deprecated, you should use --set-upstream-to instead:

git branch --set-upstream-to=origin/master master

As it prompted, you can just run:

git branch --set-upstream master origin/master

After that, you can simply run git pull to update your code.

How to get current user, and how to use User class in MVC5?

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

collapse cell in jupyter notebook

Firstly, follow Energya's instruction:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"

This is what you want!

Add regression line equation and R^2 on graph

really love @Ramnath solution. To allow use to customize the regression formula (instead of fixed as y and x as literal variable names), and added the p-value into the printout as well (as @Jerry T commented), here is the mod:

lm_eqn <- function(df, y, x){
    formula = as.formula(sprintf('%s ~ %s', y, x))
    m <- lm(formula, data=df);
    # formating the values into a summary string to print out
    # ~ give some space, but equal size and comma need to be quoted
    eq <- substitute(italic(target) == a + b %.% italic(input)*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue), 
         list(target = y,
              input = x,
              a = format(as.vector(coef(m)[1]), digits = 2), 
              b = format(as.vector(coef(m)[2]), digits = 2), 
             r2 = format(summary(m)$r.squared, digits = 3),
             # getting the pvalue is painful
             pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=1)
            )
          )
    as.character(as.expression(eq));                 
}

geom_point() +
  ggrepel::geom_text_repel(label=rownames(mtcars)) +
  geom_text(x=3,y=300,label=lm_eqn(mtcars, 'hp','wt'),color='red',parse=T) +
  geom_smooth(method='lm')

enter image description here Unfortunately, this doesn't work with facet_wrap or facet_grid.

Getting the first character of a string with $str[0]

$str = 'abcdef';
echo $str[0];                 // a

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

Current date without time

As mentioned in several answers already that have been already given, you can use ToShorDateString():

DateTime.Now.ToShortDateString();

However, you may be a bit blocked if you also want to use the culture as a parameter. In this case you can use the ToString() method with the "d" format:

DateTime.Now.ToString("d", CultureInfo.GetCultureInfo("en-US"))

How to convert from int to string in objective c: example code

You can use literals, it's more compact.

NSString* myString = [@(17) stringValue];

(Boxes as a NSNumber and uses its stringValue method)

How to get a float result by dividing two integer values using T-SQL?

I understand that CASTing to FLOAT is not allowed in MySQL and will raise an error when you attempt to CAST(1 AS float) as stated at MySQL dev.

The workaround to this is a simple one. Just do

(1 + 0.0)

Then use ROUND to achieve a specific number of decimal places like

ROUND((1+0.0)/(2+0.0), 3)

The above SQL divides 1 by 2 and returns a float to 3 decimal places, as in it would be 0.500.

One can CAST to the following types: binary, char, date, datetime, decimal, json, nchar, signed, time, and unsigned.

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

How to compare two double values in Java?

double a = 1.000001;
double b = 0.000001;

System.out.println( a.compareTo(b) );

Returns:

  • -1 : 'a' is numerically less than 'b'.

  • 0 : 'a' is equal to 'b'.

  • 1 : 'a' is greater than 'b'.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

in your WebApiConfig >> Register () You have to change to

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

Here the routeTemplate, is added with {action}

How to truncate a foreign key constrained table?

Answer is indeed the one provided by zerkms, as stated on Option 1:

Option 1: which does not risk damage to data integrity:

  1. Remove constraints
  2. Perform TRUNCATE
  3. Delete manually the rows that now have references to nowhere
  4. Create constraints

The tricky part is Removing constraints, so I want to tell you how, in case someone needs to know how to do that:

  1. Run SHOW CREATE TABLE <Table Name> query to see what is your FOREIGN KEY's name (Red frame in below image):

    enter image description here

  2. Run ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign Key Name>. This will remove the foreign key constraint.

  3. Drop the associated Index (through table structure page), and you are done.

to re-create foreign keys:

ALTER TABLE <Table Name>
ADD FOREIGN KEY (<Field Name>) REFERENCES <Foreign Table Name>(<Field Name>);

Replace multiple strings at once

Using ES6: There are many ways to search for strings and replace in JavaScript. One of them is as follow

_x000D_
_x000D_
const findFor = ['<', '>', '\n'];_x000D_
_x000D_
const replaceWith = ['&lt;', '&gt;', '<br/>'];_x000D_
_x000D_
const originalString = '<strong>Hello World</strong> \n Let\'s code';_x000D_
_x000D_
let modifiedString = originalString;_x000D_
_x000D_
findFor.forEach( (tag, i) => modifiedString = modifiedString.replace(new RegExp(tag, "g"), replaceWith[i]) )_x000D_
_x000D_
console.log('Original String: ', originalString);_x000D_
console.log('Modified String: ', modifiedString);
_x000D_
_x000D_
_x000D_

Assigning a variable NaN in python without numpy

You can do float('nan') to get NaN.

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

Multiple glibc libraries on a single host

@msb gives a safe solution.

I met this problem when I did import tensorflow as tf in conda environment in CentOS 6.5 which only has glibc-2.12.

ImportError: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by /home/

I want to supply some details:

First install glibc to your home directory:

mkdir ~/glibc-install; cd ~/glibc-install
wget http://ftp.gnu.org/gnu/glibc/glibc-2.17.tar.gz
tar -zxvf glibc-2.17.tar.gz
cd glibc-2.17
mkdir build
cd build
../configure --prefix=/home/myself/opt/glibc-2.17  # <-- where you install new glibc
make -j<number of CPU Cores>  # You can find your <number of CPU Cores> by using **nproc** command
make install

Second, follow the same way to install patchelf;

Third, patch your Python:

[myself@nfkd ~]$ patchelf --set-interpreter /home/myself/opt/glibc-2.17/lib/ld-linux-x86-64.so.2 --set-rpath /home/myself/opt/glibc-2.17/lib/ /home/myself/miniconda3/envs/tensorflow/bin/python

as mentioned by @msb

Now I can use tensorflow-2.0 alpha in CentOS 6.5.

ref: https://serverkurma.com/linux/how-to-update-glibc-newer-version-on-centos-6-x/

Node.js create folder or use existing

Just as a newer alternative to Teemu Ikonen's answer, which is very simple and easily readable, is to use the ensureDir method of the fs-extra package.

It can not only be used as a blatant replacement for the built in fs module, but also has a lot of other functionalities in addition to the functionalities of the fs package.

The ensureDir method, as the name suggests, ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. Not just the end folder, instead the entire path is created if not existing already.

the one provided above is the async version of it. It also has a synchronous method to perform this in the form of the ensureDirSync method.

What's the easiest way to escape HTML in Python?

No libraries, pure python, safely escapes text into html text:

text.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;'
        ).replace('\'','&#39;').replace('"','&#34;').encode('ascii', 'xmlcharrefreplace')

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

On CYGwin, you can install this as a typical package in the first screen. Look for

libssl-devel

How to reduce a huge excel file

i Change the format of file to *.XLSX this change compress my file and reduce file size of 15%

How to quit android application programmatically

I think that application should be kill in some case. For example, there is an app can be used only after login. The login activity has two buttons, 'login' and 'cancel'. When you click 'cancel' button, it definitely means 'Terminate the app'. Nobody wants the app alive in the background. So I agree that some cases need to shut down the app.

How to convert int[] to Integer[] in Java?

I was wrong in a previous answer. The proper solution is to use this class as a key in the map wrapping the actual int[].

public class IntArrayWrapper {
        int[] data;

        public IntArrayWrapper(int[] data) {
            this.data = data;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            IntArrayWrapper that = (IntArrayWrapper) o;

            if (!Arrays.equals(data, that.data)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return data != null ? Arrays.hashCode(data) : 0;
        }
    }

and change your code like this:

   Map<IntArrayWrapper, Double > freqs = new HashMap<IntArrayWrapper, Double>();

    for (int[] data : datas) {
        IntArrayWrapper wrapper = new IntArrayWrapper(data);

        if ( freqs.containsKey(wrapper)) {
            freqs.put(wrapper, freqs.get(wrapper) + p);
        }

        freqs.put(wrapper, p);
    }

How do I select text nodes with jQuery?

I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue conditional to your filter function, like a simple $.trim(this.nodevalue) !== '':

$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });

http://jsfiddle.net/ptp6m97v/

Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen &shy; character, newlines \n, tabs, etc.), you can try using a Regular Expression. For example, \S will match any non-whitespace characters:

$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });

How to get the <html> tag HTML with JavaScript / jQuery?

The simplest way to get the html element natively is:

document.documentElement

Here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.

UPDATE: To then grab the html element as a string you would do:

document.documentElement.outerHTML

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

Change :hover CSS properties with JavaScript

Declare a global var:

var td

Then select your guiena pig <td> getting it by its id, if you want to change all of them then

window.onload = function () {
  td = document.getElementsByTagName("td"); 
}

Make a function to be triggered and a loop to change all of your desired td's

function trigger() {
    for(var x = 0; x < td.length; x++) { 
      td[x].className = "yournewclass"; 
    }
}

Go to your CSS Sheet:

.yournewclass:hover { background-color: #00ff00; }

And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).

Clean out Eclipse workspace metadata

In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).

See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)

Angularjs prevent form submission when input validation fails

Your forms are automatically put into $scope as an object. It can be accessed via $scope[formName]

Below is an example that will work with your original setup and without having to pass the form itself as a parameter in ng-submit.

var controller = function($scope) {

    $scope.login = {
        submit: function() {
            if($scope.loginform.$invalid) return false;

        }
    }

};

Working example: http://plnkr.co/edit/BEWnrP?p=preview

How to resolve "must be an instance of string, string given" prior to PHP 7?

PHP allows "hinting" where you supply a class to specify an object. According to the PHP manual, "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported." The error is confusing because of your choice of "string" - put "myClass" in its place and the error will read differently: "Argument 1 passed to phpwtf() must be an instance of myClass, string given"

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I am able to resolved this by running below commmand

modprobe -a vboxguest vboxsf vboxvideo

What underlies this JavaScript idiom: var self = this?

It should also be noted there is an alternative Proxy pattern for maintaining a reference to the original this in a callback if you dislike the var self = this idiom.

As a function can be called with a given context by using function.apply or function.call, you can write a wrapper that returns a function that calls your function with apply or call using the given context. See jQuery's proxy function for an implementation of this pattern. Here is an example of using it:

var wrappedFunc = $.proxy(this.myFunc, this);

wrappedFunc can then be called and will have your version of this as the context.

Python 2: AttributeError: 'list' object has no attribute 'strip'

This should be what you want:

[x for y in l for x in y.split(";")]

output:

['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

What's the difference between `raw_input()` and `input()` in Python 3?

The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). (Remember that eval() is evil. Try to use safer ways of parsing your input if possible.)

How to calculate number of days between two given dates?

For calculating dates and times, there are several options but I will write the simple way:

from datetime import timedelta, datetime, date
import dateutil.relativedelta

# current time
date_and_time = datetime.now()
date_only = date.today()
time_only = datetime.now().time()

# calculate date and time
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)

# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)

# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)

# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)

# calculate time 
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)
result.time()

Hope it helps

Why is exception.printStackTrace() considered bad practice?

Throwable.printStackTrace() writes the stack trace to System.err PrintStream. The System.err stream and the underlying standard "error" output stream of the JVM process can be redirected by

  • invoking System.setErr() which changes the destination pointed to by System.err.
  • or by redirecting the process' error output stream. The error output stream may be redirected to a file/device
    • whose contents may be ignored by personnel,
    • the file/device may not be capable of log rotation, inferring that a process restart is required to close the open file/device handle, before archiving the existing contents of the file/device.
    • or the file/device actually discards all data written to it, as is the case of /dev/null.

Inferring from the above, invoking Throwable.printStackTrace() constitutes valid (not good/great) exception handling behavior, only

  • if you do not have System.err being reassigned throughout the duration of the application's lifetime,
  • and if you do not require log rotation while the application is running,
  • and if accepted/designed logging practice of the application is to write to System.err (and the JVM's standard error output stream).

In most cases, the above conditions are not satisfied. One may not be aware of other code running in the JVM, and one cannot predict the size of the log file or the runtime duration of the process, and a well designed logging practice would revolve around writing "machine-parseable" log files (a preferable but optional feature in a logger) in a known destination, to aid in support.

Finally, one ought to remember that the output of Throwable.printStackTrace() would definitely get interleaved with other content written to System.err (and possibly even System.out if both are redirected to the same file/device). This is an annoyance (for single-threaded apps) that one must deal with, for the data around exceptions is not easily parseable in such an event. Worse, it is highly likely that a multi-threaded application will produce very confusing logs as Throwable.printStackTrace() is not thread-safe.

There is no synchronization mechanism to synchronize the writing of the stack trace to System.err when multiple threads invoke Throwable.printStackTrace() at the same time. Resolving this actually requires your code to synchronize on the monitor associated with System.err (and also System.out, if the destination file/device is the same), and that is rather heavy price to pay for log file sanity. To take an example, the ConsoleHandler and StreamHandler classes are responsible for appending log records to console, in the logging facility provided by java.util.logging; the actual operation of publishing log records is synchronized - every thread that attempts to publish a log record must also acquire the lock on the monitor associated with the StreamHandler instance. If you wish to have the same guarantee of having non-interleaved log records using System.out/System.err, you must ensure the same - the messages are published to these streams in a serializable manner.

Considering all of the above, and the very restricted scenarios in which Throwable.printStackTrace() is actually useful, it often turns out that invoking it is a bad practice.


Extending the argument in the one of the previous paragraphs, it is also a poor choice to use Throwable.printStackTrace in conjunction with a logger that writes to the console. This is in part, due to the reason that the logger would synchronize on a different monitor, while your application would (possibly, if you don't want interleaved log records) synchronize on a different monitor. The argument also holds good when you use two different loggers that write to the same destination, in your application.

mongodb count num of distinct values per field/key

To find distinct in field_1 in collection but we want some WHERE condition too than we can do like following :

db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})

So, find number distinct names from a collection where age > 25 will be like :

db.your_collection_name.distinct('names', {'age': {"$gt": 25}})

Hope it helps!

Get value of input field inside an iframe

Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---

var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
    encodeURIComponent(purl) + '&callback=?',
    function (data) {
    $('#viewer').html(data.contents);
});

How can I stop a running MySQL query?

Use mysqladmin to kill the runaway query:

Run the following commands:

mysqladmin -uusername -ppassword pr

Then note down the process id.

mysqladmin -uusername -ppassword kill pid

The runaway query should no longer be consuming resources.

Total number of items defined in an enum

You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

GetNames produces much the same result as GetValues but is faster.

Registry key Error: Java version has value '1.8', but '1.7' is required

My experience:

I am using windows 8.1 and i have downgraded JAVA version from 1.8 to 1.7 and i was getting the same error.

Error: Registry key 'Software\JavaSoft\Ja has value '1.7', but '1.8' is required.

I have deleted java.exe, javaw.exe and javaws.exe from C:\Windows\System32 folder and it worked for me.

Different class for the last element in ng-repeat

<div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
   {{file.name}}
</div>

That works for me! Good luck!

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

Convert UTC to local time in Rails 3

Don't know why but in my case it doesn't work the way suggested earlier. But it works like this:

Time.now.change(offset: "-3000")

Of course you need to change offset value to yours.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

Angular - ng: command not found

I tried this and everything worked by changing the npm directory.

         mkdir ~/.npm-global
         npm config set prefix '~/.npm-global'
         export PATH=~/.npm-global/bin:$PATH
         source ~/.profile
         npm install -g jshint
         ng --version

Increasing the timeout value in a WCF service

Are you referring to the server side or the client side?

For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.

<system.serviceModel>
  <bindings>
    <netTcpBinding>
      <binding name="longTimeoutBinding"
        receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="None"/>
      </binding>
    </netTcpBinding>
  </bindings>

  <services>
    <service name="longTimeoutService"
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="net.tcp://localhost/longtimeout/"
        binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
    </service>
....

Of course, you have to map your desired endpoint to that particular binding.

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

How to delete from select in MySQL?

you can use inner join :

DELETE 
    ps 
FROM 
    posts ps INNER JOIN 
         (SELECT 
           distinct id 
         FROM 
             posts 
         GROUP BY id  
      HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id  

How to write an XPath query to match two attributes?

Adding to Brian Agnew's answer.

You can also do //div[@id='..' or @class='...] and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')].

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

Taking the record with the max date

Justin Cave answer is the best, but if you want antoher option, try this:

select A,col_date
from (select A,col_date
    from tablename 
      order by col_date desc)
      where rownum<2

Laravel 5 not finding css files

I was having the same problem, until just now.

Removing the / from before /css/app.css so that its css.app.css worked for me.

How to scroll to an element?

You could try this way:

 handleScrollToElement = e => {
    const elementTop = this.gate.offsetTop;
    window.scrollTo(0, elementTop);
 };

 render(){
  return(
      <h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
 )}

'tsc command not found' in compiling typescript

If your TSC command is not found in MacOS after proper installation of TypeScript (using the following command: $ sudo npm install -g typescript, then ensure Node /bin path is added to the PATH variable in .bash_profile.

Open .bash_profile using terminal: $ open ~/.bash_profile;

Edit/Verify bash profile to include the following line (using your favorite text editor):

export PATH="$PATH:"/usr/local/lib/node_modules/node/bin"";

Load the latest bash profile using terminal: source ~/.bash_profile;

Lastly, try the command: $ tsc --version.

How can I get column names from a table in SQL Server?

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

This is better than getting from sys.columns because it shows DATA_TYPE directly.

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

How to send email from SQL Server?

sometimes while not found sp_send_dbmail directly. You may use 'msdb.dbo.sp_send_dbmail' to try (Work fine on Windows Server 2008 R2 and is tested)

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

Quickest way to clear all sheet contents VBA

Technically, and from Comintern's accepted workaround, I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents. I.e. Sheets("Zeroes").Cells.Delete

Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:

Sub DeleteCells ()
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
End Sub

Or if you prefer to respect the Calculation State Excel is currently in:

Sub DeleteCells ()
    Dim SaveCalcState
    SaveCalcState = Application.Calculation
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = SaveCalcState
End Sub

Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but

Conditional formatting IS deleted, as is Entire Row formatting.

(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)

Catch KeyError in Python

I dont think python has a catch :)

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e

How to execute only one test spec with angular-cli

This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.

How to change lowercase chars to uppercase using the 'keyup' event?

Make sure that the field has this attribute in its html.

_x000D_
_x000D_
ClientIDMode="Static"
_x000D_
_x000D_
_x000D_

and then use this in your script:

_x000D_
_x000D_
$("#NameOfYourTextBox").change(function () {_x000D_
                 $(this).val($(this).val().toUpperCase());_x000D_
             });
_x000D_
_x000D_
_x000D_

Is there any way I can define a variable in LaTeX?

For variables describing distances, you would use \newlength (and manipulate the values with \setlength, \addlength, \settoheight, \settolength and \settodepth).

Similarly you have access to \newcounter for things like section and figure numbers which should increment throughout the document. I've used this one in the past to provide code samples that were numbered separatly of other figures...

Also of note is \makebox which allows you to store a bit of laid-out document for later re-use (and for use with \settolength...).

PHP header redirect 301 - what are the implications?

Make sure you die() after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you

For search engines, 301 is the best response code

How to discard all changes made to a branch?

Note: You CANNOT UNDO this.

Try git checkout -f this will discard any local changes which are not committed in ALL branches and master.

Preview an image before it is uploaded

TO PREVIEW MULTIPLE FILES using jquery

_x000D_
_x000D_
$(document).ready(function(){
    $('#image').change(function(){
        $("#frames").html('');
        for (var i = 0; i < $(this)[0].files.length; i++) {
            $("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
        }
    });
});
_x000D_
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <input type="file" id="image" name="image[]" multiple /><br/>
    <div id="frames"></div>
</body>
_x000D_
_x000D_
_x000D_

NSArray + remove item from array

Made a category like mxcl, but this is slightly faster.

My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

- (NSArray *)prefix_arrayByRemovingObject:(id)object 
{
    if (!object) {
        return self;
    }

    NSUInteger indexOfObject = [self indexOfObject:object];
    NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
    NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
    NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];

    return newArray;
}

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text
alt text
alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

    enableInputMethods(true);   
    addMouseListener(this);
    
  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
    
  6. Override this method:

    public void paintComponent(Graphics g)
    

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

How to register ASP.NET 2.0 to web server(IIS7)?

I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;

Using win2008R2, .NET framework 4.0

What is the best (idiomatic) way to check the type of a Python variable?

That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

{type(str()): do_something_with_a_string,
 type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()

A bit more concise and pythonic wouldn't you say?


Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

{str: do_something_with_a_string,
 dict: do_something_with_a_dict}.get(type(x), errorhandler)()

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

How to tell if a JavaScript function is defined

function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}