Programs & Examples On #Auto compile

Vim clear last search highlighting

I personnaly like to map esc to the command :noh as follow:

map <esc> :noh<cr>

I wrote a whole article recently about Vim search: how to search on vanilla Vim and the best plugin to enhance the search features.

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

Simple way to calculate median with MySQL

After reading all previous ones they didn't match with my actual requirement so I implemented my own one which doesn't need any procedure or complicate statements, just I GROUP_CONCAT all values from the column I wanted to obtain the MEDIAN and applying a COUNT DIV BY 2 I extract the value in from the middle of the list like the following query does :

(POS is the name of the column I want to get its median)

(query) SELECT
SUBSTRING_INDEX ( 
   SUBSTRING_INDEX ( 
       GROUP_CONCAT(pos ORDER BY CAST(pos AS SIGNED INTEGER) desc SEPARATOR ';') 
    , ';', COUNT(*)/2 ) 
, ';', -1 ) AS `pos_med`
FROM table_name
GROUP BY any_criterial

I hope this could be useful for someone in the way many of other comments were for me from this website.

Play audio file from the assets directory

Here my static version:

public static void playAssetSound(Context context, String soundFileName) {
    try {
        MediaPlayer mediaPlayer = new MediaPlayer();

        AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
        mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        mediaPlayer.prepare();
        mediaPlayer.setVolume(1f, 1f);
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Cross-browser window resize event - JavaScript / jQuery

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

How to initialize java.util.date to empty

It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.

How to make jQuery UI nav menu horizontal?

I'm new to stackoverflow, so please be nice :) however turning to the problem of horizontal jQuery ui menu, the only way I could manage to resolve the problem (refering to this) was to set:

#nav li {width: auto; clear: none; float: left}
#nav ul li {width: auto; clear: none; float:none}

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

How to sort an array of ints using a custom comparator?

I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.

public class ArrSortComptr {
    public static void main(String[] args) {

         int[] array = { 3, 2, 1, 5, 8, 6 };
         int[] sortedArr=SortPrimitiveInt(new intComp(),array);
         System.out.println("InPut "+ Arrays.toString(array));
         System.out.println("OutPut "+ Arrays.toString(sortedArr));

    }
 static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
 {
    Integer[] objInt=intToObject(arr);
    Arrays.sort(objInt,com);
    return intObjToPrimitive(objInt);

 }
 static Integer[] intToObject(int ... arr)
 {
    Integer[] a=new Integer[arr.length];
    int cnt=0;
    for(int val:arr)
      a[cnt++]=new Integer(val);
    return a;
 }
 static int[] intObjToPrimitive(Integer ... arr)
 {
     int[] a=new int[arr.length];
     int cnt=0;
     for(Integer val:arr)
         if(val!=null)
             a[cnt++]=val.intValue();
     return a;

 }

}
class intComp implements Comparator<Integer>
{

    @Override //your comparator implementation.
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        return o1.compareTo(o2);
    }

}

@Roman: I can't say that this is a good example but since you asked this is what came to my mind. Suppose in an array you want to sort number's just based on their absolute value.

Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);

Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.

How to download a folder from github?

If you want to automate the steps, the suggestions here will work only to an extent.

I came across this tool called fetch and it worked quite fine for me. You can even specify the release. So, it takes a step to download and set it as executable, then fetch the required folder:

curl -sSLfo ./fetch \
https://github.com/gruntwork-io/fetch/releases/download/v0.3.12/fetch_linux_amd64
chmod +x ./fetch
./fetch --repo="https://github.com/foo/bar" --tag="${VERSION}" --source-path="/baz" /tmp/baz

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

How to get numeric value from a prompt box?

parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.

Syntax:

 parseInt(string, radix);
 parseFloat(string); 
  • string: the string expression to be parsed as a number.
  • radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.

Example:

 var x = prompt("Enter a Value", "0");
 var y = prompt("Enter a Value", "0");
 var num1 = parseInt(x);
 var num2 = parseInt(y);

After this you can perform which ever calculations you want on them.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

How to use sys.exit() in Python

I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

How can I fill a div with an image while keeping it proportional?

It's a bit late but I just had the same problem and finally solved it with the help of another stackoverflow post (https://stackoverflow.com/a/29103071).

img {
   object-fit: cover;
   width: 50px;
   height: 100px;
}

Hope this still helps somebody.

Ps: Also works together with max-height, max-width, min-width and min-height css properties. It's espacially handy with using lenght units like 100% or 100vh/100vw to fill the container or the whole browser window.

How do I count unique values inside a list

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

Do you have to put Task.Run in a method to make it async?

When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.

However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.

True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html

In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description) values ((select count(1)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES');

Note : here need to use count(1) in place of max(id) column

It perfectly works for an empty table also.

Change Image of ImageView programmatically in Android

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down);

Here's a thread that talks about the differences between the two methods.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this issue but had a different fix. It involved updating the Control Panel>Administrative Tools>IIS Manager and reverting my App site's Managed Pipeline from Integrated to Classic.

How to reset AUTO_INCREMENT in MySQL?

enter image description hereThere is a very easy way with phpmyadmin under the "operations" tab, you can set, in the table options, autoincrement to the number you want.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error might be caused by the jQuery event-aliases like .load(), .unload() or .error() that all are deprecated since jQuery 1.8. Lookup for these aliases in your code and replace them with the .on() method instead. For example, replace the following deprecated excerpt:

$(window).load(function(){...});

with the following:

$(window).on('load', function(){ ...});

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

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

Though the question appears to be demanding plotting a histogram using matplotlib.hist() function, it can arguably be not done using the same as the latter part of the question demands to use the given probabilities as the y-values of bars and given names(strings) as the x-values.

I'm assuming a sample list of names corresponding to given probabilities to draw the plot. A simple bar plot serves the purpose here for the given problem. The following code can be used:

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
names = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9',
'name10', 'name11', 'name12', 'name13'] #sample names
plt.bar(names, probability)
plt.xticks(names)
plt.yticks(probability) #This may be included or excluded as per need
plt.xlabel('Names')
plt.ylabel('Probability')

How does String.Index work in Swift

I appreciate this question and all the info with it. I have something in mind that's kind of a question and an answer when it comes to String.Index.

I'm trying to see if there is an O(1) way to access a Substring (or Character) inside a String because string.index(startIndex, offsetBy: 1) is O(n) speed if you look at the definition of index function. Of course we can do something like:

let characterArray = Array(string)

then access any position in the characterArray however SPACE complexity of this is n = length of string, O(n) so it's kind of a waste of space.

I was looking at Swift.String documentation in Xcode and there is a frozen public struct called Index. We can initialize is as:

let index = String.Index(encodedOffset: 0)

Then simply access or print any index in our String object as such:

print(string[index])

