Programs & Examples On #Merging data

How can I easily add storage to a VirtualBox machine with XP installed?

Taked from here => forums.virtualbox.org/viewtopic.php?p=41118#p41118

You could try something like this (see also Tutorial - All about VDIs: How can I resize the partitions inside my VDI?):

  • Create a new VDI of the desired size.
  • Boot GParted Live in a VM with both old and new VDIs attached.
  • Check in the partition editor (opened automatically after booting) what your old and new disk locations are. (It'll be something like /dev/hda and /dev/hdb.)
  • Copy contents from old to new disk. This will take a fair amount of time. (Here /dev/hdX is your original disk and /dev/hdY the new one).

    dd if=/dev/hdX of=/dev/hdY

    Warning: Make sure you do not mix up your input and output disks or you'll wipe all information from your original disk! (if= specifies the input and of= specifies the output.)

  • Reboot (again with GParted-Live). Now you should be able to increase the Windows partition size on the new disk.

Once you've verified the larger VDI boots Windows fine (and disk size is as you'd expect) you can of course delete the old smaller VDI.

Edit: Instead of rebooting before you resize the partition you should be able to run partprobe and the hit CTRL+R in GParted instead.

Is it possible to delete an object's property in PHP?

This also works specially if you are looping over an object.

unset($object[$key])

Update

Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by @CXJ . In that case you can use brackets instead

unset($object->{$key})

How do you test running time of VBA code?

Seconds with 2 decimal spaces:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer

seconds format

Milliseconds:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer

milliseconds format

Milliseconds with comma seperator:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer

Milliseconds with comma seperator

Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.

How can I use getSystemService in a non-activity class (LocationManager)?

You can go for this :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

CSS How to set div height 100% minus nPx

Use an outer wrapper div set to 100% and then your inner wrapper div 100% should be now relative to that.

I thought for sure this used to work for me, but apparently not:

<html>
<body>
<div id="outerwrapper" style="border : 1px solid red ; height : 100%">
<div id="header" style="border : 1px solid blue ; height : 60px"></div>
<div id="wrapper"  style="border : 1px solid green ; height : 100% ; overflow : scroll ;">
  <div id="left" style="height : 100% ; width : 50% ; overflow : scroll; float : left ; clear : left ;">Some text 

on the left</div>
  <div id="right" style="height : 100% ; width 50% ; overflow : scroll; float : left ;">Some Text on the 

right</div>
</div>
</div>
</body>
</html>

python multithreading wait till all threads finished

In Python3, since Python 3.2 there is a new approach to reach the same result, that I personally prefer to the traditional thread creation/start/join, package concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html

Using a ThreadPoolExecutor the code would be:

from concurrent.futures.thread import ThreadPoolExecutor
import time

def call_script(ordinal, arg):
    print('Thread', ordinal, 'argument:', arg)
    time.sleep(2)
    print('Thread', ordinal, 'Finished')

args = ['argumentsA', 'argumentsB', 'argumentsC']

with ThreadPoolExecutor(max_workers=2) as executor:
    ordinal = 1
    for arg in args:
        executor.submit(call_script, ordinal, arg)
        ordinal += 1
print('All tasks has been finished')

The output of the previous code is something like:

Thread 1 argument: argumentsA
Thread 2 argument: argumentsB
Thread 1 Finished
Thread 2 Finished
Thread 3 argument: argumentsC
Thread 3 Finished
All tasks has been finished

One of the advantages is that you can control the throughput setting the max concurrent workers.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Why is the <center> tag deprecated in HTML?

Food for thought: what would a text-to-speech synthesizer do with <center>?

Align an element to bottom with flexbox

You can use display: flex to position an element to the bottom, but I do not think you want to use flex in this case, as it will affect all of your elements.

To position an element to the bottom using flex try this:

.container {
  display: flex;
}

.button {
  align-self: flex-end;
}

Your best bet is to set position: absolute to the button and set it to bottom: 0, or you can place the button outside the container and use negative transform: translateY(-100%) to bring it in the container like this:

.content {
    height: 400px;
    background: #000;
    color: #fff;
}
.button {
    transform: translateY(-100%);
    display: inline-block;
}

Check this JSFiddle

Updating address bar with new URL without hash or reloading the page

Changing only what's after hash - old browsers

document.location.hash = 'lookAtMeNow';

Changing full URL. Chrome, Firefox, IE10+

history.pushState('data to be passed', 'Title of the page', '/test');

The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use

history.replaceState('data to be passed', 'Title of the page', '/test');

Try running these in the console now!

jQuery UI accordion that keeps multiple sections open?

Posted this in a similar thread, but thought it might be relevant here as well.

Achieving this with a single instance of jQuery-UI Accordion

As others have noted, the Accordion widget does not have an API option to do this directly. However, if for some reason you must use the widget (e.g. you're maintaining an existing system), it is possible to achieve this by using the beforeActivate event handler option to subvert and emulate the default behavior of the widget.

For example:

$('#accordion').accordion({
    collapsible:true,

    beforeActivate: function(event, ui) {
         // The accordion believes a panel is being opened
        if (ui.newHeader[0]) {
            var currHeader  = ui.newHeader;
            var currContent = currHeader.next('.ui-accordion-content');
         // The accordion believes a panel is being closed
        } else {
            var currHeader  = ui.oldHeader;
            var currContent = currHeader.next('.ui-accordion-content');
        }
         // Since we've changed the default behavior, this detects the actual status
        var isPanelSelected = currHeader.attr('aria-selected') == 'true';

         // Toggle the panel's header
        currHeader.toggleClass('ui-corner-all',isPanelSelected).toggleClass('accordion-header-active ui-state-active ui-corner-top',!isPanelSelected).attr('aria-selected',((!isPanelSelected).toString()));

        // Toggle the panel's icon
        currHeader.children('.ui-icon').toggleClass('ui-icon-triangle-1-e',isPanelSelected).toggleClass('ui-icon-triangle-1-s',!isPanelSelected);

         // Toggle the panel's content
        currContent.toggleClass('accordion-content-active',!isPanelSelected)    
        if (isPanelSelected) { currContent.slideUp(); }  else { currContent.slideDown(); }

        return false; // Cancels the default action
    }
});

See a jsFiddle demo

Access camera from a browser

As of 2017, WebKit announces support for WebRTC on Safari

Now you can access them with video and standard javascript WebRTC

E.g.

var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';

/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
  audio: false,
  video: {
   facingMode: facingMode
  }
};

/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
  video.srcObject = stream;
});

Have a play with it.

How do I use shell variables in an awk script?

It seems that the good-old ENVIRON built-in hash is not mentioned at all. An example of its usage:

$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

How do I add to the Windows PATH variable using setx? Having weird problems

Sadly with OOTB tools, you cannot append either the system path or user path directly/easily. If you want to stick with OOTB tools, you have to query either the SYSTEM or USER path, save that value as a variable, then appends your additions and save it using setx. The two examples below show how to retrieve either, save them, and append your additions. Don't get mess with %PATH%, it is a concatenation of USER+SYSTEM, and will cause a lot of duplication in the result. You have to split them as shown below...

