Programs & Examples On #Omniauth

OmniAuth is a flexible Ruby authentication library that standardizes multi-provider authentication for web applications

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

If you're having this issue, and try to run bundle exec jekyll serve per this Jekyll documentation, it'll ask you to run bundle install, which should prompt you to install any missing gems, which in this case will be rake. This should resolve your issue.

You may also need to run bundle update to ensure Gemfile.lock is referencing the most up-to-date gems.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

The main reason for this issue will only come from chrome and chrome handles WWW and non www differently depending on how you entered your URL in the browsers and it searches from google and directly shows the results, so the redirection URL sent is different in a different case

enter image description here

Add all the possible combinations you can find the exact url sent from fiddler , the 400 error pop up will not give you the exact http and www infromation

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

Excel: replace part of cell's string value

I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:

=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")

In my case, I am using excel to view a DBF file and however it was populated has times like this:

9:16a
2:22p

So I just made a new column and put that formula in it to convert it to the excel time format.

How do AX, AH, AL map onto EAX?

no your ans is Wrong

Selection of Al and Ah is from AX not from EAX

e.g

EAX=0000 0000 0000 0000 0000 0000 0000 0111

So if we call AX it should return

0000 0000 0000 0111

if we call AH it should return

0000 0000

and when we call AL it should return

0000 0111

Example number 2

EAX: 22 33 55 77
AX: 55 77
AH: 55    
AL: 77

example 3

EAX: 1111 0000 0000 0000 0000 0000 0000 0111    
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111  

Cannot open include file with Visual Studio

For me, it helped to link the projects current directory as such:

In the properties -> C++ -> General window, instead of linking the path to the file in "additional include directories". Put "." and uncheck "inheret from parent or project defaults".

Hope this helps.

How to convert all text to lowercase in Vim

I had a similar issue, and I wanted to use ":%s/old/new/g", but ended up using two commands:

:0
gu:$

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

Display a message in Visual Studio's output window when not debug mode?

To write in the Visual Studio output window I used IVsOutputWindow and IVsOutputWindowPane. I included as members in my OutputWindow class which look like this :

public class OutputWindow : TextWriter
{
  #region Members

  private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
  private static IVsOutputWindow mOutputWindow = null;
  private static IVsOutputWindowPane mOutputPane = null;

  #endregion

  #region Constructor

  public OutputWindow(DTE2 aDte)
  {
    if( null == mOutputWindow )
    {
      IServiceProvider serviceProvider = 
      new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
      mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
    }

    if (null == mOutputPane)
    {
      Guid generalPaneGuid = mPaneGuid;
      mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);

      if ( null == pane)
      {
        mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
        mOutputWindow.GetPane(ref generalPaneGuid, out pane);
      }
      mOutputPane = pane;
    }
  }

  #endregion

  #region Properties

  public override Encoding Encoding => System.Text.Encoding.Default;

  #endregion

  #region Public Methods

  public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");

  public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());

  public void Show(DTE2 aDte)
  {
    mOutputPane.Activate();
    aDte.ExecuteCommand("View.Output", string.Empty);
  }

  public void Clear() => mOutputPane.Clear();

  #endregion
}

If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher. To write something in output window using this implementation now you can simple do this:

Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;

using (OutputWindow outputWindow = new OutputWindow(mDte))
{
  mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  {
    outputWindow.Write("Write what you want here");
  }));
}

How to get the last char of a string in PHP?

As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this:

$str[-1]

DEMO

At the request of a @mickmackusa, I supplement my answer with possible ways of application:

<?php

$str='abcdef';
var_dump($str[-2]); // => string(1) "e"

$str[-3]='.';
var_dump($str);     // => string(6) "abc.ef"

var_dump(isset($str[-4]));  // => bool(true)

var_dump(isset($str[-10])); // => bool(false)

Display / print all rows of a tibble (tbl_df)

you can print it in Rstudio with View() more convenient:

df %>% View()

View(df)

jQuery event for images loaded

I created my own script, because I found many plugins to be quite bloated, and I just wanted it to work the way I wanted. Mine checks to see if each image has a height (native image height). I've combined that with the $(window).load() function to get around the issues of caching.

I've code commented it quite heavily, so it should be interesting to look at, even if you don't use it. It works perfectly for me.

Without further ado, here it is:

imgLoad.js script

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Download the latest "sdk platform" and "sdk build tools" of same version like 23.* for 
both from "sdk Managar".

(for reference see above hosted image from back track). Then right click on your project -> properties -> Android -> in "project build properties" select "API level" 23 or the latest one which you updated. Then clean your project once.

Note: But all three should be in same version.

How do I hide a menu item in the actionbar?

I think a better approach would be to use a member variable for the menu, initialize it in onCreateOptionsMenu() and just use setVisible() afterwards, without invalidating the options menu.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

What is the role of the package-lock.json?

package-lock.json: It contains the exact version details that is currently installed for your Application.

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

How to add Google Maps Autocomplete search box?

<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
      { types: ['geocode'] });
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
}

// [START region_fillform]
function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
// [END region_geolocation]

    </script>

    <style>
      #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 99%;
      }
      .label {
        text-align: right;
        font-weight: bold;
        width: 100px;
        color: #303030;
      }
      #address {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      #address td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
    </style>
  </head>

  <body onload="initialize()">
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>
    </div>


  </body>
</html>

Self-references in object literals / initializers

You could do something like:

var foo = {
   a: 5,
   b: 6,
   init: function() {
       this.c = this.a + this.b;
       return this;
   }
}.init();

This would be some kind of one time initialization of the object.

Note that you are actually assigning the return value of init() to foo, therefore you have to return this.

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

how to write javascript code inside php

Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.

<?php
$script = <<< JS

$(function() {
   // js code goes here
});

JS;
?>

After closing the heredoc construction the $script variable contains your JS code that can be used like this:

<script><?= $script ?></script>

The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Try adding this piece of code. It worked for me.

_x000D_
_x000D_
$opts = array(_x000D_
    'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)_x000D_
);_x000D_
// SOAP 1.2 client_x000D_
$params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );_x000D_
$url = "http://www.webservicex.net/globalweather.asmx?WSDL";_x000D_
_x000D_
try{_x000D_
 $client = new SoapClient($url,$params );_x000D_
}_x000D_
catch(SoapFault $fault) {_x000D_
 echo '<br>'.$fault;_x000D_
}
_x000D_
_x000D_
_x000D_

How to get IntPtr from byte[] in C#

In some cases you can use an Int32 type (or Int64) in case of the IntPtr. If you can, another useful class is BitConverter. For what you want you could use BitConverter.ToInt32 for example.

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

Android: How to handle right to left swipe gestures

I've been doing similar things, but for horizontal swipes only

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View

abstract class OnHorizontalSwipeListener(val context: Context) : View.OnTouchListener {    

    companion object {
         const val SWIPE_MIN = 50
         const val SWIPE_VELOCITY_MIN = 100
    }

    private val detector = GestureDetector(context, GestureListener())

    override fun onTouch(view: View, event: MotionEvent) = detector.onTouchEvent(event)    

    abstract fun onRightSwipe()

    abstract fun onLeftSwipe()

    private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {    

        override fun onDown(e: MotionEvent) = true

        override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float)
            : Boolean {

            val deltaY = e2.y - e1.y
            val deltaX = e2.x - e1.x

            if (Math.abs(deltaX) < Math.abs(deltaY)) return false

            if (Math.abs(deltaX) < SWIPE_MIN
                    && Math.abs(velocityX) < SWIPE_VELOCITY_MIN) return false

            if (deltaX > 0) onRightSwipe() else onLeftSwipe()

            return true
        }
    }
}

And then it can be used for view components

private fun listenHorizontalSwipe(view: View) {
    view.setOnTouchListener(object : OnHorizontalSwipeListener(context!!) {
            override fun onRightSwipe() {
                Log.d(TAG, "Swipe right")
            }

            override fun onLeftSwipe() {
                Log.d(TAG, "Swipe left")
            }

        }
    )
}

PHP, display image with Header()

Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:

header('Content-type: image/png');

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

How to create a dotted <hr/> tag?

You can do:

<hr style="border: 1px dashed black;" />

