Programs & Examples On #Recaptcha

For questions about the reCAPTCHA service, designed to protect against spam and abuse by blocking bots while allowing valid users to pass through with ease.

Google Recaptcha v3 example demo

Simple code to implement ReCaptcha v3

The basic JS code

<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>

The basic HTML code

<form id="form_id" method="post" action="your_action.php">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="hidden" name="action" value="validate_captcha">
    .... your fields
</form>

The basic PHP code

if (isset($_POST['g-recaptcha-response'])) {
    $captcha = $_POST['g-recaptcha-response'];
} else {
    $captcha = false;
}

if (!$captcha) {
    //Do something with error
} else {
    $secret   = 'Your secret key here';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
    }
}

//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->success==true && $response->score <= 0.5) {
    //Do something to denied access
}

You have to filter access using the value of $response.score. It can takes values from 0.0 to 1.0, where 1.0 means the best user interaction with your site and 0.0 the worst interaction (like a bot). You can see some examples of use in ReCaptcha documentation.

How to validate Google reCAPTCHA v3 on server side?

I'm not a fan of any of these solutions. I use this instead:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'secret' => $privatekey,
    'response' => $_POST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
]);

$resp = json_decode(curl_exec($ch));
curl_close($ch);

if ($resp->success) {
    // Success
} else {
    // failure
}

I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify

I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.

Google reCAPTCHA: How to get user response and validate in the server side?

Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.

<?php 
if(!empty($_REQUEST))
{
      //  echo '<pre>'; print_r($_REQUEST); die('END');
        $post = [
            'secret' => 'Your Secret key',
            'response' => $_REQUEST['g-recaptcha-response'],
        ];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);

        curl_close ($ch);
        echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
  <head>
    <title>reCAPTCHA demo: Explicit render for multiple widgets</title>
    <script type="text/javascript">
      var site_key = 'Your Site key';
      var verifyCallback = function(response) {
        alert(response);
      };
      var widgetId1;
      var widgetId2;
      var onloadCallback = function() {
        // Renders the HTML element with id 'example1' as a reCAPTCHA widget.
        // The id of the reCAPTCHA widget is assigned to 'widgetId1'.
        widgetId1 = grecaptcha.render('example1', {
          'sitekey' : site_key,
          'theme' : 'light'
        });
        widgetId2 = grecaptcha.render(document.getElementById('example2'), {
          'sitekey' : site_key
        });
        grecaptcha.render('example3', {
          'sitekey' : site_key,
          'callback' : verifyCallback,
          'theme' : 'dark'
        });
      };
    </script>
  </head>
  <body>
    <!-- The g-recaptcha-response string displays in an alert message upon submit. -->
    <form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
      <div id="example1"></div>
      <br>
      <input type="submit" value="getResponse">
    </form>
    <br>
    <!-- Resets reCAPTCHA widgetId2 upon submit. -->
    <form action="javascript:grecaptcha.reset(widgetId2);">
      <div id="example2"></div>
      <br>
      <input type="submit" value="reset">
    </form>
    <br>
    <!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
    <form action="?" method="POST">
      <div id="example3"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>
    </script>
  </body>
</html>

ReCaptcha API v2 Styling

Great! Now here is styling available for reCaptcha.. I just use inline styling like:

<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXX" style="transform: scale(1.08); margin-left: 14px;"></div> 

whatever you wanna to do small customize in inline styling...

Hope it will help you!!

How do I show multiple recaptchas on a single page?

I have contact form in footer that always displays and also some pages, like Create Account, can have captcha too, so it's dynamically and I'm using next way with jQuery:

html:

<div class="g-recaptcha" id="g-recaptcha"></div>

<div class="g-recaptcha" id="g-recaptcha-footer"></div>

javascript

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit&hl=en"></script>
<script type="text/javascript">
  var CaptchaCallback = function(){        
      $('.g-recaptcha').each(function(){
        grecaptcha.render(this,{'sitekey' : 'your_site_key'});
      })
  };
</script>

reCAPTCHA ERROR: Invalid domain for site key

Make sure you fill in your domain name and it must not end with a path.

example

http://yourdomain.com (good)

http://yourdomain.com/folder (error)

Using reCAPTCHA on localhost

  1. Register your website at – https://www.google.com/recaptcha/admin
  2. add js plugin 3.add class and your site-key provived by google enter image description here
<script src='https://www.google.com/recaptcha/api.js'></script>
 <div class="g-recaptcha" data-sitekey="your site-key"></div>

Change New Google Recaptcha (v2) Width

You can use parameter from reCaptcha. By default it uses normal value on data-size, You just have to use compact to fit this on small devices or some-kind small width layouts.

example:

<div class="g-recaptcha" data-size="compact"></div>

How to hide the Google Invisible reCAPTCHA badge

I saw next comment about this

It's also helpful to place the badge inline if you want to apply your own CSS to it. But do remember that you agreed to show Google's Terms and conditions when you registered for an API key - so don't hide it, please. And while it is possible to make the badge disappear completely with CSS, we wouldn't recommend it.

How to Reload ReCaptcha using JavaScript?

if you are using new recaptcha 2.0 use this: for code behind:

ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});", true);

for simple javascript

<script>$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});</script>

How to Validate Google reCaptcha on Form Submit

//validate
$receivedRecaptcha = $_POST['recaptchaRes'];
$google_secret =  "Yoursecretgooglepapikey";
$verifiedRecaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.$google_secret.'&response='.$receivedRecaptcha;
$handle = curl_init($verifiedRecaptchaUrl);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // not safe but works
//curl_setopt($handle, CURLOPT_CAINFO, "./my_cert.pem"); // safe
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($httpCode >= 200 && $httpCode < 300) {
  if (strlen($response) > 0) {
        $responseobj = json_decode($response);
        if(!$responseobj->success) {
            echo "reCAPTCHA is not valid. Please try again!";
            }
        else {
            echo "reCAPTCHA is valid.";
        }
    }
} else {
  echo "curl failed. http code is ".$httpCode;
}

How does Google reCAPTCHA v2 work behind the scenes?

My Bots are running well against ReCaptcha.

Here my Solution.

Let your Bot do this Steps:

First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.

Also use for better results a VPN like https://www.purevpn.com

For every Recpatcha do these Steps:

  1. If you use VPN switch IP first

  2. Clear all Browser Cookies

  3. Clear all Browser Cache

  4. Set one of these Useragents by Random:

    a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

    b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange

  1. Then Click ever with random delay between

    WM_LBUTTONDOWN

    and

    WM_LBUTTONUP

  2. Take Screenshot from Image Captcha

  3. Send Screenshot to

    http://www.deathbycaptcha.com

    or

    https://2captcha.com

and let they solve.

  1. After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images

  2. Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button

In 75% all trys Recaptcha will solved

Chears Google

Tom

How can I validate google reCAPTCHA v2 using javascript/jQuery?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script type="text/javascript">
        function get_action() {
            var v = grecaptcha.getResponse();
            console.log("Resp" + v);
            if (v == '') {
                document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
                return false;
            }
            else {
                document.getElementById('captcha').innerHTML = "Captcha completed";
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return get_action();">
    <div>
    <div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
    </div>
   <%-- <input type="submit" value="Button" />--%>
   <asp:Button ID="Button1" runat="server"
       Text="Button" />
    <div id="captcha"></div>
    </form>
</body>
</html>

It will work as expected.

Linux Script to check if process is running and act on the result

I cannot get case to work at all. Heres what I have:

#! /bin/bash

logfile="/home/name/public_html/cgi-bin/check.log"

case "$(pidof -x script.pl | wc -w)" in

0)  echo "script not running, Restarting script:     $(date)" >> $logfile
#  ./restart-script.sh
;;
1)  echo "script Running:     $(date)" >> $logfile
;;
*)  echo "Removed duplicate instances of script: $(date)" >> $logfile
 #   kill $(pidof -x ./script.pl | awk '{ $1=""; print $0}')
;;
esac

rem the case action commands for now just to test the script. the above pidof -x command is returning '1', the case statement is returning the results for '0'.

Anyone have any idea where I'm going wrong?

Solved it by adding the following to my BIN/BASH Script: PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Android - Get value from HashMap

HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}

How to obtain a QuerySet of all rows, with specific fields for each one of them?

You can use values_list alongside filter like so;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)

More details here

Determine version of Entity Framework I am using?

If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.

How to exclude 0 from MIN formula Excel

if all your value are positive, you can do -max(-n)

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

Android 6.0 Marshmallow. Cannot write to SD Card

First i will give you Dangerous Permission List in Android M and Later version

enter image description here enter image description here

Then give you example of how to request for permission in Android M and later version.

I ask user to WRITE_EXTERNAL_STORAGE permission.

First add permission in your android menifest file

Step 1 Declare requestcode

 private static String TAG = "PermissionDemo";
 private static final int REQUEST_WRITE_STORAGE = 112; 