Note: be careful not to go out of bounds`

This works and that's great but what is the run-time and space complexity of doing it this way? Is it any better?

How to make a great R reproducible example

If you have one or more factor variable(s) in your data that you want to make reproducible with dput(head(mydata)), consider adding droplevels to it, so that levels of factors that are not present in the minimized data set are not included in your dput output, in order to make the example minimal:

dput(droplevels(head(mydata)))

ASP.NET Setting width of DataBound column in GridView

add HeaderStyle in your bound field:

    <asp:BoundField HeaderText="UserId"
                DataField="UserId" 
                SortExpression="UserId">

                <HeaderStyle Width="200px" />

</asp:BoundField>

How to set time zone in codeigniter?

add it in your index.php file, and it will work on all over your site

if ( function_exists( 'date_default_timezone_set' ) ) {
    date_default_timezone_set('Asia/Kolkata');
}

When to choose mouseover() and hover() function?

From the offical docs: (http://api.jquery.com/hover/)

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

Fatal error: Call to undefined function curl_init()

for php 7.0 on ubuntu use

sudo apt-get install php7.0-curl

And finally,

sudo service apache2 restart 

or

sudo service nginx restart

How to get JQuery.trigger('click'); to initiate a mouse click

Just use this:

$(function() {
 $('#watchButton').trigger('click');
});

How do I convert a PDF document to a preview image in PHP?

You can also try executing the 'convert' utility that comes with imagemagick.

exec("convert pdf_doc.pdf image.jpg");
echo 'image-0.jpg';

Catching "Maximum request length exceeded"

As you probably know, the maximum request length is configured in TWO places.

  1. maxRequestLength - controlled at the ASP.NET app level
  2. maxAllowedContentLength - under <system.webServer>, controlled at the IIS level

The first case is covered by other answers to this question.

To catch THE SECOND ONE you need to do this in global.asax:

protected void Application_EndRequest(object sender, EventArgs e)
{
    //check for the "file is too big" exception if thrown at the IIS level
    if (Response.StatusCode == 404 && Response.SubStatusCode == 13)
    {
        Response.Write("Too big a file"); //just an example
        Response.End();
    }
}

Call PHP function from Twig template

You can check your all defined function by

$arr = get_defined_functions();
print_r($arr);

this will give you array of all functions in if your function exist in it you can use it like:

 {{ user.myfunction({{parameter}}) }}

Test if a variable is a list or tuple

Go ahead and use isinstance if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str or unicode like so:

import types
isinstance(var, types.StringTypes)

N.B. Don't mistake types.StringType for types.StringTypes. The latter incorporates str and unicode objects.

The types module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str and unicode, like this:

isinstance(var, (str, unicode)):

Edit:

Better still is:

isinstance(var, basestring)

End edit

After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.

See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .

Use 'class' or 'typename' for template parameters?

There is a difference, and you should prefer class to typename.

But why?

typename is illegal for template template arguments, so to be consistent, you should use class:

template<template<class> typename MyTemplate, class Bar> class Foo { };    //  :(
template<template<class>    class MyTemplate, class Bar> class Foo { };    //  :)

How to keep two folders automatically synchronized?

You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:

It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.

But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!

I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.

Google Maps JavaScript API RefererNotAllowedMapError

I experienced the same error:

enter image description here

This link talks about how to set up API key restrictions: https://cloud.google.com/docs/authentication/api-keys#adding_http_restrictions

In my case, the problem was that I was using this restriction:

HTTP referrers (web sites) Accept requests from these HTTP referrers (web sites) (Optional) Use *'s for wildcards. If you leave this blank, requests will be accepted from any referrer. Be sure to add referrers before using this key in production. https://*.example.net/*

This means that URLs such as https://www.example.net or https://m.example.net or https://www.example.net/San-salvador/ would work. However, URLs such as https://example.net or https://example.net or https://example.net/San-salvador/ would not work. I simply needed to add a second referrer:

https://example.net/*

That fixed the problem for me.

Second line in li starts under the bullet after CSS-reset

Here is a good example -

ul li{
    list-style-type: disc;
    list-style-position: inside;
    padding: 10px 0 10px 20px;
    text-indent: -1em;
}

Working Demo: http://jsfiddle.net/d9VNk/

Adding maven nexus repo to my pom.xml

If you don't want or you cannot modify the settings.xml file, you can create a new one in your root project, and call maven passing it as a parameter with the -s parameter:

$ mvn COMMAND ... -s settings.xml

Package name does not correspond to the file path - IntelliJ

You should declare in the Project structure(Ctrl+Alt+Shift+s) in the Module section mark your folders which of them are source package(blue one) and which are test ...

How to suppress scientific notation when printing float values?

As of 3.6 (probably works with slightly older 3.x as well), this is my solution:

import locale
locale.setlocale(locale.LC_ALL, '')

def number_format(n, dec_precision=4):
    precision = len(str(round(n))) + dec_precision
    return format(float(n), f'.{precision}n')

The purpose of the precision calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).

The dec_precision argument adds additional precision to use for decimal points. Since this makes use of the n format, no insignificant zeros will be added (unlike f formats). n also will take care of rendering already-round integers without a decimal.

n does require float input, thus the cast.

What should my Objective-C singleton look like?

The accepted answer, although it compiles, is incorrect.

+ (MySingleton*)sharedInstance
{
    @synchronized(self)  <-------- self does not exist at class scope
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

Per Apple documentation:

... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.

Even if using self works, it shouldn't and this looks like a copy and paste mistake to me. The correct implementation for a class factory method would be:

+ (MySingleton*)getInstance
{
    @synchronized([MySingleton class]) 
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

Vector erase iterator

As a modification to crazylammer's answer, I often use:

your_vector_type::iterator it;
for( it = res.start(); it != res.end();)
{
    your_vector_type::iterator curr = it++;
    if (something)
        res.erase(curr);
}

The advantage of this is that you don't have to worry about forgetting to increment your iterator, making it less bug prone when you have complex logic. Inside the loop, curr will never be equal to res.end(), and it will be at the next element regardless of if you erase it from your vector.

Extracting specific selected columns to new DataFrame as a copy

If you want to have a new data frame then:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

Boolean Field in Oracle

I found this link useful.

Here is the paragraph highlighting some of the pros/cons of each approach.

The most commonly seen design is to imitate the many Boolean-like flags that Oracle's data dictionary views use, selecting 'Y' for true and 'N' for false. However, to interact correctly with host environments, such as JDBC, OCCI, and other programming environments, it's better to select 0 for false and 1 for true so it can work correctly with the getBoolean and setBoolean functions.

Basically they advocate method number 2, for efficiency's sake, using

  • values of 0/1 (because of interoperability with JDBC's getBoolean() etc.) with a check constraint
  • a type of CHAR (because it uses less space than NUMBER).

Their example:

create table tbool (bool char check (bool in (0,1));
insert into tbool values(0);
insert into tbool values(1);`

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
}

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.

...

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Difference between onLoad and ng-init in angular

Works for me.

<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>