Demo: http://jsfiddle.net/JMfC9/

Editing hosts file to redirect url?

You can't. A redirect requires a webserver to accept the first request and send back the redirect. The "hosts" file just lets you set your own DNS records.

Is it possible to use std::string in a constexpr?

No, and your compiler already gave you a comprehensive explanation.

But you could do this:

constexpr char constString[] = "constString";

At runtime, this can be used to construct a std::string when needed.

How do I escape a string inside JavaScript code inside an onClick handler?

Depending on the server-side language, you could use one of these:

.NET 4.0

string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")

Java

import org.apache.commons.lang.StringEscapeUtils;
...

String result = StringEscapeUtils.escapeJavaScript(jsString);

Python

import json
result = json.dumps(jsString)

PHP

$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', 
                                 "\r" => '\\r', "\n" => '\\n' ));

Ruby on Rails

<%= escape_javascript(jsString) %>

How to merge remote changes at GitHub?

If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:

Switch to branch "foo" and update it:

$ git checkout foo
$ git pull

You can see the branches you've got by issuing command:

$ git branch

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

Detect Safari using jQuery

    // Safari uses pre-calculated pixels, so use this feature to detect Safari
    var canva = document.createElement('canvas');
    var ctx = canva.getContext("2d");
    var img = ctx.getImageData(0, 0, 1, 1);
    var pix = img.data;     // byte array, rgba
    var isSafari = (pix[3] != 0);   // alpha in Safari is not zero

Remove all the elements that occur in one list from another

Using set.difference():

You can use set.difference() to get new set with elements in the set that are not in the others. i.e. set(A).difference(B) will return set with items present in A, but not in B. For example:

>>> set([1,2,6,8]).difference([2,3,5,8])
{1, 6}

It is a functional approach to get set difference mentioned in Arkku's answer (which uses arithmetic subtraction - operator for set difference).

Since sets are unordered, you'll loose the ordering of elements from initial list. (continue reading next section if you want to maintain the orderig of elements)

Using List Comprehension with set based lookup

If you want to maintain the ordering from initial list, then Donut's list comprehension based answer will do the trick. However, you can get better performance from the accepted answer by using set internally for checking whether element is present in other list. For example:

l1, l2 = [1,2,6,8], [2,3,5,8]
s2 = set(l2)  # Type-cast `l2` to `set`

l3 = [x for x in l1 if x not in s2]
                             #   ^ Doing membership checking on `set` s2

If you are interested in knowing why membership checking is faster is set when compared to list, please read this: What makes sets faster than lists?


Using filter() and lambda expression

Here's another alternative using filter() with the lambda expression. Adding it here just for reference, but it is not performance efficient:

>>> l1 = [1,2,6,8]
>>> l2 = set([2,3,5,8])

#     v  `filter` returns the a iterator object. Here I'm type-casting 
#     v  it to `list` in order to display the resultant value
>>> list(filter(lambda x: x not in l2, l1))
[1, 6]

How to view file history in Git?

My favorite is git log -p <filename>, which will give you a history of all the commits of the given file as well as the diffs for each commit.

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

This might be late as I think most of us are using BS4. This article explained all the questions you asked in a detailed and simple manner also includes what to do when. The detailed guide to use bs4 or bootstrap

https://uxplanet.org/how-the-bootstrap-4-grid-works-a1b04703a3b7

Use the auto keyword in C++ STL

auto keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.

Is Laravel really this slow?

Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.

The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.

kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.

There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin to your paths. [Or you can install it on Win10/Bash]

Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:

  data['vm']['synced_folder'].each do |i, folder|
    if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
      config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", 
        id: "#{folder['id']}", 
        type: "rsync",
        rsync__auto: "true",
        rsync__exclude: ".hg/"
    end
  end

Once you're all set up, try vagrant up. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!


If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.


One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

Populate nested array in mongoose

Mongoose 5.4 supports this

Project.find(query)
.populate({
  path: 'pages.page.components',
  model: 'Component'
})

Chart.js - Formatting Y axis

I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.

ticks: {
    callback: function(label, index, labels) {
        return label/1000+'k';
    }
}

More in details

var options = {
    scales: {
        yAxes: [
            {
                ticks: {
                    callback: function(label, index, labels) {
                        return label/1000+'k';
                    }
                },
                scaleLabel: {
                    display: true,
                    labelString: '1k = 1000'
                }
            }
        ]
    }
}

Reading a single char in Java

Here is a class 'getJ' with a static function 'chr()'. This function reads one char.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class getJ {
    static char  chr()throws IOException{  
        BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
        return bufferReader.readLine().charAt(0);
    }
}

In order to read a char use this:

anyFunc()throws IOException{
...
...
char c=getJ.chr();
}

Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean you don't need to do:

getJ ob = new getJ;
c=ob.chr();

You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:

anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
} 
catch(IOException e)
{
System.out.println("IOException has been caught");
}

Credit to: tutorialspoint.com

See also: geeksforgeeks.

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

How to change Jquery UI Slider handle

You also should set border:none to that css class.

What is it exactly a BLOB in a DBMS context

BLOB :

BLOB (Binary Large Object) is a large object data type in the database system. BLOB could store a large chunk of data, document types and even media files like audio or video files. BLOB fields allocate space only whenever the content in the field is utilized. BLOB allocates spaces in Giga Bytes.

USAGE OF BLOB :

You can write a binary large object (BLOB) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB value to your database, issue the appropriate INSERT or UPDATE statement and pass the BLOB value as an input parameter. If your BLOB is stored as text, such as a SQL Server text field, you can pass the BLOB as a string parameter. If the BLOB is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.

A useful link : Storing documents as BLOB in Database - Any disadvantages ?

How to sort a list of strings?

l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)

Result

['abc', 'ba', 'cd', 'dc', 'xy']

What's the best way to cancel event propagation between nested ng-click calls?

If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.

What are the differences between numpy arrays and matrices? Which one should I use?

As others have mentioned, perhaps the main advantage of matrix was that it provided a convenient notation for matrix multiplication.

However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @.

With recent NumPy versions, it can be used with ndarrays:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

So nowadays, even more, when in doubt, you should stick to ndarray.

Possible heap pollution via varargs parameter

@SafeVarargs does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.

http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.

Heap pollution is when you get a ClassCastException when doing an operation on a generic interface and it contains another type than declared.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

The best way for me is this:

Dictionary<int, int> copy= new Dictionary<int, int>(yourListOrDictionary);

Adding horizontal spacing between divs in Bootstrap 3

The best solution is not to use the same element for column and panel:

<div class="row">
    <div class="col-md-3">
        <div class="panel" id="gameplay-away-team">Away Team</div>
    </div>
    <div class="col-md-6">
        <div class="panel" id="gameplay-baseball-field">Baseball Field</div>
    </div>
    <div class="col-md-3">
        <div class="panel" id="gameplay-home-team">Home Team</div>
    </div>
</div>

and some more styles:

#gameplay-baseball-field {
  padding-right: 10px;
  padding-left: 10px;
}

How to get values and keys from HashMap?

Map is internally made up of Map.Entry objects. Each Entry contains key and value. To get key and value from the entry you use accessor and modifier methods.

If you want to get values with given key, use get() method and to insert value, use put() method.

#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)

map.get("Germany") // returns 4

If you want to get the set of keys from map, you can use keySet() method

Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
    System.out.println(key + ": " + map.get(key));
}

Generally, To get all keys and values from the map, you have to follow the sequence in the following order:

  • Convert Hashmap to MapSet to get set of entries in Map with entryset() method.:
    Set st = map.entrySet();
  • Get the iterator of this set:
    Iterator it = st.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to get keys and values.
// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

In short, use iterator directly in for