Step 2 Add this code when you want ask user for permission

 //ask for the permission in android M
    int permission = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permission to record denied");

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Permission to access the SD-CARD is required for this app to Download PDF.")
                    .setTitle("Permission required");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    Log.i(TAG, "Clicked");
                    makeRequest();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();

        } else {
            makeRequest();
        }
    }

    protected void makeRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

Step 3 Add override method for Request

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_WRITE_STORAGE: {

            if (grantResults.length == 0
                    || grantResults[0] !=
                    PackageManager.PERMISSION_GRANTED) {

                Log.i(TAG, "Permission has been denied by user");

            } else {

                Log.i(TAG, "Permission has been granted by user");

            }
            return;
        }
    }
}

Note: Do not forget to add permission in menifest file

BEST EXAMPLE BELOW WITH MULTIPLE PERMISSION PLUS COVER ALL SCENARIO

I added comments so you can easily understand.

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.production.hometech.busycoder.R;

import java.util.ArrayList;

public class PermissionInActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_PERMISSION_SETTING = 99;
    private Button bt_camera;
    private static final String[] PARAMS_TAKE_PHOTO = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int RESULT_PARAMS_TAKE_PHOTO = 11;

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

        bt_camera = (Button) findViewById(R.id.bt_camera);

        bt_camera.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.bt_camera:

                takePhoto();

                break;

        }
    }


    /**
     * shouldShowRequestPermissionRationale() = This will return true if the user had previously declined to grant you permission
     * NOTE :  that ActivityCompat also has a backwards-compatible implementation of
     * shouldShowRequestPermissionRationale(), so you can avoid your own API level
     * checks.
     * <p>
     * shouldShowRequestPermissionRationale() =  returns false if the user declined the permission and checked the checkbox to ask you to stop pestering the
     * user.
     * <p>
     * requestPermissions() = request for the permisssiion
     */
    private void takePhoto() {

        if (canTakePhoto()) {

            Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();

        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            Toast.makeText(this, "You should give permission", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);

        } else {
            ActivityCompat.requestPermissions(this, netPermisssion(PARAMS_TAKE_PHOTO), RESULT_PARAMS_TAKE_PHOTO);
        }

    }

    //  This method return  permission denied String[] so we can request again
    private String[] netPermisssion(String[] wantedPermissions) {
        ArrayList<String> result = new ArrayList<>();

        for (String permission : wantedPermissions) {
            if (!hasPermission(permission)) {
                result.add(permission);
            }
        }

        return (result.toArray(new String[result.size()]));

    }

    private boolean canTakePhoto() {
        return (hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE));
    }

    /**
     * checkSelfPermission() = you can check if you have been granted a runtime permission or not
     * ex = ContextCompat.checkSelfPermission(this,permissionString)== PackageManager.PERMISSION_GRANTED
     * <p>
     * ContextCompat offers a backwards-compatible implementation of checkSelfPermission(), ActivityCompat offers a backwards-compatible
     * implementation of requestPermissions() that you can use.
     *
     * @param permissionString
     * @return
     */
    private boolean hasPermission(String permissionString) {
        return (ContextCompat.checkSelfPermission(this, permissionString) == PackageManager.PERMISSION_GRANTED);
    }

    /**
     * requestPermissions() action goes to onRequestPermissionsResult() whether user can GARNT or DENIED those permisssions
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == RESULT_PARAMS_TAKE_PHOTO) {

            if (canTakePhoto()) {

                Toast.makeText(this, "You can take picture", Toast.LENGTH_SHORT).show();

            } else if (!(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {


                final AlertDialog.Builder settingDialog = new AlertDialog.Builder(PermissionInActivity.this);
                settingDialog.setTitle("Permissioin");
                settingDialog.setMessage("Now you need to enable permisssion from the setting because without permission this app won't run properly \n\n  goto -> setting -> appInfo");
                settingDialog.setCancelable(false);

                settingDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.cancel();

                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                        Toast.makeText(getBaseContext(), "Go to Permissions to Grant all permission ENABLE", Toast.LENGTH_LONG).show();

                    }
                });
                settingDialog.show();

                Toast.makeText(this, "You need to grant permission from setting", Toast.LENGTH_SHORT).show();

            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_PERMISSION_SETTING) {

            if (canTakePhoto()) {

                Toast.makeText(this, "You can take PHOTO", Toast.LENGTH_SHORT).show();

            }

        }

    }


}

Special Case for Configuration change

It is possible that the user will rotate the device or otherwise trigger a configuration change while our permission dialog is in the foreground. Since our activity is still visible behind that dialog, we get destroyed and recreated… but we do not want to re-raise the permission dialog again.

That is why we have a boolean, named isInPermission, that tracks whether or not we are in the middle of requesting permissions. We hold onto that value in onSaveInstanceState():

@Override
protected void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}

We restore it in onCreate(). If we do not hold all of the desired permissions, but isInPermission is true, we skip requesting the permissions, since we are in the middle of doing so already.

Why do we always prefer using parameters in SQL statements?

In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.

Also read Protect from sql injection it will guide how you can protect your database.

Hope it help you to understand also any question comment me.

Split Java String by New Line

In JDK11 the String class has a lines() method:

Returning a stream of lines extracted from this string, separated by line terminators.

Further, the documentation goes on to say:

A line terminator is one of the following: a line feed character "\n" (U+000A), a carriage return character "\r" (U+000D), or a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A). A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

With this one can simply do:

Stream<String> stream = str.lines();

then if you want an array:

String[] array = str.lines().toArray(String[]::new);

Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

What you are doing will not work for root user. Maybe you are running your services as root and hence you don't get to see the change.

To increase the ulimit for root user you should replace the * by root. * does not apply for root user. Rest is the same as you did. I will re-quote it here.

Add the following lines to the file: /etc/security/limits.conf

root soft  nofile 40000

root hard  nofile 40000

And then add following line in the file: /etc/pam.d/common-session

session required pam_limits.so

This will update the ulimit for root user. As mentioned in comments, you may don't even have to reboot to see the change.

What is the connection string for localdb for version 11

This is for others who would have struggled like me to get this working....I wasted more than half a day on a seemingly trivial thing...

If you want to use SQL Express 2012 LocalDB from VS2010 you must have this patch installed http://www.microsoft.com/en-us/download/details.aspx?id=27756

Just like mentioned in the comments above I too had Microsoft .NET Framework Version 4.0.30319 SP1Rel and since its mentioned everywhere that you need "Framework 4.0.2 or Above" I thought I am good to go...

However, when I explicitly downloaded that 4.0.2 patch and installed it I got it working....

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.

Next:

s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

A general answer

select * from [dbo].[SplitString]('1,2',',') -- Will work 

but

select [dbo].[SplitString]('1,2',',')  -- will not work and throws this error

Pagination on a list using ng-repeat

I've built a module that makes in-memory pagination incredibly simple.

It allows you to paginate by simply replacing ng-repeat with dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

How to get "wc -l" to print just the number of lines without file name?

cat file.txt | wc -l

According to the man page (for the BSD version, I don't have a GNU version to check):

If no files are specified, the standard input is used and no file name is displayed. The prompt will accept input until receiving EOF, or [^D] in most environments.

How to get Last record from Sqlite?

Suppose you are looking for last row of table dbstr.TABNAME, into an INTEGER column named "_ID" (for example BaseColumns._ID), but could be anyother column you want.

public int getLastId() {
    int _id = 0;
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = db.query(dbstr.TABNAME, new String[] {BaseColumns._ID}, null, null, null, null, null);

    if (cursor.moveToLast()) {
        _id = cursor.getInt(0);
    }

    cursor.close();
    db.close();
    return _id;
}

Make JQuery UI Dialog automatically grow or shrink to fit its contents

var w = $('#dialogText').text().length;

$("#dialog").dialog('option', 'width', (w * 10));

did what i needed it to do for resizing the width of the dialog.

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

require_once('../web/a.php');

If this is not working for anyone, following is the good Idea to include file anywhere in the project.

require_once dirname(__FILE__)."/../../includes/enter.php";

This code will get the file from 2 directory outside of the current directory.

How to install latest version of Node using Brew

Just go old skool - https://nodejs.org/en/download/current/ From there you can get the current or LTS versions

How to find out what the date was 5 days ago?

General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm

Delete everything in a MongoDB database

In MongoDB 3.2 and newer, Mongo().getDBNames() in the mongo shell will output a list of database names in the server:

> Mongo().getDBNames()
[ "local", "test", "test2", "test3" ]

> show dbs
local  0.000GB
test   0.000GB
test2  0.000GB
test3  0.000GB

A forEach() loop over the array could then call dropDatabase() to drop all the listed databases. Optionally you can opt to skip some important databases that you don't want to drop. For example:

Mongo().getDBNames().forEach(function(x) {
  // Loop through all database names
  if (['admin', 'config', 'local'].indexOf(x) < 0) {
    // Drop if database is not admin, config, or local
    Mongo().getDB(x).dropDatabase();
  }
})

Example run:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
test2   0.000GB
test3   0.000GB

> Mongo().getDBNames().forEach(function(x) {
...   if (['admin', 'config', 'local'].indexOf(x) < 0) {
...     Mongo().getDB(x).dropDatabase();
...   }
... })

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

SQL query for getting data for last 3 months

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE()) 

Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column.

or you can check against last 90 days.

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE()) 

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I was facing the same problem, and debugged it using the event logs. First it said that : "The description for Event ID 5059 from source Microsoft-Windows-WAS cannot be found".

I then turned on WAS using turn windows features on/off. Then i saw this in eventvwr "Microsoft-Windows-DistributedCOM cannot be found".

Finally I gave up and deleted the App Pool (that used to stop on accessing the website) and created it again, as it is. This resolved the problem.

vb.net get file names in directory?

Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String

For Each fileName In fileEntries
    If (System.IO.File.Exists(fileName)) Then
        'Read File and Print Result if its true
        ReadFile(fileName)
    End If
    TransfereFile(fileName, 1)
Next

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Also, you can do this:

(this.DNATranscriber as any)[character];

Edit.

It's HIGHLY recommended that you cast the object with the proper type instead of any. Casting an object as any only help you to avoid type errors when compiling typescript but it doesn't help you to keep your code type-safe.

E.g.

interface DNA {
    G: "C",
    C: "G",
    T: "A",
    A: "U"
}

And then you cast it like this:

(this.DNATranscriber as DNA)[character];

How do I duplicate a line or selection within Visual Studio Code?

The commands your are looking for are editor.action.copyLinesDownAction and editor.action.copyLinesUpAction.

You can see the associated keybindings by picking: File > Preferences > Keyboard Shortcuts

Windows:

Shift+Alt+Down and Shift+Alt+Up

Mac:

Shift+Option+Down and Shift+OptionUp

Linux:

Ctrl+Shift+Alt+Down and Ctrl+Shift+Alt+Up

(Might need to use numpad Down and Up for Linux)

Furthermore, commands editor.action.moveLinesUpAction and editor.action.moveLinesDownAction are the ones to move lines and they are bound to Alt+Down and Alt+Up on Windows and Mac and Ctrl+Down and Ctrl+Up on Linux.

Converting string from snake_case to CamelCase in Ruby

Extend String to Add Camelize

In pure Ruby you could extend the string class using code lifted from Rails .camelize

class String
  def camelize(uppercase_first_letter = true)
    string = self
    if uppercase_first_letter
      string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
    else
      string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
    end
    string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
  end
end

hide div tag on mobile view only?

try this

@media handheld{
    #title_message { display: none; }
}

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

No you can't since IEnumerable is an interface.

You should be able to create an empty instance of most non-interface types which implement IEnumerable, e.g.:-

IEnumerable<object> a = new object[] { };

or

IEnumerable<object> a = new List<object>();

Getting last day of the month in a given string date

Use GregorianCalendar. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH).

http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You don't have to repeat those format identifiers . For yyyy you just need to have Y, etc.

gmdate('Y-m-d h:i:s \G\M\T', time());

In fact you don't even need to give it a default time if you want current time

gmdate('Y-m-d h:i:s \G\M\T');  // This is fine for your purpose

Manual

You can get that list of identifiers Here

Return a `struct` from a function in C

As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.

More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.

Arrays, however, can still be passed and returned only as pointers.

How do I properly clean up Excel interop objects?

I found a useful generic template that can help implement the correct disposal pattern for COM objects, that need Marshal.ReleaseComObject called when they go out of scope:

Usage:

using (AutoReleaseComObject<Application> excelApplicationWrapper = new AutoReleaseComObject<Application>(new Application()))
{
    try
    {
        using (AutoReleaseComObject<Workbook> workbookWrapper = new AutoReleaseComObject<Workbook>(excelApplicationWrapper.ComObject.Workbooks.Open(namedRangeBase.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing)))
        {
           // do something with your workbook....
        }
    }
    finally
    {
         excelApplicationWrapper.ComObject.Quit();
    } 
}

Template:

public class AutoReleaseComObject<T> : IDisposable
{
    private T m_comObject;
    private bool m_armed = true;
    private bool m_disposed = false;

    public AutoReleaseComObject(T comObject)
    {
        Debug.Assert(comObject != null);
        m_comObject = comObject;
    }

#if DEBUG
    ~AutoReleaseComObject()
    {
        // We should have been disposed using Dispose().
        Debug.WriteLine("Finalize being called, should have been disposed");

        if (this.ComObject != null)
        {
            Debug.WriteLine(string.Format("ComObject was not null:{0}, name:{1}.", this.ComObject, this.ComObjectName));
        }

        //Debug.Assert(false);
    }
#endif

    public T ComObject
    {
        get
        {
            Debug.Assert(!m_disposed);
            return m_comObject;
        }
    }

    private string ComObjectName
    {
        get
        {
            if(this.ComObject is Microsoft.Office.Interop.Excel.Workbook)
            {
                return ((Microsoft.Office.Interop.Excel.Workbook)this.ComObject).Name;
            }

            return null;
        }
    }

    public void Disarm()
    {
        Debug.Assert(!m_disposed);
        m_armed = false;
    }

    #region IDisposable Members

    public void Dispose()
    {
        Dispose(true);
#if DEBUG
        GC.SuppressFinalize(this);
#endif
    }

    #endregion

    protected virtual void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (m_armed)
            {
                int refcnt = 0;
                do
                {
                    refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(m_comObject);
                } while (refcnt > 0);

                m_comObject = default(T);
            }

            m_disposed = true;
        }
    }
}

Reference:

http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/

How to access JSON Object name/value?

The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code

data = JSON.parse(data);

Or if you are using jQuery

data = $.parseJSON(data)

How to assign from a function which returns more than one value?

If you want to return the output of your function to the Global Environment, you can use list2env, like in this example:

myfun <- function(x) { a <- 1:x
                       b <- 5:x
                       df <- data.frame(a=a, b=b)

                       newList <- list("my_obj1" = a, "my_obj2" = b, "myDF"=df)
                       list2env(newList ,.GlobalEnv)
                       }
    myfun(3)

This function will create three objects in your Global Environment:

> my_obj1
  [1] 1 2 3

> my_obj2
  [1] 5 4 3

> myDF
    a b
  1 1 5
  2 2 4
  3 3 3

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msgs) {
        //write your code hear which give error
        }
        }

new Thread(new Runnable() {
    @Override
    public void run() {
    handler.sendEmptyMessage(1);
        //this will call handleMessage function and hendal all error
    }
    }).start();

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Running MSBuild fails to read SDKToolsPath

I had a similar problem. I had done a project using Visual Studio 2010 and then got the above error when i compiled it using Visual Studio 2012. I simple copied all the contents of C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A into C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A and that solved my problem.

MySQL error code: 1175 during UPDATE in MySQL Workbench

True, this is pointless for the most examples. But finally, I came to the following statement and it works fine:

update tablename  set column1 = '' where tablename .id = (select id from tablename2 where tablename2.column2 = 'xyz');

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

After a sequence of attempts I came into a facile solution. You can try Reinstalling ActiveX plugin for Adobe flashplayer.

Set the location in iPhone Simulator

In my delegate callback, I check to see if I'm running in a simulator (#if TARGET_ IPHONE_SIMULATOR) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.

Dynamic button click event handler

I needed a common event handler in which I can show from which button it is called without using switch case... and done like this..

  Private Sub btn_done_clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)

    MsgBox.Show("you have clicked button " & CType(CType(sender,  _
    System.Windows.Forms.Button).Tag, String))

  End Sub

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

Should I use alias or alias_method?

alias_method new_method, old_method

old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

these can be variable or method both.

Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

Generating all permutations of a given string

Let me try to tackle this problem with Kotlin:

fun <T> List<T>.permutations(): List<List<T>> {
    //escape case
    if (this.isEmpty()) return emptyList()

    if (this.size == 1) return listOf(this)

    if (this.size == 2) return listOf(listOf(this.first(), this.last()), listOf(this.last(), this.first()))

    //recursive case
    return this.flatMap { lastItem ->
        this.minus(lastItem).permutations().map { it.plus(lastItem) }
    }
}

Core concept: Break down long list into smaller list + recursion

Long answer with example list [1, 2, 3, 4]:

Even for a list of 4 it already kinda get's confusing trying to list all the possible permutations in your head, and what we need to do is exactly to avoid that. It is easy for us to understand how to make all permutations of list of size 0, 1, and 2, so all we need to do is break them down to any of those sizes and combine them back up correctly. Imagine a jackpot machine: this algorithm will start spinning from the right to the left, and write down

  1. return empty/list of 1 when list size is 0 or 1
  2. handle when list size is 2 (e.g. [3, 4]), and generate the 2 permutations ([3, 4] & [4, 3])
  3. For each item, mark that as the last in the last, and find all the permutations for the rest of the item in the list. (e.g. put [4] on the table, and throw [1, 2, 3] into permutation again)
  4. Now with all permutation it's children, put itself back to the end of the list (e.g.: [1, 2, 3][,4], [1, 3, 2][,4], [2, 3, 1][, 4], ...)

How can I create my own comparator for a map?

Yes, the 3rd template parameter on map specifies the comparator, which is a binary predicate. Example:

struct ByLength : public std::binary_function<string, string, bool>
{
    bool operator()(const string& lhs, const string& rhs) const
    {
        return lhs.length() < rhs.length();
    }
};

int main()
{
    typedef map<string, string, ByLength> lenmap;
    lenmap mymap;

    mymap["one"] = "one";
    mymap["a"] = "a";
    mymap["fewbahr"] = "foobar";

    for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
        cout << it->first << "\n";
}

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

setup android on eclipse but don't know SDK directory

You can search your hard drive for one of the programs that's installed with the SDK. For instance, if you search for aapt.exe or adb.exe, they will be in the platform-tools directory underneath the installation directory (which is what you're after).

Setting the default Java character encoding

My team encountered the same issue in machines with Windows.. then managed to resolve it in two ways:

a) Set enviroment variable (even in Windows system preferences)

JAVA_TOOL_OPTIONS
-Dfile.encoding=UTF8

b) Introduce following snippet to your pom.xml:

 -Dfile.encoding=UTF-8 

WITHIN

 <jvmArguments>
 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001
 -Dfile.encoding=UTF-8
 </jvmArguments>

oracle - what statements need to be committed?

In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).

In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.

From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.

This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD or ORA-01002: FETCH OUT OF SEQUENCE occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.

Show all current locks from get_lock

Another easy way is to use:

mysqladmin debug 

This dumps a lot of information (including locks) to the error log.

Numpy: Checking if a value is NaT

Since NumPy version 1.13 it contains an isnat function:

>>> import numpy as np
>>> np.isnat(np.datetime64('nat'))
True

It also works for arrays:

>>> np.isnat(np.array(['nat', 1, 2, 3, 4, 'nat', 5], dtype='datetime64[D]'))
array([ True, False, False, False, False,  True, False], dtype=bool)

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Changing width property of a :before css selector using JQuery

As Boltclock states in his answer to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them with jQuery.

Might just be best to set the style with jQuery instead of using the pseudo CSS selector.

open program minimized via command prompt

The answer is simple. Just look at the image.

enter image description here

Binding objects defined in code-behind

There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.

Window1.xaml

<Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>

Window1.xaml.cs

public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        }; 

        InitializeComponent();
    }
}

How to add an image in Tkinter?

It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:

  1. Make sure that your script.py is at the same folder with the image you want to show.
  2. Edit your script.py

    from Tkinter import *        
    from PIL import ImageTk, Image
    
    app_root = Tk()
    
    #Setting it up
    img = ImageTk.PhotoImage(Image.open("app.png"))
    
    #Displaying it
    imglabel = Label(app_root, image=img).grid(row=1, column=1)        
    
    
    app_root.mainloop()
    

Hope that helps!

How to delete the contents of a folder?

You can delete the folder itself, as well as all its contents, using shutil.rmtree:

import shutil
shutil.rmtree('/path/to/folder')
shutil.rmtree(path, ignore_errors=False, onerror=None)


Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

How can I combine two commits into one commit?

Lazy simple version for forgetfuls like me:

git rebase -i HEAD~3 or however many commits instead of 3.

Turn this

pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage

into this

pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage

and do some action where you hit esc then enter to save the changes. [1]

When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape enter action. [1]

Wowee, you have fewer commits. Or you just broke everything.


[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.

[2] - you'll see some stuff like # this is your n'th commit a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.

How do I horizontally center an absolute positioned element inside a 100% width div?

In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

Center form submit buttons HTML / CSS

One simple solution if only one button needs to be centered is something like:

<input type='submit' style='display:flex; justify-content:center;' value='Submit'>

You can use a similar style to handle several buttons.

Creating a byte array from a stream

In case anyone likes it, here is a .NET 4+ only solution formed as an extension method without the needless Dispose call on the MemoryStream. This is a hopelessly trivial optimization, but it is worth noting that failing to Dispose a MemoryStream is not a real failure.

public static class StreamHelpers
{
    public static byte[] ReadFully(this Stream input)
    {
        var ms = new MemoryStream();
        input.CopyTo(ms);
        return ms.ToArray();
    }
}

Deserialize JSON string to c# object

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:

string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
        {
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

        }
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
         {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
            {
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);

            }
        }

4 Sure it will work.... ;)

Find row in datatable with specific id

I could use the following code. Thanks everyone.

int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

Select All as default value for Multivalue parameter

Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything

Create Parameter (if not automaticly created)

Create Parameter

Define values - wrong way example

Define values - wrong way

Define values - correct way example

Define values - correct way

Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.

Set default values

The Result

The result

One picture for Data type: Int

One picture for Data type Int

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

Difference between two DateTimes C#?

You can do the following:

TimeSpan duration = b - a;

There's plenty of built in methods in the timespan class to do what you need, i.e.

duration.TotalSeconds
duration.TotalMinutes

More info can be found here.

Access mysql remote database from command line

Must check whether incoming access to port 3306 is block or not by the firewall.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Can you change a path without reloading the controller in AngularJS?

I use this solution

angular.module('reload-service.module', [])
.factory('reloadService', function($route,$timeout, $location) {
  return {
     preventReload: function($scope, navigateCallback) {
        var lastRoute = $route.current;

        $scope.$on('$locationChangeSuccess', function() {
           if (lastRoute.$$route.templateUrl === $route.current.$$route.templateUrl) {
              var routeParams = angular.copy($route.current.params);
              $route.current = lastRoute;
              navigateCallback(routeParams);
           }
        });
     }
  };
})

//usage
.controller('noReloadController', function($scope, $routeParams, reloadService) {
     $scope.routeParams = $routeParams;

     reloadService.preventReload($scope, function(newParams) {
        $scope.routeParams = newParams;
     });
});

This approach preserves back button functionality, and you always have the current routeParams in the template, unlike some other approaches I've seen.

Inserting into Oracle and retrieving the generated sequence ID

There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:

insert into table(batch_id, ...) values(my_sequence.nextval, ...)

...to return the next number. To find out the last created sequence nr (in your session), you would use:

my_sequence.currval

This site has several complete examples on how to use sequences.

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

Getting the class of the element that fired an event using JQuery

This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":

event.target.className

You can use jQuery to check for classes by name:

$(event.target).hasClass('konbo');

and to add or remove them with addClass and removeClass.

Can you write virtual functions / methods in Java?

Can you write virtual functions in Java?

Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:

  • Class methods (because typically each instance holds information like a pointer to a vtable about its specific methods, but no instance is available here).
  • Private instance methods (because no other class can access the method, the calling instance has always the type of the defining class itself and is therefore unambiguously known at compile time).

Here are some examples:

"Normal" virtual functions

The following example is from an old version of the wikipedia page mentioned in another answer.

import java.util.*;

public class Animal 
{
   public void eat() 
   { 
      System.out.println("I eat like a generic Animal."); 
   }

   public static void main(String[] args) 
   {
      List<Animal> animals = new LinkedList<Animal>();

      animals.add(new Animal());
      animals.add(new Fish());
      animals.add(new Goldfish());
      animals.add(new OtherAnimal());

      for (Animal currentAnimal : animals) 
      {
         currentAnimal.eat();
      }
   }
}

class Fish extends Animal 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a fish!"); 
   }
}

class Goldfish extends Fish 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a goldfish!"); 
   }
}

class OtherAnimal extends Animal {}

Output:

I eat like a generic Animal.
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Example with virtual functions with interfaces

Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.

For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implement applyBrakes()
       System.out.println("Brakes applied"); //function
    }
}

Example with virtual functions with abstract classes.

Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a "pure" virtual function 
}                                     
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden
    }                                  
}
public class Runner {
    public static void main(String[] args) {
        Dog dog = new MyDog();       // Create a MyDog and assign to plain Dog variable
        dog.jump();                  // calling the virtual function.
                                     // MyDog.jump() will be executed 
                                     // although the variable is just a plain Dog.
    }
}

passing JSON data to a Spring MVC controller

Add the following dependencies

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json

Prevent jQuery UI dialog from setting focus to first textbox

If you're using dialog buttons, just set the autofocus attribute on one of the buttons:

_x000D_
_x000D_
$('#dialog').dialog({_x000D_
  buttons: [_x000D_
    {_x000D_
      text: 'OK',_x000D_
      autofocus: 'autofocus'_x000D_
    },_x000D_
    {_x000D_
      text: 'Cancel'_x000D_
    }_x000D_
  ]_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="dialog" title="Basic dialog">_x000D_
  This is some text._x000D_
  <br/>_x000D_
  <a href="www.google.com">This is a link.</a>_x000D_
  <br/>_x000D_
  <input value="This is a textbox.">_x000D_
</div>
_x000D_
_x000D_
_x000D_

regular expression for anything but an empty string

Create "regular expression to detect empty string", and then inverse it. Invesion of regular language is the regular language. I think regular expression library in what you leverage - should support it, but if not you always can write your own library.

grep --invert-match

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

Switch to another branch without changing the workspace files

Why not just git reset --soft <branch_name>?

Demonstration:

mkdir myrepo; cd myrepo; git init
touch poem; git add poem; git commit -m 'add poem'  # first commit
git branch original
echo bananas > poem; git commit -am 'change poem'  # second commit
echo are tasty >> poem  # unstaged change
git reset --soft original

Result:

$ git diff --cached
diff --git a/poem b/poem
index e69de29..9baf85e 100644
--- a/poem
+++ b/poem
@@ -0,0 +1 @@
+bananas
$ git diff
diff --git a/poem b/poem
index 9baf85e..ac01489 100644
--- a/poem
+++ b/poem
@@ -1 +1,2 @@
 bananas
+are tasty

One thing to note though, is that the current branch changes to original. You’re still left in the previous branch after the process, but can easily git checkout original, because it’s the same state. If you do not want to lose the previous HEAD, you should note the commit reference and do git branch -f <previous_branch> <commit> after that.

Define a global variable in a JavaScript function

Here is another easy method to make the variable available in other functions without having to use global variables:

_x000D_
_x000D_
function makeObj() {_x000D_
  // var trailimage = 'test';_x000D_
  makeObj.trailimage = 'test';_x000D_
}_x000D_
function someOtherFunction() {_x000D_
  document.write(makeObj.trailimage);_x000D_
}_x000D_
_x000D_
makeObj();_x000D_
someOtherFunction();
_x000D_
_x000D_
_x000D_

Cannot delete directory with Directory.Delete(path, true)

None of the above answers worked for me. It appears that my own app's usage of DirectoryInfo on the target directory was causing it to remain locked.

Forcing garbage collection appeared to resolve the issue, but not right away. A few attempts to delete where required.

Note the Directory.Exists as it can disappear after an exception. I don't know why the delete for me was delayed (Windows 7 SP1)

        for (int attempts = 0; attempts < 10; attempts++)
        {
            try
            {
                if (Directory.Exists(folder))
                {
                    Directory.Delete(folder, true);
                }
                return;
            }
            catch (IOException e)
            {
                GC.Collect();
                Thread.Sleep(1000);
            }
        }

        throw new Exception("Failed to remove folder.");

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

put your CA & root certificate in /usr/share/ca-certificate or /usr/local/share/ca-certificate. Then

dpkg-reconfigure ca-certificates

or even reinstall ca-certificate package with apt-get.

After doing this your certificate is collected into system's DB: /etc/ssl/certs/ca-certificates.crt

Then everything should be fine.

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

python: how to send mail with TO, CC and BCC?

Don't add the bcc header.

See this: http://mail.python.org/pipermail/email-sig/2004-September/000151.html

And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since the envelope information is separate from the message headers, you can even BCC someone by including them in the method argument but not in the message header.""" from http://pymotw.com/2/smtplib

toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
    + "To: %s\r\n" % toaddr
    + "CC: %s\r\n" % ",".join(cc)
    # don't add this, otherwise "to and cc" receivers will know who are the bcc receivers
    # + "BCC: %s\r\n" % ",".join(bcc)
    + "Subject: %s\r\n" % message_subject
    + "\r\n" 
    + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

The bootstrap docs do explain it, but it still took me a while to get it. It makes more sense when I explain it to myself in one of two ways:

If you think of the columns starting out horizontally, then you can choose when you want them to stack.

For example, if you start with columns: A B C

You decide when should they stack to be like this:

A

B

C

If you choose col-lg, then the columns will stack when the width is < 1200px.

If you choose col-md, then the columns will stack when the width is < 992px.

If you choose col-sm, then the columns will stack when the width is < 768px.

If you choose col-xs, then the columns will never stack.

On the other hand, if you think of the columns starting out stacked, then you can choose at what point they become horizontal:

If you choose col-sm, then the columns will become horizontal when the width is >= 768px.

If you choose col-md, then the columns will become horizontal when the width is >= 992px.

If you choose col-lg, then the columns will become horizontal when the width is >= 1200px.

How to make html <select> element look like "disabled", but pass values?

One could use an additional hidden input element with the same name and value as that of the disabled list. This will ensure that the value is passed in $_POST variables.

Eg:

_x000D_
_x000D_
<select name="sel" disabled><option>123</select>_x000D_
<input type="hidden" name="sel" value=123>
_x000D_
_x000D_
_x000D_

Python syntax for "if a or b or c but not all of them"

As I understand it, you have a function that receives 3 arguments, but if it does not it will run on default behavior. Since you have not explained what should happen when 1 or 2 arguments are supplied I will assume it should simply do the default behavior. In which case, I think you will find the following answer very advantageous:

def method(a=None, b=None, c=None):
    if all([a, b, c]):
        # received 3 arguments
    else:
        # default behavior

However, if you want 1 or 2 arguments to be handled differently:

def method(a=None, b=None, c=None):
    args = [a, b, c]
    if all(args):
        # received 3 arguments
    elif not any(args):
        # default behavior
    else:
        # some args (raise exception?)

note: This assumes that "False" values will not be passed into this method.

changing default x range in histogram matplotlib

the following code is for making the same y axis limit on two subplots

f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [lower_limit,upper_limit]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1) 
ax[1].set_ylim(ylim)

just a reminder, plt.hist(range=[low, high]) the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

How to get row count using ResultSet in Java?

The ResultSet has it's methods that move the Cursor back and forth depending on the option provided. By default, it's forward moving(TYPE_FORWARD_ONLY ResultSet type). Unless CONSTANTS indicating Scrollability and Update of ResultSet properly, you might end up getting an error. E.g. beforeLast() This method has no effect if the result set contains no rows. Throws Error if it's not TYPE_FORWARD_ONLY.

The best way to check if empty rows got fetched --- Just to insert new record after checking non-existence

if( rs.next() ) {

   Do nothing
} else {
  No records fetched!
}

See here

How to replace an entire line in a text file by line number

I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:

#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file

This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/ and placing a wildcard in place of the_original_line.

Maven: best way of linking custom external JAR to my project?

update We have since just installed our own Nexus server, much easier and cleaner.

At our company we had some jars that we some jars that were common but were not hosted in any maven repositories, nor did we want to have them in local storage. We created a very simple mvn (public) repo on Github (but you can host it on any server or locally):
note that this is only ideal for managing a few rarely chaning jar files

  1. Create repo on GitHub:
    https://github.com/<user_name>/mvn-repo/

  2. Add Repository in pom.xml
    (Make note that the full path raw file will be a bit different than the repo name)

    <repository>
        <id>project-common</id>
        <name>Project Common</name>
        <url>https://github.com/<user_name>/mvn-repo/raw/master/</url>
    </repository>
    
  3. Add dependency to host (Github or private server)
    a. All you need to know is that files are stored in the pattern mentioned by @glitch
    /groupId/artifactId/version/artifactId-version.jar
    b. On your host create the folders to match this pattern.
    i.e if you have a jar file named service-sdk-0.0.1.jar, create the folder service-sdk/service-sdk/0.0.1/ and place the jar file service-sdk-0.0.1.jar into it.
    c. Test it by trying to download the jar from a browser (in our case: https://github.com/<user_name>/mvn-repo/raw/master/service-sdk/service-sdk/0.0.1/service-sdk-0.0.1.jar

  4. Add dependency to your pom.xml file:

    <dependency>
        <groupId>service-sdk</groupId>
        <artifactId>service-sdk</artifactId>
        <version>0.0.1</version>
    </dependency>
    
  5. Enjoy

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

Could not find method compile() for arguments Gradle

In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...

If you experienced this issue in a git project, do git status and remove the unrevisioned files. (For me elasticsearch had a problem with plugins/analysis-icu).

Gradle Version : 5.1.1

Add primary key to existing table

ALTER TABLE TABLE_NAME ADD PRIMARY KEY(`persionId`,`Pname`,`PMID`)

How to resolve 'unrecognized selector sent to instance'?

You should note that this is not necessarily the best design pattern. From the looks of it, you are essentially using your App Delegate to store what amounts to a global variable.

Matt Gallagher covered the issue of globals well in his Cocoa with Love article at http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html. In all likelyhood, your ClassA should be a singleton rather than a global in the AppDelegate, although its possible you intent ClassA to be more general purpose and not simply a singleton. In that case, you'd probably be better off with either a class method to return a pre-configured instance of Class A, something like:

+ (ClassA*) applicationClassA
{
    static ClassA* appClassA = nil;
    if ( !appClassA ) {
        appClassA = [[ClassA alloc] init];
        appClassA.downloadURL = @"http://www.abc.com/";
    }
    return appClassA;
}

Or alternatively (since that would add application specific stuff to what is possibly a general purpose class), create a new class whose sole purpose is to contain that class method.

The point is that application globals do not need to be part of the AppDelegate. Just because the AppDelegate is a known singleton, does not mean every other app global should be mixed in with it even if they have nothing conceptually to do with handling the NSApplication delegate methods.

NumPy array is not JSON serializable

I regularly "jsonify" np.arrays. Try using the ".tolist()" method on the arrays first, like this:

import numpy as np
import codecs, json 

a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
file_path = "/path.json" ## your path variable
json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) ### this saves the array in .json format

In order to "unjsonify" the array use:

obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)

How to test if a DataSet is empty?

If I understand correctly, this should work for you

if (ds.Tables[0].Rows.Count == 0)
{
    //
}

Copy multiple files in Python

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

Convert JSON string to dict using Python

When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution

import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])

Ng-model does not update controller value

Using this instead of $scope works.

_x000D_
_x000D_
function AppCtrl($scope){_x000D_
  $scope.searchText = "";_x000D_
  $scope.check = function () {_x000D_
    console.log("You typed '" + this.searchText + "'"); // used 'this' instead of $scope_x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app>_x000D_
  <div ng-controller="AppCtrl">_x000D_
    <input ng-model="searchText"/>_x000D_
    <button ng-click="check()">Write console log</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit: At the time writing this answer, I had much more complicated situation than this. After the comments, I tried to reproduce it to understand why it works, but no luck. I think somehow (don't really know why) a new child scope is generated and this refers to that scope. But if $scope is used, it actually refers to the parent $scope because of javascript's lexical scope feature.

Would be great if someone having this problem tests this way and inform us.

Windows command prompt log to a file

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

Delete all documents from index/type without deleting type

Just to add couple cents to this.

The "delete_by_query" mentioned at the top is still available as a plugin in elasticsearch 2.x.

Although in the latest upcoming version 5.x it will be replaced by "delete by query api"

How do I remove the file suffix and path portion from a path string in Bash?

Here's how to do it with the # and % operators in Bash.

$ x="/foo/fizzbuzz.bar"
$ y=${x%.bar}
$ echo ${y##*/}
fizzbuzz

