Programs & Examples On #Redo

How do I do redo (i.e. "undo undo") in Vim?

CTRL+r

The "r" is lower-case.

How to avoid HTTP error 429 (Too Many Requests) python

Another workaround would be to spoof your IP using some sort of Public VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.

There is a brief blog post demonstrating a way to use tor along with urllib2:

http://blog.flip-edesign.com/?p=119

What is the best method of handling currency/money?

Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.

Any way to generate ant build.xml file automatically from Eclipse?

I have been trying to do the same myself. What I found was that the "Export Ant Buildfile" gets kicked off in the org.eclipse.ant.internal.ui.datatransfer.AntBuildfileExportPage.java file. This resides in the org.eclipse.ant.ui plugin.

To view the source, use the Plug-in Development perspective and open the Plug-ins view. Then right-click on the org.eclipse.ant.ui plugin and select import as > source project.

My plan is to create a Java program to programmatically kick off the ant buildfile generation and call this in an Ant file every time I build by adding the ant file to the builders of my projects (Right-click preferences on a projet, under the builders tab).

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

How to avoid the "divide by zero" error in SQL?

Sometimes, 0 might not be appropriate, but sometimes 1 is also not appropriate. Sometimes a jump from 0 to 100,000,000 described as 1 or 100-percent change might also be misleading. 100,000,000 percent might be appropriate in that scenario. It depends on what kind of conclusions you intend to draw based on the percentages or ratios.

For example, a very small-selling item moving from 2-4 sold and a very large-selling item changing from 1,000,000 to 2,000,000 sold might mean very different things to an analyst or to management, but would both come through as 100% or 1 change.

It might be easier to isolate NULL values than to scour over a bunch of 0% or 100% rows mixed with legitimate data. Often, a 0 in the denominator can indicate an error or missing value, and you might not want to just fill in an arbitrary value just to make your dataset look tidy.

CASE
     WHEN [Denominator] = 0
     THEN NULL --or any value or sub case
     ELSE [Numerator]/[Denominator]
END as DivisionProblem

How to Import 1GB .sql file to WAMP/phpmyadmin

You can do it in following ways;

  1. You can go to control panel/cpanel and add host % It means now the database server can be accessed from your local machine. Now you can install and use MySQL Administrator or Navicat to import and export database with out using PHP-Myadmin, I used it several times to upload 200 MB to 500 MB of data with no issues

  2. Use gzip, bzip2 compressions for exporting and importing. I am using PEA ZIP software (free) in Windows. Try to avoid Winrar and Winzip

  3. Use MySQL Splitter that splits up the sql file into several parts. In my personal suggestion, Not recommended

  4. Using PHP INI setting (dynamically change the max upload and max execution time) as already mentioned by other friends is fruitful but not always.

Getting MAC Address

netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.

>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0', 'tun2']