for(Map.Entry entry:map.entrySet()){
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

How do I align views at the bottom of the screen?

This can be done with a linear layout too.

Just provide Height = 0dp and weight = 1 to the layout above and the one you want in the bottom. Just write height = wrap content and no weight.

It provides wrap content for the layout (the one that contains your edit text and button) and then the one that has weight occupies the rest of the layout.

I discovered this by accident.

Xcode process launch failed: Security

In iOS 9.2 they renamed the 'Profiles' to 'Device Management'

This is how you should do it now:

  1. Settings -> General -> Device Management
  2. Verify the app

Converting any object to a byte array in java

To convert the object to a byte array use the concept of Serialization and De-serialization.

The complete conversion from object to byte array explained in is tutorial.

http://javapapers.com/core-java/java-serialization/

Q. How can we convert object into byte array?

Q. How can we serialize a object?

Q. How can we De-serialize a object?

Q. What is the need of serialization and de-serialization?

Pandas: drop a level from a multi-level column index?

You could also achieve that by renaming the columns:

df.columns = ['a', 'b']

This involves a manual step but could be an option especially if you would eventually rename your data frame.

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

How do I convert strings in a Pandas data frame to a 'date' data type?

Essentially equivalent to @waitingkuo, but I would use to_datetime here (it seems a little cleaner, and offers some additional functionality e.g. dayfirst):

In [11]: df
Out[11]:
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [12]: pd.to_datetime(df['time'])
Out[12]:
0   2013-01-01 00:00:00
1   2013-01-02 00:00:00
2   2013-01-03 00:00:00
Name: time, dtype: datetime64[ns]

In [13]: df['time'] = pd.to_datetime(df['time'])

In [14]: df
Out[14]:
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

Handling ValueErrors
If you run into a situation where doing

df['time'] = pd.to_datetime(df['time'])

Throws a

ValueError: Unknown string format

That means you have invalid (non-coercible) values. If you are okay with having them converted to pd.NaT, you can add an errors='coerce' argument to to_datetime:

df['time'] = pd.to_datetime(df['time'], errors='coerce')

How to add key,value pair to dictionary?

For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:

data['a']=1  

data.update({'a':1})

data.update(dict(a=1))

data.update(a=1)

You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'

data.update({'c':3,'d':4})  

scp from Linux to Windows

Download pscp from Putty download page, then use it from Windows Command Line CMD as follows:

pscp username_linux_machine@ip_of_linux_machine:/home/ubuntu/myfile.ext C:\Users\Name\Downloads

Copying starts once you enter the password for the Linux machine.

Shell script to send email

mail -s "Your Subject" [email protected] < /file/with/mail/content

(/file/with/mail/content should be a plaintext file, not a file attachment or an image, etc)

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

A general tree implementation?

A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

Then interact:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
...   print c.data
... 
6
7
>>> 

This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.

How to embed a PDF?

Here is the code you can use for every browser:

<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Tested on firefox and chrome

How to get the current directory of the cmdlet being executed

Yes, that should work. But if you need to see the absolute path, this is all you need:

(Get-Item .).FullName

Redirect using AngularJS

With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.

Try doing this on the directive scope.$apply(function() { $location.path("/route"); });

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

How to use function srand() with time.h?

#include"stdio.h"//rmv coding for randam number access

#include"conio.h"

#include"time.h"

void main()
{
    time_t t;
    int rmvivek;

    srand(time(&t));
    rmvivek=1;

    while(rmvivek<=5)
    {
        printf("%c\t",rand()%10);
        rmvivek++;
    }
    getch();
}

How to load URL in UIWebView in Swift?

Swift 4 Update Creating a WebView programatically.

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

var webView: WKWebView!

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView
}
override func viewDidLoad() {
    super.viewDidLoad()

    let myURL = URL(string: "https://www.apple.com")
    let myRequest = URLRequest(url: myURL!)
    webView.loadRequest(myRequest)
}}

Could not load type 'XXX.Global'

If your using visual studio 2010 this error can occur when you change the configuration deployment type. The 3 types are x86, x64 and Mixed mode. Changing to mixed mode setting for all projects in solution should resolve the issue. Don't forget to delete the bin, Lib files and change the tempdirectory output if your an ASP.NET website.

how do I make a single legend for many subplots with matplotlib?

if you are using subplots with bar charts, with different colour for each bar. it may be faster to create the artefacts yourself using mpatches

Say you have four bars with different colours as r m c k you can set the legend as follows

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']


#####################################
# insert code for the subplots here #
#####################################


# now, create an artist for each color
red_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') #this will create a red bar with black borders, you can leave out edgecolor if you do not want the borders
black_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')
magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')
cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')
fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch],labels=labels,
       loc="center right", 
       borderaxespad=0.1)
plt.subplots_adjust(right=0.85) #adjust the subplot to the right for the legend

Call a "local" function within module.exports from another function in module.exports?

Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. You can then export that variable and you're good to go.

var self = {
  foo: function (req, res, next) {
    return ('foo');
  },
  bar: function (req, res, next) {
    return self.foo();
  }
};
module.exports = self;

ipynb import another ipynb file

It is really simple in newer Jupyter:

%run MyOtherNotebook.ipynb

How does one parse XML files?

I'd use LINQ to XML if you're in .NET 3.5 or higher.

Reverse ip, find domain names on ip address

They're just trawling lists of web sites, and recording the resulting IP addresses in a database.

All you're seeing is the reverse mapping of that list. It's not guaranteed to be a full list (indeed more often than not it won't be) because it's impossible to learn every possible web site address.

Calling an executable program using awk

#!/usr/bin/awk -f

BEGIN {
    command = "ls -lh"

    command |getline
}

Runs "ls -lh" in an awk script

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


Given a class, see if instance has method (Ruby)

If you're checking to see if an object can respond to a series of methods, you could do something like:

methods = [:valid?, :chase, :test]

def has_methods?(something, methods)
  methods & something.methods == methods
end

the methods & something.methods will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:

[1,2] & [1,2,3,4,5]
==> [1,2]

so

[1,2] & [1,2,3,4,5] == [1,2]
==> true

In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"], it'd return false.

Get the second highest value in a MySQL table

simple solution

SELECT * FROM TBLNAME ORDER BY COLNAME ASC LIMIT (n - x), 1

Note: n = total number of records in column

  x = value 2nd, 3rd, 4th highest etc

e.g

//to find employee with 7th highest salary

n = 100
x = 7

SELECT * FROM tbl_employee ORDER BY salary ASC LIMIT 93, 1

hope this helps

How to output in CLI during execution of PHP Unit tests?

Update: See rdlowrey's update below regarding the use of fwrite(STDERR, print_r($myDebugVar, TRUE)); as a much simpler work around


This behaviour is intentional (as jasonbar has pointed out). The conflicting state of the manual has been reported to PHPUnit.

A work-around is to have PHPUnit assert the expected output is empty (when infact there is output) which will trigger the unexpected output to be shown.

class theTest extends PHPUnit_Framework_TestCase
{
    /**
     * @outputBuffering disabled
     */
    public function testOutput() {
        $this->expectOutputString(''); // tell PHPUnit to expect '' as output
        print_r("Hello World");
        print "Ping";
        echo "Pong";
        $out = "Foo";
        var_dump($out);
    }   
}

gives:

PHPUnit @package_version@ by Sebastian Bergmann.

F

Time: 1 second, Memory: 3.50Mb

There was 1 failure:

1) theTest::testOutput
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-''
+'Hello WorldPingPongstring(4) "Foo"
+'

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Be certain to disable any other assertions you have for the test as they may fail before the output assertion is tested (and hence you wont see the output).

Function stoi not declared

Install the latest version of TDM-GCC here is the link-http://wiki.codeblocks.org/index.php/MinGW_installation

Image, saved to sdcard, doesn't appear in Android's Gallery app

Use this after saving the image

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

Access Enum value using EL with JSTL

You have 3 choices here, none of which is perfect:

  1. You can use a scriptlet in the test attribute:

    <c:when test="<%= dp.getStatus() == Status.VALID %>">

    This uses the enum, but it also uses a scriptlet, which is not the "right way" in JSP 2.0. But most importantly, this doesn't work when you want to add another condition to the same when using ${}. And this means all the variables you want to test have to be declared in a scriptlet, or kept in request, or session (pageContext variable is not available in .tag files).

  2. You can compare against string:

    <c:when test="${dp.status == 'VALID'}">

    This looks clean, but you're introducing a string that duplicates the enum value and cannot be validated by the compiler. So if you remove that value from the enum or rename it, you will not see that this part of code is not accessible anymore. You basically have to do a search/replace through the code each time.

  3. You can add each of the enum values you use into the page context:

    <c:set var="VALID" value="<%=Status.VALID%>"/>

    and then you can do this:

    <c:when test="${dp.status == VALID}">