${x%.bar} could also be ${x%.*} to remove everything after a dot or ${x%%.*} to remove everything after the first dot.

Example:

$ x="/foo/fizzbuzz.bar.quux"
$ y=${x%.*}
$ echo $y
/foo/fizzbuzz.bar
$ y=${x%%.*}
$ echo $y
/foo/fizzbuzz

Documentation can be found in the Bash manual. Look for ${parameter%word} and ${parameter%%word} trailing portion matching section.

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

in python how do I convert a single digit number into a double digits string?

In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.

>>> f'{a:02d}'
'05'

NSDictionary to NSArray?

There are a few things that could be happening here.

Is the dictionary you have listed the myDict? If so, then you don't have an object with a key of @"items", and the dict variable will be nil. You need to iterate through myDict directly.

Another thing to check is if _myArray is a valid instance of an NSMutableArray. If it's nil, the addObject: method will silently fail.

And a final thing to check is that the objects inside your dictionary are properly encased in NSNumbers (or some other non-primitive type).

referenced before assignment error in python

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

Because doA() does not modify the global total the output is 1 not 11.

Regex to get string between curly braces

Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

What are unit tests, integration tests, smoke tests, and regression tests?

Everyone will have slightly different definitions, and there are often grey areas. However:

  • Unit test: does this one little bit (as isolated as possible) work?
  • Integration test: do these two (or more) components work together?
  • Smoke test: does this whole system (as close to being a production system as possible) hang together reasonably well? (i.e. are we reasonably confident it won't create a black hole?)
  • Regression test: have we inadvertently re-introduced any bugs we'd previously fixed?

Eclipse error "ADB server didn't ACK, failed to start daemon"

I had a similar issue. Killing an existing instance of the ADB process from Task Manager did not work for me.

Just few days back, I had tried to install MIPS SDK and ADT-17 earlier and Eclipse gave me the error, and I did not fix that issue.

So, now, when I got this ADB server didn't ACK, failed to start daemon... issue, I executed 'Check for Updates' in the Eclipse Help menu item. There were no updates available, but at least 'ADB server did not ACK' error disappeared.

I hope this might help in a few cases.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Even though this answer was too late, I'm adding it because I also went through a horrible time finding answer for the same matter. Only different was, I was struggling with AWS Comprehend Medical API.

At the moment I'm writing this answer, if anyone come across the same issue with any AWS SDKs please downgrade jackson-annotaions or any jackson dependencies to 2.8.* versions. The latest 2.9.* versions does not working properly with AWS SDK for some reason. Anyone have any idea about the reason behind that feel free to comment below.

Just in case if anyone is lazy to google maven repos, I have linked down necessary repos.Check them out!

How to create composite primary key in SQL Server 2008

create table my_table (
     column_a integer not null,
     column_b integer not null,
     column_c varchar(50),
     primary key (column_a, column_b)
);

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

Stop an input field in a form from being submitted

_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Get Current date in epoch from Unix shell script

echo $(($(date +%s) / 60 / 60 / 24))

How to create a RelativeLayout programmatically with two buttons one on top of the other?

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

How to determine if a decimal/double is an integer?

If upper and lower bound of Int32 matters:

public bool IsInt32(double value)
{
    return  value >= int.MinValue && value <= int.MaxValue && value == (int)value;
}

Copy a table from one database to another in Postgres

Here is what worked for me. First dump to a file:

pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump

then load the dumped file:

psql -U myuser -d second_db</tmp/table_dump

.htaccess not working on localhost with XAMPP

I've setup xampp for my localhost as well, I've not done anything with the files created by xampp during or after setup.

But in the '.htaccess' file, make sure you've set it to something like this. Works for me, and this should not make any difference for you.

RewriteEngine On
RewriteRule ^filename/?$ filename.html

Change .html to whatever format you're using.

Make sure your install is clean, and just make the .htaccess file. Also remember to put one .htaccess file for each directory (don't really know if you can use ONE file for all folders, but to be safe, just do this and it will always work.

Benefits of EBS vs. instance-store (and vice-versa)

I'm just starting to use EC2 myself so not an expert, but Amazon's own documentation says:

we recommend that you use the local instance store for temporary data and, for data requiring a higher level of durability, we recommend using Amazon EBS volumes or backing up the data to Amazon S3.

Emphasis mine.

I do more data analysis than web hosting, so persistence doesn't matter as much to me as it might for a web site. Given the distinction made by Amazon itself, I wouldn't assume that EBS is right for everyone.

I'll try to remember to weigh in again after I've used both.

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

How to round the minute of a datetime object

Based on Stijn Nevens and modified for Django use to round current time to the nearest 15 minute.

from datetime import date, timedelta, datetime, time

    def roundTime(dt=None, dateDelta=timedelta(minutes=1)):

        roundTo = dateDelta.total_seconds()

        if dt == None : dt = datetime.now()
        seconds = (dt - dt.min).seconds
        # // is a floor division, not a comment on following line:
        rounding = (seconds+roundTo/2) // roundTo * roundTo
        return dt + timedelta(0,rounding-seconds,-dt.microsecond)

    dt = roundTime(datetime.now(),timedelta(minutes=15)).strftime('%H:%M:%S')

 dt = 11:45:00

if you need full date and time just remove the .strftime('%H:%M:%S')

MySQL Job failed to start

First make a backup of your /var/lib/mysql/ directory just to be safe.

sudo mkdir /home/<your username>/mysql/
cd /var/lib/mysql/
sudo cp * /home/<your username>/mysql/ -R

Next purge MySQL (this will remove php5-mysql and phpmyadmin as well as a number of other libraries so be prepared to re-install some items after this.

sudo apt-get purge mysql-server-5.1 mysql-common

Remove the folder /etc/mysql/ and it's contents

sudo rm /etc/mysql/ -R

Next check that your old database files are still in /var/lib/mysql/ if they are not then copy them back in to the folder then chown root:root

(only run these if the files are no longer there)

sudo mkdir /var/lib/mysql/
sudo chown root:root /var/lib/mysql/ -R
cd ~/mysql/
sudo cp * /var/lib/mysql/ -R

Next install mysql server

sudo apt-get install mysql-server

Finally re-install any missing packages like phpmyadmin and php5-mysql.

Is SQL syntax case sensitive?

SQL keywords are case insensitive themselves.

Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).

Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.

Reset AutoIncrement in SQL Server after Delete

I want to add this answer because the DBCC CHECKIDENT-approach will product problems when you use schemas for tables. Use this to be sure:

DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);

If you want to check the success of the operation, use

SELECT IDENT_CURRENT(@Table);

which should output 0 in the example above.

How to install Hibernate Tools in Eclipse?

For Eclipse plugins, you just unzip them and drop the folder in the Eclipse\Plugins directory. Simple as that.

Highcharts - how to have a chart with dynamic height?

Alternatively, you can directly use javascript's window.onresize

As example, my code (using scriptaculos) is :

window.onresize = function (){
    var w = $("form").getWidth() + "px";
    $('gfx').setStyle( { width : w } );
}

Where form is an html form on my webpage and gfx the highchart graphics.

How do I set/unset a cookie with jQuery?

I know there are many great answers. Often, I only need to read cookies and I do not want to create overhead by loading additional libraries or defining functions.

Here is how to read cookies in one line of javascript. I found the answer in Guilherme Rodrigues' blog article:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

This reads the cookie named key, nice, clean and simple.

How to concatenate two strings in SQL Server 2005

Try something like

SELECT 'rupesh''s' + 'malviya'

+ (String Concatenation)

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

WebDriver: check if an element exists?

This works for me every time:

    if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
        //THEN CLICK ON THE SUBMIT BUTTON
    }else{
        //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
    }