>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
[{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]

How to assign Php variable value to Javascript variable?

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If one or both of the files you wish to compare isn't in an Eclipse project:

  1. Open the Quick Access search box

    • Linux/Windows: Ctrl+3
    • Mac: ?+3
  2. Type compare and select Compare With Other Resource

  3. Select the files to compare ? OK

You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys

Basic HTML - how to set relative path to current folder?

<html>
    <head>
        <title>Page</title>
    </head>
    <body>
       <a href="./">Folder directory</a> 
    </body>
</html>

How to validate a credit card number

I'm sure all of these algorithms are great, but you cannot verify that a card number is valid just by running an algorithm on it.

Algorithms make sure the format is correct and its checksums are valid. However, they do not guarantee the bank will accept the card... For that, you need to actually pass the card number to your bank for approval.

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

How to make input type= file Should accept only pdf and xls

While this particular example is for a multiple file upload, it gives the general information one needs:

https://developer.mozilla.org/en-US/docs/DOM/File.type

As far as acting upon a file upon /download/ this is not a Javascript question -- but rather a server configuration. If a user does not have something installed to open PDF or XLS files, their only choice will be to download them.

"Bitmap too large to be uploaded into a texture"

As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.

Get int from String, also containing letters, in Java

You can also use Scanner :

Scanner s = new Scanner(MyString);
s.nextInt();

Truncate all tables in a MySQL database in one command?

Use phpMyAdmin in this way:

Database View => Check All (tables) => Empty

If you want to ignore foreign key checks, you can uncheck the box that says:

[ ] Enable foreign key checks

You'll need to be running atleast version 4.5.0 or higher to get this checkbox.

Its not MySQL CLI-fu, but hey, it works!

How to search for a part of a word with ElasticSearch

without changing your index mappings you could do a simple prefix query that will do partial searches like you are hoping for

ie.

{
  "query": { 
    "prefix" : { "name" : "Doe" }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html

addEventListener in Internet Explorer

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->

What is the GAC in .NET?

The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework.

Path of assets in CSS files in Symfony 2

I'll post what worked for me, thanks to @xavi-montero.

Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.

Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.

In config.yml, add rule css_rewrite to assetic:

assetic:
    filters:
        cssrewrite:
            apply_to: "\.css$"

Now install assets and compile with assetic:

$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod

This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.

For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:

$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals

All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg

python tuple to dict

A slightly simpler method:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}

What is the difference between a deep copy and a shallow copy?

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

To show only file name without the entire directory path

There are several ways you can achieve this. One would be something like:

for filepath in /path/to/dir/*
do
    filename=$(basename $filepath)

    ... whatever you want to do with the file here
done

Set background colour of cell to RGB value of data in cell

You can use VBA - something like

Range("A1:A6").Interior.Color = RGB(127,187,199)

Just pass in the cell value.

Utils to read resource text file to String (Java)

public static byte[] readResoureStream(String resourcePath) throws IOException {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);

    //Create buffer
    byte[] buffer = new byte[4096];
    for (;;) {
        int nread = in.read(buffer);
        if (nread <= 0) {
            break;
        }
        byteArray.write(buffer, 0, nread);
    }
    return byteArray.toByteArray();
}

Charset charset = StandardCharsets.UTF_8;
String content = new   String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");

How exactly do you configure httpOnlyCookies in ASP.NET?

If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:

<httpCookies httpOnlyCookies="true"/>

git remote add with other SSH port

You need to edit your ~/.ssh/config file. Add something like the following:

Host example.com
    Port 1234

A quick google search shows a few different resources that explain it in more detail than me.

Changing image on hover with CSS/HTML

_x000D_
_x000D_
.hover_image:hover {text-decoration: none} /* Optional (avoid undesired underscore if a is used as wrapper) */_x000D_
.hide {display:none}_x000D_
/* Do the shift: */_x000D_
.hover_image:hover img:first-child{display:none}_x000D_
.hover_image:hover img:last-child{display:inline-block}
_x000D_
<body> _x000D_
    <a class="hover_image" href="#">_x000D_
        <!-- path/to/first/visible/image: -->_x000D_
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_silverstone_2016.jpg" />_x000D_
        <!-- path/to/hover/visible/image: -->_x000D_
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_malasia_2016.jpg" class="hide" />_x000D_
    </a>_x000D_
</body>
_x000D_
_x000D_
_x000D_

To try to improve this Rashid's good answer I'm adding some comments:

The trick is done over the wrapper of the image to be swapped (an 'a' tag this time but maybe another) so the 'hover_image' class has been put there.

Advantages:

  • Keeping both images url together in the same place helps if they need to be changed.

  • Seems to work with old navigators too (CSS2 standard).

  • It's self explanatory.

  • The hover image is preloaded (no delay after hovering).

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

gradle build fails on lint task

In Android Studio v1.2, it tells you how to fix it:

enter image description here

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

Enumerations on PHP

Stepping on the answer of @Brian Cline I thought I might give my 5 cents

<?php 
/**
 * A class that simulates Enums behaviour
 * <code>
 * class Season extends Enum{
 *    const Spring  = 0;
 *    const Summer = 1;
 *    const Autumn = 2;
 *    const Winter = 3;
 * }
 * 
 * $currentSeason = new Season(Season::Spring);
 * $nextYearSeason = new Season(Season::Spring);
 * $winter = new Season(Season::Winter);
 * $whatever = new Season(-1);               // Throws InvalidArgumentException
 * echo $currentSeason.is(Season::Spring);   // True
 * echo $currentSeason.getName();            // 'Spring'
 * echo $currentSeason.is($nextYearSeason);  // True
 * echo $currentSeason.is(Season::Winter);   // False
 * echo $currentSeason.is(Season::Spring);   // True
 * echo $currentSeason.is($winter);          // False
 * </code>
 * 
 * Class Enum
 * 
 * PHP Version 5.5
 */
abstract class Enum
{
    /**
     * Will contain all the constants of every enum that gets created to 
     * avoid expensive ReflectionClass usage
     * @var array
     */
    private static $_constCacheArray = [];
    /**
     * The value that separates this instance from the rest of the same class
     * @var mixed
     */
    private $_value;
    /**
     * The label of the Enum instance. Will take the string name of the 
     * constant provided, used for logging and human readable messages
     * @var string
     */
    private $_name;
    /**
     * Creates an enum instance, while makes sure that the value given to the 
     * enum is a valid one
     * 
     * @param mixed $value The value of the current
     * 
     * @throws \InvalidArgumentException
     */
    public final function __construct($value)
    {
        $constants = self::_getConstants();
        if (count($constants) !== count(array_unique($constants))) {
            throw new \InvalidArgumentException('Enums cannot contain duplicate constant values');
        }
        if ($name = array_search($value, $constants)) {
            $this->_value = $value;
            $this->_name = $name;
        } else {
            throw new \InvalidArgumentException('Invalid enum value provided');
        }
    }
    /**
     * Returns the constant name of the current enum instance
     * 
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }
    /**
     * Returns the value of the current enum instance
     * 
     * @return mixed
     */
    public function getValue()
    {
        return $this->_value;
    }
    /**
     * Checks whether this enum instance matches with the provided one.
     * This function should be used to compare Enums at all times instead
     * of an identity comparison 
     * <code>
     * // Assuming EnumObject and EnumObject2 both extend the Enum class
     * // and constants with such values are defined
     * $var  = new EnumObject('test'); 
     * $var2 = new EnumObject('test');
     * $var3 = new EnumObject2('test');
     * $var4 = new EnumObject2('test2');
     * echo $var->is($var2);  // true
     * echo $var->is('test'); // true
     * echo $var->is($var3);  // false
     * echo $var3->is($var4); // false
     * </code>
     * 
     * @param mixed|Enum $enum The value we are comparing this enum object against
     *                         If the value is instance of the Enum class makes
     *                         sure they are instances of the same class as well, 
     *                         otherwise just ensures they have the same value
     * 
     * @return bool
     */
    public final function is($enum)
    {
        // If we are comparing enums, just make
        // sure they have the same toString value
        if (is_subclass_of($enum, __CLASS__)) {
            return get_class($this) === get_class($enum) 
                    && $this->getValue() === $enum->getValue();
        } else {
            // Otherwise assume $enum is the value we are comparing against
            // and do an exact comparison
            return $this->getValue() === $enum;   
        }
    }

    /**
     * Returns the constants that are set for the current Enum instance
     * 
     * @return array
     */
    private static function _getConstants()
    {
        if (self::$_constCacheArray == null) {
            self::$_constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$_constCacheArray)) {
            $reflect = new \ReflectionClass($calledClass);
            self::$_constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$_constCacheArray[$calledClass];
    }
}

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

Stopping a JavaScript function when a certain condition is met

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

Compute a confidence interval from sample data

Here a shortened version of shasan's code, calculating the 95% confidence interval of the mean of array a:

import numpy as np, scipy.stats as st

st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))

But using StatsModels' tconfint_mean is arguably even nicer:

import statsmodels.stats.api as sms

sms.DescrStatsW(a).tconfint_mean()

The underlying assumptions for both are that the sample (array a) was drawn independently from a normal distribution with unknown standard deviation (see MathWorld or Wikipedia).

For large sample size n, the sample mean is normally distributed, and one can calculate its confidence interval using st.norm.interval() (as suggested in Jaime's comment). But the above solutions are correct also for small n, where st.norm.interval() gives confidence intervals that are too narrow (i.e., "fake confidence"). See my answer to a similar question for more details (and one of Russ's comments here).

Here an example where the correct options give (essentially) identical confidence intervals:

In [9]: a = range(10,14)

In [10]: mean_confidence_interval(a)
Out[10]: (11.5, 9.4457397432391215, 13.554260256760879)

In [11]: st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))
Out[11]: (9.4457397432391215, 13.554260256760879)

In [12]: sms.DescrStatsW(a).tconfint_mean()
Out[12]: (9.4457397432391197, 13.55426025676088)

And finally, the incorrect result using st.norm.interval():

In [13]: st.norm.interval(0.95, loc=np.mean(a), scale=st.sem(a))
Out[13]: (10.23484868811834, 12.76515131188166)

Long vs Integer, long vs int, what to use and when?

  • By default use an int, when holding numbers.
  • If the range of int is too small, use a long
  • If the range of long is too small, use BigInteger
  • If you need to handle your numbers as object (for example when putting them into a Collection, handling null, ...) use Integer/Long instead

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

MYSQL query between two timestamps

You just need to convert your dates to UNIX_TIMESTAMP. You can write your query like this:

SELECT *
FROM eventList
WHERE
  date BETWEEN
      UNIX_TIMESTAMP('2013/03/26')
      AND
      UNIX_TIMESTAMP('2013/03/27 23:59:59');

When you don't specify the time, MySQL will assume 00:00:00 as the time for the given date.

What is the effect of encoding an image in base64?

Encoding an image to base64 will make it about 30% bigger.

See the details in the wikipedia article about the Data URI scheme, where it states:

Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)