I prefer the last option (3), even though it also uses a scriptlet. This is because it only uses it when you set the value. Later on you can use it in more complex EL expressions, together with other EL conditions. While in option (1) you cannot use a scriptlet and an EL expression in the test attribute of a single when tag.

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

Create Pandas DataFrame from a string

In one line, but first import IO

import pandas as pd
import io   

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

df = pd.read_csv(  io.StringIO(TESTDATA)  , sep=";")
print ( df )

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

c++ exception : throwing std::string

Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?

boost has an excellent document on good style for exceptions and error handling. It's worth a read.

installing vmware tools: location of GCC binary?

First execute this

sudo apt-get install gcc binutils make linux-source

Then run again

/usr/bin/vmware-config-tools.pl

This is all you need to do. Now your system has the gcc make and the linux kernel sources.

How do I get multiple subplots in matplotlib?

There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:

import matplotlib.pyplot as plt

x = range(10)
y = range(10)

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

for row in ax:
    for col in row:
        col.plot(x, y)

plt.show()

enter image description here

However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:

fig = plt.figure()

plt.subplot(2, 2, 1)
plt.plot(x, y)

plt.subplot(2, 2, 2)
plt.plot(x, y)

plt.subplot(2, 2, 3)
plt.plot(x, y)

plt.subplot(2, 2, 4)
plt.plot(x, y)

plt.show()

enter image description here

Add unique constraint to combination of two columns

And if you have lot insert queries but not wanna ger a ERROR message everytime , you can do it:

CREATE UNIQUE NONCLUSTERED INDEX SK01 ON dbo.Person(ID,Name,Active,PersonNumber) 
WITH(IGNORE_DUP_KEY = ON)

enter image description here

Query to search all packages for table and/or column

Sometimes the column you are looking for may be part of the name of many other things that you are not interested in.

For example I was recently looking for a column called "BQR", which also forms part of many other columns such as "BQR_OWNER", "PROP_BQR", etc.

So I would like to have the checkbox that word processors have to indicate "Whole words only".

Unfortunately LIKE has no such functionality, but REGEXP_LIKE can help.

SELECT *
  FROM user_source
 WHERE regexp_like(text, '(\s|\.|,|^)bqr(\s|,|$)');

This is the regular expression to find this column and exclude the other columns with "BQR" as part of the name:

(\s|\.|,|^)bqr(\s|,|$)

The regular expression matches white-space (\s), or (|) period (.), or (|) comma (,), or (|) start-of-line (^), followed by "bqr", followed by white-space, comma or end-of-line ($).

Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}?

How can I create a memory leak in Java?

One of the java memory leakings examples is MySQLs memory leaking bug resulting when ResultSets close method is forgotten to be called. For example:

while(true) {
    ResultSet rs = database.select(query);
    ...
    // going to next step of loop and leaving resultset without calling rs.close();
}

Add missing dates to pandas dataframe

Here's a nice method to fill in missing dates into a dataframe, with your choice of fill_value, days_back to fill in, and sort order (date_order) by which to sort the dataframe:

def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):

    df.set_index(date_col_name,drop=True,inplace=True)
    df.index = pd.DatetimeIndex(df.index)
    d = datetime.now().date()
    d2 = d - timedelta(days = days_back)
    idx = pd.date_range(d2, d, freq = "D")
    df = df.reindex(idx,fill_value=fill_value)
    df[date_col_name] = pd.DatetimeIndex(df.index)

    return df

Multiple submit buttons on HTML form – designate one button as default

Quick'n'dirty you could create an hidden duplicate of the submit-button, which should be used, when pressing enter.

Example CSS

input.hidden {
    width: 0px;
    height: 0px;
    margin: 0px;
    padding: 0px;
    outline: none;
    border: 0px;
}

Example HTML

<input type="submit" name="next" value="Next" class="hidden" />
<input type="submit" name="prev" value="Previous" />
<input type="submit" name="next" value="Next" />

If someone now hits enter in your form, the (hidden) next-button will be used as submitter.

Tested on IE9, Firefox, Chrome and Opera

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

How do I test which class an object is in Objective-C?

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

or

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

How Best to Compare Two Collections in Java and Act on Them?

I'd move to lists and solve it this way:

  1. Sort both lists by id ascending using custom Comparator if objects in lists aren't Comparable
  2. Iterate over elements in both lists like in merge phase in merge sort algorithm, but instead of merging lists, you check your logic.

The code would be more or less like this:

/* Main method */
private void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {
  List<Foo> oldList = asSortedList(oldSet);
  List<Foo> newList = asSortedList(newSet);

  int oldIndex = 0;
  int newIndex = 0;
  // Iterate over both collections but not always in the same pace
  while( oldIndex < oldList.size() 
      && newIndex < newIndex.size())  {
    Foo oldObject = oldList.get(oldIndex);
    Foo newObject = newList.get(newIndex);

    // Your logic here
    if(oldObject.getId() < newObject.getId()) {
      doRemove(oldObject);
      oldIndex++;
    } else if( oldObject.getId() > newObject.getId() ) {
      doAdd(newObject);
      newIndex++;
    } else if( oldObject.getId() == newObject.getId() 
            && isModified(oldObject, newObject) ) {
      doUpdate(oldObject, newObject);
      oldIndex++;
      newIndex++;
    } else {
      ... 
    }
  }// while

  // Check if there are any objects left in *oldList* or *newList*

  for(; oldIndex < oldList.size(); oldIndex++ ) {
    doRemove( oldList.get(oldIndex) );  
  }// for( oldIndex )

  for(; newIndex < newList.size(); newIndex++ ) {
    doAdd( newList.get(newIndex) );
  }// for( newIndex ) 
}// execute( oldSet, newSet )

/** Create sorted list from collection 
    If you actually perform any actions on input collections than you should 
    always return new instance of list to keep algorithm simple.
*/
private List<Foo> asSortedList(Collection<Foo> data) {
  List<Foo> resultList;
  if(data instanceof List) {
     resultList = (List<Foo>)data;
  } else {
     resultList = new ArrayList<Foo>(data);
  }
  Collections.sort(resultList)
  return resultList;
}

Auto Generate Database Diagram MySQL

On a Mac, SQLEditor will do what you want.

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

Branch from a previous commit using Git

Select Commit

For Git GUI users you can visualize all the history (if necessary) and then right click on the commit you wish to branch from and enter the branch name.

Enter Branch name

Visualize all the history

How do I enable --enable-soap in php on linux?

Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.

For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:

$ php -i | grep -i soap

to ensure that it is the PHP extension that is missing.

Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.

In Ubuntu/Debian you can search with:

$ apt-cache search php | grep -i soap

or in RHEL/Fedora you can search with:

$ yum search php | grep -i soap

There are usually two PHP SOAP packages available to you, usually php-soap and php-nusoap. php-soap is typically what you get with configuring PHP with --enable-soap.

In Ubuntu/Debian you can install with:

$ sudo apt-get install php-soap

Or in RHEL/Fedora you can install with:

$ sudo yum install php-soap

After the installation, you might need to place an ini file and restart Apache.

How can I convert IPV6 address to IPV4 address?

There isn't a 1-1 correspondence between IPv4 and IPv6 addresses (nor between IP addresses and devices), so what you're asking for generally isn't possible.

There is a particular range of IPv6 addresses that actually represent the IPv4 address space, but general IPv6 addresses will not be from this range.

Detecting Browser Autofill

I also faced the same problem where label did not detect autofill and animation for moving label on filling text was overlapping and this solution worked for me.

input:-webkit-autofill ~ label {
    top:-20px;
} 

How to store Emoji Character in MySQL Database

Step 1, change your database's default charset:

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

if the db is not created yet, create it with correct encodings:

CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;

Step 2, set charset when creating table:

CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;

or alter table

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;

Installing python module within code

The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

Use sys.executable to ensure that you will call the same pip associated with the current runtime.

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

How do I use Notepad++ (or other) with msysgit?

UPDATE 2015

If you unpack/install Notepad++ into c:\utils\npp\ and rename notepad++.exe to npp.exe for simplicity, then all you have to do is