Append to System PATH

for /f "usebackq tokens=2,*" %A in (`reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) do set SYSPATH=%B

setx PATH "%SYSPATH%;C:\path1;C:\path2" /M

Append to User PATH

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set userPATH=%B

setx PATH "%userPATH%;C:\path3;C:\path4"

How to find out which package version is loaded in R?

Use the R method packageDescription to get the installed package description and for version just use $Version as:

packageDescription("AppliedPredictiveModeling")$Version
[1] "1.1-6"

How to recompile with -fPIC

Briefly, the error means that you can't use a static library to be linked w/ a dynamic one. The correct way is to have a libavcodec compiled into a .so instead of .a, so the other .so library you are trying to build will link well.

The shortest way to do so is to add --enable-shared at ./configure options. Or even you may try to disable shared (or static) libraries at all... you choose what is suitable for you!

How do I find out what version of WordPress is running?

On the Admin panel in the footer you should see the words "Wordpress x.x" where x.x is your version number :)

Alternatively you can echo out the WP_VERSION constant in your script, it's up to you. The former is a lot quicker and easier.

Python: finding lowest integer

Python has a built in min function to help you with finding the smallest.

However, you need to convert your list items to numbers before you can find the lowest integer( what, isn't that float? )

min(float(i) for i in l)

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Creating a file only if it doesn't exist in Node.js

With async / await and Typescript I would do:

import * as fs from 'fs'

async function upsertFile(name: string) {
  try {
    // try to read file
    await fs.promises.readFile(name)
  } catch (error) {
    // create empty file, because it wasn't found
    await fs.promises.writeFile(name, '')
  }
}

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

Conditionally load latest/legacy jQuery version and fallback:

<!--[if lt IE 9]>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery-legacy/dist/jquery.min.js">\x3C/script>')</script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery/dist/jquery.min.js">\x3C/script>')</script>
<!--<![endif]-->

How to implement 2D vector array?

Another way to define a 2-d vector is to declare a vector of pair's.

 vector < pair<int,int> > v;

**To insert values**
 cin >> x >>y;
 v.push_back(make_pair(x,y));

**Retrieve Values**
 i=0 to size(v)
 x=v[i].first;
 y=v[i].second;

For 3-d vectors take a look at tuple and make_tuple.

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

How to split the name string in mysql?

select (case when locate('(', LocationName) = 0 
        then 
            horse_name
        else 
           left(LocationName, locate('(', LocationName) - 1)
       end) as Country            
from   tblcountry;

Telegram Bot - how to get a group chat id?

After mid-2018:
1:) Invite @getidsbot or @RawDataBot to your group and get your group id from the chat id field.

Message
 + message_id: 338
 + from
 ?  + id: *****
 ?  + is_bot: false
 ?  + first_name: ???
 ?  + username: ******
 ?  + language_code: en
 + chat
 ?  + id: -1001118554477    // This is Your Group id
 ?  + title: Test Group
 ?  + type: supergroup
 + date: 1544948900
 + text: A

2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.

Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm

in angularjs how to access the element that triggered the event?

I'm not sure which version you had, but this question was asked for long time ago. Currently with Angular 1.5, I can use the ng-keypress event and debounce function from Lodash to emulate similar behavior like ng-change, so I can capture the $event

<input type="text" ng-keypress="edit($event)" ng-model="myModel">

$scope.edit = _.debounce(function ($event) { console.log("$event", $event) }, 800)

Get Context in a Service

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)

How do I move a file (or folder) from one folder to another in TortoiseSVN?

You have to drag the file using the right mouse button. The moment you release the file to the new destination you will observe the option:

SVN move versioned files here.

Just select this option and you are done !!

phpMyAdmin mbstring error

In php's directory try change extension of configuration file (php.ini-development - default value of this file). I changed it to php.ini and phpmyadmin has worked.

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

ADB Android Device Unauthorized

I was tiered with this, I got that permission dialog by turning off wi-fi of my phone.

Return datetime object of previous month

Here is some code to do just that. Haven't tried it out myself...

def add_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month earlier.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> add_one_month(datetime.date(2010, 1, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_later = t + one_day
    while one_month_later.month == t.month:  # advance to start of next month
        one_month_later += one_day
    target_month = one_month_later.month
    while one_month_later.day < t.day:  # advance to appropriate day
        one_month_later += one_day
        if one_month_later.month != target_month:  # gone too far
            one_month_later -= one_day
            break
    return one_month_later

def subtract_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month later.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> subtract_one_month(datetime.date(2010, 3, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_earlier = t - one_day
    while one_month_earlier.month == t.month or one_month_earlier.day > t.day:
        one_month_earlier -= one_day
    return one_month_earlier

format a number with commas and decimals in C# (asp.net MVC3)

All that is needed is "#,0.00", c# does the rest.

Num.ToString("#,0.00"")

  • The "#,0" formats the thousand separators
  • "0.00" forces two decimal points

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s') where invoice.date comes in the form of anFixnum and then converted to a String.

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

How does ApplicationContextAware work in Spring?

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.

So, it seemed to be invoked when Spring container has started, if you want to do something at that time.

It just has one method to set the context, so you will get the context and do something to sth now already in context I think.

How to add a line to a multiline TextBox?

Try this

textBox1.Text += "SomeText\r\n" 

you can also try

textBox1.Text += "SomeText" + Environment.NewLine;

Where \r is carriage return and \n is new line

Could not load NIB in bundle

the error means that there is no .xib file with "JRProvidersController" name. recheck whether JRProvidersController.xib exists.

you will load .xib file with

controller = [[JRProvidersController alloc] initWithNibName:@"JRProvidersController" bundle:nil];

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

How to wait for a number of threads to complete?

If you make a list of the threads, you can loop through them and .join() against each, and your loop will finish when all the threads have. I haven't tried it though.

http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join()

What are .iml files in Android Studio?

They are project files, that hold the module information and meta data.

Just add *.iml to .gitignore.

In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml files will be generated.

How do I add a simple jQuery script to WordPress?

The solutions I've seen are from the perspective of adding javascript features to a theme. However, the OP asked, specifically, "How exactly do I add it for a single WordPress page?" This sounds like it might be how I use javascript in my Wordpress blog, where individual posts may have different javascript-powered "widgets". For instance, a post might let the user change variables (sliders, checkboxes, text input fields), and plots or lists the results.

Starting from the JavaScript perspective:

  1. Write your JavaScript functions in a separate “.js” file

Don’t even think about including significant JavaScript in your post’s html—create a JavaScript file, or files, with your code.

  1. Interface your JavaScript with your post's html

If your JavaScript widget interacts with html controls and fields, you’ll need to understand how to query and set those elements from JavaScript, and also how to let UI elements call your JavaScript functions. Here are a couple of examples; first, from JavaScript:

var val = document.getElementById(“AM_Freq_A_3”).value;

And from html:

<input type="range" id="AM_Freq_A_3" class="freqSlider" min="0" max="1000" value="0" oninput='sliderChanged_AM_widget(this);'/>
  1. Use jQuery to call your JavaScript widget’s initialization function

Add this to your .js file, using the name of your function that configures and draws your JavaScript widget when the page is ready for it:

jQuery(document).ready(function( $ ) {
    your_init_function();
});
  1. In your post’s html code, load the scripts needed for your post

In the Wordpress code editor, I typically specify the scripts at the end of the post. For instance, I have a scripts folder in my main directory. Inside I have a utilities directory with common JavaScript that some of my posts may share—in this case some of my own math utility function and the flotr2 plotting library. I find it more convenient to group the post-specific JavaScript in another directory, with subdirectories based on date instead of using the media manager, for instance.

<script type="text/javascript" src="/scripts/utils/flotr2.min.js"></script>
<script type="text/javascript" src="/scripts/utils/math.min.js"></script>
<script type="text/javascript" src="/scripts/widgets/20161207/FreqRes.js"></script>
  1. Enqueue jQuery

Wordpress registers jQuery, but it isn’t available unless you tell Wordpress you need it, by enqueuing it. If you don’t, the jQuery command will fail. Many sources tell you how to add this command to your functions.php, but assume you know some other important details.

First, it’s a bad idea to edit a theme—any future update of the theme will wipe out your changes. Make a child theme. Here’s how:

https://developer.wordpress.org/themes/advanced-topics/child-themes/

The child’s functions.php file does not override the parent theme’s file of the same name, it adds to it. The child-themes tutorial suggest how to enqueue the parent and child style.css file. We can simply add another line to that function to also enqueue jQuery. Here's my entire functions.php file for the child theme:

<?php
add_action( 'wp_enqueue_scripts', 'earlevel_scripts_enqueue' );
function earlevel_scripts_enqueue() {
    // styles
    $parent_style = 'parent-style';
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );

    // posts with js widgets need jquery
    wp_enqueue_script('jquery');
}

All ASP.NET Web API controllers return 404

I'm a bit stumped, not sure if this was due to an HTTP output caching issue.

Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.

Guess the code just had to sit and cook overnight... :)

Thanks for helping, guys!

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Get Root Directory Path of a PHP project

I want to point to the way Wordpress handles this:

define( 'ABSPATH', dirname( __FILE__ ) . '/' );

As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

Where is the itoa function in Linux?

Reading the code of guys who do it for a living will get you a LONG WAY.

Check out how guys from MySQL did it. The source is VERY WELL COMMENTED and will teach you much more than hacked up solutions found all over the place.

MySQL's implementation of int2str

I provide the mentioned implementation here; the link is here for reference and should be used to read the full implementation.

char *
int2str(long int val, char *dst, int radix, 
        int upcase)
{
  char buffer[65];
  char *p;
  long int new_val;
  char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
  ulong uval= (ulong) val;

  if (radix < 0)
  {
    if (radix < -36 || radix > -2)
      return NullS;
    if (val < 0)
    {
      *dst++ = '-';
      /* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
      uval = (ulong)0 - uval;
    }
    radix = -radix;
  }
  else if (radix > 36 || radix < 2)
    return NullS;

  /*
    The slightly contorted code which follows is due to the fact that
    few machines directly support unsigned long / and %.  Certainly
    the VAX C compiler generates a subroutine call.  In the interests
    of efficiency (hollow laugh) I let this happen for the first digit
    only; after that "val" will be in range so that signed integer
    division will do.  Sorry 'bout that.  CHECK THE CODE PRODUCED BY
    YOUR C COMPILER.  The first % and / should be unsigned, the second
    % and / signed, but C compilers tend to be extraordinarily
    sensitive to minor details of style.  This works on a VAX, that's
    all I claim for it.
  */
  p = &buffer[sizeof(buffer)-1];
  *p = '\0';
  new_val= uval / (ulong) radix;
  *--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
  val = new_val;
  while (val != 0)
  {
    ldiv_t res;
    res=ldiv(val,radix);
    *--p = dig_vec[res.rem];
    val= res.quot;
  }
  while ((*dst++ = *p++) != 0) ;
  return dst-1;
}

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

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

by default you would need to use the postgres user:

sudo -u postgres psql postgres

extract part of a string using bash/cut/split

Using a single sed

echo "/var/cpanel/users/joebloggs:DNS9=domain.com" | sed 's/.*\/\(.*\):.*/\1/'

How to create a md5 hash of a string in C?

Here's a complete example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE__)
#  define COMMON_DIGEST_FOR_OPENSSL
#  include <CommonCrypto/CommonDigest.h>
#  define SHA1 CC_SHA1
#else
#  include <openssl/md5.h>
#endif

char *str2md5(const char *str, int length) {
    int n;
    MD5_CTX c;
    unsigned char digest[16];
    char *out = (char*)malloc(33);

    MD5_Init(&c);

    while (length > 0) {
        if (length > 512) {
            MD5_Update(&c, str, 512);
        } else {
            MD5_Update(&c, str, length);
        }
        length -= 512;
        str += 512;
    }

    MD5_Final(digest, &c);

    for (n = 0; n < 16; ++n) {
        snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
    }

    return out;
}

    int main(int argc, char **argv) {
        char *output = str2md5("hello", strlen("hello"));
        printf("%s\n", output);
        free(output);
        return 0;
    }

MongoDB running but can't connect using shell

I don't see this having an accepted answer yet, so I'll just add my 2 cents.

I had the exact same issue just now. After a while I realized I've locked localhost out in my iptables rules. So, check your firewall.

Line Break in HTML Select Option?

I know this is an older post, but I'm leaving this for whomever else comes looking in the future.

You can't format line breaks into an option; however, you can use the title attibute to give a mouse-over tooltip to give the full info. Use a short descriptor in the option text and give the full skinny in the title.

<option value="1" title="This is my lengthy explanation of what this selection really means, so since you only see 1 on the drop down list you really know that you're opting to elect me as King of Willywarts!  Always be sure to read the fine print!">1</option>

Using ZXing to create an Android barcode scanning app

I had a problem with implementing the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.

It would pull up the application, but it wouldn't recognize any barcodes, and when I changed it from.

intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

to

intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");

It worked great. Just a tip for any other novice Android programmers.

Finding three elements in an array whose sum is closest to a given number

Here is the C++ code:

bool FindSumZero(int a[], int n, int& x, int& y, int& z)
{
    if (n < 3)
        return false;

    sort(a, a+n);

    for (int i = 0; i < n-2; ++i)
    {
        int j = i+1;
        int k = n-1;

        while (k >= j)
        {
            int s = a[i]+a[j]+a[k];

            if (s == 0 && i != j && j != k && k != i)
            {
                x = a[i], y = a[j], z = a[k];
                return true;
            }

            if (s > 0)
                --k;
            else
                ++j;
        }
    }

    return false;
}

A KeyValuePair in Java

import java.util.Map;

public class KeyValue<K, V> implements Map.Entry<K, V>
{
    private K key;
    private V value;

    public KeyValue(K key, V value)
    {
        this.key = key;
        this.value = value;
    }

    public K getKey()
    {
        return this.key;
    }

    public V getValue()
    {
        return this.value;
    }

    public K setKey(K key)
    {
        return this.key = key;
    }

    public V setValue(V value)
    {
        return this.value = value;
    }
}

In Tensorflow, get the names of all the Tensors in a graph

The accepted answer only gives you a list of strings with the names. I prefer a different approach, which gives you (almost) direct access to the tensors:

graph = tf.get_default_graph()
list_of_tuples = [op.values() for op in graph.get_operations()]

list_of_tuples now contains every tensor, each within a tuple. You could also adapt it to get the tensors directly:

graph = tf.get_default_graph()
list_of_tuples = [op.values()[0] for op in graph.get_operations()]

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

I used this:

HTML

<div class="container">
 <div class="parent">
  <div class="child">
   <div class="inner-container"></div>
  </div>
 </div>
</div>

CSS

.container {
  overflow-x: hidden;
}

.child {
  position: relative;
  width: 200%;
  left: -50%;
}

.inner-container{
  max-width: 1179px;
  margin:0 auto;
}

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Pass variables by reference in JavaScript

If you want to pass variables by reference, a better way to do that is by passing your arguments in an object and then start changing the value by using window:

window["varName"] = value;

Example:

// Variables with first values
var x = 1, b = 0, f = 15;


function asByReference (
    argumentHasVars = {},   // Passing variables in object
    newValues = [])         // Pass new values in array
{
    let VarsNames = [];

    // Getting variables names one by one
    for(let name in argumentHasVars)
        VarsNames.push(name);

    // Accessing variables by using window one by one
    for(let i = 0; i < VarsNames.length; i += 1)
        window[VarsNames[i]] = newValues[i]; // Set new value
}

console.log(x, b, f); // Output with first values

asByReference({x, b, f}, [5, 5, 5]); // Passing as by reference

console.log(x, b, f); // Output after changing values

Ajax request returns 200 OK, but an error event is fired instead of success

I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Difference between Running and Starting a Docker container

Explanation with an example:

Consider you have a game (iso) image in your computer.

When you run (mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]

But when you stop (similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]

And when you do start (similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]

In this example - The game image is your Docker image and virtual drive is your container.

How do I know the script file name in a Bash script?

if your invoke shell script like

/home/mike/runme.sh

$0 is full name

 /home/mike/runme.sh

basename $0 will get the base file name

 runme.sh

and you need to put this basic name into a variable like

filename=$(basename $0)

and add your additional text

echo "You are running $filename"

so your scripts like

/home/mike/runme.sh
#!/bin/bash 
filename=$(basename $0)
echo "You are running $filename"

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

Error installing mysql2: Failed to build gem native extension

In my case this helped:

$ export LDFLAGS="-L/usr/local/opt/openssl/lib"
$ export CPPFLAGS="-I/usr/local/opt/openssl/include"

Then:

gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/' -- --with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib

Result:

Building native extensions with: '--with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib'
This could take a while...
Successfully installed mysql2-0.5.2
Parsing documentation for mysql2-0.5.2
Installing ri documentation for mysql2-0.5.2
Done installing documentation for mysql2 after 0 seconds
1 gem installed

See this post (WARNING: Japanese language inside).

How to split a number into individual digits in c#?

Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.

The fastest way to get what you want is probably the ToCharArray() method of a String:

var myString = "12345";

var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}

You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:

byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();

A little more performant if you're using ASCII/Unicode strings:

byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();

That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

What does this GCC error "... relocation truncated to fit..." mean?

Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

Visual Studio move project to a different folder

I figured out this try this it worked for me.

In visual studio 2017 community edition it creates a project at this path "C:\Users\mark\source\repos\mipmaps\mipmaps" This will create a access to file is denied issue

Now, you can fix that this way.

close your visual studio process. Then, find your project and copy the project folder But, first make a Sub-folder Named Projects inside of your visual studio 2017 folder in documents. Next, paste the project folder inside of your visual studio 2017 Project folder not the main visual studio 2017 folder it should go into the Sub-folder called Projects. Next, restart Visual studio 2017 Then, choose Open project Solution Then, find your project you pasted in your visual studio 2017 Projects folder Then clean the Project and rebuild it , It, should build and compile just fine. Hope, this Helped out anybody else. Not to sure why Microsoft thought building your projects in a path where it needs write permissions is beyond me.

Adding a Scrollable JTextArea (Java)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

Groovy write to file (newline)

I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.

class Doh {
   def ln = System.getProperty('line.separator')
   File file //assume it's initialized 

   void append(String content) {
       file << "$content$ln"
   }
}

Pretty neat I think :)

Unit Tests not discovered in Visual Studio 2017

Don't read out of date articles under MSDN. .NET Core relevant materials are under docs.microsoft.com

https://docs.microsoft.com/en-us/dotnet/articles/core/testing/

Generally speaking you need a .NET Core console app to contain the unit test cases.

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

Insert Update trigger how to determine if insert or update

Triggers have special INSERTED and DELETED tables to track "before" and "after" data. So you can use something like IF EXISTS (SELECT * FROM DELETED) to detect an update. You only have rows in DELETED on update, but there are always rows in INSERTED.

Look for "inserted" in CREATE TRIGGER.

Edit, 23 Nov 2011

After comment, this answer is only for INSERTED and UPDATED triggers.
Obviously, DELETE triggers can not have "always rows in INSERTED" as I said above

How to make 'submit' button disabled?

As seen in this Angular example, there is a way to disable a button until the whole form is valid:

<button type="submit" [disabled]="!ngForm.valid">Submit</button>

Optimal way to Read an Excel file (.xls/.xlsx)

Read from excel, modify and write back

 /// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
    var _xl = new Excel.Application();
    var wb = _xl.Workbooks.Open(filename);
    var sheets = wb.Sheets;
    DataSet dataSet = null;
    if (sheets != null && sheets.Count != 0)
    {
        dataSet = new DataSet();
        foreach (var item in sheets)
        {
            var sheet = (Excel.Worksheet)item;
            DataTable dt = null;
            if (sheet != null)
            {
                dt = new DataTable();
                var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                for (int j = 0; j < ColumnCount; j++)
                {
                    var cell = (Excel.Range)sheet.Cells[1, j + 1];
                    var column = new DataColumn(headers ? cell.Value : string.Empty);
                    dt.Columns.Add(column);
                }

                for (int i = 0; i < rowCount; i++)
                {
                    var r = dt.NewRow();
                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                        r[j] = cell.Value;
                    }
                    dt.Rows.Add(r);
                }

            }
            dataSet.Tables.Add(dt);
        }
    }
    _xl.Quit();
    return dataSet;
}



 public string Export(DataTable dt, bool headers = false)
    {
        var wb = _xl.Workbooks.Add();
        var sheet = (Excel.Worksheet)wb.ActiveSheet;
        //process columns
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var col = dt.Columns[i];
            //added columns to the top of sheet
            var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
            currentCell.Value = col.ToString();
            currentCell.Font.Bold = true;
            //process rows
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                var row = dt.Rows[j];
                //added rows to sheet
                var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
                cell.Value = row[i];
            }
            currentCell.EntireColumn.AutoFit();
        }
        var fileName="{somepath/somefile.xlsx}";
        wb.SaveCopyAs(fileName);
        _xl.Quit();
        return fileName;
    }

Java NIO FileChannel versus FileOutputstream performance / usefulness

I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.

FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.

Difference between "process.stdout.write" and "console.log" in node.js?

One big difference that hasn't been mentioned is that process.stdout only takes strings as arguments (can also be piped streams), while console.log takes any Javascript data type.

e.g:

// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))

// any other data type passed as param will throw a TypeError
process.stdout.write('1')

// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

Difference between MongoDB and Mongoose

From the first answer,

"Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB."

You can now also define schema with mongoDB native driver using

##For new collection

`db.createCollection("recipes",
    validator: { $jsonSchema: {
         <<Validation Rules>>
        }
    }
)`

##For existing collection

`db.runCommand( {
        collMod: "recipes",
        validator: { $jsonSchema: {
             <<Validation Rules>>
            }
        }
    } )`
    

##full example

`db.createCollection("recipes", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "servings", "ingredients"],
      additionalProperties: false,
      properties: {
        _id: {},
        name: {
          bsonType: "string",
          description: "'name' is required and is a string"
        },
        servings: {
          bsonType: ["int", "double"],
          minimum: 0,
          description:
            "'servings' is required and must be an integer with a minimum of zero."
        },
        cooking_method: {
          enum: [
            "broil",
            "grill",
            "roast",
            "bake",
            "saute",
            "pan-fry",
            "deep-fry",
            "poach",
            "simmer",
            "boil",
            "steam",
            "braise",
            "stew"
          ],
          description:
            "'cooking_method' is optional but, if used, must be one of the listed options."
        },
        ingredients: {
          bsonType: ["array"],
          minItems: 1,
          maxItems: 50,
          items: {
            bsonType: ["object"],
            required: ["quantity", "measure", "ingredient"],
            additionalProperties: false,
            description: "'ingredients' must contain the stated fields.",
            properties: {
              quantity: {
                bsonType: ["int", "double", "decimal"],
                description:
                  "'quantity' is required and is of double or decimal type"
              },
              measure: {
                enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
                description:
                  "'measure' is required and can only be one of the given enum values"
              },
              ingredient: {
                bsonType: "string",
                description: "'ingredient' is required and is a string"
              },
              format: {
                bsonType: "string",
                description:
                  "'format' is an optional field of type string, e.g. chopped or diced"
              }
            }
          }
        }
      }
    }
  }
});`

Insert collection Example

`db.recipes.insertOne({
  name: "Chocolate Sponge Cake Filling",
  servings: 4,
  ingredients: [
    {
      quantity: 7,
      measure: "ounce",
      ingredient: "bittersweet chocolate",
      format: "chopped"
    },
    { quantity: 2, measure: "cup", ingredient: "heavy cream" }
  ]
});`

Dynamically fill in form values with jQuery

Automatically fill all form fields from an array

http://jsfiddle.net/brynner/wf0rk7tz/2/

JS

function fill(a){
    for(var k in a){
        $('[name="'+k+'"]').val(a[k]);
    }
}

array_example = {"God":"Jesus","Holy":"Spirit"};

fill(array_example);

HTML

<form>
<input name="God">
<input name="Holy">
</form>

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

from django.db import models

class Foo(models.Model):
    any_field = models.BooleanField(default=True)

How to use __doPostBack()

This is how I do it

    public void B_ODOC_OnClick(Object sender, EventArgs e)
    {
        string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);               
    }

extract digits in a simple way from a python string

The simplest way to extract a number from a string is to use regular expressions and findall.

>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']

It might be that you need something more complex, but this is a good first step.

Note that you'll still have to call int on the result to get a proper numeric type (rather than another string):

>>> map(int, re.findall('\d+', s))
[300, 200, 439843]

Set NA to 0 in R

Why not try this

  na.zero <- function (x) {
        x[is.na(x)] <- 0
        return(x)
    }
    na.zero(df)

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

How to add button tint programmatically

If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:

myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))

You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:

fun MaterialButton.changeColor(color: Int) {
    this.background.setTintList(ContextCompat.getColorStateList(context, color))
}

Then, you can use your function everywhere like this:

myButton.changeColor(R.color.myColor)

css 'pointer-events' property alternative for IE

I've found another solution to solve this problem. I use jQuery to set the href-attribute to javascript:; (not ' ', or the browser will reload the page) if the browser window width is greater than 1'000px. You need to add an ID to your link. Here's what I'm doing:

// get current browser width
var width = $(window).width();
if (width >= 1001) {

    // refer link to nothing
    $("a#linkID").attr('href', 'javascript:;'); 
}

Maybe it's useful for you.

How to escape special characters in building a JSON string?

A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.

See this list of special character used in JSON :

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\"  Double quote
\\  Backslash character


However, even if it is totally contrary to the spec, the author could use \'.

This is bad because :

  • It IS contrary to the specs
  • It is no-longer JSON valid string

But it works, as you want it or not.

For new readers, always use a double quotes for your json strings.

Get IPv4 addresses from Dns.GetHostEntry()

IPv6

lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()


IPv4

lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

Server certificate verification failed: issuer is not trusted

during command line works. I'm using Ant to commit an artifact after build completes. Experienced the same issue... Manually excepting the cert did not work (Jenkins is funny that way). Add these options to your svn command:

--non-interactive

--trust-server-cert

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

How to use jQuery to show/hide divs based on radio button selection?

Below code is perfectly workd for me:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('input[type="radio"]').click(function(){_x000D_
        var inputValue = $(this).attr("value");_x000D_
        var targetBox = $("." + inputValue);_x000D_
        $(".box").not(targetBox).hide();_x000D_
        $(targetBox).show();_x000D_
    });_x000D_
});
_x000D_
.box{_x000D_
        color: #fff;_x000D_
        padding: 20px;_x000D_
        display: none;_x000D_
        margin-top: 20px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
    label{ margin-right: 15px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
        <label><input type="radio" name="colorRadio" value="red"> red</label>_x000D_
        <label><input type="radio" name="colorRadio" value="green"> green</label>_x000D_
        <label><input type="radio" name="colorRadio" value="blue"> blue</label>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red radio button</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green radio button</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
_x000D_
_x000D_
_x000D_

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

SELECT from nothing?

In Standard SQL, no. A WHERE clause implies a table expression.

From the SQL-92 spec:

7.6 "where clause"

Function

Specify a table derived by the application of a "search condition" to the result of the preceding "from clause".

In turn:

7.4 "from clause"

Function

Specify a table derived from one or more named tables.

A Standard way of doing it (i.e. should work on any SQL product):

SELECT DISTINCT 'Hello world' AS new_value
  FROM AnyTableWithOneOrMoreRows
 WHERE 1 = 1;

...assuming you want to change the WHERE clause to something more meaningful, otherwise it can be omitted.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})

It would be helpful if you posted your code.

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

js window.open then print()

Turgut gave the right solution. Just for clarity, you need to add close after writing.

function openWin()
  {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");


    myWindow.document.close(); //missing code


    myWindow.focus();
    myWindow.print(); 
  }

Detect network connection type on Android

You can make custom Method to accomplish this task.

  public String getNetworkClass(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mTelephonyManager.getNetworkType();
        switch (networkType) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G";
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "Unknown";
        }
    }

How to handle a lost KeyStore password in Android?

In case a wrong password is provided, even just once, it keeps saying on next attempts:

Keystore tampered with or password incorrect.

Even when you provide the correct one. I tried it several times, maybe it's some kind of protection.
Close the export wizard and start it again with the correct password, now it works :)

How to take backup of a single table in a MySQL database?

We can take a mysql dump of any particular table with any given condition like below

mysqldump -uusername -p -hhost databasename tablename --skip-lock-tables

If we want to add a specific where condition on table then we can use the following command

mysqldump -uusername -p -hhost databasename tablename --where="date=20140501" --skip-lock-tables

How to run travis-ci locally

Use wwtd (what would travis do) ruby gem to run tests on your local machine roughly as they would run on travis.

It will recreate the build matrix and run each configuration, great to sanity check setup before pushing.

gem i wwtd
wwtd

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

test if display = none

Try this instead to only select the visible elements under the tbody:

$('tbody :visible').highlight(myArray[i]);

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

Java recursive Fibonacci sequence

Fibonacci series is one simple code that shows the power of dynamic programming. All we learned from school days is to run it via iterative or max recursive code. Recursive code works fine till 20 or so, if you give numbers bigger than that you will see it takes a lot of time to compute. In dynamic programming you can code as follows and it takes secs to compute the answer.

static double fib(int n) {
    if (n < 2)
        return n;
    if (fib[n] != 0)
        return fib[n];
    fib[n] = fib(n - 1) + fib(n - 2);
    return fib[n];
}

You store values in an array and proceed to fresh computation only when the array cannot provide you the answer.

How can I declare enums using java

public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

How to get UTC timestamp in Ruby?

What good is a timestamp with its granularity given in seconds? I find it much more practical working with Time.now.to_f. Heck, you may even throw a to_s.sub('.','') to get rid of the decimal point, or perform a typecast like this: Integer(1e6*Time.now.to_f).

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

How to recognize swipe in all 4 directions

In Swift 5,

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeGesture.direction = [.left, .right, .up, .down]
view.addGestureRecognizer(swipeGesture)

Mockito matcher and array of primitives

I used Matchers.refEq for this.

AngularJS disable partial caching on dev machine

I found that the HTTP interceptor method works pretty nicely, and allows additional flexibility & control. Additionally, you can cache-bust for each production release by using a release hash as the buster variable.

Here is what the dev cachebusting method looks like using Date.

app.factory('cachebustInjector', function(conf) {   
    var cachebustInjector = {
        request: function(config) {    
            // new timestamp will be appended to each new partial .html request to prevent caching in a dev environment               
            var buster = new Date().getTime();

            if (config.url.indexOf('static/angular_templates') > -1) {
                config.url += ['?v=', buster].join('');
            }
            return config;
        }
    };
    return cachebustInjector;
});

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('cachebustInjector');
}]);

How do I change the font size and color in an Excel Drop Down List?

Unfortunately, you can't change the font size or styling in a drop-down list that is created using data validation.

You can style the text in a combo box, however. Follow the instructions here: Excel Data Validation Combo Box

Git: force user and password prompt

With git config -l, I now see I have a credential.helper=osxkeychain option

That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")

You can disable that option entirely, or only for a single repo.

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

How to sleep for five seconds in a batch file/cmd

Make a cmd file called sleep.cmd:

REM Usage: SLEEP Time_in_MiliSECONDS
@ECHO off
ping 1.0.0.0 -n 1 -w %1 > nul

Copy sleep.cmd to c:\windows\system32

Usage:

sleep 500

Sleeps for 0.5 seconds. Arguments in ms. Once copied to System32, can be used everywhere.

EDIT: You should also be away that if the machine isn't connected to a network (say a portable that your using in the subway), the ping trick doesn't really work anymore.

Python `if x is not None` or `if not x is None`?

The is not operator is preferred over negating the result of is for stylistic reasons. "if x is not None:" reads just like English, but "if not x is None:" requires understanding of the operator precedence and does not read like english.

If there is a performance difference my money is on is not, but this almost certainly isn't the motivation for the decision to prefer that technique. It would obviously be implementation-dependent. Since is isn't overridable, it should be easy to optimise out any distinction anyhow.

Can a variable number of arguments be passed to a function?

If I may, Skurmedel's code is for python 2; to adapt it to python 3, change iteritems to items and add parenthesis to print. That could prevent beginners like me to bump into: AttributeError: 'dict' object has no attribute 'iteritems' and search elsewhere (e.g. Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp()) why this is happening.

def myfunc(**kwargs):
for k,v in kwargs.items():
   print("%s = %s" % (k, v))

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

and:

def myfunc2(*args, **kwargs):
   for a in args:
       print(a)
   for k,v in kwargs.items():
       print("%s = %s" % (k, v))

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

Visual Studio Code Automatic Imports

2018 now. You don't need any extensions for auto-imports in Javascript (as long as you have checkjs: true in your jsconfig.json file) and TypeScript.

There are two types of auto imports: the add missing import quick fix which shows up as a lightbulb on errors:

enter image description here

And the auto import suggestions. These show up a suggestion items as you type. Accepting an auto import suggestion automatically adds the import at the top of the file

enter image description here

Both should work out of the box with JavaScript and TypeScript. If auto imports still do not work for you, please open an issue

calculating number of days between 2 columns of dates in data frame

You could find the difference between dates in columns in a data frame by using the function difftime as follows:

df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))

Create Excel files from C# without office

You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.

The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

remove legend title in ggplot

This works too and also demonstrates how to change the legend title:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

Latex - Change margins of only a few pages

For figures you can use the method described here :
http://texblog.net/latex-archive/layout/centering-figure-table/
namely, do something like this:

\begin{figure}[h]
\makebox[\textwidth]{%
        \includegraphics[width=1.5\linewidth]{bla.png}
    }
\end{figure}

Notice that if you have subfigures in the figure, you'll probably want to enter into paragraph mode inside the box, like so:

\begin{figure}[h]
\makebox[\textwidth]{\parbox{1.5\textwidth}{ %
\centering
\subfigure[]{\includegraphics[width=0.7\textwidth]{a.png}}
\subfigure[]{\includegraphics[width=0.7\textwidth]{b.png}}
\end{figure}

For allowing the figure to be centered in the page, protruding into both margins rather than only the right margin.
This usually does the trick for images. Notice that with this method, the caption of the image will still be in the delimited by the normal margins of the page (which is a good thing).

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

Remove duplicates from an array of objects in JavaScript

Here's another option to do it using Array iterating methods if you need comparison only by one field of an object:

    function uniq(a, param){
        return a.filter(function(item, pos, array){
            return array.map(function(mapItem){ return mapItem[param]; }).indexOf(item[param]) === pos;
        })
    }

    uniq(things.thing, 'place');

What is the proper way to check and uncheck a checkbox in HTML5?

You can refer to this page at w3schools but basically you could use any of:

<input checked>
<input checked="checked">
<input checked="">

How to get screen width and height

If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

UPDATE: With API level 17+, you can use getRealSize:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

If you want the available window size, you can use getDecorView to calculate the available area by subtracting the decor view size from the real display size:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

Rect windowSize = new Rect();
ctivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowSize);

int width = displaySize.x - Math.abs(windowSize.width());
int height = displaySize.y - Math.abs(windowSize.height());
return new Point(width, height);

getRealMetrics may also work (requires API level 17+), but I haven't tried it yet:

DisplayMetrics metrics = new DisplayMetrics();
activity.GetWindowManager().getDefaultDisplay().getRealMetrics(metrics);

mysqli_fetch_array while loop columns

Try this :

   $i = 0;    
    while($row = mysqli_fetch_array($result)) {  

            $posts['post_id'] = $row[$i]['post_id'];
            $posts['post_title'] = $row[$i]['post_title'];
            $posts['type'] = $row[$i]['type'];
            $posts['author'] = $row[$i]['author'];  

        }   
    $i++;
    }

print_r($posts);

Setting a Sheet and cell as variable

Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:

Sub RangeExample()
Dim MyRNG As Range

Set MyRNG = Sheets("Sheet1").Cells(23, 4)

Debug.Print MyRNG.Value

End Sub

Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:

Sub ValueExample()
Dim MyVal As String

MyVal = Sheets("Sheet1").Cells(23, 4).Value

Debug.Print MyVal

End Sub

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

Hbase quickly count number of rows

To count the Hbase table record count on a proper YARN cluster you have to set the map reduce job queue name as well:

hbase org.apache.hadoop.hbase.mapreduce.RowCounter -Dmapreduce.job.queuename= < Your Q Name which you have SUBMIT access>
 < TABLE_NAME>

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

What happens to a declared, uninitialized variable in C? Does it have a value?

It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.

As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code

int num;
int a = num;
int b = num;

does not guarantee that variables a and b will receive identical values. Interestingly, this is not some pedantic theoretical concept, this readily happens in practice as consequence of optimization.

So in general, the popular answer that "it is initialized with whatever garbage was in memory" is not even remotely correct. Uninitialized variable's behavior is different from that of a variable initialized with garbage.

Xampp MySQL not starting - "Attempting to start MySQL service..."

  1. In the cmd type: services.msc Find MySql and change properties to the disabled.
  2. In the control panel of Xampp uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.

How to increment a JavaScript variable using a button press event

Use type = "button" instead of "submit", then add an onClick handler for it.

For example:

<input type="button" value="Increment" onClick="myVar++;" />

Find duplicate characters in a String and count the number of occurances using Java

In java... using for loop:

import java.util.Scanner;

/**
 *
 * @author MD SADDAM HUSSAIN */
public class Learn {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        char process[] = input.toCharArray();
        boolean status = false;
        int index = 0;
        for (int i = 0; i < process.length; i++) {
            for (int j = 0; j < process.length; j++) {

                if (i == j) {
                    continue;
                } else {
                    if (process[i] == process[j]) {
                        status = true;
                        index = i;
                        break;
                    } else {
                        status = false;

                    }
                }

            }
            if (status) {
                System.out.print("" + process[index]);

            }
        }
    }
}

Where can I get a list of Countries, States and Cities?

geonames.org has an api and a data dump of worldwide geographical places.

Retrofit 2 - Dynamic URL

You can use the encoded flag on the @Path annotation:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • This will prevent the replacement of / with %2F.
  • It will not save you from ? being replaced by %3F, however, so you still can't pass in dynamic query strings.

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Applying function with multiple arguments to create a new pandas column

One more dict style clean syntax:

df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)

or,

df["new_column"] = df["A"] * df["B"]

What is the difference between the kernel space and the user space?

Trying to give a very simplified explanation

Virtual Memory is divided into kernel space and the user space. Kernel space is that area of virtual memory where kernel processes will run and user space is that area of virtual memory where user processes will be running.

This division is required for memory access protections.

Whenever a bootloader starts a kernel after loading it to a location in RAM, (on an ARM based controller typically)it needs to make sure that the controller is in supervisor mode with FIQ's and IRQ's disabled.

SQLDataReader Row Count

This will get you the row count, but will leave the data reader at the end.

dataReader.Cast<object>().Count();

Redirect stderr and stdout in Bash

Take a look here. Should be:

yourcommand &>filename

(redirects both stdout and stderr to filename).

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

Get data from fs.readFile

sync and async file reading way:

//fs module to read file in sync and async way

var fs = require('fs'),
    filePath = './sample_files/sample_css.css';

// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
});*/

//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);

Node Cheat Available at read_file.

How to access URL segment(s) in blade in Laravel 5?

The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.

{{ Request::segment(1) }} 

Better way to sum a property value in an array

can also use Array.prototype.forEach()

let totalAmount = 0;
$scope.traveler.forEach( data => totalAmount = totalAmount + data.Amount);
return totalAmount;

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

How to change row color in datagridview?

Some people like to use the Paint, CellPainting or CellFormatting events, but note that changing a style in these events causes recursive calls. If you use DataBindingComplete it will execute only once. The argument for CellFormatting is that it is called only on visible cells, so you don't have to format non-visible cells, but you format them multiple times.

ExpressionChangedAfterItHasBeenCheckedError Explained

Follow the below steps:

1. Use 'ChangeDetectorRef' by importing it from @angular/core as follows:

import{ ChangeDetectorRef } from '@angular/core';

2. Implement it in constructor() as follows:

constructor(   private cdRef : ChangeDetectorRef  ) {}

3. Add the following method to your function which you are calling on an event like click of button. So it look like this:

functionName() {   
    yourCode;  
    //add this line to get rid of the error  
    this.cdRef.detectChanges();     
}

Sublime Text 3 how to change the font size of the file sidebar?

Navigate to Sublime Text>Preferences>Browse Packages. You should see a file tree.

In the Packages folder, you should see

Theme - Default > Default.sublime-theme (substitute Default for your theme name)

Open that file and find the "class": "sidebar_label: entry and add "font.size".

example:

    {
        "class": "sidebar_label",
        "color": [0, 0, 0],
        "font.bold": false,
        "font.size": 14
    },

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

How to apply !important using .css()?

I would assume you tried it without adding !important?

Inline CSS (which is how JavaScript adds styling) overrides the stylesheet CSS. I'm pretty sure that's the case even when the stylesheet CSS rule has !important.

Another question (maybe a stupid question but must be asked.): Is the element you are trying to work on display:block; or display:inline-block;?

Not knowing your expertise in CSS... inline elements don't always behave as you would expect.

When to create variables (memory management)

Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.

Nonprimitive (ints, chars, doubles, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.

On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.

In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.

And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.

Java's actually very nicely made so that you shouldn't have to worry about nulling variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.

*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.

Setting Windows PATH for Postgres tools

Incase any one still wondering how to add environment variables then please use this link to add variables. Link: https://sqlbackupandftp.com/blog/setting-windows-path-for-postgres-tools

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
        <thead>
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            </tr>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>
            </tr>
        </tbody>
    </table>

bootply

Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

        <thead>
            <tr>
                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>
            </tr>
        </thead>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

Using Caps Lock as Esc in Mac OS X

Seil isn't yet available on macOS Sierra (10.12 beta). As such, I've been using Keyboard Maestro with these settings: enter image description here

Credit to this github comment: https://github.com/tekezo/Seil/issues/68#issuecomment-230131664

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

How to match all occurrences of a regex

if you have a regexp with groups:

str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
re=/(\d+)[m-t]/

you can use String's scan method to find matching groups:

str.scan re
#> [["54"], ["1"], ["3"]]

To find the matching pattern:

str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]

Generating Unique Random Numbers in Java

Though it's an old thread, but adding another option might not harm. (JDK 1.8 lambda functions seem to make it easy);

The problem could be broken down into the following steps;

  • Get a minimum value for the provided list of integers (for which to generate unique random numbers)
  • Get a maximum value for the provided list of integers
  • Use ThreadLocalRandom class (from JDK 1.8) to generate random integer values against the previously found min and max integer values and then filter to ensure that the values are indeed contained by the originally provided list. Finally apply distinct to the intstream to ensure that generated numbers are unique.

Here is the function with some description:

/**
 * Provided an unsequenced / sequenced list of integers, the function returns unique random IDs as defined by the parameter
 * @param numberToGenerate
 * @param idList
 * @return List of unique random integer values from the provided list
 */
private List<Integer> getUniqueRandomInts(List<Integer> idList, Integer numberToGenerate) {

    List<Integer> generatedUniqueIds = new ArrayList<>();

    Integer minId = idList.stream().mapToInt (v->v).min().orElseThrow(NoSuchElementException::new);
    Integer maxId = idList.stream().mapToInt (v->v).max().orElseThrow(NoSuchElementException::new);

            ThreadLocalRandom.current().ints(minId,maxId)
            .filter(e->idList.contains(e))
            .distinct()
            .limit(numberToGenerate)
            .forEach(generatedUniqueIds:: add);

    return generatedUniqueIds;

}

So that, to get 11 unique random numbers for 'allIntegers' list object, we'll call the function like;

    List<Integer> ids = getUniqueRandomInts(allIntegers,11);

The function declares new arrayList 'generatedUniqueIds' and populates with each unique random integer up to the required number before returning.

P.S. ThreadLocalRandom class avoids common seed value in case of concurrent threads.

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

How to get file path from OpenFileDialog and FolderBrowserDialog?

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

How to use external ".js" files

Code like this

 <html>
    <head>
          <script type="text/javascript" src="path/to/script.js"></script>
          <!--other script and also external css included over here-->
    </head>
    <body>
        <form>
            <select name="users" onChange="showUser(this.value)">
               <option value="1">Tom</option>
               <option value="2">Bob</option>
               <option value="3">Joe</option>
            </select>
        </form>
    </body>
    </html>

I hope it will help you.... thanks

How to create a TextArea in Android

Use TextView inside a ScrollView to display messages with any no.of lines. User can't edit the text in this view as in EditText.

I think this is good for your requirement. Try it once.

You can change the default color and text size in XML file only if you want to fix them as below:

<TextView 
    android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="100px"
    android:textColor="#f00"
    android:textSize="25px"
    android:typeface="serif"
    android:textStyle="italic"/>

or if you want to change dynamically whenever you want use as below:

TextView textarea = (TextView)findViewById(R.id.tv);  // tv is id in XML file for TextView
textarea.setTextSize(20);
textarea.setTextColor(Color.rgb(0xff, 0, 0));
textarea.setTypeface(Typeface.SERIF, Typeface.ITALIC);

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

IE11 meta element Breaks SVG

After trying the other suggestions to no avail I discovered that this issue was related to styling for me. I don't know a lot about the why but I found that my SVGs were not visible because they were not holding their place in the DOM.

In essence, the containers around my SVGs were at width: 0 and overflow: hidden.

I fixed this by setting a width on the containers but it is possible that there is a more direct solution to that particular issue.

Refused to load the script because it violates the following Content Security Policy directive

To elaborate some more on this, adding

script-src 'self' http://somedomain 'unsafe-inline' 'unsafe-eval';

to the meta tag like so,

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; script-src 'self' https://somedomain.com/ 'unsafe-inline' 'unsafe-eval';  media-src *">

fixes the error.

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

AngularJS event on window innerWidth size change

If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout to not update the attribute until it has been unchanged for 500ms.

var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
    var newWidth = window.innerWidth,
        updateStuffTimer;

    if (newWidth !== oldWidth) {
        $timeout.cancel(updateStuffTimer);
    }

    updateStuffTimer = $timeout(function() {
         updateStuff(newWidth); // Update the attribute based on window.innerWidth
    }, 500);
});

$scope.$on('$destroy',function (){
    $(window).off('resize.doResize'); // remove the handler added earlier
});

Reference: https://gist.github.com/tommaitland/7579618

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

How to make a checkbox checked with jQuery?

You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.

This JS snippet should work fine:

document.TheFormHere.test.Value = true;

What does '&' do in a C++ declaration?

One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

void foo(int &x)
{
    x = x + 1;
}

void foo(int *x)
{
    *x = *x + 1;
}

The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

How to make a button redirect to another page using jQuery or just Javascript

is this what you mean?

$('button selector').click(function(){
   window.location.href='the_link_to_go_to.html';
})

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

How can I mimic the bottom sheet from the Maps app?

I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.

See below link for more details.

https://github.com/OfTheWolf/UBottomSheet

ubottom sheet

How to terminate a Python script

Another way is:

raise SystemExit

Form Submission without page refresh

The problem is the Method 'POST' your form is submitting by using the "post" method, and in the AJAX you are using "GET".

How to generate the "create table" sql statement for an existing table in postgreSQL

If you want to find the create statement for a table without using pg_dump, This query might work for you (change 'tablename' with whatever your table is called):

SELECT                                          
  'CREATE TABLE ' || relname || E'\n(\n' ||
  array_to_string(
    array_agg(
      '    ' || column_name || ' ' ||  type || ' '|| not_null
    )
    , E',\n'
  ) || E'\n);\n'
from
(
  SELECT 
    c.relname, a.attname AS column_name,
    pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
    case 
      when a.attnotnull
    then 'NOT NULL' 
    else 'NULL' 
    END as not_null 
  FROM pg_class c,
   pg_attribute a,
   pg_type t
   WHERE c.relname = 'tablename'
   AND a.attnum > 0
   AND a.attrelid = c.oid
   AND a.atttypid = t.oid
 ORDER BY a.attnum
) as tabledefinition
group by relname;

when called directly from psql, it is usefult to do:

\pset linestyle old-ascii

Also, the function generate_create_table_statement in this thread works very well.

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

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

<asp:TemplateField>
<ItemTemplate>
        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
        </asp:Label>
</ItemTemplate>
</asp:TemplateField>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

When should I use Kruskal as opposed to Prim (and vice versa)?

Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.