Listing available com ports with Python

You can use:

python -c "import serial.tools.list_ports;print serial.tools.list_ports.comports()"

Filter by know port: python -c "import serial.tools.list_ports;print [port for port in serial.tools.list_ports.comports() if port[2] != 'n/a']"

See more info here: https://pyserial.readthedocs.org/en/latest/tools.html#module-serial.tools.list_ports

What is the meaning of curly braces?

"Curly Braces" are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another - kind of like how an English dictionary maps a word to its definition.

Python:

dict = {
    "a" : "Apple",
    "b" : "Banana",
}

They are also used to format strings, instead of the old C style using %, like:

ds = ['a', 'b', 'c', 'd']
x = ['has_{} 1'.format(d) for d in ds]

print x

['has_a 1', 'has_b 1', 'has_c 1', 'has_d 1']

They are not used to denote code blocks as they are in many "C-like" languages.

C:

if (condition) {
    // do this
}

Best way to store passwords in MYSQL database

Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

How do I restart my C# WinForm Application?

I had the same exact problem and I too had a requirement to prevent duplicate instances - I propose an alternative solution to the one HiredMind is proposing (which will work fine).

What I am doing is starting the new process with the processId of the old process (the one that triggers the restart) as a cmd line argument:

// Shut down the current app instance.
Application.Exit();