git config --global core.editor c:/utils/npp/npp.exe

No wrapper scripts or other trickery. No need to have Notepad++ in PATH.

How to switch Python versions in Terminal?

Here is a nice and simple way to do it (but on CENTOS), without braking the operating system.

yum install scl-utils

next

yum install centos-release-scl-rh

And lastly you install the version that you want, lets say python3.5

yum install rh-python35

And lastly:

scl enable rh-python35 bash

Since MAC-OS is a unix operating system, the way to do it it should be quite similar.

pyplot axes labels for subplots

One simple way using subplots:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 4, sharex=True, sharey=True)
# add a big axes, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
plt.xlabel("common X")
plt.ylabel("common Y")

Message Queue vs. Web Services?

I think in general, you'd want a web service for a blocking task (this tasks needs to be completed before we execute more code), and a message queue for a non-blocking task (could take quite a while, but we don't need to wait for it).

Pushing empty commits to remote

You won't face any terrible consequence, just the history will look kind of confusing.

You could change the commit message by doing

git commit --amend
git push --force-with-lease # (as opposed to --force, it doesn't overwrite others' work)

BUT this will override the remote history with yours, meaning that if anybody pulled that repo in the meanwhile, this person is going to be very mad at you...

Just do it if you are the only person accessing the repo.

Converting <br /> into a new line for use in a text area

EDIT: previous answer was backwards of what you wanted. Use str_replace. replace <br> with \n

echo str_replace('<br>', "\n", $var1);

C++ Boost: undefined reference to boost::system::generic_category()

This answer actually helped when using Boost and cmake.

Adding add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY) for cmake file.

My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.12)
project(proj)

set(CMAKE_CXX_STANDARD 17)


set(SHARED_DIR "${CMAKE_SOURCE_DIR}/../shared")

set(BOOST_LATEST_DIR            "${SHARED_DIR}/boost_1_68_0")
set(BOOST_LATEST_BIN_DIR        "${BOOST_LATEST_DIR}/stage/lib")
set(BOOST_LATEST_INCLUDE_DIR    "${BOOST_LATEST_DIR}/boost")
set(BOOST_SYSTEM                "${BOOST_LATEST_BIN_DIR}/libboost_system.so")
set(BOOST_FS                    "${BOOST_LATEST_BIN_DIR}/libboost_filesystem.so")
set(BOOST_THREAD                "${BOOST_LATEST_BIN_DIR}/libboost_thread.so")

set(HYRISE_SQL_PARSER_DIR           "${SHARED_DIR}/hyrise_sql_parser")
set(HYRISE_SQL_PARSER_BIN_DIR       "${HYRISE_SQL_PARSER_DIR}")
set(HYRISE_SQL_PARSER_INCLUDE_DIR   "${HYRISE_SQL_PARSER_DIR}/src")
set(HYRISE_SQLPARSER                "${HYRISE_SQL_PARSER_BIN_DIR}/libsqlparser.so")


include_directories(${CMAKE_SOURCE_DIR} ${BOOST_LATEST_INCLUDE_DIR} ${HYRISE_SQL_PARSER_INCLUDE_DIR})

set(BOOST_LIBRARYDIR "/usr/lib/x86_64-linux-gnu/")
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)

find_package(Boost 1.68.0 REQUIRED COMPONENTS system thread filesystem)

add_executable(proj main.cpp row/row.cpp row/row.h table/table.cpp table/table.h page/page.cpp page/page.h
        processor/processor.cpp processor/processor.h engine_instance.cpp engine_instance.h utils.h
        meta_command.h terminal/terminal.cpp terminal/terminal.h)


if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    target_link_libraries(proj PUBLIC Boost::system Boost::filesystem Boost::thread ${HYRISE_SQLPARSER})
endif()

Insert Update trigger how to determine if insert or update

This might be a faster way:

DECLARE @action char(1)

IF COLUMNS_UPDATED() > 0 -- insert or update
BEGIN
    IF EXISTS (SELECT * FROM DELETED) -- update
        SET @action = 'U'
    ELSE
        SET @action = 'I'
    END
ELSE -- delete
    SET @action = 'D'

What is the difference between vmalloc and kmalloc?

In short, vmalloc and kmalloc both could fix fragmentation. vmalloc use memory mappings to fix external fragmentation; kmalloc use slab to fix internal frgamentation. Fot what it's worth, kmalloc also has many other advantages.

How to search if dictionary value contains certain string with Python

You can do it like this:

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

"The system cannot find the file specified"

I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.

NOTE: My App: ASP.NET 4.5 (by VS2013), Server: Windows 2008 R2 64bit, SQL: MS-SQL WEB 2012 SP1 Also other web applications works great at web browsers with their database on same server.


After one day suffering I found the solution of my issue:

First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.

I changed code as this:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    //public ApplicationDbContext() : base("DefaultConnection") ---> this was original
    public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
    {
    }
}

So, after all, I re-builded and published my project and everything works fine now :)

How to subtract X days from a date using Java calendar?

Taken from the docs here:

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).

Set selected item in Android BottomNavigationView

This will probably be added in coming updates. But in the meantime, to accomplish this you can use reflection.

Create a custom view extending from BottomNavigationView and access some of its fields.

public class SelectableBottomNavigationView extends BottomNavigationView {

    public SelectableBottomNavigationView(Context context) {
        super(context);
    }

    public SelectableBottomNavigationView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SelectableBottomNavigationView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setSelected(int index) {
        try {
            Field f = BottomNavigationView.class.getDeclaredField("mMenuView");
            f.setAccessible(true);
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) f.get(this);

            try {
                Method method = menuView.getClass().getDeclaredMethod("activateNewButton", Integer.TYPE);
                method.setAccessible(true);
                method.invoke(menuView, index);
            } catch (SecurityException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

}

And then use it in your xml layout file.

<com.your.app.SelectableBottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/primary"
        app:itemIconTint="@drawable/nav_item_color_state"
        app:itemTextColor="@drawable/nav_item_color_state"
        app:menu="@menu/bottom_navigation_menu"/>

How to create a button programmatically?

For Swift 3

let button = UIButton()
button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
button.backgroundColor = UIColor.red
button.setTitle("your Button Name", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

For Swift 4+

 let button = UIButton()
 button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
 button.backgroundColor = UIColor.red
 button.setTitle("Name your Button ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

 @objc func buttonAction(sender: UIButton!) {
    print("Button tapped")
 }

Convert command line argument to string

I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

#include <cstdio>
#include <iostream>

using namespace std;

namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  }
  return true;
}
}  // namespace _

int main(int args_count, char** args) {
  cout << "\n\nTesting ArgsToString...\n";

  if (args_count <= 1) return 1;
  cout << "\nArguments:\n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
  }
  cout << "\n\nContiguous Args:\n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "\n\nContiguous Args:\n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
    else
      cout << c;
  }
  cout << "\n\nPrinting argument string...\n";
  _::ArgsToString(args_count, args);
  cout << "\n" << args[1];
  return 0;
}

Delete first character of a string in Javascript

You can do it with substring method:

let a = "My test string";

a = a.substring(1);

console.log(a); // y test string

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to make my layout able to scroll down?

Yes, it is very Simple. Just Put your Code Inside this:

<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

//YOUR CODE

</androidx.core.widget.NestedScrollView>

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

To sum up, 'valid' padding means no padding. The output size of the convolutional layer shrinks depending on the input size & kernel size.

On the contrary, 'same' padding means using padding. When the stride is set as 1, the output size of the convolutional layer maintains as the input size by appending a certain number of '0-border' around the input data when calculating convolution.

Hope this intuitive description helps.

Java Does Not Equal (!=) Not Working?

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.

Converting SVG to PNG using C#

You can call the command-line version of inkscape to do this:

http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx

Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:

Original Project
http://www.codeplex.com/svg

Fork with fixes and more activity: (added 7/2013)
https://github.com/vvvv/SVG

What's the meaning of exception code "EXC_I386_GPFLT"?

In my case the error was thrown in Xcode when running an app on the iOS simulator. While I cannot answer the specific question "what the error means", I can say what helped me, maybe it also helps others.