Why is 1/1/1970 the "epoch time"?

Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0 (called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.

Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.

Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.

What does %s and %d mean in printf in the C language?

%(letter) denotes the format type of the replacement text. %s specifies a string, %d an integer, and %c a char.

notifyDataSetChanged not working on RecyclerView

Clear your old viewmodel and set the new data to the adapter and call notifyDataSetChanged()

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

Install NuGet via PowerShell script

  1. Run Powershell with Admin rights
  2. Type the below PowerShell security protocol command for TLS12:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

How can I get the current time in C#?

DateTime.Now.ToShortTimeString().ToString()

This Will give you DateTime as 10:50PM

HTML5 and frameborder

This works

iframe{
    border-width: 0px;
}

php how to go one level up on dirname(__FILE__)

One level up, I have used:

str_replace(basename(__DIR__) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';

or for php < 5.3:

str_replace(basename(dirname(__FILE__)) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';

C++ IDE for Macs

Another (albeit non-free) option is to install VMware Fusion or Parallels Desktop on the Mac and run Windows with Visual Studio in a VM.

This works really pretty well. The downsides are:

  • it'll cost money for the virtual machine software and Windows (the school may have some academic licensing that may help here)
  • the Mac needs to be an x86 Mac with a fair bit of memory

The upside is that you and the student don't need to hassle with differences in the IDE that may not be accounted for in your instruction materials.

How to convert vector to array

std::vector<double> vec;
double* arr = vec.data();

How to find the serial port number on Mac OS X?

Try this: ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

indexOf Case Sensitive?

Converting both strings to lower-case is usually not a big deal but it would be slow if some of the strings is long. And if you do this in a loop then it would be really bad. For this reason, I would recommend indexOfIgnoreCase.

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

Maximum number of threads per process in Linux?

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Javascript communication between browser tabs/windows

For a more modern solution check out https://stackoverflow.com/a/12514384/270274

Quote:

I'm sticking to the shared local data solution mentioned in the question using localStorage. It seems to be the best solution in terms of reliability, performance, and browser compatibility.

localStorage is implemented in all modern browsers.

The storage event fires when other tabs makes changes to localStorage. This is quite handy for communication purposes.

Reference:
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event

How do I login and authenticate to Postgresql after a fresh install?

you can also connect to database as "normal" user (not postgres):

postgres=# \connect opensim Opensim_Tester localhost;

Password for user Opensim_Tester:    

You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"

Detect browser or tab closing

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

How to parse XML in Bash?

This is sufficient...

xpath xhtmlfile.xhtml '/html/head/title/text()' > titleOfXHTMLPage.txt

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

Java List.add() UnsupportedOperationException

instead of using add() we can use addall()

{ seeAlso.addall(groupDn); }

add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.

How to dismiss keyboard for UITextView with return key?

-(BOOL)textFieldShouldReturn:(UITextField *)textField; // called from textfield (keyboard)

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; // good tester function - thanks

Autoplay audio files on an iPad with HTML5

It seems to me that the answer to this question is (at least now) clearly documented on the Safari HTML5 docs:

User Control of Downloads Over Cellular Networks

In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.

This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">

This does nothing on iOS: <body onLoad="document.myMovie.play()">

Determine which MySQL configuration file is being used

mysqld --help --verbose is dangerous. You can easily overwrite pidfile for running instance! use it with --pid-file=XYZ

Oh, and you can't really use it if you have more than 1 instance running. It will only show you default value.

Really good article about it:

How to find MySQL configuration file?

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

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());
      }
   }
}

Detecting a mobile browser

what about using "window.screen.width" ?

if (window.screen.width < 800) {
// do something
}

or

if($(window).width() < 800) {
//do something
}

I guess this is the best way because there is a new mobile device every day !

(although I think it's not that supported in old browsers, but give it a try :) )

grep using a character vector with multiple patterns

Good answers, however don't forget about filter() from dplyr:

patterns <- c("A1", "A9", "A6")
>your_df
  FirstName Letter
1      Alex     A1
2      Alex     A6
3      Alex     A7
4       Bob     A1
5     Chris     A9
6     Chris     A6

result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))

>result
  FirstName Letter
1      Alex     A1
2      Alex     A6
3       Bob     A1
4     Chris     A9
5     Chris     A6

Handling null values in Freemarker

Starting from freemarker 2.3.7, you can use this syntax :

${(object.attribute)!}

or, if you want display a default text when the attribute is null :

${(object.attribute)!"default text"}

Why maven settings.xml file is not there?

I also underwent the same issue as Maven doesn't create the settings.xml file under .m2 folder. What I did was the following and it works smoothly without any issues.

Go to the location where you maven was unzipped.

Direct to following path,

\apache-maven-3.0.4\conf\ and copy the settings.xml file and paste it inside your .m2 folder.

Now create a maven project.

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

Android/Java - Date Difference in days

Most of the answers were good and right for your problem of

so i want to find the difference between date in number of days, how do i find difference in days?

I suggest this very simple and straightforward approach that is guaranteed to give you the correct difference in any time zone:

int difference= 
((int)((startDate.getTime()/(24*60*60*1000))
-(int)(endDate.getTime()/(24*60*60*1000))));

And that's it!

Removing specific rows from a dataframe

One simple solution:

cond1 <- df$sub == 1 & df$day == 2

cond2 <- df$sub == 3 & df$day == 4

df <- df[!(cond1 | cond2),]

Removing the fragment identifier from AngularJS urls (# symbol)

Guess this is reallllly late for this. But adding the below config to the app.module imports does the job:

RouterModule.forRoot(routes, { useHash: false })

Signed to unsigned conversion in C - is it always safe?

Referring to the bible:

  • Your addition operation causes the int to be converted to an unsigned int.
  • Assuming two's complement representation and equally sized types, the bit pattern does not change.
  • Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
  • The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.

Adding an external directory to Tomcat classpath

In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see

set CLASSPATH=%JAVA_HOME%\lib\tools.jar

then in catalina.bat, it's used like so

%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% 
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" 
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" 
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat

set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar

R - test if first occurrence of string1 is followed by string2

> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE

basically, look for everything at the beginning except _, and then the _2.

+1 to @Ananda_Mahto for suggesting grepl instead of grep.

Remove all stylings (border, glow) from textarea

try this:

textarea {
        border-style: none;
        border-color: Transparent;
        overflow: auto;
        outline: none;
      }

jsbin: http://jsbin.com/orozon/2/

How to make a <div> appear in front of regular text/tables

make these changes in your div's style

  1. z-index:100; some higher value makes sure that this element is above all
  2. position:fixed; this makes sure that even if scrolling is done,

div lies on top and always visible

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Swift 3 - Comparing Date objects

Swift 5:

1) If you use Date type:

let firstDate  = Date()
let secondDate = Date()

print(firstDate > secondDate)  
print(firstDate < secondDate)
print(firstDate == secondDate)

2) If you use String type:

let firstStringDate  = "2019-05-22T09:56:00.1111111"
let secondStringDate = "2019-05-22T09:56:00.2222222"

print(firstStringDate > secondStringDate)  // false
print(firstStringDate < secondStringDate)  // true
print(firstStringDate == secondStringDate) // false 