// Restart the app passing "/restart [processId]" as cmd line args
Process.Start(Application.ExecutablePath, "/restart" + Process.GetCurrentProcess().Id);

Then when the new app starts I first parse the cm line args and check if the restart flag is there with a processId, then wait for that process to Exit:

if (_isRestart)
{
   try
   {
      // get old process and wait UP TO 5 secs then give up!
      Process oldProcess = Process.GetProcessById(_restartProcessId);
      oldProcess.WaitForExit(5000);
   }
   catch (Exception ex)
   { 
      // the process did not exist - probably already closed!
      //TODO: --> LOG
   }
}

I am obviously not showing all the safety checks that I have in place etc.

Even if not ideal - I find this a valid alternative so that you don't have to have in place a separate app just to handle restart.

Java keytool easy way to add server cert from url/port

I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool can do the whole job:

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]

Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 

What are the differences between .gitignore and .gitkeep?

.gitignore

is a text file comprising a list of files in your directory that git will ignore or not add/update in the repository.

.gitkeep

Since Git removes or doesn't add empty directories to a repository, .gitkeep is sort of a hack (I don't think it's officially named as a part of Git) to keep empty directories in the repository.

Just do a touch /path/to/emptydirectory/.gitkeep to add the file, and Git will now be able to maintain this directory in the repository.

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