The solution for me was to Erase All Content and Settings in the simulator and to Clean Build Folder... in Xcode.

How to get first character of string?

Looks like I am late to the party, but try the below solution which I personally found the best solution:

var x = "testing sub string"
alert(x[0]);
alert(x[1]);

Output should show alert with below values: "t" "e"

java.lang.ClassCastException

According to the documentation:

Thrown to indicate that the code has attempted to cast an Object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x); 

How can I change NULL to 0 when getting a single value from a SQL function?

You could use

SELECT ISNULL(SUM(ISNULL(Price, 0)), 0).

I'm 99% sure that will work.

How do I start Mongo DB from Windows?

This worked for me

mongod --port 27017 --dbpath C:\MongoDB\data\db

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

This is an updated version to the answer provided by @PodTech.io

This version has all of the vbs code correctly escaped in the batch file. It's also created into a sub-routine, which can be called with a single line from anywhere in your batch script:

:: === Main code:

call :ZipUp "C:\Some\Path" "C:\Archive.zip"


:: === SubRoutines:

:ZipUp
::Arguments: Source_folder, destination_zip
(
    echo:Set fso = CreateObject^("Scripting.FileSystemObject"^)
    echo:InputFolder = fso.GetAbsolutePathName^(WScript.Arguments.Item^(0^)^)
    echo:ZipFile = fso.GetAbsolutePathName^(WScript.Arguments.Item^(1^)^)
    echo:
    echo:' Create empty ZIP file.
    echo:CreateObject^("Scripting.FileSystemObject"^).CreateTextFile^(ZipFile, True^).Write "PK" ^& Chr^(5^) ^& Chr^(6^) ^& String^(18, vbNullChar^)
    echo:
    echo:Set objShell = CreateObject^("Shell.Application"^)
    echo:Set source = objShell.NameSpace^(InputFolder^).Items
    echo:objShell.NameSpace^(ZipFile^).CopyHere^(source^)
    echo:
    echo:' Keep script waiting until compression is done
    echo:Do Until objShell.NameSpace^( ZipFile ^).Items.Count = objShell.NameSpace^( InputFolder ^).Items.Count
    echo:    WScript.Sleep 200
    echo:Loop
)>_zipup.vbs
CScript //Nologo _zipup.vbs "%~1" "%~2"
del _zipup.vbs
goto :eof

Generating random numbers in Objective-C

//The following example is going to generate a number between 0 and 73.

int value;
value = (arc4random() % 74);
NSLog(@"random number: %i ", value);

//In order to generate 1 to 73, do the following:
int value1;
value1 = (arc4random() % 73) + 1;
NSLog(@"random number step 2: %i ", value1);

Output:

  • random number: 72

  • random number step 2: 52

nginx - read custom header from upstream server

$http_name_of_the_header_key

i.e if you have origin = domain.com in header, you can use $http_origin to get "domain.com"

In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores

Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_

For your example the variable would be $http_my_custom_header.

How to prevent form from being submitted?

Try this one...

HTML Code

<form class="submit">
    <input type="text" name="text1"/>
    <input type="text" name="text2"/>
    <input type="submit" name="Submit" value="submit"/>
</form>

jQuery Code

$(function(){
    $('.submit').on('submit', function(event){
        event.preventDefault();
        alert("Form Submission stopped.");
    });
});

or

$(function(){
    $('.submit').on('submit', function(event){
       event.preventDefault();
       event.stopPropagation();
       alert("Form Submission prevented / stopped.");
    });
});

<DIV> inside link (<a href="">) tag

I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

Getting Django admin url for an object

For pre 1.1 django it is simple (for default admin site instance):

reverse('admin_%s_%s_change' % (app_label, model_name), args=(object_id,))

UIImage: Resize, then Crop

I modified Brad Larson's Code. It will aspect fill the image in given rect.

-(UIImage*) scaleAndCropToSize:(CGSize)newSize;
{
    float ratio = self.size.width / self.size.height;

    UIGraphicsBeginImageContext(newSize);

    if (ratio > 1) {
        CGFloat newWidth = ratio * newSize.width;
        CGFloat newHeight = newSize.height;
        CGFloat leftMargin = (newWidth - newHeight) / 2;
        [self drawInRect:CGRectMake(-leftMargin, 0, newWidth, newHeight)];
    }
    else {
        CGFloat newWidth = newSize.width;
        CGFloat newHeight = newSize.height / ratio;
        CGFloat topMargin = (newHeight - newWidth) / 2;
        [self drawInRect:CGRectMake(0, -topMargin, newSize.width, newSize.height/ratio)];
    }

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

Permanently hide Navigation Bar in an activity

After watching the DevBytes video (by Roman Nurik) and reading the very last line in the docs, which says:

Note: If you like the auto-hiding behavior of IMMERSIVE_STICKY but need to show your own UI controls as well, just use IMMERSIVE combined with Handler.postDelayed() or something similar to re-enter immersive mode after a few seconds.

the answer, radu122 gave, worked for me. Just setup a handler and your will be good to go.

Here is the code which works for me:

@Override
protected void onResume() {
    super.onResume();
    executeDelayed();
}


private void executeDelayed() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // execute after 500ms
            hideNavBar();
        }
    }, 500);
}


private void hideNavBar() {
    if (Build.VERSION.SDK_INT >= 19) {
        View v = getWindow().getDecorView();
        v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

Google says "after a few seconds" - but I want to provide this functionality as soon as possible. Maybe I will change the value later, if I have to, I will update this answer.

How to view the committed files you have not pushed yet?

Assuming you're on local branch master, which is tracking origin/master:

git diff --stat origin/master..

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

Joining Spark dataframes on the key

inner join with scala

val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show

Preferred way of loading resources in Java

I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

public class ResourceLoader {

    public static URL getResource(String resource) {
        final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
        classLoaders.add(Thread.currentThread().getContextClassLoader());
        classLoaders.add(ResourceLoader.class.getClassLoader());

        for (ClassLoader classLoader : classLoaders) {
            final URL url = getResourceWith(classLoader, resource);
            if (url != null) {
                return url;
            }
        }

        final URL systemResource = ClassLoader.getSystemResource(resource);
        if (systemResource != null) {
            return systemResource;
        } else {
            try {
                return new File(resource).toURI().toURL();
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }

    private static URL getResourceWith(ClassLoader classLoader, String resource) {
        if (classLoader != null) {
            return classLoader.getResource(resource);
        }
        return null;
    }

}

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
*/
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
{
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    valueBuf.resize(bufferSize);
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
        HKEY_LOCAL_MACHINE,
        regSubKey.c_str(),
        regValue.c_str(),
        RRF_RT_REG_SZ,
        nullptr,
        static_cast<void*>(valueBuf.data()),
        &cbData
    );
    while (rc == ERROR_MORE_DATA)
    {
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
        {
            bufferSize = static_cast<size_t>(cbData);
        }
        else
        {
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        }
        valueBuf.resize(bufferSize);
        rc = RegGetValueW(
            HKEY_LOCAL_MACHINE,
            regSubKey.c_str(),
            regValue.c_str(),
            RRF_RT_REG_SZ,
            nullptr,
            static_cast<void*>(valueBuf.data()),
            &cbData
        );
    }
    if (rc == ERROR_SUCCESS)
    {
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
    }
    else
    {
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));
    }
}

int main()
{
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
#else
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
#endif
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
    try
    {
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
    std::wcout << valueFromRegistry;
}

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

UILabel text margin

This is the easiest way I found. It works like a charm for me.

UIView *titleSection = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 100)];
[titleSection addSubview:titleSection];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(titleSection.frame, PADDING, 0)];
[titleSection addSubview:label];

Protecting cells in Excel but allow these to be modified by VBA script

You can modify a sheet via code by taking these actions

  • Unprotect
  • Modify
  • Protect

In code this would be:

Sub UnProtect_Modify_Protect()

  ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

  ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect

End Sub

The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.

The code could be improved by taking these actions

  • Re-protect
  • Modify

The code to do this would be:

Sub Re-Protect_Modify()

ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
 UserInterfaceOnly:=True
'Protect, even if already protected

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

End Sub

This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.

This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.

So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.

Clearing my form inputs after submission