MVC which submit button has been pressed

To make it easier I will say you can change your buttons to the following:

<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />

Your controller:

public ActionResult Create(string btnSubmit, string btnProcess)
{
    if(btnSubmit != null)
       // do something for the Button btnSubmit
    else 
       // do something for the Button btnProcess
}

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

Here is my solution:

You need to tell the TableView the estimatedHeight before it loads the view. Otherwise it wont be able to behave like expected.

Objective-C

- (void)viewWillAppear:(BOOL)animated {
    _messageField.delegate = self;
    _tableView.estimatedRowHeight = 65.0;
    _tableView.rowHeight = UITableViewAutomaticDimension;
}

Update to Swift 4.2

override func viewWillAppear(_ animated: Bool) {
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 65.0
}

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

When compiling memcached under Centos 5.x i got the same problem.

The solution is to upgrade gcc and g++ to version 4.4 at least.

Make sure your CC/CXX is set (exported) to right binaries before compiling.

Html.DropDownList - Disabled/Readonly

Put this in style

 select[readonly] option, select[readonly] optgroup {
        display: none;
    }

ArrayList - How to modify a member of an object?

You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:

for(Customer customer : myList) {
    if(customer!=null && "Doe".equals(customer.getName())) {
        customer.setEmail("[email protected]");
        break;
    }
}

Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.

No mapping found for HTTP request with URI Spring MVC

I added META-INF folder with context.xml contain

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/SpringGradleDemo"/>

SpringGradleDemo is my project name and it work. My servlet-mapping is "/" I read it here https://tomcat.apache.org/tomcat-5.5-doc/config/context.html

How to paste into a terminal?

same for Terminator

Ctrl + Shift + V

Look at your terminal key-bindings if any if that doesn't work

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.

    <div class="featured-image" style="height:300px">
     <img id="thumbnail" src="01.jpg"/>
    </div>

    <div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
    <img src='01.jpg'>
    <img src='02.jpg'>
    <img src='03.jpg'>
    <img src='04.jpg'>
    </div>

    <script type="text/javascript">
            function changeThumbnail()
            {
            $("#thumbnail").fadeOut(200);
            var path=$("#thumbnail").attr('src');
            var arr= new Array(); var i=0;
            $("#thumblist img").each(function(index, element) {
               arr[i]=$(this).attr('src');
               i++;
            });
            var index= arr.indexOf(path);
            if(index==(arr.length-1))
            path=arr[0];
            else
            path=arr[index+1];
            $("#thumbnail").attr('src',path).fadeIn(200);
            setTimeout(changeThumbnail, 5000);  
            }
            setTimeout(changeThumbnail, 5000);
    </script>

How to create virtual column using MySQL SELECT?

Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW

IndexError: list index out of range and python

Yes. The sequence doesn't have the 54th item.

Passing event and argument to v-on in Vue.js

Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:

<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>

What operator is <> in VBA

It means not equal to, as the others said..

I just wanted to say that I read that as "greater than or lesser than".

e.g.

let x = 12

if x <> 0 then
    //code

In this case 'x' is greater than (that's the '>' symbol) 0.

Hope this helps. :D

How to add new elements to an array?

If one really want to resize an array you could do something like this:

String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr)); 
// Output is: [a, b, c]

arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";

System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]

How to generate a unique hash code for string input in android...?

I use this i tested it as key from my EhCacheManager Memory map ....

Its cleaner i suppose

   /**
     * Return Hash256 of String value
     *
     * @param text
     * @return 
     */
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }

am using maven but this is the jar commons-codec-1.9.jar

How do you redirect HTTPS to HTTP?

For those that are using a .conf file.

<VirtualHost *:443>
    ServerName domain.com
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/domain.crt
    SSLCertificateKeyFile /etc/apache2/ssl/domain.key
    SSLCACertificateFile /etc/apache2/ssl/domain.crt

</VirtualHost>

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

Restart node upon changing a file

Various NPM packages are available to make this task easy.

For Development

For Production (with extended functionality such as clustering, remote deploy etc.)

Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.

Resize Cross Domain Iframe Height

It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.

https://github.com/davidjbradshaw/iframe-resizer

It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.

Works in all modern browsers and IE8 upwards.

How can I listen for keypress event on the whole page?

I think this does the best job

https://angular.io/api/platform-browser/EventManager

for instance in app.component

constructor(private eventManager: EventManager) {
    const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
      'document',
      'keypress',
      (ev) => {
        console.log('ev', ev);
      }
    );
  }

Clearing content of text file using php

//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");

//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);

//use location header to go back to index.html
header("Location:index.html");

I don't exactly know where u want to show the result.

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

Are complex expressions possible in ng-hide / ng-show?

Use a controller method if you need to run arbitrary JavaScript code, or you could define a filter that returned true or false.

I just tested (should have done that first), and something like ng-show="!a && b" worked as expected.

SQL SELECT WHERE field contains words

Instead of SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3', add And in between those words like:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 And word2 And word3'

for details, see here https://msdn.microsoft.com/en-us/library/ms187787.aspx

UPDATE

For selecting phrases, use double quotes like:

SELECT * FROM MyTable WHERE Column1 CONTAINS '"Phrase one" And word2 And "Phrase Two"'

p.s. you have to first enable Full Text Search on the table before using contains keyword. for more details, See here https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search

How to print a string multiple times?

It amazes me that this simple answer did not occur in the previous answers.

In my viewpoint, the easiest way to print a string on multiple lines, is the following :

print("Random String \n" * 100), where 100 stands for the number of lines to be printed.

'this' vs $scope in AngularJS controllers

I recommend you to read the following post: AngularJS: "Controller as" or "$scope"?

It describes very well the advantages of using "Controller as" to expose variables over "$scope".

I know you asked specifically about methods and not variables, but I think that it's better to stick to one technique and be consistent with it.

So for my opinion, because of the variables issue discussed in the post, it's better to just use the "Controller as" technique and also apply it to the methods.

How to get the android Path string to a file on Assets folder?

You can use this method.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

In Kotlin (;D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }

How to implement a tree data-structure in Java?

public class Tree {
    private List<Tree> leaves = new LinkedList<Tree>();
    private Tree parent = null;
    private String data;

    public Tree(String data, Tree parent) {
        this.data = data;
        this.parent = parent;
    }
}

Obviously you can add utility methods to add/remove children.

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

GitHub relative link in Markdown file

For example, you have a repo like the following:

project/
    text.md
    subpro/
       subtext.md
       subsubpro/
           subsubtext.md
       subsubpro2/
           subsubtext2.md

The relative link to subtext.md in text.md might look like this:

[this subtext](subpro/subtext.md)

The relative link to subsubtext.md in text.md might look like this:

[this subsubtext](subpro/subsubpro/subsubtext.md)

The relative link to subtext.md in subsubtext.md might look like this:

[this subtext](../subtext.md)

The relative link to subsubtext2.md in subsubtext.md might look like this:

[this subsubtext2](../subsubpro2/subsubtext2.md)

The relative link to text.md in subsubtext.md might look like this:

[this text](../../text.md)

getFilesDir() vs Environment.getDataDirectory()

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Environment.getDataDirectory()

Return the user data directory.

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag prevents git merge from executing a "fast-forward" if it detects that your current HEAD is an ancestor of the commit you're trying to merge. A fast-forward is when, instead of constructing a merge commit, git just moves your branch pointer to point at the incoming commit. This commonly occurs when doing a git pull without any local changes.

However, occasionally you want to prevent this behavior from happening, typically because you want to maintain a specific branch topology (e.g. you're merging in a topic branch and you want to ensure it looks that way when reading history). In order to do that, you can pass the --no-ff flag and git merge will always construct a merge instead of fast-forwarding.

Similarly, if you want to execute a git pull or use git merge in order to explicitly fast-forward, and you want to bail out if it can't fast-forward, then you can use the --ff-only flag. This way you can regularly do something like git pull --ff-only without thinking, and then if it errors out you can go back and decide if you want to merge or rebase.

Run cURL commands from Windows console

I have also found that if I put the cygwin bin on my windows path I can run curl from a windows command line. It also will give you access to things like ls and grep

How to pass form input value to php function

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT  c2.field1 ,
        field2
FROM    (SELECT DISTINCT
                field1
         FROM   dbo.TABLE AS C
        ) AS c1
        JOIN dbo.TABLE AS c2 ON c1.field1 = c2.field1

How to use WHERE IN with Doctrine 2

In researching this issue, I found something that will be important to anyone running into this same issue and looking for a solution.

From the original post, the following line of code:

$qb->add('where', $qb->expr()->in('r.winner', array('?1')));

Wrapping the named parameter as an array causes the bound parameter number issue. By removing it from its array wrapping:

$qb->add('where', $qb->expr()->in('r.winner', '?1'));

This issue should be fixed. This might have been a problem in previous versions of Doctrine, but it is fixed in the most recent versions of 2.0.

Sort a single String in Java

Convert to array of chars ? Sort ? Convert back to String:

String s = "edcba";
char[] c = s.toCharArray();        // convert to array of chars 
java.util.Arrays.sort(c);          // sort
String newString = new String(c);  // convert back to String
System.out.println(newString);     // "abcde"

Uninstall mongoDB from ubuntu

Stop MongoDB

Stop the mongod process by issuing the following command:

sudo service mongod stop

Remove Packages

Remove any MongoDB packages that you had previously installed.

sudo apt-get purge mongodb-org*

Remove Data Directories.

Remove MongoDB databases and log files.

 sudo rm -r /var/log/mongodb /var/lib/mongodb

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

Is it a good practice to place C++ definitions in header files?

I put all the implementation out of the class definition. I want to have the doxygen comments out of the class definition.

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

C programming: Dereferencing pointer to incomplete type error

You haven't defined struct stasher_file by your first definition. What you have defined is an nameless struct type and a variable stasher_file of that type. Since there's no definition for such type as struct stasher_file in your code, the compiler complains about incomplete type.

In order to define struct stasher_file, you should have done it as follows

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

Note where the stasher_file name is placed in the definition.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl as appropriate).

  1. Download (by right click and "save target") get-pip to local drive.

  2. At the command prompt, navigate to the directory containing get-pip.py and run

    python get-pip.py

    which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

  3. Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl into the above directory (C:\Python27\Scripts)

  4. Still at the command prompt, navigate to the above directory and run:

    pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"

Microsoft.ReportViewer.Common Version=12.0.0.0

In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved

Here is the screenshot for installing data tools

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

From http://developer.android.com/guide/components/processes-and-threads.html :

Additionally, the Android UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

  1. Do not block the UI thread
  2. Do not access the Android UI toolkit from outside the UI thread

You have to detect idleness in a worker thread and show a toast in the main thread.

Please post some code, if you want a more detailed answer.

After code publication :

In strings.xml

<string name="idleness_toast">"You are getting late do it fast"</string>

In YourWorkerThread.java

Toast.makeText(getApplicationContext(), getString(R.string.idleness_toast), 
    Toast.LENGTH_LONG).show();

Don't use AlertDialog, make a choice. AlertDialog and Toast are two different things.

How to hide iOS status bar

Steps for hide status bar in iOS
1. open AppDelegate.m file, add application.statusBarHidden in didFinishLaunchingWithOptions method

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    application.statusBarHidden = YES;
    return YES;
    }
  1. open info.plist and set

View controller-based status bar appearance set NO

How do you convert CString and std::string std::wstring to each other?

According to CodeGuru:

CString to std::string:

CString cs("Hello");
std::string s((LPCTSTR)cs);

BUT: std::string cannot always construct from a LPCTSTR. i.e. the code will fail for UNICODE builds.

As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary.

CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);

std::string to CString: (From Visual Studio's CString FAQs...)

std::string s("Hello");
CString cs(s.c_str());

CStringT can construct from both character or wide-character strings. i.e. It can convert from char* (i.e. LPSTR) or from wchar_t* (LPWSTR).

In other words, char-specialization (of CStringT) i.e. CStringA, wchar_t-specilization CStringW, and TCHAR-specialization CString can be constructed from either char or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the "null-termination" part in the comments:

NUL-termination is not required.
CStringT has conversion constructors that take an explicit length argument. This also means that you can construct CStringT objects from std::string objects with embedded NUL characters.

TextView - setting the text size programmatically doesn't seem to work

In Kotlin, you can use simply use like this,

textview.textSize = 20f

Are email addresses case sensitive?

Per @l3x, it depends.

There are clearly two sets of general situations where the correct answer can be different, along with a third which is not as general:

a) You are a user sending private mails:

Very few modern email systems implement case sensitivity, so you are probably fine to ignore case and choose whatever case you feel like using. There is no guarantee that all your mails will be delivered - but so few mails would be negatively affected that you should not worry about it.

b) You are developing mail software:

See RFC5321 2.4 excerpt at the bottom.

When you are developing mail software, you want to be RFC-compliant. You can make your own users' email addresses case insensitive if you want to (and you probably should). But in order to be RFC compliant, you MUST treat outside addresses as case sensitive.

c) Managing business-owned lists of email addresses as an employee:

It is possible that the same email recipient is added to a list more than once - but using different case. In this situation though the addresses are technically different, it might result in a recipient receiving duplicate emails. How you treat this situation is similar to situation a) in that you are probably fine to treat them as duplicates and to remove a duplicate entry. It is better to treat these as special cases however, by sending a "reminder" mail to both addresses to ask them if the case of the email address is accurate.

From a legal standpoint, if you remove a duplicate without acknowledgement/permission from both addresses, you can be held responsible for leaking private information/authentication to an unauthorised address simply because two actually-separate recipients have the same address with different cases.