I'm not sure or the second option works at 100%. But how much would I not change the values of firstStringDate and secondStringDate the result was correct.

PostgreSQL Autoincrement

Since PostgreSQL 10

CREATE TABLE test_new (
    id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    payload text
);

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

How to add a new row to datagridview programmatically

An example of copy row from dataGridView and added a new row in The same dataGridView:

DataTable Dt = new DataTable();
Dt.Columns.Add("Column1");
Dt.Columns.Add("Column2");

DataRow dr = Dt.NewRow();
DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
dr[0] = dgvR.Cells[0].Value; 
dr[1] = dgvR.Cells[1].Value;              

Dt.Rows.Add(dR);
dataGridView1.DataSource = Dt;

How to get a variable value if variable name is stored as string?

modern shells already support arrays( and even associative arrays). So please do use them, and use less of eval.

var1="this is the real value"
array=("$var1")
# or array[0]="$var1"

then when you want to call it , echo ${array[0]}

Good beginners tutorial to socket.io?

A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)

http://browserquest.mozilla.org/

https://github.com/mozilla/BrowserQuest

Filter multiple values on a string column in dplyr

Using the base package:

df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))

# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]

# One line
df[df$name %in% c("Tom", "Lynn"), ] 

Output:

  days name
1   88 Lynn
2   11  Tom
6    1  Tom
7  222 Lynn
8    2 Lynn

Using sqldf:

library(sqldf)
# Two alternatives:
sqldf('SELECT *
      FROM df 
      WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
      FROM df 
      WHERE name IN ("Tom", "Lynn")')

Matplotlib 2 Subplots, 1 Colorbar

To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow instead of pcolormesh because of the 1:1 aspect ratio imposed by imshow.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
    im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.flat)
plt.show()

enter image description here

How do I make Git use the editor of my choice for commits?

For Mac OS X, using TextEdit or the natural environmental editor for text:

git config --global core.editor "open -W -n"

Setting a system environment variable from a Windows batch file?

The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:

C:\Program Files\Support Tools>setx /?

SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.

1) Command Line Mode: setx variable value [-m]
   Optional Switches:
    -m  Set value in the Machine environment. Default is User.

...
For more information and example use: SETX -i

I think Windows 7 actually comes with setx as part of a standard install.

How do I get multiple subplots in matplotlib?

read the documentation: matplotlib.pyplot.subplots

pyplot.subplots() returns a tuple fig, ax which is unpacked in two variables using the notation

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

the code

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

does not work because subplots()is a function in pyplot not a member of the object Figure.

Git: list only "untracked" files (also, custom commands)

All previous answers which I checked would list the files to be committed, too. Here is a simple and easy solution that only lists files which are not yet in the repo and not subject to .gitignore.

git status --porcelain | awk '/^\?\?/ { print $2; }'

or

git status --porcelain | grep -v '\?\?'

What is the equivalent of Java static methods in Kotlin?

Docs recommends to solve most of the needs for static functions with package-level functions. They are simply declared outside a class in a source code file. The package of a file can be specified at the beginning of a file with the package keyword.

Declaration

package foo

fun bar() = {}

Usage

import foo.bar

Alternatively

import foo.*

You can now call the function with:

bar()

or if you do not use the import keyword:

foo.bar()

If you do not specify the package the function will be accessible from the root.

If you only have experience with java, this might seem a little strange. The reason is that kotlin is not a strictly object-oriented language. You could say it supports methods outside of classes.

Edit: They have edited the documentation to no longer include the sentence about recommending package level functions. This is the original that was referred to above.

Android/Eclipse: how can I add an image in the res/drawable folder?

Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.

How to create EditText with rounded corners?

Thanks for Norfeldt's answer. I slightly changed its gradient for a better inner shadow effect.

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient
            android:centerY="0.2"
            android:startColor="#D3D3D3"
            android:centerColor="#65FFFFFF"
            android:endColor="#00FFFFFF"
            android:angle="270"
            />
        <stroke
            android:width="0.7dp"
            android:color="#BDBDBD" />
        <corners
            android:radius="15dp" />
    </shape>
</item>

Looks great in a light backgrounded layout..

enter image description here

How to set a selected option of a dropdown list control using angular JS

I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.

You can use track by attribute in your ng-options.

Assume that you have:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

You can mention your ng-options as:

ng-options="v.name for v in variants track by v.id"

Hope this helps someone in future.

Are there .NET implementation of TLS 1.2?

If you are dealing with older versions of .NET Framework, then support for TLS 1.2 is available in our SecureBlackbox product in both client and server components. SecureBlackbox contains its own implementation of all algorithms, so it doesn't matter which version of .NET-based framework you use (including .NET CF) - you'll have TLS 1.2 with the latest additions in all cases.

Please note that SecureBlackbox wont magically add TLS 1.2 to framework classes - instead you need to use SecureBlackbox classes and components explicitly.

scrollIntoView Scrolls just too far

Building on an earlier answer, I am doing this in an Angular5 project.

Started with:

// el.scrollIntoView(true);
el.scrollIntoView({
   behavior: 'smooth',
   block: 'start'
});
window.scrollBy(0, -10); 

But this gave some problems and needed to setTimeout for the scrollBy() like this:

//window.scrollBy(0,-10);
setTimeout(() => {
  window.scrollBy(0,-10)
  }, 500);

And it works perfectly in MSIE11 and Chrome 68+. I have not tested in FF. 500ms was the shortest delay I would venture. Going lower sometimes failed as the smooth scroll had not yet completed. Adjust as required for your own project.

+1 to Fred727 for this simple but effective solution.

what is the use of Eval() in asp.net

IrishChieftain didn't really address the question, so here's my take:

eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

Tips for using Vim as a Java IDE?

Use vim. ^-^ (gVim, to be precise)

You'll have it all (with some plugins).

Btw, snippetsEmu is a nice tool for coding with useful snippets (like in TextMate). You can use (or modify) a pre-made package or make your own.

Getting the ID of the element that fired an event

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });

Convert a Unicode string to a string in Python (containing extra symbols)

Well, if you're willing/ready to switch to Python 3 (which you may not be due to the backwards incompatibility with some Python 2 code), you don't have to do any converting; all text in Python 3 is represented with Unicode strings, which also means that there's no more usage of the u'<text>' syntax. You also have what are, in effect, strings of bytes, which are used to represent data (which may be an encoded string).

http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(Of course, if you're currently using Python 3, then the problem is likely something to do with how you're attempting to save the text to a file.)

Collection that allows only unique items in .NET?

From the HashSet<T> page on MSDN:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

(emphasis mine)

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.

how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;

PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0

(swedish translated: 'It is not possible to find the module' )

in this perticular case, the php.ini was: extension_dir = "C:/php"

the dll is put in two places C:\php and C:\php\ext

IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??

jquery toggle slide from left to right and back

See this: Demo

$('#cat_icon,.panel_title').click(function () {
   $('#categories,#cat_icon').stop().slideToggle('slow');
});