I used the following with jQuery $("#submitForm").val("");

where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:

function extractValue() { var value = $("#submitForm").val().trim(); console.log(value); };

Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

What is the meaning of "__attribute__((packed, aligned(4))) "

The attribute packed means that the compiler will not add padding between fields of the struct. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.

aligned(4) means that the struct should be aligned to an address that is divisible by 4.

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

in build file change compile files('AF-Android-SDK.jar') to compile files('libs/AF-Android-SDK.jar') it will work

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

Django CSRF Cookie Not Set

try to check if your have installed in the settings.py

 MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)

In the template the data are formatted with the csrf_token:

<form>{% csrf_token %}
</form>

How to serialize object to CSV file?

You can use gererics to work for any class

public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
    if (t.isEmpty()) {
        return null;
    }

    List<String> reportData = new ArrayList<String>();

    addDataToReport(t.get(0), reportData, 0);

    for (T k : t) {
        addDataToReport(k, reportData, 1);
    }
    return !dumpReport(filePath, reportData) ? null : filePath;
}

public static Boolean dumpReport(String filePath, List<String> lines) {
    Boolean isFileCreated = false;

    
    String[] dirs = filePath.split(File.separator);
    String baseDir = "";
    for (int i = 0; i < dirs.length - 1; i++) {
        baseDir += " " + dirs[i];
    }
    baseDir = baseDir.replace(" ", "/");
    
    File base = new File(baseDir);
    base.mkdirs();

    File file = new File(filePath);
    try {
        if (!file.exists())
            file.createNewFile();
    } catch (Exception e) {
        e.printStackTrace();
        return isFileCreated;
    }

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
        for (String line : lines) {
            writer.write(line + System.lineSeparator());
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

void addDataToReport(T t, List<String> reportData, int index) {
    String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
    StringBuilder row = new StringBuilder();

    for (int i = 0; i < jsonObjectAsArray.length; i++) {
        String str = jsonObjectAsArray[i];
        str = str.replaceFirst(":", "_").split("_")[index];

        if (i == 0) {
            if (str != null) {
                row.append(str.replace("\"", ""));
            } else {
                row.append("N/A");
            }
        } else {
            if (str != null) {
                row.append(", " + str.replace("\"", ""));
            } else {
                row.append(", N/A");
            }
        }
    }
    reportData.add(row.toString());
}

Rotating a two-dimensional array in Python

Rotating Counter Clockwise ( standard column to row pivot ) As List and Dict

rows = [
  ['A', 'B', 'C', 'D'],
  [1,2,3,4],
  [1,2,3],
  [1,2],
  [1],
]

pivot = []

for row in rows:
  for column, cell in enumerate(row):
    if len(pivot) == column: pivot.append([])
    pivot[column].append(cell)

print(rows)
print(pivot)
print(dict([(row[0], row[1:]) for row in pivot]))

Produces:

[['A', 'B', 'C', 'D'], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
[['A', 1, 1, 1, 1], ['B', 2, 2, 2], ['C', 3, 3], ['D', 4]]
{'A': [1, 1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3], 'D': [4]}

Creating hard and soft links using PowerShell

In Windows 7, the command is

fsutil hardlink create new-file existing-file

PowerShell finds it without the full path (c:\Windows\system32) or extension (.exe).

How to simplify a null-safe compareTo() implementation?

we can use java 8 to do a null-friendly comparasion between object. supposed i hava a Boy class with 2 fields: String name and Integer age and i want to first compare names and then ages if both are equal.

static void test2() {
    List<Boy> list = new ArrayList<>();
    list.add(new Boy("Peter", null));
    list.add(new Boy("Tom", 24));
    list.add(new Boy("Peter", 20));
    list.add(new Boy("Peter", 23));
    list.add(new Boy("Peter", 18));
    list.add(new Boy(null, 19));
    list.add(new Boy(null, 12));
    list.add(new Boy(null, 24));
    list.add(new Boy("Peter", null));
    list.add(new Boy(null, 21));
    list.add(new Boy("John", 30));

    List<Boy> list2 = list.stream()
            .sorted(comparing(Boy::getName, 
                        nullsLast(naturalOrder()))
                   .thenComparing(Boy::getAge, 
                        nullsLast(naturalOrder())))
            .collect(toList());
    list2.stream().forEach(System.out::println);

}

private static class Boy {
    private String name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Boy(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "name: " + name + " age: " + age;
    }
}

and the result:

    name: John age: 30
    name: Peter age: 18
    name: Peter age: 20
    name: Peter age: 23
    name: Peter age: null
    name: Peter age: null
    name: Tom age: 24
    name: null age: 12
    name: null age: 19
    name: null age: 21
    name: null age: 24

Pythonic way to return list of every nth item in a larger list

Why not just use a step parameter of range function as well to get:

l = range(0, 1000, 10)

For comparison, on my machine:

H:\>python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
10000 loops, best of 3: 90.8 usec per loop
H:\>python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
1000000 loops, best of 3: 0.861 usec per loop
H:\>python -m timeit -s "l = range(0, 1000, 10)"
100000000 loops, best of 3: 0.0172 usec per loop

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

How to set up default schema name in JPA configuration?

Just to save time of people who come to the post (like me, who looking for Spring config type and want you schema name be set by an external source (property file)). The configuration will work for you is

<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="JiraManager"/>
    <property name="dataSource" ref="domainDataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="false"/>
            <property name="showSql" value="false"/>
            <property name="databasePlatform" value="${hibernate.dialect}"/>
        </bean>
    </property>
    <property name="jpaProperties">
       <props>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
            <prop key="hibernate.default_schema">${yourSchema}</prop>
       </props>
</property>

</bean>

Ps : For the hibernate.hdm2ddl.auto, you could look in the post Hibernate hbm2ddl.auto possible values and what they do? I have used to set create-update,because it is convenient. However, in production, I think it is better to take control of the ddl, so I take whatever ddl generate first time, save it, rather than let it automatically create and update.

Sequence contains more than one element

As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.

But to the point i wanted to give you a quick overview.

//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();

//success on 0-n, returns first element in the list or default() if 0 
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();

//success on 0-n, returns first element in the list or default() if 0 
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();

for more Linq expressions have a look at System.Linq.Expressions

Load a bitmap image into Windows Forms using open file dialog

You should try to:

  • Create the picturebox visually in form (it's easier)
  • Set Dock property of picturebox to Fill (if you want image to fill form)
  • Set SizeMode of picturebox to StretchImage

Finally:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open Image";
    dlg.Filter = "bmp files (*.bmp)|*.bmp";
    if (dlg.ShowDialog() == DialogResult.OK)
    {                     
        PictureBox1.Image = Image.FromFile(dlg.Filename);
    }
    dlg.Dispose();
}

Is there a way to reduce the size of the git folder?

Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.

The preferred way of creating a new element with jQuery

If #box is empty, nothing, but if it's not these do very different things. The former will add a div as the last child node of #box. The latter completely replaces the contents of #box with a single empty div, text and all.

jquery stop child triggering parent event

I stumbled upon this question, looking for another answer.

I wanted to prevent all children from triggering the parent.

JavaScript:

document.getElementById("parent").addEventListener("click",  function (e) {
    if (this !== event.target) return;
    // Do something
});

jQuery:

$("#parent").click(function () {
    // Do something
}).children().on("click", function (e) {
    e.stopPropagation();
});

Show hide fragment in android

Hi you do it by using this approach, all fragments will remain in the container once added initially and then we are simply revealing the desired fragment and hiding the others within the container.

// Within an activity
private FragmentA fragmentA;
private FragmentB fragmentB;
private FragmentC fragmentC;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        fragmentA = FragmentA.newInstance("foo");
        fragmentB = FragmentB.newInstance("bar");
        fragmentC = FragmentC.newInstance("baz");
    }
}


// Replace the switch method
protected void displayFragmentA() {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    if (fragmentA.isAdded()) { // if the fragment is already in container
        ft.show(fragmentA);
    } else { // fragment needs to be added to frame container
        ft.add(R.id.flContainer, fragmentA, "A");
    }
    // Hide fragment B
    if (fragmentB.isAdded()) { ft.hide(fragmentB); }
    // Hide fragment C
    if (fragmentC.isAdded()) { ft.hide(fragmentC); }
    // Commit changes
    ft.commit();
}

Please see https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments for more info. I hope I get to help anyone. Even if it this is an old question.

What happens if you don't commit a transaction to a database (say, SQL Server)?

Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.

Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).