Excerpt from RFC5321 2.4:

The local-part of a mailbox MUST BE treated as case sensitive. Therefore, SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith". However, exploiting the case sensitivity of mailbox local-parts impedes interoperability and is discouraged.

How to say no to all "do you want to overwrite" prompts in a batch file copy?

Unless there's a scenario where you'd not want to copy existing files in the source that have changed since the last copy, why not use XCOPY with /D without specifying a date?

header location not working in my php code

That is because you have an output:

?>
<?php

results in blank line output.

header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.

also after header('location: index.php'); add exit(); if you have any other scripts bellow.

Also move your redirect header after the last if.

If there is content, then you can also redirect by injecting javascript:

<?php
    echo "<script>window.location.href='target.php';</script>";
    exit;
?>

How do you use NSAttributedString?

To solve such kind of problems I created library in swift which is called Atributika.

let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
        Style("r").foregroundColor(.red),
        Style("g").foregroundColor(.green),
        Style("b").foregroundColor(.blue)).attributedString

label.attributedText = str

You can find it here https://github.com/psharanda/Atributika

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

What is the default access modifier in Java?

Is the access modifier of this constructor protected or package?

I think implicitly your constructors access modifier would be your class's access modifier. as your class has public access, constructor would have public access implicitly

How do I link a JavaScript file to a HTML file?

You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>

Then in your javascript file you can refer to jQuery either using $ sign or jQuery. Example:

jQuery.each(arr, function(i) { console.log(i); }); 

Latex Remove Spaces Between Items in List

You could do something like this:

\documentclass{article}

\begin{document}

Normal:

\begin{itemize}
  \item foo
  \item bar
  \item baz
\end{itemize}

Less space:

\begin{itemize}
  \setlength{\itemsep}{1pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
  \item foo
  \item bar
  \item baz
\end{itemize}

\end{document}

Why use #define instead of a variable

I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.

Like this:

int Marylyn[256], Ann[1024];

The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:

 #define TWO_FIFTY_SIX 256
 #define TEN_TWENTY_FOUR 1024

 int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];

On the following Monday afternoon I was called in and accused of having passive defiant tendencies.

"message failed to fetch from registry" while trying to install any module

I had this issue with npm v1.1.4 (and node v0.6.12), which are the Ubuntu 12.04 repository versions.

It looks like that version of npm isn't supported any more, updating node (and npm with it) resolved the issue.

First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).

sudo apt-get purge nodejs npm

Then enable nodesource's repo and install:

curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs

Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:

From: here

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

you have to check your pip package to be updated to the latest version in your pycharm and then install numpy package. in settings -> project:progLangComp -> Project Interpreter there is a table of packages and their current version (just labelled as Version) and their latest version (labelled as Latest). Pip current version number should be the same as latest version. If you see a blue arrow in front of pip, you have to update it to the latest then trying to install numpy or any other packages that you couldn't install, for me it was pandas which I wanted to install.

enter image description here

How to connect to Mysql Server inside VirtualBox Vagrant?

Well, since neither of the given replies helped me, I had to look more, and found solution in this article.

And the answer in a nutshell is the following:

Connecting to MySQL using MySQL Workbench

Connection Method: Standard TCP/IP over SSH
SSH Hostname: <Local VM IP Address (set in PuPHPet)>
SSH Username: vagrant (the default username)
SSH Password: vagrant (the default password)
MySQL Hostname: 127.0.0.1
MySQL Server Port: 3306
Username: root
Password: <MySQL Root Password (set in PuPHPet)>

Using given approach I was able to connect to mysql database in vagrant from host Ubuntu machine using MySQL Workbench and also using Valentina Studio.

python pandas dataframe columns convert to dict key and value

With pandas it can be done as:

If lakes is your DataFrame:

area_dict = lakes.to_dict('records')

How do I set bold and italic on UILabel of iPhone/iPad?

With Swift 5

For style = BOLD

label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)

For style = Medium

label.font = UIFont(name:"HelveticaNeue-Medium", size: 15.0)

For style = Thin

label.font = UIFont(name:"HelveticaNeue-Thin", size: 15.0)

C split a char array into different variables

You could simply replace the separator characters by NULL characters, and store the address after the newly created NULL character in a new char* pointer:

char* input = "asdf|qwer"
char* parts[10];
int partcount = 0;

parts[partcount++] = input;

char* ptr = input;
while(*ptr) { //check if the string is over
    if(*ptr == '|') {
        *ptr = 0;
        parts[partcount++] = ptr + 1;
    }
    ptr++;
}

Note that this code will of course not work if the input string contains more than 9 separator characters.

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

What is IPV6 for localhost and 0.0.0.0?

The ipv6 localhost is ::1. The unspecified address is ::. This is defined in RFC 4291 section 2.5.

Plotting a fast Fourier transform in Python

There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:

Adding the required modules:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal

Generating sample data:

N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise

Sorting the data set:

order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]

Resampling:

T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)

Plotting the data and resampled data:

plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")

Enter image description here

Now calculating the FFT:

Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]

plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)

Enter image description here

P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

For me commenting out

'grappelli.dashboard',
'grappelli',

in INSTALLED_APPS worked

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

Reading a plain text file in Java

What do you want to do with the text? Is the file small enough to fit into memory? I would try to find the simplest way to handle the file for your needs. The FileUtils library is very handle for this.

for(String line: FileUtils.readLines("my-text-file"))
    System.out.println(line);

Exit from app when click button in android phonegap?

@Pradip Kharbuja

In Cordova-2.6.0.js (l. 4032) :

exitApp:function() {
  console.log("Device.exitApp() is deprecated. Use App.exitApp().");
  app.exitApp();
}

How can git be installed on CENTOS 5.5?

OK, there is more to it than that, you need zlib. zlib is part of CentOS, but you need the development form to get zlib.h ... notice that the yum name of zlib development is quite different possibly than for apt-get on ubuntu/debian, what follows actually works with my CentOS version
in particular, you do ./configure on git, then try make, and the first build fails with missing zlib.h

I used a two-step procedure to resolve this a) Got RPMFORGE for my version of CentOS

See: www.centos.org/modules/newbb/viewtopic.php?topic_id=18506&forum=38 and this: wiki.centos.org/AdditionalResources/Repositories/RPMForge

In my case [as root, or with sudo]

$ wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
$ rpm -K rpmforge-release-0.5.2-2.el5.rf.*.rpm
$ rpm -i rpmforge-release-0.5.2-2.el5.rf.*.rpm
## Note: the RPM for rpmforge is small (like 12.3K) but don't let that fool
## you; it augments yum the next time you use yum
## [this is the name that YUM found] (still root or sudo)
$ yum install zlib-devel.x86_64
## and finally in the source directory for git (still root or sudo):
$ ./configure (this worked before, but I ran it again to be sure)
$ make
$ make install

(this install put it by default in /usr/local/bin/git ... not my favorite choice, but OK for the default)... and git works fine!