Update : To slide from left to right: Demo2

Note: Second one uses jquery-ui also

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Convert date formats in bash

If you would like a bash function that works both on Mac OS X and Linux:

#
# Convert one date format to another
# 
# Usage: convert_date_format <input_format> <date> <output_format>
#
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
convert_date_format() {
  local INPUT_FORMAT="$1"
  local INPUT_DATE="$2"
  local OUTPUT_FORMAT="$3"
  local UNAME=$(uname)

  if [[ "$UNAME" == "Darwin" ]]; then
    # Mac OS X
    date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT"
  elif [[ "$UNAME" == "Linux" ]]; then
    # Linux
    date -d "$INPUT_DATE" +"$OUTPUT_FORMAT"
  else
    # Unsupported system
    echo "Unsupported system"
  fi
}

# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10'
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'

How do I concatenate strings?

Simple ways to concatenate strings in Rust

There are various methods available in Rust to concatenate strings

First method (Using concat!() ):

fn main() {
    println!("{}", concat!("a", "b"))
}

The output of the above code is :

ab


Second method (using push_str() and + operator):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = "c".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

    println!("{}", _a + &_c);
}

The output of the above code is:

ab

abc


Third method (Using format!()):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = format!("{}{}", _a, _b);

    println!("{}", _c);
}

The output of the above code is :

ab

Check it out and experiment with Rust playground.

How to pass a form input value into a JavaScript function

Use onclick="foo(document.getElementById('formValueId').value)"

Angular2 RC6: '<component> is not a known element'

I fetch same problem for <flash-messages></flash-messages> with angular 5.

You just need add below lines in app.module.ts file

import { ---, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FlashMessageModule } from "angular-flash-message";


@NgModule({
  ---------------
  imports: [
    FlashMessageModule,
    ------------------         
  ], 
  -----------------
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  ------------
})

NB: I am using this one for message flash-messages

PHP fwrite new line

How about you store it like this? Maybe in username:password format, so

sebastion:password123
anotheruser:password321

Then you can use list($username,$password) = explode(':',file_get_contents('users.txt')); to parse the data on your end.

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

jQuery form input select by id

You can do that using the descendant selectors:

 $("#a #b")

However, id values are supposed to be unique on a page.

Is it possible to send a variable number of arguments to a JavaScript function?

Yes you can pass variable no. of arguments to a function. You can use apply to achieve this.

E.g.:

var arr = ["Hi","How","are","you"];

function applyTest(){
    var arg = arguments.length;
    console.log(arg);
}

applyTest.apply(null,arr);

How to disassemble a memory range with GDB?

gdb disassemble has a /m to include source code alongside the instructions. This is equivalent of objdump -S, with the extra benefit of confining to just the one function (or address-range) of interest.

How to INNER JOIN 3 tables using CodeIgniter

function fetch_comments($ticket_id){
    $this->db->select('tbl_tickets_replies.comments, 
           tbl_users.username,tbl_roles.role_name');
    $this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
    $this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
    $this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
    return $this->db->get('tbl_tickets_replies');
}

Convert Time DataType into AM PM Format:

Multiple functions, but this will give you what you need (tested on SQL Server 2008)

Edit: The following works not only for a time type, but for a datetime as well.

SELECT SUBSTRING(CONVERT(varchar(20),StartTime,22), 10, 11) AS Start, SUBSTRING(CONVERT(varchar(20),EndTime,22), 10, 11) AS End FROM [TableA];

How to create a GUID in Excel?

The formula for Polish version:

=ZLACZ.TEKSTY(
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4)
)

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

Initialise numpy array of unknown length

You can do this:

a = np.array([])
for x in y:
    a = np.append(a, x)

Objective-C : BOOL vs bool

Yup, BOOL is a typedef for a signed char according to objc.h.

I don't know about bool, though. That's a C++ thing, right? If it's defined as a signed char where 1 is YES/true and 0 is NO/false, then I imagine it doesn't matter which one you use.

Since BOOL is part of Objective-C, though, it probably makes more sense to use a BOOL for clarity (other Objective-C developers might be puzzled if they see a bool in use).

OAuth: how to test with local URLs?

You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts

localhost name resolution is handled within DNS itself.

127.0.0.1 mywebsite.com

after you finish your tests you just comment the line you add to disable it

127.0.0.1 mywebsite.com

Generating an MD5 checksum of a file

hashlib.md5(pathlib.Path('path/to/file').read_bytes()).hexdigest()

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

MySQL with Node.js

connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.

npm install [email protected]

var http = require('http'),
   mysql = require('mysql');

var sqlInfo = {
   host: 'localhost',
   user: 'root',
   password: 'urpass',
   database: 'dbname'
}
client = mysql.createConnection(sqlInfo);

client.connect();

For NodeJS mysql connecting and querying example

How can I center a div within another div?

To make a div in center. There isn't any need to assign the width of the div.

A working demo is here:

http://jsfiddle.net/6yukdmwq/

    .container {
        width: 100%;
        height: 500px;
        display: table;
        border: 1px solid red;
        text-align: center;}

    .center {
        display: table-cell;
        vertical-align: middle;
    }

    .content {
        display: inline-block;
        text-align: center;
        border: 1px solid green;
    }
    <section class="container">
        <div class="center">
            <div class="content">
                <h1>Helllo Center Text</h1>
            </div>
        </div>
    </section>

Reading HTML content from a UIWebView

(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

Android : How to set onClick event for Button in List item of ListView

In Adapter Class

public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = getLayoutInflater();
    View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
    Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
    deleteImageView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //...
        }
    });
}

But you can get an issue - listView row not clickable. Solution:

  • make ListView focusable android:focusable="true"
  • Button not focusable android:focusable="false"

How to enable Google Play App Signing

Do the following :

"CREATE APPLICATION" having the same name which you want to upload before.
Click create.
After creation of the app now click on the "App releases"
Click on the "MANAGE PRODUCTION"
Click on the "CREATE RELEASE"
Here you see "Google Play App Signing" dialog.
Just click on the "OPT-OUT" button.
It will ask you to confirm it. Just click on the "confirm" button

Open web in new tab Selenium + Python

In a discussion, Simon clearly mentioned that:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.


Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2) and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened) as required. Here is a solution where you can open http://www.google.co.in in the initial TAB and https://www.yahoo.com in the adjacent TAB:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("http://www.google.co.in")
    print("Initial Page Title is : %s" %driver.title)
    windows_before  = driver.current_window_handle
    print("First Window Handle is : %s" %windows_before)
    driver.execute_script("window.open('https://www.yahoo.com')")
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to_window(new_window)
    print("Page Title after Tab Switching is : %s" %driver.title)
    print("Second Window Handle is : %s" %new_window)
    
  • Console Output:

    Initial Page Title is : Google
    First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
    Page Title after Tab Switching is : Yahoo
    Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
    
  • Browser Snapshot:

multiple__tabs


Outro

You can find the based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

For me better this:

var uA = window.navigator.userAgent,
    onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
    checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;

Go run: http://output.jsbin.com/solicul/1/ o http://jsfiddle.net/Webnewbie/apa1nvu8/

How to recover stashed uncommitted changes

The easy answer to the easy question is git stash apply

Just check out the branch you want your changes on, and then git stash apply. Then use git diff to see the result.

After you're all done with your changes—the apply looks good and you're sure you don't need the stash any more—then use git stash drop to get rid of it.

I always suggest using git stash apply rather than git stash pop. The difference is that apply leaves the stash around for easy re-try of the apply, or for looking at, etc. If pop is able to extract the stash, it will immediately also drop it, and if you the suddenly realize that you wanted to extract it somewhere else (in a different branch), or with --index, or some such, that's not so easy. If you apply, you get to choose when to drop.

It's all pretty minor one way or the other though, and for a newbie to git, it should be about the same. (And you can skip all the rest of this!)


What if you're doing more-advanced or more-complicated stuff?

There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":

  1. You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.

    This is the easy case, described above. Run git stash save (or plain git stash, same thing). Check out the other branch and use git stash apply. This gets git to merge in your earlier changes, using git's rather powerful merge mechanism. Inspect the results carefully (with git diff) to see if you like them, and if you do, use git stash drop to drop the stash. You're done!

  2. You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.

    Now you want to keep, or even move, these changes, and apply your stash too.

    You can in fact git stash save again, as git stash makes a "stack" of changes. If you do that you have two stashes, one just called stash—but you can also write stash@{0}—and one spelled stash@{1}. Use git stash list (at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop, it drops the newest, and the one that was stash@{1} moves to the top of the stack. If you had even more, the one that was stash@{2} becomes stash@{1}, and so on.

    You can apply and then drop a specific stash, too: git stash apply stash@{2}, and so on. Dropping a specific stash, renumbers only the higher-numbered ones. Again, the one without a number is also stash@{0}.

    If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@{7} or was it stash@{4}? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December means a lot more to me than stash@{12}. (The git stash command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch.)

  3. (Extra-advanced) You've used git stash save -p, or carefully git add-ed and/or git rm-ed specific bits of your code before running git stash save. You had one version in the stashed index/staging area, and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index, and that sometimes fails with:

    Conflicts in index.  Try without --index.
    
  4. You're using git stash save --keep-index in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.

For complicated cases, I recommend starting in a "clean" working directory first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:

git status               # see if there's anything you need to commit
                         # uh oh, there is - let's put it on a new temp branch
git checkout -b temp     # create new temp branch to save stuff
git add ...              # add (and/or remove) stuff as needed
git commit               # save first set of changes

Now you're on a "clean" starting point. Or maybe it goes more like this:

git status               # see if there's anything you need to commit
                         # status says "nothing to commit"
git checkout -b temp     # optional: create new branch for "apply"
git stash apply          # apply stashed changes; see below about --index

The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply operation looks at what the commit changed, and tries to repeat it wherever you are now. The stash will still be there (apply keeps it around), so you can look at it more, or decide this was the wrong place to apply it and try again differently, or whatever.


Any time you have a stash, you can use git stash show -p to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index restores separately.) The command git stash apply, without --index, just tries to make those same changes in your work-directory now.

This is true even if you already have some changes. The apply command is happy to apply a stash to a modified working directory (or at least, to try to apply it). You can, for instance, do this:

git stash apply stash      # apply top of stash stack
git stash apply stash@{1}  # and mix in next stash stack entry too

You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:

Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.

If you start with a clean directory and are just doing several git apply operations, it's easy to back out: use git reset --hard to get back to the clean state, and change your apply operations. (That's why I recommend starting in a clean working directory first, for these complicated cases.)


What about the very worst possible case?

Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index, but it's no longer possible to apply the saved stash with --index, because the branch has diverged too much since the time you saved it.

This is what git stash branch is for.

If you:

  1. check out the exact commit you were on when you did the original stash, then
  2. create a new branch, and finally
  3. git stash apply --index

the attempt to re-create the changes definitely will work. This is what git stash branch newbranch does. (And it then drops the stash since it was successfully applied.)


Some final words about --index (what the heck is it?)

What the --index does is simple to explain, but a bit complicated internally:

  • When you have changes, you have to git add (or "stage") them before commiting.
  • Thus, when you ran git stash, you might have edited both files foo and zorg, but only staged one of those.
  • So when you ask to get the stash back, it might be nice if it git adds the added things and does not git add the non-added things. That is, if you added foo but not zorg back before you did the stash, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.

The --index flag to apply tries to set things up this way. If your work-tree is clean, this usually just works. If your work-tree already has stuff added, though, you can see how there might be some problems here. If you leave out --index, the apply operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes git's merge machinery, using the work-tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index makes it a lot easier for git stash apply to do its thing.

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

How do I change the value of a global variable inside of a function

var a = 10;

myFunction();

function myFunction(){
   a = 20;
}

alert("Value of 'a' outside the function " + a); //outputs 20

How do I format XML in Notepad++?

You can find details here To Quickly Format XML using Pretty Print (libXML)

Installing the XML Tools

If you run Notepad++ and look in the Plugins menu, you’ll see that the XML Tools aren’t there:

  1. Download the XML tools from here.

  2. Unzip the file and copy the XMLTools.dll to the Notepad++ plugins folder (in the example above: C:\Program Files (x86)\Notepad++\plugins):

  3. Re-start Notepad++ and you should now see the XMLTools appear in the Plugins menu.

  4. Unzip the ext_libs.zip file and then copy the unzipped DLLs to the Notepad++ installation directory (in the example above: C:\Program Files (x86)\Notepad++).

  5. Re-start Notepad++ and you should finally see the proper XML Tools menu.

  6. The feature I use the most is “Pretty print (XML only – with line breaks)”. This will format any piece of XML with all the proper line spacing.

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

passing argument to DialogFragment

Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:

so you have to create a companion objet to create new newInstance function

you can set the paremter of the function whatever you want. using

 val args = Bundle()

you can set your args.

You can now use args.putSomthing to add you args which u give as a prameter in your newInstance function. putString(key:String,str:String) to add string for example and so on

Now to get the argument you can use arguments.getSomthing(Key:String)=> like arguments.getString("1")

here is a full example

class IntervModifFragment : DialogFragment(), ModContract.View
{
    companion object {
        fun newInstance(  plom:String,type:String,position: Int):IntervModifFragment {
            val fragment =IntervModifFragment()
            val args = Bundle()
            args.putString( "1",plom)
            args.putString("2",type)
            args.putInt("3",position)
            fragment.arguments = args
            return fragment
        }
    }

...
    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fillSpinerPlom(view,arguments.getString("1"))
         fillSpinerType(view, arguments.getString("2"))
        confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})


        val dateSetListener = object : DatePickerDialog.OnDateSetListener {
            override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
                                   dayOfMonth: Int) {
                val datep= DateT(year,monthOfYear,dayOfMonth)
                updateDateInView(datep.date)
            }
        }

    }
  ...
}