Check whether a path is valid in Python without creating a file at the path's target

With Python 3, how about:

try:
    with open(filename, 'x') as tempfile: # OSError if file exists or is invalid
        pass
except OSError:
    # handle error here

With the 'x' option we also don't have to worry about race conditions. See documentation here.

Now, this WILL create a very shortlived temporary file if it does not exist already - unless the name is invalid. If you can live with that, it simplifies things a lot.

Converting file size in bytes to human-readable string

Here is a prototype to convert a number to a readable string respecting the new international standards.

There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 1024

https://wiki.ubuntu.com/UnitsPolicy

http://en.wikipedia.org/wiki/Template:Quantities_of_bytes

Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
 return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
 d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
 +' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});

This function contains no loop, and so it's probably faster than some other functions.

Usage:

IEC prefix

console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

SI prefix

console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB 
//kB,MB,GB,TB,PB,EB,ZB,YB

i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024


If you just want one of them in a short oneliner function:

SI

function fileSizeSI(a,b,c,d,e){
 return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB

IEC

function fileSizeIEC(a,b,c,d,e){
 return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

Usage:

console.log(fileSizeIEC(7412834521));

if you have some questions about the functions just ask

How to insert an element after another element in JavaScript without using a library?

This is the simplest way we can add an element after another one using vanilla javascript

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Rails 3 execute custom sql query without a model

You could also use find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

Linking to an external URL in Javadoc?

Javadocs don't offer any special tools for external links, so you should just use standard html:

See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.

or

@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of 
the Martian invasion.

Don't use {@link ...} or {@linkplain ...} because these are for links to the javadocs of other classes and methods.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

One liner anyone?

I haven't seen anyone mention the browser-image-compression library. It's got a helper function perfect for this.

Usage: const orientation = await imageCompression.getExifOrientation(file)

Such a useful tool in many other ways too.

Advantages of std::for_each over for loop

For loop can break; I dont want to be a parrot for Herb Sutter so here is the link to his presentation: http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T Be sure to read the comments also :)

Do I need <class> elements in persistence.xml?

In Java SE environment, by specification you have to specify all classes as you have done:

A list of all named managed persistence classes must be specified in Java SE environments to insure portability

and

If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element should be used. The exclude-unlisted-classes element is not intended for use in Java SE environments.

(JSR-000220 6.2.1.6)

In Java EE environments, you do not have to do this as the provider scans for annotations for you.

Unofficially, you can try to set <exclude-unlisted-classes>false</exclude-unlisted-classes> in your persistence.xml. This parameter defaults to false in EE and truein SE. Both EclipseLink and Toplink supports this as far I can tell. But you should not rely on it working in SE, according to spec, as stated above.

You can TRY the following (may or may not work in SE-environments):

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
     <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
    </properties>
</persistence-unit>

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
var keys = [];

for (var k in obj) keys.push(k);

console.log("total " + keys.length + " keys: " + keys);
_x000D_
_x000D_
_x000D_

ERROR in Cannot find module 'node-sass'

npm install --save-dev --unsafe-perm node-sass

This will do magic, you can use it with sudo

How to send data with angularjs $http.delete() request?

You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.

Otherwise I guess you can just pass the user id as part of the query params? Something like

$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...

How to enable NSZombie in Xcode?

NSZombieEnabled is used for Debugging BAD_ACCESS,

enable the NSZombiesEnabled environment variable from Xcode’s schemes sheet.

Click on Product?Edit Scheme to open the sheet and set the Enable Zombie Objects check box

this video will help you to see what i'm trying to say.

How to compile python script to binary executable

Since other SO answers link to this question it's worth noting that there is another option now in PyOxidizer.

It's a rust utility which works in some of the same ways as pyinstaller, however has some additional features detailed here, to summarize the key ones:

  • Single binary of all packages by default with the ability to do a zero-copy load of modules into memory, vs pyinstaller extracting them to a temporary directory when using onefile mode
  • Ability to produce a static linked binary

(One other advantage of pyoxidizer is that it does not seem to suffer from the GLIBC_X.XX not found problem that can crop up with pyinstaller if you've created your binary on a system that has a glibc version newer than the target system).

Overall pyinstaller is much simpler to use than PyOxidizer, which often requires some complexity in the configuration file, and it's less Pythony since it's written in Rust and uses a configuration file format not very familiar in the Python world, but PyOxidizer does some more advanced stuff, especially if you are looking to produce single binaries (which is not pyinstaller's default).

counting number of directories in a specific directory

Using zsh:

a=(*(/N)); echo ${#a}

The N is a nullglob, / makes it match directories, # counts. It will neatly cope with spaces in directory names as well as returning 0 if there are no directories.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

How to fully delete a git repository created with init?

I tried:

rm -rf .git and also

Git keeps all of its files in the .git directory. Just remove that one and init again.

Neither worked for me. Here's what did:

  • Delete all files except for .git
  • git add . -A
  • git commit -m "deleted entire project"
  • git push

Then create / restore the project from backup:

  • Create new project files (or copy paste a backup)
  • git add . -A
  • git commit -m "recreated project"
  • git push

Spring Data JPA findOne() change to Optional how to use this?

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Now, findOne() has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository interface as:

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is the one defined in the QueryByExampleExecutor interface as:

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want that as a replacement.

In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional, which is not so bad to prevent NullPointerException.

So, the actual method to invoke is now Optional<T> findById(ID id).

How to use that?
Learning Optional usage. Here's important information about its specification:

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).


Some hints on how to use Optional with Optional<T> findById(ID id).

Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.

Here are three classical usage examples.

  1. Suppose that if the entity is found you want to get it otherwise you want to get a default value.

You could write :

Foo foo = repository.findById(id)
                    .orElse(new Foo());

or get a null default value if it makes sense (same behavior as before the API change) :

Foo foo = repository.findById(id)
                    .orElse(null);
  1. Suppose that if the entity is found you want to return it, else you want to throw an exception.

You could write :

return repository.findById(id)
        .orElseThrow(() -> new EntityNotFoundException(id));
  1. Suppose you want to apply a different processing according to if the entity is found or not (without necessarily throwing an exception).

You could write :

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
    Foo foo = fooOptional.get();
    // processing with foo ...
} else {
    // alternative processing....
}

What is the simplest way to get indented XML with line breaks from XmlDocument?

A simple way is to use:

writer.WriteRaw(space_char);

Like this sample code, this code is what I used to create a tree view like structure using XMLWriter :

private void generateXML(string filename)
        {
            using (XmlWriter writer = XmlWriter.Create(filename))
            {
                writer.WriteStartDocument();
                //new line
                writer.WriteRaw("\n");
                writer.WriteStartElement("treeitems");
                //new line
                writer.WriteRaw("\n");
                foreach (RootItem root in roots)
                {
                    //indent
                    writer.WriteRaw("\t");
                    writer.WriteStartElement("treeitem");
                    writer.WriteAttributeString("name", root.name);
                    writer.WriteAttributeString("uri", root.uri);
                    writer.WriteAttributeString("fontsize", root.fontsize);
                    writer.WriteAttributeString("icon", root.icon);
                    if (root.children.Count != 0)
                    {
                        foreach (ChildItem child in children)
                        {
                            //indent
                            writer.WriteRaw("\t");
                            writer.WriteStartElement("treeitem");
                            writer.WriteAttributeString("name", child.name);
                            writer.WriteAttributeString("uri", child.uri);
                            writer.WriteAttributeString("fontsize", child.fontsize);
                            writer.WriteAttributeString("icon", child.icon);
                            writer.WriteEndElement();
                            //new line
                            writer.WriteRaw("\n");
                        }
                    }
                    writer.WriteEndElement();
                    //new line
                    writer.WriteRaw("\n");
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();

            }

        }

This way you can add tab or line breaks in the way you are normally used to, i.e. \t or \n

Syntax error: Illegal return statement in JavaScript

return only makes sense inside a function. There is no function in your code.

Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:

return confirm(".json_encode($message).");

EDIT much much later: Changed code to use json_encode to ensure the message contents don't break just because of an apostrophe in the message.

How do you set the max number of characters for an EditText in Android?

it doesn't work from XML with maxLenght I used this code, you can limit the number of characters

String editorName = mEditorNameNd.getText().toString().substring(0, Math.min(mEditorNameNd.length(), 15));

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

What are the special dollar sign shell variables?

Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.

#!/bin/bash

echo "parameter 0 --> $0" ; exit 0

Output:

parameter 0 --> ./mytry.sh

This is on a current (year 2016) version of Bash, via Slackware 14.2

How to close TCP and UDP ports via windows command line

Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.

Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic.

So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it.

There is at least one program (CurrPorts) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.

Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.

How to play an android notification sound

You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.

Variable length (Dynamic) Arrays in Java

Yes: use ArrayList.

In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.

Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.

One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.

Reading a file line by line in Go

import (
     "bufio"
     "os"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func ReadFromStdin() string{
    result, _ := reader.ReadString('\n')
    witl := result[:len(result)-1]
    return witl
}

Here is an example with function ReadFromStdin() it's like fmt.Scan(&name) but its takes all strings with blank spaces like: "Hello My Name Is ..."

var name string = ReadFromStdin()

println(name)

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I have just solved this problem. Recently, I changed my language setting of my MacBook from English-UK to Chinese. And I suppose that setting will also change the setting in the "locale." Becuase when I switched back, I found that the setting of locale had been changed again, and I am fine to import the pandas again,.

So if you have changed the language setting recently, you may worth to have a try change it back.

Byte Array to Image object

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

How to avoid 'cannot read property of undefined' errors?

I usually use like this:

 var x = object.any ? object.any.a : 'def';

Keep CMD open after BAT file executes

Put pause at the end of your .BAT file.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Best Way to Refresh Adapter/ListView on Android

Just write in your Custom ArrayAdaper this code:

private List<Cart_items> customListviewList ;

refreshEvents(carts);

public void refreshEvents(List<Cart_items> events)
{
    this.customListviewList.clear();
    this.customListviewList.addAll(events);
    notifyDataSetChanged();
}

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

how to check if string contains '+' character

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Right way to reverse a pandas DataFrame?

None of the existing answers resets the index after reversing the dataframe.

For this, do the following:

 data[::-1].reset_index()

Here's a utility function that also removes the old index column, as per @Tim's comment:

def reset_my_index(df):
  res = df[::-1].reset_index(drop=True)
  return(res)

Simply pass your dataframe into the function

Java, How to specify absolute value and square roots

Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.

Failed to load the JNI shared Library (JDK)

On the download page of Eclipse, it should be written "JRE 32 bits" or "JRE 64 bits" and not "Windows 32 bits" or "Windows 64 bits".

Be sure to use the correct version compatible with your JDE, as answered previously.

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

How to validate date with format "mm/dd/yyyy" in JavaScript?

You could use Date.parse()

You can read in MDN documentation

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

And check if the result of Date.parse isNaN

let isValidDate = Date.parse('01/29/1980');

if (isNaN(isValidDate)) {
  // when is not valid date logic

  return false;
}

// when is valid date logic

Please take a look when is recommended to use Date.parse in MDN

Static methods in Python?

Aside from the particularities of how static method objects behave, there is a certain kind of beauty you can strike with them when it comes to organizing your module-level code.

# garden.py
def trim(a):
    pass

def strip(a):
    pass

def bunch(a, b):
    pass

def _foo(foo):
    pass

class powertools(object):
    """
    Provides much regarded gardening power tools.
    """
    @staticmethod
    def answer_to_the_ultimate_question_of_life_the_universe_and_everything():
        return 42

    @staticmethod
    def random():
        return 13

    @staticmethod
    def promise():
        return True

def _bar(baz, quux):
    pass

class _Dice(object):
    pass

class _6d(_Dice):
    pass

class _12d(_Dice):
    pass

class _Smarter:
    pass

class _MagicalPonies:
    pass

class _Samurai:
    pass

class Foo(_6d, _Samurai):
    pass

class Bar(_12d, _Smarter, _MagicalPonies):
    pass

...

# tests.py
import unittest
import garden

class GardenTests(unittest.TestCase):
    pass

class PowertoolsTests(unittest.TestCase):
    pass

class FooTests(unittest.TestCase):
    pass

class BarTests(unittest.TestCase):
    pass

...

# interactive.py
from garden import trim, bunch, Foo

f = trim(Foo())
bunch(f, Foo())

...

# my_garden.py
import garden
from garden import powertools

class _Cowboy(garden._Samurai):
    def hit():
        return powertools.promise() and powertools.random() or 0

class Foo(_Cowboy, garden.Foo):
    pass

It now becomes a bit more intuitive and self-documenting in which context certain components are meant to be used and it pans out ideally for naming distinct test cases as well as having a straightforward approach to how test modules map to actual modules under tests for purists.

I frequently find it viable to apply this approach to organizing a project's utility code. Quite often, people immediately rush and create a utils package and end up with 9 modules of which one has 120 LOC and the rest are two dozen LOC at best. I prefer to start with this and convert it to a package and create modules only for the beasts that truly deserve them:

# utils.py
class socket(object):
    @staticmethod
    def check_if_port_available(port):
        pass

    @staticmethod
    def get_free_port(port)
        pass

class image(object):
    @staticmethod
    def to_rgb(image):
        pass

    @staticmethod
    def to_cmyk(image):
        pass

How do I convert a column of text URLs into active hyperlinks in Excel?

There is a very simple way to do this. Create one hyperlink, and then use the Format Painter to copy down the formatting. It will create a hyperlink for every item.

Show a number to two decimal places

Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

Making a Bootstrap table column fit to content

This solution is not good every time. But i have only two columns and I want second column to take all the remaining space. This worked for me

 <tr>
    <td class="text-nowrap">A</td>
    <td class="w-100">B</td>
 </tr>

How to use the unsigned Integer in Java 8 and Java 9?

If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger.

(Disclaimer: I work for the company behind these libraries)

HTML Submit-button: Different value / button-text?

If you handle "adding tag" via JScript:

<form ...>
<button onclick="...">any text you want</button>
</form>

Or above if handle via page reload

Is it possible to focus on a <div> using JavaScript focus() function?

Yes - this is possible. In order to do it, you need to assign a tabindex...

<div tabindex="0">Hello World</div>

A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.

Add to Array jQuery

For JavaScript arrays, you use push().

var a = [];
a.push(12);
a.push(32);

For jQuery objects, there's add().

$('div.test').add('p.blue');

Note that while push() modifies the original array in-place, add() returns a new jQuery object, it does not modify the original one.

Why does my 'git branch' have no master?

If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status from your terminal you'd see which location you are. In some cases, you'd see origin/main.

If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.

example: git push heroku main

Tell Ruby Program to Wait some amount of time

Like this

sleep(no_of_seconds)

Or you may pass other possible arguments like:

sleep(5.seconds)

sleep(5.minutes)

sleep(5.hours)

sleep(5.days)