Boolean vs boolean in Java

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.

Get elements by attribute when querySelectorAll is not available without using libraries?

That works too:

document.querySelector([attribute="value"]);

So:

document.querySelector([data-foo="bar"]);

JQuery - Storing ajax response into global variable

There's no way around it except to store it. Memory paging should reduce potential issues there.

I would suggest instead of using a global variable called 'xml', do something more like this:

var dataStore = (function(){
    var xml;

    $.ajax({
      type: "GET",
      url: "test.xml",
      dataType: "xml",
      success : function(data) {
                    xml = data;
                }
    });

    return {getXml : function()
    {
        if (xml) return xml;
        // else show some error that it isn't loaded yet;
    }};
})();

then access it with:

$(dataStore.getXml()).find('something').attr('somethingElse');

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

JavaScript Regular Expression Email Validation

You can also try this expression, I have tested it against many email addresses.

var pattern = /^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;

Get keys from HashMap in Java

To get keys in HashMap, We have keySet() method which is present in java.util.Hashmap package. ex :

Map<String,String> map = new Hashmap<String,String>();
map.put("key1","value1");
map.put("key2","value2");

// Now to get keys we can use keySet() on map object
Set<String> keys = map.keySet();

Now keys will have your all keys available in map. ex: [key1,key2]

Postgres manually alter sequence

The parentheses are misplaced:

SELECT setval('payments_id_seq', 21, true);  # next value will be 22

Otherwise you're calling setval with a single argument, while it requires two or three.

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

How to force remounting on React components?

Change the key of the component.

<Component key="1" />
<Component key="2" />

Component will be unmounted and a new instance of Component will be mounted since the key has changed.

edit: Documented on You Probably Don't Need Derived State:

When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

Fetching data from MySQL database to html dropdown list

What you are asking is pretty straight forward

  1. execute query against your db to get resultset or use API to get the resultset

  2. loop through the resultset or simply the result using php

  3. In each iteration simply format the output as an element

the following refernce should help

HTML option tag

Getting Datafrom MySQL database

hope this helps :)

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I also faced a similar issue. While for anyone this may be an issue of various bad usages in Code such as

  1. Wrong Layout tag in XML
  2. Loading of heavy resource directly into ImageView resulting in OOM
  3. Issues with usage of styles.

One most ignored factor may be usage of correct Context while inflating views. Please check that you are not using ApplicationContext where an Activity context is required. While, ApplicationContext may not end up in error always, but depending upon your view hierarchy it may be crucial.

I resolved my issue with a BAD context (using ApplicationContext instead of Activity in a span of 4 days! So try if that solves. Happy Coding!!

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Conditionally formatting cells if their value equals any value of another column

All you need to do for that is a simple loop.
This doesn't handle testing for lower case, upper-case mismatch. If this isn't exactly what you are looking for, comment, and I can revise.

If you are planning to learn VBA. This is a great start.

TESTED:

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String

    sheetName = "Sheet1"            'Insert your sheet name here
    lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

    For lRow = 2 To lastRow         'Loop through all rows

        If Sheets(sheetName).Cells(lRow, "A") = Sheets(sheetName).Cells(lRow, "B") Then
            Sheets(sheetName).Cells(lRow, "A").Interior.ColorIndex = 3  'Set Color to RED
        End If

    Next lRow

End Sub

EXAMPLE

How to get the hostname of the docker host from inside a docker container on that host without env vars

I think the reason that I have the same issue is a bug in the latest Docker for Mac beta, but buried in the comments there I was able to find a solution that worked for me & my team. We're using this for local development, where we need our containerized services to talk to a monolith as we work to replace it. This is probably not a production-viable solution.

On the host machine, alias a known available IP address to the loopback interface:

$ sudo ifconfig lo0 alias 10.200.10.1/24

Then add that IP with a hostname to your docker config. In my case, I'm using docker-compose, so I added this to my docker-compose.yml:

extra_hosts:
# configure your host to alias 10.200.10.1 to the loopback interface:
#       sudo ifconfig lo0 alias 10.200.10.1/24
- "relevant_hostname:10.200.10.1"

I then verified that the desired host service (a web server) was available from inside the container by attaching to a bash session, and using wget to request a page from the host's web server:

$ docker exec -it container_name /bin/bash
$ wget relevant_hostname/index.html
$ cat index.html

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

Just add 'unsigned' for the FOREIGN constraint

`FK` int(11) unsigned DEFAULT NULL,

Include an SVG (hosted on GitHub) in MarkDown

Just like this worked for me on Github.

![Imgae Caption](ImageAddressOnGitHub.svg)

or

<img src="ImageAddressOnGitHub.svg">

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

Convert js Array() to JSon object for use with JQuery .ajax

When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

$array = $_POST['jObject'];
$array = stripslashes_deep($array);

$data = json_decode($array, true);
print_r($data);
?>

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part

Detect if value is number in MySQL

If your data is 'test', 'test0', 'test1111', '111test', '111'

To select all records where the data is a simple int:

SELECT * 
FROM myTable 
WHERE col1 REGEXP '^[0-9]+$';

Result: '111'

(In regex, ^ means begin, and $ means end)

To select all records where an integer or decimal number exists:

SELECT * 
FROM myTable 
WHERE col1 REGEXP '^[0-9]+\\.?[0-9]*$'; - for 123.12

Result: '111' (same as last example)

Finally, to select all records where number exists, use this:

SELECT * 
FROM myTable 
WHERE col1 REGEXP '[0-9]+';

Result: 'test0' and 'test1111' and '111test' and '111'

python date of the previous month

With the Pendulum very complete library, we have the subtract method (and not "subStract"):

import pendulum
today = pendulum.datetime.today()  # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'

We see that it handles jumping years.

The reverse equivalent is add.

https://pendulum.eustace.io/docs/#addition-and-subtraction

How to create a temporary directory/folder in Java?

Naively written code to solve this problem suffers from race conditions, including several of the answers here. Historically you could think carefully about race conditions and write it yourself, or you could use a third-party library like Google's Guava (as Spina's answer suggested.) Or you could write buggy code.

But as of JDK 7, there is good news! The Java standard library itself now provides a properly working (non-racy) solution to this problem. You want java.nio.file.Files#createTempDirectory(). From the documentation:

public static Path createTempDirectory(Path dir,
                       String prefix,
                       FileAttribute<?>... attrs)
                                throws IOException

Creates a new directory in the specified directory, using the given prefix to generate its name. The resulting Path is associated with the same FileSystem as the given directory.

The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.

This effectively resolves the embarrassingly ancient bug report in the Sun bug tracker which asked for just such a function.

How do I run a single test using Jest?

Jest documentation recommends the following:

If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. In Jest it's simple to run only one test - just temporarily change that test command to a test.only

test.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});

or

it.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});

Opacity of background-color, but not the text

Relaxing your requirement to work on IE6 and legacy browsers you can use ::before and display: inline-block