Now how to create your dialog you can do somthing like this in another class

  val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)

like this for example

class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
   ... 
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        ...
        holder.btn_update!!.setOnClickListener {
           val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
           val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
            dialog.show(ft, ContentValues.TAG)
        }
        ...
    }
..

}

The differences between initialize, define, declare a variable

For C, at least, per C11 6.7.5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

  • for an object, causes storage to be reserved for that object;

  • for a function, includes the function body;

  • for an enumeration constant, is the (only) declaration of the identifier;

  • for a typedef name, is the first (or only) declaration of the identifier.

Per C11 6.7.9.8-10:

An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.

So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.

Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).

So, if you define an automatic variable without specifying an initial value for it, such as:

int myfunc(void) {
    int myvar;
    ...

You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.

TypeError: 'undefined' is not a function (evaluating '$(document)')

Use jQuery's noConflict. It did wonders for me

var example=jQuery.noConflict();
example(function(){
example('div#rift_connect').click(function(){
    example('span#resultado').text("Hello, dude!");
    });
});

That is, assuming you included jQuery on your HTML

<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

how to insert date and time in oracle?

Try this:

...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));

Convert List(of object) to List(of string)

Can you do the string conversion while the List(of object) is being built? This would be the only way to avoid enumerating the whole list after the List(of object) was created.

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

Get HTML inside iframe using jQuery

var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();

Deserializing a JSON file with JavaScriptSerializer()

Create a sub-class User with an id field and screen_name field, like this:

public class User
{
    public string id { get; set; }
    public string screen_name { get; set; }
}

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }
    public User user { get; set; }
}

Clear form fields with jQuery

Why does it need to be done with any JavaScript at all?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


Tried that one first, it won't clear fields with default values.

Here's a way to do it with jQuery, then:

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});

Using "margin: 0 auto;" in Internet Explorer 8

As far as this being a "bug" with relation to the spec; it isn't. As the author of the post questions, the behaviour for this would be "undefined" since this behaviour in IE only happens on form controls, as per spec:

CSS 2.1 does not define which properties apply to form controls and frames, or how CSS can be used to style them. User agents may apply CSS properties to these elements. Authors are recommended to treat such support as experimental.

( http://www.w3.org/TR/CSS21/conform.html#conformance )

Cheers!

Add resources, config files to your jar using gradle

I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).

None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle file :

sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]

It tells Gradle to look for resources in the src folder, and ask it to include only PNG files.

EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/ for example, and to set it as srcDirs instead of src/.

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Cross domain POST request is not sending cookie Ajax Jquery

There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

To have a cookie sent by the browser to another site during a request the following criteria must be met:

A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

How to change DataTable columns order

I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.

Virtualbox shared folder permissions

In my personal experience, it's difficult to enable shared folders in VirtualBox but it Is posible. I have a debian Buster guest virtual machine installed in my Windows 10 host.

I don't recognize exactly what did it, but I remember I went to Windows defender, my antivirus to see if they recognize VirtualBox as a program and not as a virus. After that, I press right click on the document file and allowed to share the folder and I gave click to some buttons there and accepted to share with groups and with muy user in Windows 10.

Also, I found a webpage of Windows about something like virtual machines that I don't remember well, but it took me to a panel and I had to change three things double clicking so when I update Windows, it recognizes my virtual machine. Also, in muy debian, in the terminal, using some command lines, muy VirtualBox recognized my user giving permissions, I based on some info in the Ubuntu forums. I put all what I remember.

Clearing coverage highlighting in Eclipse

Close the IDE and open it again. This works if you did not use any code coverage tools and have just clicked the basic "Coverage" icon in the IDE.

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

TypeError: Image data can not convert to float

The problem was that my array was in type u3 i changed it to float and it worked for me . I had a dataframe with Image column having the image/pic data.Reshaping part depends to person to person and image they deal with mine had 9126 size hence it was 96*96.

a = np.array(df_train.iloc[0].Image.split(),dtype='float')
a = a.reshape(96,96)
plt.imshow(a)

In a Git repository, how to properly rename a directory?

For case sensitive renaming, git mv somefolder someFolder has worked for me before but didn't today for some reason. So as a workaround I created a new folder temp, moved all the contents of somefolder into temp, deleted somefolder, committed the temp, then created someFolder, moved all the contents of temp into someFolder, deleted temp, committed and pushed someFolder and it worked! Shows up as someFolder in git.

What is the difference between `throw new Error` and `throw someObject`?

throw "I'm Evil"

throw will terminate the further execution & expose message string on catch the error.

_x000D_
_x000D_
try {
  throw "I'm Evil"
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e); // I'm Evil
}
_x000D_
_x000D_
_x000D_

Console after throw will never be reached cause of termination.


throw new Error("I'm Evil")

throw new Error exposes an error event with two params name & message. It also terminate further execution

_x000D_
_x000D_
try {
  throw new Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
_x000D_
_x000D_

throw Error("I'm Evil")

And just for completeness, this works also, though is not technically the correct way to do it -

_x000D_
_x000D_
try {
  throw Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
_x000D_
_x000D_

Use a URL to link to a Google map with a marker on it

This URL format worked like a charm:

http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}

Example for Mount Everest:

http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141

Preview

Full reference here:

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

-- EDIT --

Apparently the zoom parameter stopped working, here's the updated format.

Format

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center={LAT},{LONG}&zoom={ZOOM}

Example

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center=27.9879012,86.9253141&zoom=14

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

No Access-Control-Allow-Origin header is present on the requested resource

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

What does 'git blame' do?

The git blame command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame", especially in a linear history (which is the norm we should optimize for).

See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre). (Merged by Junio C Hamano -- gitster -- in commit 4d8c4da, 25 Apr 2019)

blame.c: don't drop origin blobs as eagerly

When a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.

Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.

bitwise XOR of hex numbers in python

If the two hex strings are the same length and you want a hex string output then you might try this.

def hexxor(a, b):    # xor two hex strings of the same length
    return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

There is also th:classappend.

<a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>

If isAdmin is true, then this will result in:

<a href="" class="baseclass adminclass"></a>

How to calculate the bounding box for a given lat/lng location?

You're looking for an ellipsoid formula.

The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN. It gives you a baseline to create your tests off of and to compare your results with its results. I used it as the basis for a similar library for PHP at my previous employer.

Geo::Ellipsoid

Take a look at the location method. Call it twice and you've got your bbox.

You didn't post what language you were using. There may already be a geocoding library available for you.

Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.

How to add jQuery in JS file

/* Adding the script tag to the head as suggested before */

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://code.jquery.com/jquery-2.2.1.min.js";

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = handler;
    script.onload = handler;

    // Fire the loading
    head.appendChild(script);

    function handler(){
       console.log('jquery added :)');
    }

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I unplugged my cable and saw this. After it reached the end I was able to run it no problems.

Xcode screenshot of status bar showing "Preparing debugger support"

You don't have to unplug to see this; just hit cancel and you will see its progress.