Make a div fill the height of the remaining screen space

There really isn't a sound, cross-browser way to do this in CSS. Assuming your layout has complexities, you need to use JavaScript to set the element's height. The essence of what you need to do is:

Element Height = Viewport height - element.offset.top - desired bottom margin

Once you can get this value and set the element's height, you need to attach event handlers to both the window onload and onresize so that you can fire your resize function.

Also, assuming your content could be larger than the viewport, you will need to set overflow-y to scroll.

How to trigger a phone call when clicking a link in a web page on mobile phone

Want to add an answer here for the sake of completeness.

<a href="tel:1234567">Call 123-4567</a>

Works just fine on most devices. However, on desktops this will appear as a link which does nothing when you click on it so you should consider using CSS to make it conditionally visible only on mobile devices.

Also, you should know that Skype (which is fairly popular) uses a different syntax by default (but can be parametered to use tel:).

<a href="callto:1234567">Call 123-4567</a>

However, I think in latest mobile browsers (I know for sure on Android) now the tel syntax should offer a popup of available applications that can be used to complete the calling action.

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

How to diff a commit with its parent?

Uses aliases, so doesn't answer your question exactly but I find these useful for doing what you intend...

alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"

alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"

How do you check for permissions to write to a directory or file?

None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..

/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath)) return false;

    try
    {
        AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        foreach (FileSystemAccessRule rule in rules)
        {
            if (identity.Groups.Contains(rule.IdentityReference))
            {
                if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
                {
                    if (rule.AccessControlType == AccessControlType.Allow)
                        return true;
                }
            }
        }
    }
    catch {}
    return false;
}

Where to change the value of lower_case_table_names=2 on windows xampp

Look for a file named my.ini in your hard disk, in my system it's in

c:\program files\mysql\mysql server 5.1

If it's not my.ini it should be my.cnf

How to resize datagridview control when form resizes

For me, anchoring works only if I set it to all four sides:

Anchoring: Top, Bottom, Left, Right

Setting anchoring just to Left, Bottom moves the whole object when the form is resized in bottom, left side. Setting all four sizes really resizes the object, when parent is resized.

How to adjust text font size to fit textview

I found the following to work nicely for me. It doesn't loop and accounts for both height and width. Note that it is important to specify the PX unit when calling setTextSize on the view. Thanks to the tip in a previous post for this!

Paint paint = adjustTextSize(getPaint(), numChars, maxWidth, maxHeight);
setTextSize(TypedValue.COMPLEX_UNIT_PX,paint.getTextSize());

Here is the routine I use, passing in the getPaint() from the view. A 10 character string with a 'wide' character is used to estimate the width independent from the actual string.

private static final String text10="OOOOOOOOOO";
public static Paint adjustTextSize(Paint paint, int numCharacters, int widthPixels, int heightPixels) {
    float width = paint.measureText(text10)*numCharacters/text10.length();
    float newSize = (int)((widthPixels/width)*paint.getTextSize());
    paint.setTextSize(newSize);

    // remeasure with font size near our desired result
    width = paint.measureText(text10)*numCharacters/text10.length();
    newSize = (int)((widthPixels/width)*paint.getTextSize());
    paint.setTextSize(newSize);

    // Check height constraints
    FontMetricsInt metrics = paint.getFontMetricsInt();
    float textHeight = metrics.descent-metrics.ascent;
    if (textHeight > heightPixels) {
        newSize = (int)(newSize * (heightPixels/textHeight));
        paint.setTextSize(newSize);
    }

    return paint;
}

Postgres: check if array field contains value?

This worked for me:

select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'

Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.

jquery animate .css

The example from jQuery's website animates size AND font but you could easily modify it to fit your needs

$("#go").click(function(){
  $("#block").animate({ 
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em", 
    borderWidth: "10px"
  }, 1500 );

http://api.jquery.com/animate/

Unique random string generation

My one stop solution for Linux commands on windows is scoop. Install scoop from scoop.sh

scoop install openssl
openssl rand -base64 32
Dca3c3pptVkcb8fx243wN/3f/rQxx/rWYL8y7rZrGrA=

"ImportError: No module named" when trying to run Python script

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

Copy entire directory contents to another directory?

public static void copyFolder(File source, File destination)
{
    if (source.isDirectory())
    {
        if (!destination.exists())
        {
            destination.mkdirs();
        }

        String files[] = source.list();

        for (String file : files)
        {
            File srcFile = new File(source, file);
            File destFile = new File(destination, file);

            copyFolder(srcFile, destFile);
        }
    }
    else
    {
        InputStream in = null;
        OutputStream out = null;

        try
        {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, length);
            }
        }
        catch (Exception e)
        {
            try
            {
                in.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }

            try
            {
                out.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to enable assembly bind failure logging (Fusion) in .NET

Set the following registry value:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1

To disable, set to 0 or delete the value.

[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001

Then run the file from windows explorer and ignore the warning about possible damage.

Validate Dynamically Added Input fields

The one mahesh posted is not working because the attribute name is missing:

So instead of

<input id="list" class="required"  />

You can use:

<input id="list" name="list" class="required"  />

Modified version

How to specify a multi-line shell variable?

Thanks to dimo414's answer to a similar question, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

how to auto select an input field and the text in it on page load

Let the input text field automatically get focus when the page loads:

<form action="/action_page.php">
  <input type="text" id="fname" name="fname" autofocus>
  <input type="submit">
</form>

Source : https://www.w3schools.com/tags/att_input_autofocus.asp

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Pass parameters in setInterval function

I know this topic is so old but here is my solution about passing parameters in setInterval function.

Html:

var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);

JavaScript:

function startTimer(duration, display) {
    var timer = duration,
        minutes, seconds;

    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        --timer; // put boolean value for minus values.

    }, 1000);
}

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

Parenthesis/Brackets Matching using Stack algorithm

I tried this using javascript below is the result.

function bracesChecker(str) {
  if(!str) {
    return true;
  }
  var openingBraces = ['{', '[', '('];
  var closingBraces = ['}', ']', ')'];
  var stack = [];
  var openIndex;
  var closeIndex;
  //check for opening Braces in the val
  for (var i = 0, len = str.length; i < len; i++) {
    openIndex = openingBraces.indexOf(str[i]);
    closeIndex = closingBraces.indexOf(str[i]);
    if(openIndex !== -1) {
      stack.push(str[i]);
    }  
    if(closeIndex !== -1) {
      if(openingBraces[closeIndex] === stack[stack.length-1]) { 
        stack.pop();
      } else {
        return false;
      }
    }
  }
  if(stack.length === 0) {
    return true;
  } else {
    return false;
  }
}
var testStrings = [
  '', 
  'test', 
  '{{[][]()()}()}[]()', 
  '{test{[test]}}', 
  '{test{[test]}', 
  '{test{(yo)[test]}}', 
  'test{[test]}}', 
  'te()s[]t{[test]}', 
  'te()s[]t{[test'
];

testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));

Error importing SQL dump into MySQL: Unknown database / Can't create database

It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.

How to suppress Update Links warning?

I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:

while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
   controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd

So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

How to check if input file is empty in jQuery

I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:

if (!$('#videoUploadFile').val()) {
  alert('Please Upload File');
}

Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:

$(document).on("click", ":submit", function (e) {

  if (!$('#videoUploadFile').val()) {
  e.preventDefault();
  alert('Please Upload File');
  }

}

Send a ping to each IP on a subnet

FOR /L %i in (1,1,254) DO PING 192.168.1.%i -n 1 -w 100 | for /f "tokens=3 delims=: " %j in ('find /i "TTL="') do echo %j>>IPsOnline.txt

Radio buttons not checked in jQuery

If my firebug profiler work fine (and i know how to use it well), this:

$('#communitymode').attr('checked')

is faster than

$('#communitymode').is('checked')

You can try on this page :)

And then you can use it like

if($('#communitymode').attr('checked')===true) { 
// do something
}