div
{
  display: inline-block;
  position: relative;    
}
div::before
{
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background:red;
  opacity: .2;
}

Demo at http://jsfiddle.net/KVyFH/172/ ?

It will work on any modern browser

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

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

Java naming convention for static final variables

That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.


The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

interface ProcessStates {
  int PS_RUNNING = 0;
  int PS_SUSPENDED = 1;
}

Obscuring involving constant names is rare:

  • Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
  • Constant names cannot obscure method names, because they are distinguished syntactically.

How to generate all permutations of a list?

In a functional style

def addperm(x,l):
    return [ l[0:i] + [x] + l[i:]  for i in range(len(l)+1) ]

def perm(l):
    if len(l) == 0:
        return [[]]
    return [x for y in perm(l[1:]) for x in addperm(l[0],y) ]

print perm([ i for i in range(3)])

The result:

[[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]]

Changing cursor to waiting in javascript/jquery

Here is something else interesting you can do. Define a function to call just before each ajax call. Also assign a function to call after each ajax call is complete. The first function will set the wait cursor and the second will clear it. They look like the following:

$(document).ajaxComplete(function(event, request, settings) {
    $('*').css('cursor', 'default');
  });

function waitCursor() {
    $('*').css('cursor', 'progress');
  }

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>
    </span>
</div>

This is the javascript:

$('.date').datepicker();

I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

What is Join() in jQuery?

You would probably use your example like this

var newText = "<span>" + $("p").text().split(" ").join("</span> <span>") + "</span>";

This will put span tags around all the words in you paragraphs, turning

<p>Test is a demo.</p>

into

<p><span>Test</span> <span>is</span> <span>a</span> <span>demo.</span></p>

I do not know what the practical use of this could be.

500 internal server error at GetResponse()

For me the error was misleading. I discovered the true error by testing the errant web service with SoapUI.

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

Most Pythonic way to provide global configuration variables in config.py?

How about using classes?

# config.py
class MYSQL:
    PORT = 3306
    DATABASE = 'mydb'
    DATABASE_TABLES = ['tb_users', 'tb_groups']

# main.py
from config import MYSQL

print(MYSQL.PORT) # 3306

How to allow users to check for the latest app version from inside the app?

Google updated play store two months before. This is the solution working right now for me..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

and don't forget to add JSoup library

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

and on Oncreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

that's it.. Thanks to this link

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

How do I encode/decode HTML entities in Ruby?

If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

Hpricot.uxs "foo&nbsp;b&auml;r"
=> "foo bär"

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

How about a solution where you put the actual "data" of the table inside its own div, with overflow: scroll;? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that <div>.

Not sure how that would work with scrolling horizontally though.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

And here is a similar batch-file for the time portion.

:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
      set 'hh'=%%i
      set 'mm'=%%j
      set 'ss'=%%k
      set 'ff'=%%l)
    ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%

    ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
    set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
    echo %timestring%

    :EOF

--jeroen

How to add font-awesome to Angular 2 + CLI project

With Angular2 RC5 and angular-cli 1.0.0-beta.11-webpack.8 you can achieve this with css imports.

Just install font awesome:

npm install font-awesome --save

and then import font-awesome in one of your configured style files:

@import '../node_modules/font-awesome/css/font-awesome.css';

(style files are configured in angular-cli.json)

Return list of items in list greater than some value

Use filter (short version without doing a function with lambda, using __le__):

j2 = filter((5).__le__, j)

Example (python 3):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
<filter object at 0x000000955D16DC18>
>>> list(j2)
[5, 6, 7, 7, 5]
>>> 

Example (python 2):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
[5, 6, 7, 7, 5]
>>>

Use __le__ i recommend this, it's very easy, __le__ is your friend

If want to sort it to desired output (both versions):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> sorted(j2)
[5, 5, 6, 7, 7]
>>> 

Use sorted

Timings:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5]) # Michael Mrozek
1.4558496298222325
>>> timeit(lambda: filter(lambda x: x >= 5, j)) # Justin Ardini
0.693048732089828
>>> timeit(lambda: filter((5).__le__, j)) # Mine
0.714461565831428
>>> 

So Justin wins!!

With number=1:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=1) # Michael Mrozek
1.642193421957927e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=1) # Justin Ardini
3.421236300482633e-06
>>> timeit(lambda: filter((5).__le__, j),number=1) # Mine
1.8474676011237534e-05
>>> 

So Michael wins!!

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=10) # Michael Mrozek
4.721306089550126e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=10) # Justin Ardini
1.0947956184281793e-05
>>> timeit(lambda: filter((5).__le__, j),number=10) # Mine
1.5053439710754901e-05
>>> 

So Justin wins again!!

How to decorate a class?

No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:

def addId(cls):

    class AddId(cls):

        def __init__(self, id, *args, **kargs):
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        def getId(self):
            return self.__id

    return AddId

Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:

class Foo:
    pass

FooId = addId(Foo)

And in Python 3 like this (but be careful to use super() in your classes):

@addId
class Foo:
    pass

So you can have your cake and eat it - inheritance and decorators!

Regular Expression to reformat a US phone number in Javascript

Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.

Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:

//format text input as phone number (nnn) nnn-nnnn
$('.myPhoneField').on('input', function (e){
    var $phoneField = e.target;
    var cursorPosition = $phoneField.selectionStart;
    var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);

    // let user backspace over the '-'
    if (cursorPosition === 9 && numericString.length > 6) return;

    // let user backspace over the ') '
    if (cursorPosition === 5 && numericString.length > 3) return;
    if (cursorPosition === 4 && numericString.length > 3) return;

    var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
    if (match) {
        var newVal = '(' + match[1];
        newVal += match[2] ? ') ' + match[2] : '';
        newVal += match[3] ? '-' + match[3] : '';

        // to help us put the cursor back in the right place
        var delta = newVal.length - Math.min($phoneField.value.length, 14);      
        $phoneField.value = newVal;
        $phoneField.selectionEnd = cursorPosition + delta;
    } else {
        $phoneField.value = '';        
    }
})

Converting a Java Keystore into PEM Format

The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

Best tool for inspecting PDF files?

Besides the GUI-based tools mentioned in the other answers, there are a few command line tools which can transform the original PDF source code into a different representation which lets you inspect the (now modified file) with a text editor. All of the tools below work on Linux, Mac OS X, other Unix systems or Windows.

qpdf (my favorite)

Use qpdf to uncompress (most) object's streams and also dissect ObjStm objects into individual indirect objects:

qpdf --qdf --object-streams=disable orig.pdf uncompressed-qpdf.pdf

qpdf describes itself as a tool that does "structural, content-preserving transformations on PDF files".

Then just open + inspect the uncompressed-qpdf.pdf file in your favorite text editor. Most of the previously compressed (and hence, binary) bytes will now be plain text.

mutool