Android - drawable with rounded corners at the top only

You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

and below there is a Note.

Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

Subtract two dates in Java

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date2));

long diff = d2.getTime() - d1.getTime();

System.out.println("Difference between  " + d1 + " and "+ d2+" is "
        + (diff / (1000 * 60 * 60 * 24)) + " days.");

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A and then Ctrl+D. Doing this will detach you from the screen session which you can later resume by doing screen -r.

  • You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach to be detached from the running screen session.

Using regular expressions to do mass replace in Notepad++ and Vim

There are two problems with your original solution. Firstly, your example text:

<option value value='1' >A

has two occurences of the "value" word. Your regex does not. Also, you need to escape the opening brace in the quantifier of your regex or Vim will interpret it as a literal brace. This regex works:

:%s/<option value value='.\{1,}' >//g

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

Table 'performance_schema.session_variables' doesn't exist

I was able to log on to the mysql server after running the command @robregonm suggested:

mysql_upgrade -u root -p --force

A MySQL server restart is required.

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

jQuery & CSS - Remove/Add display:none

jQuery provides you with:

$(".news").hide();
$(".news").show();

You can then easily show and hide the element(s).

Total size of the contents of all the files in a directory

If you use busybox's "du" in emebedded system, you can not get a exact bytes with du, only Kbytes you can get.

BusyBox v1.4.1 (2007-11-30 20:37:49 EST) multi-call binary

Usage: du [-aHLdclsxhmk] [FILE]...

Summarize disk space used for each FILE and/or directory.
Disk space is printed in units of 1024 bytes.

Options:
        -a      Show sizes of files in addition to directories
        -H      Follow symbolic links that are FILE command line args
        -L      Follow all symbolic links encountered
        -d N    Limit output to directories (and files with -a) of depth < N
        -c      Output a grand total
        -l      Count sizes many times if hard linked
        -s      Display only a total for each argument
        -x      Skip directories on different filesystems
        -h      Print sizes in human readable format (e.g., 1K 243M 2G )
        -m      Print sizes in megabytes
        -k      Print sizes in kilobytes(default)

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

How to set the DefaultRoute to another Route in React Router

UPDATE : 2020

Instead of using Redirect, Simply add multiple route in the path

Example:

<Route exact path={["/","/defaultPath"]} component={searchDashboard} />

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

How to get the version of ionic framework?

Running ionic info on your project directory give all the info you need the npm version, cli, app script and some more

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

I made the following filter:

angular.module('app').filter('ifEmpty', function() {
    return function(input, defaultValue) {
        if (angular.isUndefined(input) || input === null || input === '') {
            return defaultValue;
        }

        return input;
    }
});

To be used like this:

<span>{{aPrice | currency | ifEmpty:'N/A'}}</span>
<span>{{aNum | number:3 | ifEmpty:0}}</span>

Extract images from PDF without resampling, in python?

In Python with PyPDF2 for CCITTFaxDecode filter:

import PyPDF2
import struct

"""
Links:
PDF format: http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
CCITT Group 4: https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.6-198811-I!!PDF-E&type=items
Extract images from pdf: http://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-python
Extract images coded with CCITTFaxDecode in .net: http://stackoverflow.com/questions/2641770/extracting-image-from-pdf-with-ccittfaxdecode-filter
TIFF format and tags: http://www.awaresystems.be/imaging/tiff/faq.html
"""


def tiff_header_for_CCITT(width, height, img_size, CCITT_group=4):
    tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
    return struct.pack(tiff_header_struct,
                       b'II',  # Byte order indication: Little indian
                       42,  # Version number (always 42)
                       8,  # Offset to first IFD
                       8,  # Number of tags in IFD
                       256, 4, 1, width,  # ImageWidth, LONG, 1, width
                       257, 4, 1, height,  # ImageLength, LONG, 1, lenght
                       258, 3, 1, 1,  # BitsPerSample, SHORT, 1, 1
                       259, 3, 1, CCITT_group,  # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding
                       262, 3, 1, 0,  # Threshholding, SHORT, 1, 0 = WhiteIsZero
                       273, 4, 1, struct.calcsize(tiff_header_struct),  # StripOffsets, LONG, 1, len of header
                       278, 4, 1, height,  # RowsPerStrip, LONG, 1, lenght
                       279, 4, 1, img_size,  # StripByteCounts, LONG, 1, size of image
                       0  # last IFD
                       )

pdf_filename = 'scan.pdf'
pdf_file = open(pdf_filename, 'rb')
cond_scan_reader = PyPDF2.PdfFileReader(pdf_file)
for i in range(0, cond_scan_reader.getNumPages()):
    page = cond_scan_reader.getPage(i)
    xObject = page['/Resources']['/XObject'].getObject()
    for obj in xObject:
        if xObject[obj]['/Subtype'] == '/Image':
            """
            The  CCITTFaxDecode filter decodes image data that has been encoded using
            either Group 3 or Group 4 CCITT facsimile (fax) encoding. CCITT encoding is
            designed to achieve efficient compression of monochrome (1 bit per pixel) image
            data at relatively low resolutions, and so is useful only for bitmap image data, not
            for color images, grayscale images, or general data.

            K < 0 --- Pure two-dimensional encoding (Group 4)
            K = 0 --- Pure one-dimensional encoding (Group 3, 1-D)
            K > 0 --- Mixed one- and two-dimensional encoding (Group 3, 2-D)
            """
            if xObject[obj]['/Filter'] == '/CCITTFaxDecode':
                if xObject[obj]['/DecodeParms']['/K'] == -1:
                    CCITT_group = 4
                else:
                    CCITT_group = 3
                width = xObject[obj]['/Width']
                height = xObject[obj]['/Height']
                data = xObject[obj]._data  # sorry, getData() does not work for CCITTFaxDecode
                img_size = len(data)
                tiff_header = tiff_header_for_CCITT(width, height, img_size, CCITT_group)
                img_name = obj[1:] + '.tiff'
                with open(img_name, 'wb') as img_file:
                    img_file.write(tiff_header + data)
                #
                # import io
                # from PIL import Image
                # im = Image.open(io.BytesIO(tiff_header + data))
pdf_file.close()

How to change values in a tuple?

You can't. If you want to change it, you need to use a list instead of a tuple.

Note that you could instead make a new tuple that has the new value as its first element.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How to use gitignore command in git

If you don't have a .gitignore file. You can create a new one by

touch .gitignore

And you can exclude a folder by entering the below command in the .gitignore file

/folderName

push this file into your git repository so that when a new person clone your project he don't have to add the same again

How to clear or stop timeInterval in angularjs?

var interval = $interval(function() {
  console.log('say hello');
}, 1000);

$interval.cancel(interval);

How to delete a cookie?

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");

How do I download a tarball from GitHub using cURL?

You can also use wget to »untar it inline«. Simply specify stdout as the output file (-O -):

wget --no-check-certificate https://github.com/pinard/Pymacs/tarball/v0.24-beta2 -O - | tar xz