There is also the mutool command line tool which comes bundled with the MuPDF PDF viewer (which is a sister product to Ghostscript, made by the same company, Artifex). The following command does also uncompress streams and makes them more easy to inspect through a text editor:

mutool clean -d orig.pdf uncompressed-mutool.pdf

podofouncompress

PoDoFo is an FreeSoftware/OpenSource library to work with the PDF format and it includes a few command line tools, including podofouncompress. Use it like this to uncompress PDF streams:

podofouncompress orig.pdf uncompressed-podofo.pdf

peepdf.py

PeePDF is a Python-based tool which helps you to explore PDF files. Its original purpose was for research and dissection of PDF-based malware, but I find it useful also to investigate the structure of completely benign PDF files.

It can be used interactively to "browse" the objects and streams contained in a PDF.

I'll not give a usage example here, but only a link to its documentation:

pdfid.py and pdf-parser.py

pdfid.py and pdf-parser.py are two PDF tools by Didier Stevens written in Python.

Their background is also to help explore malicious PDFs -- but I also find it useful to analyze the structure and contents of benign PDF files.

Here is an example how I would extract the uncompressed stream of PDF object no. 5 into a *.dump file:

pdf-parser.py -o 5 -f -d obj5.dump my.pdf

Final notes

  1. Please note that some binary parts inside a PDF are not necessarily uncompressible (or decode-able into human readable ASCII code), because they are embedded and used in their native format inside PDFs. Such PDF parts are JPEG images, fonts or ICC color profiles.

  2. If you compare above tools and the command line examples given, you will discover that they do NOT all produce identical outputs. The effort of comparing them for their differences in itself can help you to better understand the nature of the PDF syntax and file format.

How can I extract the folder path from file path in Python?

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder

How to do an Integer.parseInt() for a decimal number?

This kind of conversion is actually suprisingly unintuitive in Java

Take for example a following string : "100.00"

C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)

int i = atoi(decimalstring);

Java : mandatory passage by Double (or Float) parse, followed by a cast

int i = (int)Double.parseDouble(decimalstring);

Java sure has some oddities up it's sleeve

Facebook page automatic "like" URL (for QR Code)

I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.

You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.

onKeyPress Vs. onKeyUp and onKeyDown

onkeydown is fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrl is held 'down'.

onkeyup is fired when the key is released (including modifier/etc keys)

onkeypress is fired as a combination of onkeydown and onkeyup, or depending on keyboard repeat (when onkeyup isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)

textInput (webkit only) is fired when some text is entered (for example, Shift+A would enter uppercase 'A', but Ctrl+A would select text and not enter any text input. In that case, all other events are fired)

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

The requested operation cannot be performed on a file with a user-mapped section open

Happened to me after I have changed the project target CPU from 'Any CPU' to 'X64' and then back to 'Any CPU'.
Solved it by deleting the Obj folder (for beginners: don`t worry about deleting the obj folder, it will be recreated again in the next compile).

multiple where condition codeigniter

you can try this function for multi-purpose

function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
    $ci->db->where($condition);
if($is_insert)
{
    $ci->db->insert($table_name,$udata);
    return 0;
}
else
{
    $ci->db->update($table_name,$udata);
    return 1;
}

}

Python extract pattern matches

You can use groups (indicated with '(' and ')') to capture parts of the string. The match object's group() method then gives you the group's contents:

>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0)  # the entire match
'name my_user_name is valid'
>>> match.group(1)  # the first parenthesized subgroup
'my_user_name'

In Python 3.6+ you can also index into a match object instead of using group():

>>> match[0]  # the entire match 
'name my_user_name is valid'
>>> match[1]  # the first parenthesized subgroup
'my_user_name'

Creating watermark using html and css

Possibly this can be of great help for you.

div.image
{
width:500px;
height:250px;  
border:2px solid;
border-color:#CD853F;
}
div.box
{
width:400px;
height:180px;
margin:30px 50px;
background-color:#ffffff;
border:1px solid;
border-color:#CD853F;
opacity:0.6;
filter:alpha(opacity=60);
}
   div.box p
{
margin:30px 40px;
font-weight:bold;
color:#CD853F;
}

Check this link once.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

Two Solutions:

  1. Make Sure if you have some binding variables then move that code to settimeout( { }, 0);
  2. Move your related code to ngAfterViewInit method

Git - How to close commit editor?

As an alternative to 'save & quit', you can use git-commit's function git-commit-commit, by default bound to C-c C-c. It will save the file and close it. Afterwards, you still have to close emacs with C-x C-c, as mentioned before. I am currently trying to find out how to make emacs quit automatically.

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

Batch file to perform start, run, %TEMP% and delete all

@echo off
RD %TEMP%\. /S /Q

::pause
explorer %temp%

This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.

How do I add a .click() event to an image?

Enclose <img> in <a> tag.

<a href="http://www.google.com.pk"><img src="smiley.gif"></a>

it will open link on same tab, and if you want to open link on new tab then use target="_blank"

<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>

jQuery Select first and second td

$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");

http://jsfiddle.net/68wbx/1/

Replace all occurrences of a String using StringBuilder?

You could use Pattern/Matcher. From the Matcher javadocs:

 Pattern p = Pattern.compile("cat");
 Matcher m = p.matcher("one cat two cats in the yard");
 StringBuffer sb = new StringBuffer();
 while (m.find()) {
     m.appendReplacement(sb, "dog");
 }
 m.appendTail(sb);
 System.out.println(sb.toString());

ASP.NET 4.5 has not been registered on the Web server

If you've installed .NET framework 4.6, you may see this error due to a VS bug. Workarounds and resolutions here:

http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

EDIT:

As noted in some of the comments, this can happen behind the scenes after upgrading to Windows 10 or Visual Studio 2015.

Node.js: get path from the request

A more modern solution that utilises the URL WebAPI:

(req, res) => {
  const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}

How to drop all tables from the database with manage.py CLI in Django?

Drops all tables and recreates them:

python manage.py sqlclear app1 app2 appN | sed -n "2,$p" | sed -n "$ !p" | sed "s/";/" CASCADE;/" | sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/" | python manage.py dbshell
python manage.py syncdb

Explanation:

manage.py sqlclear - "prints the DROP TABLE SQL statements for the given app name(s)"

sed -n "2,$p" - grabs all lines except first line

sed -n "$ !p" - grabs all lines except last line

sed "s/";/" CASCADE;/" - replaces all semicolons (;) with (CASCADE;)

sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/" - inserts (BEGIN;) as first text, inserts (COMMIT;) as last text

manage.py dbshell - "Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER, PASSWORD, etc., settings"

manage.py syncdb - "Creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created"

Dependencies:


Credits:

@Manoj Govindan and @Mike DeSimone for sqlclear piped to dbshell

@jpic for 'sed "s/";/" CASCADE;/"'

Delete last commit in bitbucket

In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

On git:

git revert <commit>

On mercurial:

hg backout <REV>

EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.