Programs & Examples On #Infocard

Merge up to a specific commit

Sure, being in master branch all you need to do is:

git merge <commit-id>

where commit-id is hash of the last commit from newbranch that you want to get in your master branch.

You can find out more about any git command by doing git help <command>. It that case it's git help merge. And docs are saying that the last argument for merge command is <commit>..., so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.

How to add a search box with icon to the navbar in Bootstrap 3?

This one I implemented for my website , If some one got more no's of menu item and longer search bar can use this

enter image description here

enter image description here

Here is the code

       <style>
        .navbar-inverse .navbar-nav > li > a {
            color: white !important;
        }

            .navbar-inverse .navbar-nav > li > a:hover {
                text-decoration: underline;
            }

        .navbar-collapse ul li {
            padding-top: 0px;
            padding-bottom: 0px;
        }

            .navbar-collapse ul li a {
                padding-top: 0px;
                padding-bottom: 0px;
            }

        .navbar-brand img {
            width: 200px;
            height: 40px;
        }

        .navbar-inverse {
            background-color: #3A1B37;
        }
    </style>
   <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" runat="server" href="~/">
                    <img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin"></a>
                <div class="col-md-6 col-sm-8 col-xs-11 navbar-left">
                    <div class="navbar-form " role="search">
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term" style="max-width: 100%; width: 100%;">
                            <div class="input-group-btn">
                                <button class="btn btn-default" style="background: rgb(72, 166, 72);" type="submit"><i class="glyphicon glyphicon-search"></i></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="navbar-brand  visible-md visible-lg visible-sm" style="visibility: hidden;" runat="server">
                        <img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin" />
                    </li>
                    <li><a runat="server" href="~/">Home</a></li>
                    <li><a runat="server" href="~/About">About</a></li>
                    <li><a runat="server" href="~/Contact">Contact</a></li>
                    <li><a runat="server" href="~/">Somthing</a></li>
                    <li><a runat="server" href="~/">Somthing</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li><a runat="server" href="~/Account/Register">Register</a></li>
                    <li><a runat="server" href="~/Account/Login">Log in</a></li>
                </ul> </div>

        </div>
    </div>

How can I read the client's machine/computer name from the browser?

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.

EDIT: Not possible across all browser at least.

How to set shadows in React Native for android?

Generating shadows for a circle, react native, android

Based on the answers here, and on text that I found in github (react-native-shadow), I made few tests and thought that some people may find the following helpful.

Here is how the screen looks like:

enter image description here

Code:

import React, { Component } from 'react';
import { View, TouchableHighlight, Text } from 'react-native';
import { BoxShadow } from 'react-native-shadow'

export default class ShadowsTest extends Component {

  render() {
    const shadowOpt = {
      width: 100,
      height: 100,
      color: "#000",
      border: 2,
      radius: 50,
      opacity: 0.8,
      x: 3,
      y: 3,
      //style: { marginVertical: 5 }
    }

    return (
      <View style={{ flex: 1 }}>
        <Header
          text={"Shadows Test"} />

        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
            <TouchableHighlight style={{
              position: 'relative',
              width: 100,
              height: 100,
              backgroundColor: "#fff",
              borderRadius: 50,
              borderWidth: 0.8,
              borderColor: '#000',
              // marginVertical:5,
              alignItems: 'center',
              justifyContent: 'center',
              overflow: "hidden" }}>
              <Text style={{ textAlign: 'center' }}>
                0: plain border
              </Text>
            </TouchableHighlight>
          </View>

          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
            <BoxShadow setting={ shadowOpt }>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden" }}>
                <Text style={{ textAlign: 'center' }}>
                  1: RN shadow package
                </Text>
              </TouchableHighlight>
            </BoxShadow>
          </View>
        </View>

        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                shadowOffset: { width: 15, height: 15 },
                shadowColor: "black",
                shadowOpacity: 0.9,
                shadowRadius: 10,
               }}>
                <Text style={{ textAlign: 'center' }}>
                  2: vanilla RN: shadow (may work on iOS)
                </Text>
              </TouchableHighlight>
          </View>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 15,
               }}>
                <Text style={{ textAlign: 'center' }}>
                  3: vanilla RN: elevation only (15)
                </Text>
              </TouchableHighlight>
          </View>
        </View>

        <View style={{ flexDirection: 'row', justifyContent: 'center', marginBottom: 30 }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 5,
               }}>
                <Text style={{ textAlign: 'center' }}>
                  4: vanilla RN: elevation only (5)
                </Text>
              </TouchableHighlight>
          </View>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 50,
               }}>
                <Text style={{ textAlign: 'center' }}>
                  5: vanilla RN: elevation only (50)
                </Text>
              </TouchableHighlight>
          </View>
        </View>
      </View>
    )
  }
}

How do I select a random value from an enumeration?

Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

Using Composer's Autoload

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?

One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:

<?php

$loader = require 'vendor/autoload.php';
$loader->add('AppName', __DIR__.'/../src/');

Fire event on enter key press for a textbox

my jQuery powered solution is below :)

Text Element:

<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />

Javascript behind:

<script type="text/javascript" language="javascript">
    function fnCheckValue() {
        var myVal = $("#txtTextBox").val();
        if (myVal == "") {
            alert("Blank message");
            return false;
        }
        else {
            return true;
        }
    }

    function EnterEvent(e) {
        if (e.keyCode == 13) {
            if (fnCheckValue()) {
                $("#btnSubmitButton").trigger("click");
            } else {
                return false;
            }
        }
    }

    $("#btnSubmitButton").click(function () {
        return fnCheckValue();
    });
</script>

Euclidean distance of two vectors

As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

RepeatingOperation = function(op, yieldEveryIteration) {

  //keeps count of how many times we have run heavytask() 
  //before we need to temporally check back with the browser.
  var count = 0;   

  this.step = function() {

    //Each time we run heavytask(), increment the count. When count
    //is bigger than the yieldEveryIteration limit, pass control back 
    //to browser and instruct the browser to immediately call op() so
    //we can pick up where we left off.  Repeat until we are done.
    if (++count >= yieldEveryIteration) {
      count = 0;

      //pass control back to the browser, and in 1 millisecond, 
      //have the browser call the op() function.  
      setTimeout(function() { op(); }, 1, [])

      //The following return statement halts this thread, it gives 
      //the browser a sigh of relief, your long-running javascript
      //loop has ended (even though technically we havn't yet).
      //The browser decides there is no need to alarm the user of
      //an unresponsive javascript process.
      return;
      }
    op();
  };
};

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

process10000HeavyTasks = function() {
  var len = 10000;  
  for (var i = len - 1; i >= 0; i--) {
    heavytask();   //heavytask() can be run about 20  times before
                   //an 'unresponsive script' dialog appears.
                   //If heavytask() is run more than 20 times in one
                   //javascript thread, the browser informs the user that
                   //an unresponsive script needs to be dealt with.  

                   //This is where we need to terminate this long running
                   //thread, instruct the browser not to panic on an unresponsive
                   //script, and tell it to call us right back to pick up
                   //where we left off.
  }
}

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

process10000HeavyTasks = function() {

  var global_i = 10000; //initialize your 'for loop stepper' (i) here.

  var repeater = new this.RepeatingOperation(function() {

    heavytask();

    if (--global_i >= 0){     //Your for loop conditional goes here.
      repeater.step();        //while we still have items to process,
                              //run the next iteration of the loop.
    }
    else {
       alert("we are done");  //when this line runs, the for loop is complete.
    }
  }, 10);                   //10 means process 10 heavytask(), then
                            //yield back to the browser, and have the
                            //browser call us right back.

  repeater.step();          //this command kicks off the recursive closure.

};

Adapted from this source:

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

Python display text with font & color?

You can use your own custom fonts by setting the font path using pygame.font.Font

pygame.font.Font(filename, size): return Font

example:

pygame.font.init()
font_path = "./fonts/newfont.ttf"
font_size = 32
fontObj = pygame.font.Font(font_path, font_size)

Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)

Inserting the same value multiple times when formatting a string

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.

How to decode jwt token in javascript without using a library?

all features of jwt.io doesn't support all languages. In NodeJs you can use

var decoded = jwt.decode(token);

ToList()-- does it create a new list?

 var objectList = objects.ToList();
  objectList[0].SimpleInt=5;

This will update the original object as well. The new list will contain references to the objects contained within it, just like the original list. You can change the elements either and the update will be reflected in the other.

Now if you update a list (adding or deleting an item) that will not be reflected in the other list.

How to check for a valid URL in Java?

I didn't like any of the implementations (because they use a Regex which is an expensive operation, or a library which is an overkill if you only need one method), so I ended up using the java.net.URI class with some extra checks, and limiting the protocols to: http, https, file, ftp, mailto, news, urn.

And yes, catching exceptions can be an expensive operation, but probably not as bad as Regular Expressions:

final static Set<String> protocols, protocolsWithHost;

static {
  protocolsWithHost = new HashSet<String>( 
      Arrays.asList( new String[]{ "file", "ftp", "http", "https" } ) 
  );
  protocols = new HashSet<String>( 
      Arrays.asList( new String[]{ "mailto", "news", "urn" } ) 
  );
  protocols.addAll(protocolsWithHost);
}

public static boolean isURI(String str) {
  int colon = str.indexOf(':');
  if (colon < 3)                      return false;

  String proto = str.substring(0, colon).toLowerCase();
  if (!protocols.contains(proto))     return false;

  try {
    URI uri = new URI(str);
    if (protocolsWithHost.contains(proto)) {
      if (uri.getHost() == null)      return false;

      String path = uri.getPath();
      if (path != null) {
        for (int i=path.length()-1; i >= 0; i--) {
          if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1)
            return false;
        }
      }
    }

    return true;
  } catch ( Exception ex ) {}

  return false;
}

Inner join with count() on three tables

Your solution is nearly correct. You could add DISTINCT:

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON (orders.pe_id = people.pe_id)
    INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
    people.pe_id;

"Unknown class <MyClass> in Interface Builder file" error at runtime

My case - Trying to use a Class from a swift framework in my objective c project, I got this error. Solution was to add Module (swift framework) of the class in Interface builder/ Storyboard as shown below. Nothing else

enter image description here

Get current location of user in Android without using GPS or internet

boolean gps_enabled = false;
boolean network_enabled = false;

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    //smaller the number more accurate result will
    if (gps_loc.getAccuracy() > net_loc.getAccuracy()) 
        finalLoc = net_loc;
    else
        finalLoc = gps_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = gps_loc;
    } else if (net_loc != null) {
        finalLoc = net_loc;
    }
}

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

    app.config([
        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
            $routeProvider
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                })
                .otherwise({ redirectTo: '/Home' });
        }])
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
        restangularProvider.setBaseUrl('/api');
    }]);
} 

And here's the way to use it...

ng-click="homeCtrl.addCustomer(customer)"

Try it.. It might work for you as it worked for me... ;)

Unable to preventDefault inside passive event listener

To handle sortable list in Framework7 when user release currently sorting element in new position, you can use this code:

  $$('li').on('sortable:sort',function(event){
    alert("From " + event.detail.startIndex + " to " + event.detail.newIndex);
  });

Fiddle : https://jsfiddle.net/0zf5w4y7/

What does it mean to inflate a view from an xml file?

When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:

class Name extends Activity{
    public void onCreate(){
         // the OS will inflate the your_layout.xml
         // file and use it for this activity
         setContentView(R.layout.your_layout);
    }
}

You can also inflate views explicitly by using the LayoutInflater. In that case you have to:

  1. Get an instance of the LayoutInflater
  2. Specify the XML to inflate
  3. Use the returned View
  4. Set the content view with returned view (above)

For instance:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

Preserve line breaks in angularjs

I had a similar problem to you. I'm not that keen on the other answers here because they don't really allow you to style the newline behaviour very easily. I'm not sure if you have control over the original data, but the solution I adopted was to switch "items" from being an array of strings to being an array of arrays, where each item in the second array contained a line of text. That way you can do something like:

<div ng-repeat="item in items">
  <p ng-repeat="para in item.description">
     {{para}}
  </p>
</div>

This way you can apply classes to the paragraphs and style them nicely with CSS.

How to play a sound using Swift?

Game style:

file Sfx.swift

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {
    
    static let shared = Sfx()
    
    var apCheer: AVAudioPlayer? = nil
    
    private override init() {
        guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else {
            return  print("Sfx woe")
        }
        do {
            apComment = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s))
        } catch {
            return  print("Sfx woe")
        }
    }
    
    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() } .. etc
}

Anywhere at all in code

sfx.explosion()
sfx.cheer()

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

Is there a built-in function to print all the current properties and values of an object?

I like working with python object built-in types keys or values.

For attributes regardless they are methods or variables:

o.keys()

For values of those attributes:

o.values()

How can I "disable" zoom on a mobile web page?

The solution using a meta-tag did not work for me (tested on Chrome win10 and safari IOS 14.3), and I also believe that the concerns regarding accessibility, as mentioned by Jack and others, should be honored.

My solution is to disable zooming only on elements that are damaged by the default zoom.

I did this by registering event listeners for zoom-gestures and using event.preventDefault() to suppress the browsers default zoom-behavior.

This needs to be done with several events (touch gestures, mouse wheel and keys). The following snippet is an example for the mouse wheel and pinch gestures on touchpads:

noteSheetCanvas.addEventListener("wheel", e => {
        // suppress browsers default zoom-behavior:
        e.preventDefault();

        // execution my own custom zooming-behavior:
        if (e.deltaY > 0) {
            this._zoom(1);
        } else {
            this._zoom(-1);
        }
    });

How to detect touch gestures is described here: https://stackoverflow.com/a/11183333/1134856

I used this to keep the standard zooming behavior for most parts of my application and to define custom zooming-behavior on a canvas-element.

Detecting when user scrolls to bottom of div with jQuery

There are some properties/methods you can use:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

So you can take the sum of the first two properties, and when it equals to the last property, you've reached the end:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});

http://jsfiddle.net/doktormolle/w7X9N/

Edit: I've updated 'bind' to 'on' as per:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

In-Short Differences are

1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.

2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.

3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.

An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link

http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/

How to return values in javascript

It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:

function myFunction(value1,callback)
{
     //Do stuff and 

     if(typeof callback == 'function'){
        callback(somevalue2,somevalue3);
    }
}


myFunction("1", function(value2, value3){
    if(value2 && value3)
    {
    //Do some stuff
    }
});

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

Masking password input from the console : Java

You would use the Console class

char[] password = console.readPassword("Enter password");  
Arrays.fill(password, ' ');

By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.

If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained

How to fast get Hardware-ID in C#?

The following approach was inspired by this answer to a related (more general) question.

The approach is to read the MachineGuid value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography. This value is generated during OS installation.

There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid value.

However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.

public string GetMachineGuid()
{
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
   {
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
       {
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();
       }
   }
}

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

How to set Highcharts chart maximum yAxis value

Taking help from above answer link mentioned in the above answer sets the max value with option

yAxis: { max: 100 },

On similar line min value can be set.So if you want to set min-max value then

yAxis: {
   min: 0,     
   max: 100
},

If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option

$series->yAxis->min=0;
$series->yAxis->max=100;

Right HTTP status code to wrong input

Codes starting with 4 (4xx) are meant for client errors. Maybe 400 (Bad Request) could be suitable to this case? Definition in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html says:

"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. "

Delete last char of string

string.Join is better, but if you really want a LINQ ForEach:

var strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    if(strgroupids != string.Empty){
        strgroupids += ",";
    }

    strgroupids += g;
});

Some notes:

  • string.Join and foreach are both better than this, vastly slower, approach
  • No need to remove the last , since it's never appended
  • The increment operator (+=) is handy for appending to strings
  • .ToString() is unnecessary as it is called automatically when concatenating non-strings
  • When handling large strings, StringBuilder should be considered instead of concatenating strings

How to change an application icon programmatically in Android?

It's an old question, but still active as there is no explicit Android feature. And the guys from facebook found a work around - somehow. Today, I found a way that works for me. Not perfect (see remarks at the end of this answer) but it works!

Main idea is, that I update the icon of my app's shortcut, created by the launcher on my home screen. When I want to change something on the shortcut-icon, I remove it first and recreate it with a new bitmap.

Here is the code. It has a button increment. When pressed, the shortcut is replaced with one that has a new counting number.

First you need these two permissions in your manifest:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

Then you need this two methods for installing and uninstalling shortcuts. The shortcutAdd method creates a bitmap with a number in it. This is just to demonstrate that it actually changes. You probably want to change that part with something, you want in your app.

private void shortcutAdd(String name, int number) {
    // Intent to be send, when shortcut is pressed by user ("launched")
    Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
    shortcutIntent.setAction(Constants.ACTION_PLAY);

    // Create bitmap with number in it -> very default. You probably want to give it a more stylish look
    Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    Paint paint = new Paint();
    paint.setColor(0xFF808080); // gray
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(50);
    new Canvas(bitmap).drawText(""+number, 50, 50, paint);
    ((ImageView) findViewById(R.id.icon)).setImageBitmap(bitmap);

    // Decorate the shortcut
    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);

    // Inform launcher to create shortcut
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);
}

private void shortcutDel(String name) {
    // Intent to be send, when shortcut is pressed by user ("launched")
    Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
    shortcutIntent.setAction(Constants.ACTION_PLAY);

    // Decorate the shortcut
    Intent delIntent = new Intent();
    delIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    delIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

    // Inform launcher to remove shortcut
    delIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(delIntent);
}

And finally, here are two listener to add the first shortcut and update the shortcut with an incrementing counter.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.test);
    findViewById(R.id.add).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            shortcutAdd("changeIt!", count);
        }
    });
    findViewById(R.id.increment).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            shortcutDel("changeIt!");
            count++;
            shortcutAdd("changeIt!", count);
        }
    });
}

Remarks:

  • This way works also if your App controls more shortcuts on the home screen, e.g. with different extra's in the Intent. They just need different names so that the right one is uninstalled and reinstalled.

  • The programmatical handling of shortcuts in Android is a well known, widely used but not officially supported Android feature. It seems to work on the default launcher and I never tried it anywhere else. So dont blame me, when you get this user-emails "It does not work on my XYZ, double rooted, super blasted phone"

  • The launcher writes a Toast when a shortcut was installad and one when a shortcut was uninstalled. So I get two Toasts every time I change the icon. This is not perfect, but well, as long as the rest of my app is perfect...

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

How to downgrade or install an older version of Cocoapods

Actually, you don't need to downgrade – if you need to use older version in some projects, just specify the version that you need to use after pod command.

pod _0.37.2_ setup

Choosing line type and color in Gnuplot 4.0

Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.

You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:


set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"

How to select date from datetime column?

You can use MySQL's DATE() function:

WHERE DATE(datetime) = '2009-10-20'

You could also try this:

WHERE datetime LIKE '2009-10-20%'

See this answer for info on the performance implications of using LIKE.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Postgres sql has a way of doing it

pls refer: http://www.postgresonline.com/journal/archives/41-How-to-SELECT-ALL-EXCEPT-some-columns-in-a-table.html

The Information Schema Hack Way

SELECT 'SELECT ' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'officepark' 
            AND  c.column_name NOT IN('officeparkid', 'contractor')
    ), ',') || ' FROM officepark As o' As sqlstmt

The above for my particular example table - generates an sql statement that looks like this

SELECT o.officepark,o.owner,o.squarefootage FROM officepark As o

Pointer vs. Reference

A reference is an implicit pointer. Basically you can change the value the reference points to but you can't change the reference to point to something else. So my 2 cents is that if you only want to change the value of a parameter pass it as a reference but if you need to change the parameter to point to a different object pass it using a pointer.

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

Python date string to date object

If you are lazy and don't want to fight with string literals, you can just go with the parser module.

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

Just a side note, as we are trying to match any string representation, it is 10x slower than strptime

SQL Error: ORA-01861: literal does not match format string 01861

You can also change the date format for the session. This is useful, for example, in Perl DBI, where the to_date() function is not available:

ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'

You can permanently set the default nls_date_format as well:

ALTER SYSTEM SET NLS_DATE_FORMAT='YYYY-MM-DD'

In Perl DBI you can run these commands with the do() method:

$db->do("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD');

http://www.dba-oracle.com/t_dbi_interface1.htm https://community.oracle.com/thread/682596?start=15&tstart=0

How do I switch between command and insert mode in Vim?

Pressing ESC quits from insert mode to normal mode, where you can press : to type in a command. Press i again to back to insert mode, and you are good to go.

I'm not a Vim guru, so someone else can be more experienced and give you other options.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How do you specify a byte literal in Java?

What about overriding the method with

void f(int value)
{
  f((byte)value);
}

this will allow for f(0)

how to check confirm password field in form without reloading page

$('input[type=submit]').on('click', validate);


function validate() {
  var password1 = $("#password1").val();
  var password2 = $("#password2").val();

    if(password1 == password2) {
       $("#validate-status").text("valid");        
    }
    else {
        $("#validate-status").text("invalid");  
    } 
}

Logic is to check on keyup if the value in both fields match or not.

How to install libusb in Ubuntu

you can creat symlink to your libusb after locate it in your system :

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so.0.1.0 

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so

Reactjs convert html string to jsx

You can also use Parser() from html-react-parser. I have used the same. Link shared.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

How to delete files/subfolders in a specific directory at the command prompt in Windows

You can use this shell script to clean up the folder and files within C:\Temp source:

del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q

Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat

Nginx reverse proxy causing 504 Gateway Timeout

Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.

I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:

server {
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_pass http://localhost:5000;
    }
}

Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive

How do I make a transparent border with CSS?

You could remove the border and increase the padding:

_x000D_
_x000D_
li {_x000D_
  display: inline-block;_x000D_
  padding: 6px;_x000D_
  border-width: 0px;_x000D_
}_x000D_
_x000D_
li:hover {_x000D_
  border: 1px solid #FC0;_x000D_
  padding: 5px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Hovering is great</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Change button background color using swift language

You can set the background color of a button using the getRed function.
Let's assume you have:

  1. A UIButton called button, and
  2. You want to change button's background color to some known RBG value

Then, place the following code in the function where you want to change the background color of your UIButton

var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0

// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0) 

if color.getRed(&r, green: &g, blue: &b, alpha: &a){
    button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}

Python: convert string from UTF-8 to Latin-1

data="UTF-8 data"
udata=data.decode("utf-8")
data=udata.encode("latin-1","ignore")

Should do it.

How to rotate a 3D object on axis three.js?

with r55 you have to change
rotationMatrix.multiplySelf( object.matrix );
to
rotationMatrix.multiply( object.matrix );

Search for a particular string in Oracle clob column

ok, you may use substr in correlation to instr to find the starting position of your string

select 
  dbms_lob.substr(
       product_details, 
       length('NEW.PRODUCT_NO'), --amount
       dbms_lob.instr(product_details,'NEW.PRODUCT_NO') --offset
       ) 
from my_table
where dbms_lob.instr(product_details,'NEW.PRODUCT_NO')>=1;

PyCharm shows unresolved references error for valid code

If you are using vagrant the error can be caused by wrong python interpreter. In our vagrant we are using pyenv so I had to change Python Interpreter path path from /usr/bin/python to /home/vagrant/.pyenv/versions/vagrant/bin/python enter image description here

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Try to use this exact startup tag in your app.config under configuration node

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <requiredRuntime version="v4.0.20506" />
  </startup>

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

Difference between abstraction and encapsulation?

Another example:

Suppose I created an immutable Rectangle class like this:

class Rectangle {
 public:
  Rectangle(int width, int height) : width_(width), height_(height) {}
  int width() const { return width_; }
  int height() const { return height_; }

 private:
  int width_;
  int height_;
}

Now it's obvious that I've encapsulated width and height (access is somehow restricted), but I've not abstracted anything (okay, maybe I've ignored where the rectangle is located in the coordinates space, but this is a flaw of the example).

Good abstraction usually implies good encapsulation.

An example of good abstraction is a generic database connection class. Its public interface is database-agnostic, and is very simple, yet allows me to do what I want with the connection. And you see? There's also encapsulation there, because the class must have all the low-level handles and calls inside.

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

Convert sqlalchemy row object to python dict

In SQLAlchemy v0.8 and newer, use the inspection system.

from sqlalchemy import inspect

def object_as_dict(obj):
    return {c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs}

user = session.query(User).first()

d = object_as_dict(user)

Note that .key is the attribute name, which can be different from the column name, e.g. in the following case:

class_ = Column('class', Text)

This method also works for column_property.

Bootstrap: Open Another Modal in Modal

I also had some trouble with my scrollable modals, so I did something like this:

  $('.modal').on('shown.bs.modal', function () {
    $('body').addClass('modal-open');
    // BS adds some padding-right to acomodate the scrollbar at right
    $('body').removeAttr('style');
  })

  $(".modal [data-toggle='modal']").click(function(){
    $(this).closest(".modal").modal('hide');
  });

It will serve for any modal whithin a modal that comes to appear. Note that the first its closed so the second can appear. No changes in the Bootstrap structure.

Where do I find some good examples for DDD?

Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action. While the book is focused on the presentation layer, the application is modeled using DDD.

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

How to prevent "The play() request was interrupted by a call to pause()" error?

It looks like a lot of programmers encountered this problem. a solution should be quite simple. media element return Promise from actions so

n.pause().then(function(){
    n.currentTime = 0;
    n.play();
})

should do the trick

How to remove duplicate values from an array in PHP

try this short & sweet code -

$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();

foreach($array as $v){
  isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
  }

var_dump($unique);

Output -

array(6) {
  [0]=>
  int(1)
  [1]=>
  int(4)
  [2]=>
  int(2)
  [3]=>
  int(7)
  [4]=>
  int(9)
  [5]=>
  int(5)
}

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

.NET console application as Windows service

You can use

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v ServiceName /d "c:\path\to\service\file\exe"

And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.

There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

intellij idea - Error: java: invalid source release 1.9

I have had the same problem. There is an answer:

  • 1.CTRL + ALT + SHIFT + S;
    1. Then go to "Modules";
    2. "Dependencies;
    3. Change "Module SDK".

Got it! Now u have Java 9!

Get the first item from an iterable that matches a condition

I would write this

next(x for x in xrange(10) if x > 3)

How to reset form body in bootstrap modal box?

Just set the empty values to the input fields when modal is hiding.

$('#Modal_Id').on('hidden', function () {
   $('#Form_Id').find('input[type="text"]').val('');
});

Access Form - Syntax error (missing operator) in query expression

Try making the field names legal by removing spaces. It's a long shot but it has actually helped me before.

JQuery - how to select dropdown item based on value

In your case $("#mySelect").val("fg") :)

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Try to import import { CommonModule } from '@angular/common'; in angular final as *ngFor ,*ngIf all are present in CommonModule

How to implement a SQL like 'LIKE' operator in java?

This's my take on this, it's in Kotlin but can be converted to Java with little effort:

val percentageRegex = Regex("""(?<!\\)%""")
val underscoreRegex = Regex("""(?<!\\)_""")

infix fun String.like(predicate: String): Boolean {

    //Split the text by every % not preceded by a slash.
    //We transform each slice before joining them with .* as a separator.
    return predicate.split(percentageRegex).joinToString(".*") { percentageSlice ->

        //Split the text by every _ not preceded by a slash.
        //We transform each slice before joining them with . as a separator.
        percentageSlice.split(underscoreRegex).joinToString(".") { underscoreSlice ->

            //Each slice is wrapped in "Regex quotes" to ignore all
            // the metacharacters they contain.
            //We also remove the slashes from the escape sequences
            // since they are now treated literally.
            Pattern.quote(
                underscoreSlice.replace("\\_", "_").replace("\\%", "%")
            )
        }

    }.let { "^$it$" }.toRegex().matches(this@like)
}

It might not be the most performant of all the solutions here, but it's probably the most accurate.

It ignores all the other Regex metacharacters other than % and _ and also supports escaping them with a slash.

jQuery - add additional parameters on submit (NOT ajax)

Similar answer, but I just wanted to make it available for an easy/quick test.

_x000D_
_x000D_
var input = $("<input>")_x000D_
               .attr("name", "mydata").val("go Rafa!");_x000D_
_x000D_
$('#easy_test').append(input);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<form id="easy_test">_x000D_
  _x000D_
</form>
_x000D_
_x000D_
_x000D_

How to programmatically close a JFrame

Here would be your options:

System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window

Set the layout weight of a TextView programmatically

This should works to you

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT LayoutParams.MATCH_PARENT);

param.weight=1.0f;

How to "comment-out" (add comment) in a batch/cmd?

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

Count cells that contain any text

COUNTIF function will only count cells that contain numbers in your specified range.

COUNTA(range) will count all values in the list of arguments. Text entries and numbers are counted, even when they contain an empty string of length 0.

Example: Function in A7 =COUNTA(A1:A6)

Range:

A1 a

A2 b

A3 banana

A4 42

A5

A6

A7 4 -> result

Google spreadsheet function list contains a list of all available functions for future reference https://support.google.com/drive/table/25273?hl=en.

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

How to write new line character to a file in Java

Split the string in to string array and write using above method (I assume your text contains \n to get new line)

String[] test = test.split("\n");

and the inside a loop

bufferedWriter.write(test[i]);
bufferedWriter.newline();

Convert array of strings into a string in Java

From Java 8, the simplest way I think is:

    String[] array = { "cat", "mouse" };
    String delimiter = "";
    String result = String.join(delimiter, array);

This way you can choose an arbitrary delimiter.

Is it possible to add dynamically named properties to JavaScript object?

in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:

var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex = {
    [ personId ]: person
//  ^ computed property name
};

personIndex[ personId ]; // "John Doe"

reference: Understanding ECMAScript 6 - Nickolas Zakas

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Is there a Python equivalent of the C# null-coalescing operator?

The two functions below I have found to be very useful when dealing with many variable testing cases.

def nz(value, none_value, strict=True):
    ''' This function is named after an old VBA function. It returns a default
        value if the passed in value is None. If strict is False it will
        treat an empty string as None as well.

        example:
        x = None
        nz(x,"hello")
        --> "hello"
        nz(x,"")
        --> ""
        y = ""   
        nz(y,"hello")
        --> ""
        nz(y,"hello", False)
        --> "hello" '''

    if value is None and strict:
        return_val = none_value
    elif strict and value is not None:
        return_val = value
    elif not strict and not is_not_null(value):
        return_val = none_value
    else:
        return_val = value
    return return_val 

def is_not_null(value):
    ''' test for None and empty string '''
    return value is not None and len(str(value)) > 0

port forwarding in windows

I've solved it, it can be done executing:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111

Official docs

Fake "click" to activate an onclick method

var clickEvent = new MouseEvent('click', {
  view: window,
  bubbles: true,
  cancelable: true
});
var element = document.getElementById('element-id'); 
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
  // A handler called preventDefault.
  alert("cancelled");
} else {
  // None of the handlers called preventDefault.
  alert("not cancelled");
}

element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.

Getting byte array through input type = file

This is a long post, but I was tired of all these examples that weren't working for me because they used Promise objects or an errant this that has a different meaning when you are using Reactjs. My implementation was using a DropZone with reactjs, and I got the bytes using a framework similar to what is posted at this following site, when nothing else above would work: https://www.mokuji.me/article/drop-upload-tutorial-1 . There were 2 keys, for me:

  1. You have to get the bytes from the event object, using and during a FileReader's onload function.
  2. I tried various combinations, but in the end, what worked was:

    const bytes = e.target.result.split('base64,')[1];

Where e is the event. React requires const, you could use var in plain Javascript. But that gave me the base64 encoded byte string.

So I'm just going to include the applicable lines for integrating this as if you were using React, because that's how I was building it, but try to also generalize this, and add comments where necessary, to make it applicable to a vanilla Javascript implementation - caveated that I did not use it like that in such a construct to test it.

These would be your bindings at the top, in your constructor, in a React framework (not relevant to a vanilla Javascript implementation):

this.uploadFile = this.uploadFile.bind(this);
this.processFile = this.processFile.bind(this);
this.errorHandler = this.errorHandler.bind(this);
this.progressHandler = this.progressHandler.bind(this);

And you'd have onDrop={this.uploadFile} in your DropZone element. If you were doing this without React, this is the equivalent of adding the onclick event handler you want to run when you click the "Upload File" button.

<button onclick="uploadFile(event);" value="Upload File" />

Then the function (applicable lines... I'll leave out my resetting my upload progress indicator, etc.):

uploadFile(event){
    // This is for React, only
    this.setState({
      files: event,
    });
    console.log('File count: ' + this.state.files.length);

    // You might check that the "event" has a file & assign it like this 
    // in vanilla Javascript:
    // var files = event.target.files;
    // if (!files && files.length > 0)
    //     files = (event.dataTransfer ? event.dataTransfer.files : 
    //            event.originalEvent.dataTransfer.files);

    // You cannot use "files" as a variable in React, however:
    const in_files = this.state.files;

    // iterate, if files length > 0
    if (in_files.length > 0) {
      for (let i = 0; i < in_files.length; i++) {
      // use this, instead, for vanilla JS:
      // for (var i = 0; i < files.length; i++) {
        const a = i + 1;
        console.log('in loop, pass: ' + a);
        const f = in_files[i];  // or just files[i] in vanilla JS

        const reader = new FileReader();
        reader.onerror = this.errorHandler;
        reader.onprogress = this.progressHandler;
        reader.onload = this.processFile(f);
        reader.readAsDataURL(f);
      }      
   }
}

There was this question on that syntax, for vanilla JS, on how to get that file object:

JavaScript/HTML5/jQuery Drag-And-Drop Upload - "Uncaught TypeError: Cannot read property 'files' of undefined"

Note that React's DropZone will already put the File object into this.state.files for you, as long as you add files: [], to your this.state = { .... } in your constructor. I added syntax from an answer on that post on how to get your File object. It should work, or there are other posts there that can help. But all that Q/A told me was how to get the File object, not the blob data, itself. And even if I did fileData = new Blob([files[0]]); like in sebu's answer, which didn't include var with it for some reason, it didn't tell me how to read that blob's contents, and how to do it without a Promise object. So that's where the FileReader came in, though I actually tried and found I couldn't use their readAsArrayBuffer to any avail.

You will have to have the other functions that go along with this construct - one to handle onerror, one for onprogress (both shown farther below), and then the main one, onload, that actually does the work once a method on reader is invoked in that last line. Basically you are passing your event.dataTransfer.files[0] straight into that onload function, from what I can tell.

So the onload method calls my processFile() function (applicable lines, only):

processFile(theFile) {
  return function(e) {
    const bytes = e.target.result.split('base64,')[1];
  }
}

And bytes should have the base64 bytes.

Additional functions:

errorHandler(e){
    switch (e.target.error.code) {
      case e.target.error.NOT_FOUND_ERR:
        alert('File not found.');
        break;
      case e.target.error.NOT_READABLE_ERR:
        alert('File is not readable.');
        break;
      case e.target.error.ABORT_ERR:
        break;    // no operation
      default:
        alert('An error occurred reading this file.');
        break;
    }
  }

progressHandler(e) {
    if (e.lengthComputable){
      const loaded = Math.round((e.loaded / e.total) * 100);
      let zeros = '';

      // Percent loaded in string
      if (loaded >= 0 && loaded < 10) {
        zeros = '00';
      }
      else if (loaded < 100) {
        zeros = '0';
      }

      // Display progress in 3-digits and increase bar length
      document.getElementById("progress").textContent = zeros + loaded.toString();
      document.getElementById("progressBar").style.width = loaded + '%';
    }
  }

And applicable progress indicator markup:

<table id="tblProgress">
  <tbody>
    <tr>
      <td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
    </tr>                    
  </tbody>
</table>

And CSS:

.progressBar {
  background-color: rgba(255, 255, 255, .1);
  width: 100%;
  height: 26px;
}
#progressBar {
  background-color: rgba(87, 184, 208, .5);
  content: '';
  width: 0;
  height: 26px;
}

EPILOGUE:

Inside processFile(), for some reason, I couldn't add bytes to a variable I carved out in this.state. So, instead, I set it directly to the variable, attachments, that was in my JSON object, RequestForm - the same object as my this.state was using. attachments is an array so I could push multiple files. It went like this:

  const fileArray = [];
  // Collect any existing attachments
  if (RequestForm.state.attachments.length > 0) {
    for (let i=0; i < RequestForm.state.attachments.length; i++) {
      fileArray.push(RequestForm.state.attachments[i]);
    }
  }
  // Add the new one to this.state
  fileArray.push(bytes);
  // Update the state
  RequestForm.setState({
    attachments: fileArray,
  });

Then, because this.state already contained RequestForm:

this.stores = [
  RequestForm,    
]

I could reference it as this.state.attachments from there on out. React feature that isn't applicable in vanilla JS. You could build a similar construct in plain JavaScript with a global variable, and push, accordingly, however, much easier:

var fileArray = new Array();  // place at the top, before any functions

// Within your processFile():
var newFileArray = [];
if (fileArray.length > 0) {
  for (var i=0; i < fileArray.length; i++) {
    newFileArray.push(fileArray[i]);
  }
}
// Add the new one
newFileArray.push(bytes);
// Now update the global variable
fileArray = newFileArray;

Then you always just reference fileArray, enumerate it for any file byte strings, e.g. var myBytes = fileArray[0]; for the first file.

Android update activity UI from service

I would use a bound service to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

You should use this GBDeviceInfo framework or ...

Apple defines this:

public enum UIUserInterfaceIdiom : Int {

    case unspecified

    case phone // iPhone and iPod touch style UI

    case pad // iPad style UI

    @available(iOS 9.0, *)
    case tv // Apple TV style UI

    @available(iOS 9.0, *)
    case carPlay // CarPlay style UI
}

so for the strict definition of the device can be used this code

struct ScreenSize
{
    static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
    static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
    static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

struct DeviceType
{
    static let IS_IPHONE_4_OR_LESS  = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
    static let IS_IPHONE_5          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
    static let IS_IPHONE_6_7          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
    static let IS_IPHONE_6P_7P         = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
    static let IS_IPAD              = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
    static let IS_IPAD_PRO          = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
}

how to use

if DeviceType.IS_IPHONE_6P_7P {
    print("IS_IPHONE_6P_7P")
}

to detect iOS version

struct Version{
    static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
    static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
    static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
    static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
}

how to use

if Version.iOS8 {
    print("iOS8")
}

How can I prevent the backspace key from navigating back?

Using Dojo toolkit 1.7, this works in IE 8:

require(["dojo/on", "dojo/keys", "dojo/domReady!"],
function(on, keys) {
    on(document.body,"keydown",function(evt){if(evt.keyCode == keys.BACKSPACE)evt.preventDefault()});
});

How do I draw a circle in iOS Swift?

WARNING! This is an incorrect solution. layers are added infinitely in the drawRect method (every time the view is drawn). You should NEVER add layers in the drawRect method. Use layoutSubview instead.

You can draw a circle with this (Swift 3.0+):

let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100, y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
    
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
    
// Change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
// You can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
// You can change the line width
shapeLayer.lineWidth = 3.0
    
view.layer.addSublayer(shapeLayer)

With the code you have posted you are cropping the corners of the UIView, not adding a circle to the view.


Here's a full example of using that method:

/// A special UIView displayed as a ring of color
class Ring: UIView {
    override func drawRect(rect: CGRect) {
        drawRingFittingInsideView()
    }
    
    internal func drawRingFittingInsideView() -> () {
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = 1 // your desired value
            
        let circlePath = UIBezierPath(
                arcCenter: CGPoint(x:halfSize,y:halfSize),
                radius: CGFloat( halfSize - (desiredLineWidth/2) ),
                startAngle: CGFloat(0),
                endAngle:CGFloat(M_PI * 2),
                clockwise: true)
    
         let shapeLayer = CAShapeLayer()
         shapeLayer.path = circlePath.CGPath
            
         shapeLayer.fillColor = UIColor.clearColor().CGColor
         shapeLayer.strokeColor = UIColor.redColor().CGColor
         shapeLayer.lineWidth = desiredLineWidth
    
         layer.addSublayer(shapeLayer)
     }
}

A circle outlined in red and filled with yellow on a yellow background.


Note, however there's an incredibly handy call:

let circlePath = UIBezierPath(ovalInRect: rect)

which does all the work of making the path. (Don't forget to inset it for the line thickness, which is also incredibly easy with CGRectInset.)

internal func drawRingFittingInsideView(rect: CGRect) {
    let desiredLineWidth:CGFloat = 4    // Your desired value
    let hw:CGFloat = desiredLineWidth/2
    
    let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw))
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    shapeLayer.lineWidth = desiredLineWidth
    layer.addSublayer(shapeLayer)
}

An ellipses (oval-like) outlined in red and filled with yellow on a yellow background.


In practice these days in Swift, you would certainly use @IBDesignable and @IBInspectable. Using these you can actually see and change the rendering, in Storyboard!

As you can see, it actually adds new features to the Inspector on the Storyboard, which you can change on the Storyboard:

Xcode Storyboard Attributes Inspector with custom fields.

/// A dot with a border, which you can control completely in Storyboard
@IBDesignable class Dot: UIView {

    @IBInspectable var mainColor: UIColor = UIColor.blueColor() {
        didSet { 
             print("mainColor was set here")
        }
    }

    @IBInspectable var ringColor: UIColor = UIColor.orangeColor() {
         didSet {
             print("bColor was set here") 
        }
    }

    @IBInspectable var ringThickness: CGFloat = 4 {
        didSet { 
            print("ringThickness was set here")
        }
    }
    
    @IBInspectable var isSelected: Bool = true
    
    override func drawRect(rect: CGRect) {
        let dotPath = UIBezierPath(ovalInRect:rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.CGPath
        shapeLayer.fillColor = mainColor.CGColor
        layer.addSublayer(shapeLayer)
        
        if (isSelected) { 
            drawRingFittingInsideView(rect)
        }
    }
    
    internal func drawRingFittingInsideView(rect: CGRect) {
        let hw:CGFloat = ringThickness/2
        let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw) )
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.CGPath
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = ringColor.CGColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

Finally, note that if you have a UIView (which is square, and which you set to say red in Storyboard) and you simply want to turn it in to a red circle, you can just do the following:

// Makes a UIView into a circular dot of color
class Dot: UIView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.width/2
    }
}

Concat all strings inside a List<string> using LINQ

You can use Aggregate, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.

You can use Aggregate function with a seed string.

var seed = string.Empty;
var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carAggregate = cars.Aggregate(seed,
                (partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');

you can use string.Join doesn’t care if you pass it an empty collection.

var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carJoin = string.Join(seperator, cars);

Add values to app.config and retrieve them

This works:

public static void AddValue(string key, string value)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add(key, value);
    config.Save(ConfigurationSaveMode.Minimal);
}

How to extract the first two characters of a string in shell scripting?

Is this what your after?

my $string = 'USCAGoleta9311734.5021-120.1287855805';

my $first_two_chars = substr $string, 0, 2;

ref: substr

What is the standard naming convention for html/css ids and classes?

I just recently started learning XML. The underscore version helps me separate everything XML-related (DOM, XSD, etc.) from programming languages like Java, JavaScript (camel case). And I agree with you that using identifiers which are allowed in programming languages looks better.

Edit: Might be unrelated, but here is a link for rules and recommendations on naming XML elements which I follow when naming ids (sections "XML Naming Rules" and "Best Naming Practices").

http://www.w3schools.com/xml/xml_elements.asp

How do you tell if a string contains another string in POSIX sh?

Sadly, I am not aware of a way to do this in sh. However, using bash (starting in version 3.0.0, which is probably what you have), you can use the =~ operator like this:

#!/bin/bash
CURRENT_DIR=`pwd`

if [[ "$CURRENT_DIR" =~ "String1" ]]
then
 echo "String1 present"
elif [[ "$CURRENT_DIR" =~ "String2" ]]
then
 echo "String2 present"
else
 echo "Else"
fi

As an added bonus (and/or a warning, if your strings have any funny characters in them), =~ accepts regexes as the right operand if you leave out the quotes.

Use VBA to Clear Immediate Window?

For cleaning Immediate window I use (VBA Excel 2016) next function:

Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub

But direct call of ClrImmediate() like this:

Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents    
    Debug.Print "next..."
End Sub

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames() - NOT before Debug.Print. Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).

How to execute an SSIS package from .NET?

Here is how to set variables in the package from code -

using Microsoft.SqlServer.Dts.Runtime;

private void Execute_Package()
    {           
        string pkgLocation = @"c:\test.dtsx";

        Package pkg;
        Application app;
        DTSExecResult pkgResults;
        Variables vars;

        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);

        vars = pkg.Variables;
        vars["A_Variable"].Value = "Some value";               

        pkgResults = pkg.Execute(null, vars, null, null, null);

        if (pkgResults == DTSExecResult.Success)
            Console.WriteLine("Package ran successfully");
        else
            Console.WriteLine("Package failed");
    }

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

When to use the !important property in CSS

This is a real-world example.

While working with GWT-Bootstrap V2, it will inject some CSS file, which will override my CSS styles. In order to make my properties to be not overridden, I used !important.

String replace a Backslash

This will replace backslashes with forward slashes in the string:

source = source.replace('\\','/');

pip install gives error: Unable to find vcvarsall.bat

Thanks to "msoliman" for his hint, however his answer doesn't give clear solution for those who doesn't have VS2010
For example I have VS2012 and VS2013 and there are no such KEYs in system registry.

Solution:
Edit file: "[Python_install_loc]/Lib/distutils/msvc9compiler.py"
Change on line 224:

productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
                               "productdir")

to:

productdir = "C:\Program Files (x86)\Microsoft Visual Studio [your_vs_version(11/12...)]\VC"

and that should work

View RDD contents in Python Spark?

Try this:

data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()

Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

jQuery serialize does not register checkboxes

I had a similar problem and the following allowed me to collect all form input values and checked/unchecked checkboxes.

var serialized = this.$('#myform input').map(function() {
return { name: this.name, id: this.id, value: this.checked ? "checked" : "false" };
});

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

Wrote my own test. tested the code on stackoverflow, works fine tells me that chrome/FF can do 6

var change = 0;
var simultanius = 0;
var que = 20; // number of tests

Array(que).join(0).split(0).forEach(function(a,i){
    var xhr = new XMLHttpRequest;
    xhr.open("GET", "/?"+i); // cacheBust
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 2){
            change++;
            simultanius = Math.max(simultanius, change);
        }
        if(xhr.readyState == 4){
            change--;
            que--;
            if(!que){
                console.log(simultanius);
            }
        }
    };
    xhr.send();
});

it works for most websites that can trigger readystate change event at different times. (aka: flushing)

I notice on my node.js server that i had to output at least 1025 bytes to trigger the event/flush. otherwise the events would just trigger all three state at once when the request is complete so here is my backend:

var app = require('express')();

app.get("/", function(req,res) {
    res.write(Array(1025).join("a"));
    setTimeout(function() {
        res.end("a");
    },500);
});

app.listen(80);

Update

I notice that You can now have up to 2x request if you are using both xhr and fetch api at the same time

_x000D_
_x000D_
var change = 0;_x000D_
var simultanius = 0;_x000D_
var que = 30; // number of tests_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    fetch("/?b"+i).then(r => {_x000D_
        change++;_x000D_
        simultanius = Math.max(simultanius, change);_x000D_
        return r.text()_x000D_
    }).then(r => {_x000D_
        change--;_x000D_
        que--;_x000D_
        if(!que){_x000D_
            console.log(simultanius);_x000D_
        }_x000D_
    });_x000D_
});_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    var xhr = new XMLHttpRequest;_x000D_
    xhr.open("GET", "/?a"+i); // cacheBust_x000D_
    xhr.onreadystatechange = function() {_x000D_
        if(xhr.readyState == 2){_x000D_
            change++;_x000D_
            simultanius = Math.max(simultanius, change);_x000D_
        }_x000D_
        if(xhr.readyState == 4){_x000D_
            change--;_x000D_
            que--;_x000D_
            if(!que){_x000D_
                document.body.innerHTML = simultanius;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
    xhr.send();_x000D_
});
_x000D_
_x000D_
_x000D_

read subprocess stdout line by line

The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):

import os
import subprocess

process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
  line = process.stdout.readline()
  if line != '':
    os.write(1, line)
  else:
    break

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

How can I reverse a NSArray in Objective-C?

Try this:

for (int i = 0; i < [arr count]; i++)
{
    NSString *str1 = [arr objectAtIndex:[arr count]-1];
    [arr insertObject:str1 atIndex:i];
    [arr removeObjectAtIndex:[arr count]-1];
}

Leap year calculation

There's an algorithm on wikipedia to determine leap years:

function isLeapYear (year):
    if ((year modulo 4 is 0) and (year modulo 100 is not 0))
    or (year modulo 400 is 0)
        then true
    else false

There's a lot of information about this topic on the wikipedia page about leap years, inclusive information about different calendars.

Using Case/Switch and GetType to determine the object

One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.

Convert DataSet to List

 List<GSTEntity.gst_jobwork_to_mfgmaster> ListToGetJwToMfData = new List<GSTEntity.gst_jobwork_to_mfgmaster>();
            DataSet getJwtMF = new DataSet();
            getJwtMF = objgst_jobwork_to_mfgmaster_BLL.GetDataJobWorkToMfg(AssesseeId, PremiseId,  Fyear,  MonthId, out webex);
            if(getJwtMF.Tables["gst_jobwork_to_mfgmaster"] != null)
            {

                ListToGetJwToMfData = (from master in getJwtMF.Tables["gst_jobwork_to_mfgmaster"].AsEnumerable() select new GSTEntity.gst_jobwork_to_mfgmaster { Partygstin = master.Field<string>("Partygstin"), Partystate =
                                       master.Field<string>("Partystate"), NatureOfTransaction = master.Field<string>("NatureOfTransaction"), ChallanNo = master.Field<string>("ChallanNo"), ChallanDate=master.Field<int>("ChallanDate"),  OtherJW_ChallanNo=master.Field<string>("OtherJW_ChallanNo"),   OtherJW_ChallanDate = master.Field<int>("OtherJW_ChallanDate"),
                    OtherJW_GSTIN=master.Field<string>("OtherJW_GSTIN"),
                    OtherJW_State = master.Field<string>("OtherJW_State"),
                    InvoiceNo = master.Field<string>("InvoiceNo"),
                    InvoiceDate=master.Field<int>("InvoiceDate"),
                    Description =master.Field<string>("Description"),
                    UQC= master.Field<string>("UQC"),
                    qty=master.Field<decimal>("qty"),
                    TaxValue=master.Field<decimal>("TaxValue"),
                    Id=master.Field<int>("Id")                        

                }).ToList();

Initializing C dynamic arrays

You cannot use the syntax you have suggested. If you have a C99 compiler, though, you can do this:

int *p;

p = malloc(3 * sizeof p[0]);
memcpy(p, (int []){ 0, 1, 2 }, 3 * sizeof p[0]);

If your compiler does not support C99 compound literals, you need to use a named template to copy from:

int *p;

p = malloc(3 * sizeof p[0]);
{
    static const int p_init[] = { 0, 1, 2 };
    memcpy(p, p_init, 3 * sizeof p[0]);
}

how to evenly distribute elements in a div next to each other?

You just need to display the div with id #menu as flex container like this:

#menu{
    width: 800px;
    display: flex;
    justify-content: space-between;
}

CSS - display: none; not working

In the HTML source provided, the element #tfl has an inline style "display:block". Inline style will always override stylesheets styles…

Then, you have some options (while as you said you can't modify the html code nor using javascript):

  • force display:none with !important rule (not recommended)
  • put the div offscreen with theses rules :

    #tfl {
        position: absolute;
        left: -9999px;
    }
    

Unable to install Android Studio in Ubuntu

I understand the question is regarding UBUNTU, but I had similar problem in Debian Jessie 64bit and warsongs suggestion worked for it also.
When I ran studio.sh android studio would start, but when I tried to configure the android SDK I got the error
Unable to run mksdcard SDK tool
WHen I tried
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
Got error
E: Package 'lib32bz2-1.0' has no installation candidate
So took warsongs suggestion and only tried to install lib32stdc++6.
sudo apt-get install lib32stdc++6
After this was able to add the Android SDK into Android Studio.

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

Should you commit .gitignore into the Git repos?

Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.

Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.

Compare one String with multiple values in one expression

!string.matches("a|b|c|d") 

works fine for me.

android get real path by Uri.getPath()

@Rene Juuse - above in comments... Thanks for this link !

. the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.

getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested) getRealPathFromURI_API11to18(): returns real path for API 11 to API 18 getRealPathFromURI_below11(): returns real path for API below 11

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

     // Split at colon, use second item in the array
     String id = wholeID.split(":")[1];

     String[] column = { MediaStore.Images.Media.DATA };     

     // where id is equal to             
     String sel = MediaStore.Images.Media._ID + "=?";

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                               column, sel, new String[]{ id }, null);

     int columnIndex = cursor.getColumnIndex(column[0]);

     if (cursor.moveToFirst()) {
         filePath = cursor.getString(columnIndex);
     }   
     cursor.close();
     return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      String result = null;

      CursorLoader cursorLoader = new CursorLoader(
              context, 
        contentUri, proj, null, null, null);        
      Cursor cursor = cursorLoader.loadInBackground();

      if(cursor != null){
       int column_index = 
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       result = cursor.getString(column_index);
      }
      return result;  
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
           String[] proj = { MediaStore.Images.Media.DATA };
           Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
}

font: http://hmkcode.com/android-display-selected-image-and-its-real-path/


UPDATE 2016 March

To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.

https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Newtonsoft JSON Deserialize

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);

Console.WriteLine(customer1.Name);
// James

Integer to hex string in C++

To make it lighter and faster I suggest to use direct filling of a string.

template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
    static const char* digits = "0123456789ABCDEF";
    std::string rc(hex_len,'0');
    for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
        rc[i] = digits[(w>>j) & 0x0f];
    return rc;
}

How to modify the nodejs request default timeout time?

Try this:

var options = {
    url:  'http://url',
    timeout: 120000
}

request(options, function(err, resp, body) {});

Refer to request's documentation for other options.

How can I selectively merge or pick changes from another branch in Git?

While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.

Let’s say you have the master, exp1, and exp2 branches. You want to merge one file from each of the experimental branches into master. I would do something like this:

git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b

# Save these files as a stash
git stash

# Merge stash with master
git merge stash

This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.

This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space option)

Typing Greek letters etc. in Python plots

You need to make the strings raw and use latex:

fig.gca().set_ylabel(r'$\lambda$')

As of matplotlib 2.0 the default font supports most western alphabets and can simple do

ax.set_xlabel('?')

with unicode.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();

Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

Is there a Mutex in Java?

To ensure that a Semaphore is binary you just need to make sure you pass in the number of permits as 1 when creating the semaphore. The Javadocs have a bit more explanation.

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

Difference between binary tree and binary search tree

  • Binary search tree: when inorder traversal is made on binary tree, you get sorted values of inserted items
  • Binary tree: no sorted order is found in any kind of traversal

Bootstrap dropdown menu not working (not dropping down when clicked)

Adding this script to my code fixed the dropdown menu.

<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

Iterating Over Dictionary Key Values Corresponding to List in Python

You can very easily iterate over dictionaries, too:

for team, scores in NL_East.iteritems():
    runs_scored = float(scores[0])
    runs_allowed = float(scores[1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print '%s: %.1f%%' % (team, win_percentage)

Set a div width, align div center and text align left

All of these answers should suffice. However if you don't have a defined width, auto margins will not work.

I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).

.div {
   position: absolute;
   left: 0;
   right: 0;
   margin-left: 0;
   margin-right: 0;
}

ssh : Permission denied (publickey,gssapi-with-mic)

Nobody has mention this in. above answers so i am mentioning it.

This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command

cd KeyPair
ssh -i Keypair.pem [email protected]

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.

Git Clone: Just the files, please?

No need to use git at all, just append "/zipball/master/" to URL (source).

Downloading

This solution is the closest to "Download ZIP" button on github page. One advantage is lack of .git directory. The other one - it downloads single ZIP file instead of each file one by one, and this can make huge difference. It can be done from command line by wget: wget -O "$(basename $REPO_URL)".zip "$REPO_URL"/zipball/master/. The only problem is, that some repositories might not have master branch at all. If this is the case, "master" in URL should be replaced by appropriate branch.

Unzipping

Once the ZIP is there, the final unzipped directory name may still be pretty weird and unexpected. To fix this, name can be extracted by this script, and mv-ed to basename of the URL. Final script.sh could look something like (evals for dealing with spaces):

#Script for downloading from github. If no BRANCH_NAME is given, default is "master".
#usage: script.sh URL [BRANCH_NAME]
__repo_name__='basename "$1"'
__repo_name__="$(eval $__repo_name__)"
__branch__="${2:-master}"
#downloading
if [ ! -e ./"$__repo_name__"".zip" ] ; then
wget -O "$__repo_name__"".zip" "$1""/zipball/$__branch__/"
fi
#unpacking and renaming
if [ ! -e ./"$__repo_name__" ] ; then
unzip "$__repo_name__"".zip" && 
__dir_name__="$(unzip -qql $__repo_name__.zip | sed -r '1 {s/([ ]+[^ ]+){3}\s+//;q}')" &&
rm "$__repo_name__"".zip" &&
mv "$__dir_name__" "$__repo_name__"
fi

Maintaining

This approach shoud do the work for "just the files", and it is great for quick single-use access to small repositories.

However. If the source is rather big, and the only possibility to update is to download and rebuild all, then (to the best of my knowledge) there is no possibility to update .git-less directory, so the full repo has to be downloaded again. Then the best solution is - as VonC has already explained - to stick with shallow copy git clone --depth 1 $REPO_URL. But what next? To "check for updates" see link, and to update see great wiki-like answer.

Why am I not getting a java.util.ConcurrentModificationException in this example?

This runs fine on Java 1.6

~ % javac RemoveListElementDemo.java
~ % java RemoveListElementDemo
~ % cat RemoveListElementDemo.java

import java.util.*;
public class RemoveListElementDemo {    
    private static final List<Integer> integerList;

    static {
        integerList = new ArrayList<Integer>();
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);
    }

    public static void remove(Integer remove) {
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }

    public static void main(String... args) {                
        remove(Integer.valueOf(2));

        Integer remove = Integer.valueOf(3);
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }
}

~ %

How to turn off the Eclipse code formatter for certain sections of Java code?

AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.

Else there is this ugly hack

String query = //
    "SELECT FOO, BAR, BAZ" + //
    "  FROM ABC"           + //
    " WHERE BAR > 4";

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Here is another simple implementation -

/**
 * Date range
 *
 * @param $first
 * @param $last
 * @param string $step
 * @param string $format
 * @return array
 */
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
    $dates = [];
    $current = strtotime( $first );
    $last = strtotime( $last );

    while( $current <= $last ) {

        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current );
    }

    return $dates;
}

Example:

print_r( dateRange( '2010-07-26', '2010-08-05') );

Array (
    [0] => 2010-07-26
    [1] => 2010-07-27
    [2] => 2010-07-28
    [3] => 2010-07-29
    [4] => 2010-07-30
    [5] => 2010-07-31
    [6] => 2010-08-01
    [7] => 2010-08-02
    [8] => 2010-08-03
    [9] => 2010-08-04
    [10] => 2010-08-05
)

no sqljdbc_auth in java.library.path

Here are the steps if you want to do this from Eclipse :

1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder

1) Go to Run> Run Configurations

2) Choose the 'Arguments' tab for your class

3) Add the below code in VM arguments:

-Djava.library.path="C:\\sqlauth"

4) Hit 'Apply' and click 'Run'

Feel free to try other methods .

How to validate Google reCAPTCHA v3 on server side?

it is similar with mattgen88, but I just fixed CURLOPT_HEADER, and redefine array for it work in domain.com host server. this one doesn't work on my xampp localhost. Those small error but took long to figure out. this code was tested on domain.com hosting.

   $privatekey = 'your google captcha private key';

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

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

    if ($resp->success) {
        // Success
        echo 'captcha';
    } else {
        // failure
        echo 'no captcha';
    }

How do I send a POST request with PHP?

I was looking for a similar problem and found a better approach of doing this. So here it goes.

You can simply put the following line on the redirection page (say page1.php).

header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php

I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.

Here is the reference link.

ReactJS: Maximum update depth exceeded error

Forget about the react first:
This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).

function a() {

};

Q.1) How to call the function that we have defined?
Ans: a();

Q.2) How to pass reference of function so that we can call it latter?
Ans: let fun = a;

Now coming to your question, you have used paranthesis with function name, mean that function will be called when following statement will be render.

_x000D_
_x000D_
<td><span onClick={this.toggle()}>Details</span></td>
_x000D_
_x000D_
_x000D_

Then How to correct it?
Simple!! Just remove parenthesis. By this way you have given the reference of that function to onClick event. It will call back your function only when your component is clicked.

_x000D_
_x000D_
 <td><span onClick={this.toggle}>Details</span></td>
_x000D_
_x000D_
_x000D_

One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue. Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.

_x000D_
_x000D_
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
_x000D_
_x000D_
_x000D_

https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578

How can I force a long string without any blank to be wrapped?

for block elements:

_x000D_
_x000D_
<textarea style="width:100px; word-wrap:break-word;">_x000D_
  ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

for inline elements:

_x000D_
_x000D_
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
   ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
_x000D_
_x000D_

How can I determine if a variable is 'undefined' or 'null'?

var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}

PIG how to count a number of rows in alias

What you want is to count all the lines in a relation (dataset in Pig Latin)

This is very easy following the next steps:

logs = LOAD 'log'; --relation called logs, using PigStorage with tab as field delimiter
logs_grouped = GROUP logs ALL;--gives a relation with one row with logs as a bag
number = FOREACH LOGS_GROUP GENERATE COUNT_STAR(logs);--show me the number

I have to say it is important Kevin's point as using COUNT instead of COUNT_STAR we would have only the number of lines which first field is not null.

Also I like Jerome's one line syntax it is more concise but in order to be didactic I prefer to divide it in two and add some comment.

In general I prefer:

numerito = FOREACH (GROUP CARGADOS3 ALL) GENERATE COUNT_STAR(CARGADOS3);

over

name = GROUP CARGADOS3 ALL
number = FOREACH name GENERATE COUNT_STAR(CARGADOS3);

Give column name when read csv file pandas

I'd do it like this:

colnames=['TIME', 'X', 'Y', 'Z'] 
user1 = pd.read_csv('dataset/1.csv', names=colnames, header=None)

HTML button to NOT submit form

It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)

Some reference material

How to work with complex numbers in C?

The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.

Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...

Real and imaginary part, of a negative square root example:

#include <stdio.h>   
#include <complex.h>

int main() 
{
    int negNum;

    printf("Calculate negative square roots:\n"
           "Enter negative number:");

    scanf("%d", &negNum);

    double complex negSqrt = csqrt(negNum);

    double pReal = creal(negSqrt);
    double pImag = cimag(negSqrt);

    printf("\nReal part %f, imaginary part %f"
           ", for negative square root.(%d)",
           pReal, pImag, negNum);

    return 0;
}

what do these symbolic strings mean: %02d %01d?

http://en.wikipedia.org/wiki/Printf#printf_format_placeholders

The article is about the class of printf functions, in several languages, from the 50s to this day.

CSS Outside Border

I shared two solutions depending on your needs:

<style type="text/css" ref="stylesheet">
  .border-inside-box {
    border: 1px solid black;
  }
  .border-inside-box-v1 {
    outline: 1px solid black; /* 'border-radius' not available */
  }
  .border-outside-box-v2 {
    box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
  }
</style>

example: https://codepen.io/danieldd/pen/gObEYKj

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

I have Visual Studio Code version 1.27.2 and can do this:

Compare two files

  1. Drag and drop the two files into Visual Studio Code enter image description here
  2. Select both files and select Select for Compare from the context menu enter image description here
  3. Then you see the diff enter image description here
  4. With Alt+F5 you can jump to the next diff enter image description here

Compare two in-memory documents or tabs

Sometimes, you don't have two files but want to copy text from somewhere and do a quick diff without having to save the contents to files first. Then you can do this:

  1. Open two tabs by hitting Ctrl+N twice: enter image description here
  2. Paste your first text sample from the clipboard to the first tab and the second text sample from the clipboard to the second tab
  3. Select the first document Untitled-1 with Select for Compare: enter image description here
  4. Select the second document Untitled-2 with Compare with Selected: enter image description here
  5. Then you see the diff: enter image description here

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

How to calculate the SVG Path for an arc (of a circle)

A slight modification to @opsb's answer. We cant draw a full circle with this method. ie If we give (0, 360) it will not draw anything at all. So a slight modification made to fix this. It could be useful to display scores that sometimes reach 100%.

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var endAngleOriginal = endAngle;
    if(endAngleOriginal - startAngle === 360){
        endAngle = 359;
    }

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";

    if(endAngleOriginal - startAngle === 360){
        var d = [
              "M", start.x, start.y, 
              "A", radius, radius, 0, arcSweep, 0, end.x, end.y, "z"
        ].join(" ");
    }
    else{
      var d = [
          "M", start.x, start.y, 
          "A", radius, radius, 0, arcSweep, 0, end.x, end.y
      ].join(" ");
    }

    return d;       
}

document.getElementById("arc1").setAttribute("d", describeArc(120, 120, 100, 0, 359));

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Inserting a string into a list without getting split into characters

best put brackets around foo, and use +=

list+=['foo']

Using std::max_element on a vector<double>

min_element and max_element return iterators, not values. So you need *min_element... and *max_element....

node.js require all files in a folder?

I know this question is 5+ years old, and the given answers are good, but I wanted something a bit more powerful for express, so i created the express-map2 package for npm. I was going to name it simply express-map, however the people at yahoo already have a package with that name, so i had to rename my package.

1. basic usage:

app.js (or whatever you call it)

var app = require('express'); // 1. include express

app.set('controllers',__dirname+'/controllers/');// 2. set path to your controllers.

require('express-map2')(app); // 3. patch map() into express

app.map({
    'GET /':'test',
    'GET /foo':'middleware.foo,test',
    'GET /bar':'middleware.bar,test'// seperate your handlers with a comma. 
});

controller usage:

//single function
module.exports = function(req,res){

};

//export an object with multiple functions.
module.exports = {

    foo: function(req,res){

    },

    bar: function(req,res){

    }

};

2. advanced usage, with prefixes:

app.map('/api/v1/books',{
    'GET /': 'books.list', // GET /api/v1/books
    'GET /:id': 'books.loadOne', // GET /api/v1/books/5
    'DELETE /:id': 'books.delete', // DELETE /api/v1/books/5
    'PUT /:id': 'books.update', // PUT /api/v1/books/5
    'POST /': 'books.create' // POST /api/v1/books
});

As you can see, this saves a ton of time and makes the routing of your application dead simple to write, maintain, and understand. it supports all of the http verbs that express supports, as well as the special .all() method.

How to Select a substring in Oracle SQL up to a specific character?

Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:

SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output
  FROM DUAL

Result:

output
------
ABC

Use:

SELECT NVL(SUBSTR(t.column, 0, INSTR(t.column, '_')-1), t.column) AS output
  FROM YOUR_TABLE t

Reference:

Addendum

If using Oracle10g+, you can use regex via REGEXP_SUBSTR.

How do I use variables in Oracle SQL Developer?

There are two types of variable in SQL-plus: substitution and bind.

This is substitution (substitution variables can replace SQL*Plus command options or other hard-coded text):

define a = 1;
select &a from dual;
undefine a;

This is bind (bind variables store data values for SQL and PL/SQL statements executed in the RDBMS; they can hold single values or complete result sets):

var x number;
exec :x := 10;
select :x from dual;
exec select count(*) into :x from dual;
exec print x;

SQL Developer supports substitution variables, but when you execute a query with bind :var syntax you are prompted for the binding (in a dialog box).

Reference:

UPDATE substitution variables are a bit tricky to use, look:

define phone = '+38097666666';
select &phone from dual; -- plus is stripped as it is a number
select '&phone' from dual; -- plus is preserved as it is a string

Repeat table headers in print mode

This is what the THEAD element is for. Official docs here.

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Set drawable size programmatically

Probably a little late. But here is the solution that finally worked for me in every situation.

The idea is to create a custom drawable with fixed intrinic size and pass the drawing job on to the original drawable.

Drawable icon = new ColorDrawable(){
        Drawable iconOrig = resolveInfo.loadIcon(packageManager);

        @Override
        public void setBounds(int left, int top, int right, int bottom){
            super.setBounds(left, top, right, bottom);//This is needed so that getBounds on this class would work correctly.
            iconOrig.setBounds(left, top, right, bottom);
        }

        @Override
        public void draw(Canvas canvas){
            iconOrig.draw(canvas);
        }

        @Override
        public int getIntrinsicWidth(){
            return  mPlatform.dp2px(30);
        }

        @Override
        public int getIntrinsicHeight(){
            return  mPlatform.dp2px(30);
        }
    };

PowerShell Connect to FTP server and get files

Invoke-WebRequest can download HTTP, HTTPS, and FTP links.

$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password

# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing

Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

We have this problem with one database we don't control and it requried another solution (The ones listed here didn't work). For mine I needed:

-Djdk.tls.client.protocols="TLSv1,TLSv1.1"

I think in my case it had to do with forcing a certain order.

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

Find something in column A then show the value of B for that row in Excel 2010

Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...

e.g.

in Column A we have field called company....

Column A                             Column B            Column C

Company_Name                         Value        
Monster                              25000                              
Naukri                               30000  
WNS                                  80000  
American Express                     40000  
Bank of America                      50000  
Alcatel Lucent                       35000  
Google                               75000  
Microsoft                            60000  
Monster                              35000  
Bank of America                      15000 

Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem

Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)..........Result will be Monster_1 for first line item and for row no 10 & 11.....Monster_2, Bank of America_2 respectively....Here you go now you have the unique value so now you can pick any data easily now..

Cheers!!! Anil Dhawan

Why when I transfer a file through SFTP, it takes longer than FTP?

I'm the author of HPN-SSH and I was asked by a commenter here to weigh in. I'd like to start with a couple of background items. First off, it's important to keep in mind that SSHv2 is a multiplexed protocol - multiple channels over a single TCP connection. As such, the SSH channels are essentially unaware of the underlying flow control algorithm used by TCP. This means that SSHv2 has to implement its own flow control algorithm. The most common implementation basically reimplements sliding windows. The means that you have the SSH sliding window riding on top of the TCP sliding window. The end results is that the effective size of the receive buffer is the minimum of the receive buffers of the two sliding windows. Stock OpenSSH has a maximum receive buffer size of 2MB but this really ends up being closer to ~1.2MB. Most modern OSes have a buffer that can grow (using auto-tuning receive buffers) up to an effective size of 4MB. Why does this matter? If the receive buffer size is less than the bandwidth delay product (BDP) then you will never be able to fully fill the pipe regardless of how fast your system is.

This is complicated by the fact that SFTP adds another layer of flow control onto of the TCP and SSH flow controls. SFTP uses a concept of outstanding messages. Each message may be a command, a result of a command, or bulk data flow. The outstanding messages may be up to a specific datagram size. So you end up with what you might as well think of as yet another receive buffer. The size of this receive buffer is datagram size * maximum outstanding messages (both of which may be set on the command line). The default is 32k * 64 (2MB). So when using SFTP you have to make sure that the TCP receive buffer, the SSH receive buffer, and the SFTP receive buffer are all of sufficient size (without being too large or you can have over buffering problems in interactive sessions).

HPN-SSH directly addresses the SSH buffer problem by having a maximum buffer size of around 16MB. More importantly, the buffer dynamically grows to the proper size by polling the proc entry for the TCP connection's buffer size (basically poking a hole between layers 3 and 4). This avoids overbuffering in almost all situations. In SFTP we raise the maximum number of outstanding requests to 256. At least we should be doing that - it looks like that change didn't propagate as expected to the 6.3 patch set (though it is in 6.2. I'll fix that soon). There isn't a 6.4 version because 6.3 patches cleanly against 6.4 (which is a 1 line security fix from 6.3). You can get the patch set from sourceforge.

I know this sounds odd but right sizing the buffers was the single most important change in terms of performance. In spite of what many people think the encryption is not the real source of poor performance in most cases. You can prove this to yourself by transferring data to sources that are increasingly far away (in terms of RTT). You'll notice that the longer the RTT the lower the throughput. That clearly indicates that this is an RTT dependent performance problem.

Anyway, with this change I started seeing improvements of up to 2 orders of magnitude. If you understand TCP you'll understand why this made such a difference. It's not about the size of the datagram or the number of packets or anything like that. It's entire because in order to make efficient use of the network path you must have a receive buffer equal to the amount of data that can be in transit between the two hosts. This also means that you may not see any improvement whatsoever if the path isn't sufficiently fast and long enough. If the BDP is less than 1.2MB HPN-SSH may be of no value to you.

The parallelized AES-CTR cipher is a performance boost on systems with multiple cores if you need to have full encryption end to end. Usually I suggest people (or have control over both the server and client) to use the NONE cipher switch (encrypted authentication, bulk data passed in clear) as most data isn't all that sensitive. However, this only works in non-interactive sessions like SCP. It doesn't work in SFTP.

There are some other performance improvements as well but nothing as important as the right sizing of the buffers and the encryption work. When I get some free time I'll probably pipeline the HMAC process (currently the biggest drag on performance) and do some more minor optimization work.

So if HPN-SSH is so awesome why hasn't OpenSSH adopted it? That's a long story and people who know the OpenBSD team probably already know the answer. I understand many of their reasons - it's a big patch which would require additional work on their end (and they are a small team), they don't care as much about performance as security (though there is no security implications to HPN-SSH), etc etc etc. However, even though OpenSSH doesn't use HPN-SSH Facebook does. So do Google, Yahoo, Apple, most ever large research data center, NASA, NOAA, the government, the military, and most financial institutions. It's pretty well vetted at this point.

If anyone has any questions feel free to ask but I may not be keeping up to date on this forum. You can always send me mail via the HPN-SSH email address (google it).

Javascript Regexp dynamic generation from variables?

Use the below:

var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');

str.match(regEx);

How to set up Spark on Windows?

Here are seven steps to install spark on windows 10 and run it from python:

Step 1: download the spark 2.2.0 tar (tape Archive) gz file to any folder F from this link - https://spark.apache.org/downloads.html. Unzip it and copy the unzipped folder to the desired folder A. Rename the spark-2.2.0-bin-hadoop2.7 folder to spark.

Let path to the spark folder be C:\Users\Desktop\A\spark

Step 2: download the hardoop 2.7.3 tar gz file to the same folder F from this link - https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-2.7.3/hadoop-2.7.3.tar.gz. Unzip it and copy the unzipped folder to the same folder A. Rename the folder name from Hadoop-2.7.3.tar to hadoop. Let path to the hadoop folder be C:\Users\Desktop\A\hadoop

Step 3: Create a new notepad text file. Save this empty notepad file as winutils.exe (with Save as type: All files). Copy this O KB winutils.exe file to your bin folder in spark - C:\Users\Desktop\A\spark\bin

Step 4: Now, we have to add these folders to the System environment.

4a: Create a system variable (not user variable as user variable will inherit all the properties of the system variable) Variable name: SPARK_HOME Variable value: C:\Users\Desktop\A\spark

Find Path system variable and click edit. You will see multiple paths. Do not delete any of the paths. Add this variable value - ;C:\Users\Desktop\A\spark\bin

4b: Create a system variable

Variable name: HADOOP_HOME Variable value: C:\Users\Desktop\A\hadoop

Find Path system variable and click edit. Add this variable value - ;C:\Users\Desktop\A\hadoop\bin

4c: Create a system variable Variable name: JAVA_HOME Search Java in windows. Right click and click open file location. You will have to again right click on any one of the java files and click on open file location. You will be using the path of this folder. OR you can search for C:\Program Files\Java. My Java version installed on the system is jre1.8.0_131. Variable value: C:\Program Files\Java\jre1.8.0_131\bin

Find Path system variable and click edit. Add this variable value - ;C:\Program Files\Java\jre1.8.0_131\bin

Step 5: Open command prompt and go to your spark bin folder (type cd C:\Users\Desktop\A\spark\bin). Type spark-shell.

C:\Users\Desktop\A\spark\bin>spark-shell

It may take time and give some warnings. Finally, it will show welcome to spark version 2.2.0

Step 6: Type exit() or restart the command prompt and go the spark bin folder again. Type pyspark:

C:\Users\Desktop\A\spark\bin>pyspark

It will show some warnings and errors but ignore. It works.

Step 7: Your download is complete. If you want to directly run spark from python shell then: go to Scripts in your python folder and type

pip install findspark

in command prompt.

In python shell

import findspark
findspark.init()

import the necessary modules

from pyspark import SparkContext
from pyspark import SparkConf

If you would like to skip the steps for importing findspark and initializing it, then please follow the procedure given in importing pyspark in python shell

How do I concatenate two text files in PowerShell?

Since most of the other replies often get the formatting wrong (due to the piping), the safest thing to do is as follows:

add-content $YourMasterFile -value (get-content $SomeAdditionalFile)

I know you wanted to avoid reading the content of $SomeAdditionalFile into a variable, but in order to save for example your newline formatting i do not think there is proper way to do it without.

A workaround would be to loop through your $SomeAdditionalFile line by line and piping that into your $YourMasterFile. However this is overly resource intensive.

Navigation drawer: How do I set the selected item at startup?

This is my solution, very simple.

Here is my menu.xml file:

<group
    android:id="@+id/grp1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_all_deals"
        android:checked="true"
        android:icon="@drawable/ic_all_deals"
        android:title="@string/all_deals" />
    <item
        android:id="@+id/nav_news_and_events"
        android:icon="@drawable/ic_news"
        android:title="@string/news_and_events" />
    <item
        android:id="@+id/nav_histories"
        android:icon="@drawable/ic_histories"
        android:title="@string/histories" />
</group>

Above menu will highlight the first menu item. Below line will do something(eg: show the first fragment, etc). NOTE: write after 'configure your drawer code'

onNavigationItemSelected(mNavigationView.getMenu().getItem(0));

How to run (not only install) an android application using .apk file?

You can't install and run in one go - but you can certainly use adb to start your already installed application. Use adb shell am start to fire an intent - you will need to use the correct intent for your application though. A couple of examples:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.Settings 

will launch Settings, and

adb shell am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity 

will launch the Browser. If you want to point the Browser at a particular page, do this

adb shell am start -a android.intent.action.VIEW -n com.android.browser/.BrowserActivity http://www.google.co.uk

If you don't know the name of the activities in the APK, then do this

aapt d xmltree <path to apk> AndroidManifest.xml

the output content will includes a section like this:

   E: activity (line=32)
    A: android:theme(0x01010000)=@0x7f080000
    A: android:label(0x01010001)=@0x7f070000
    A: android:name(0x01010003)="com.anonymous.MainWindow"
    A: android:launchMode(0x0101001d)=(type 0x10)0x3
    A: android:screenOrientation(0x0101001e)=(type 0x10)0x1
    A: android:configChanges(0x0101001f)=(type 0x11)0x80
    E: intent-filter (line=33)
      E: action (line=34)
        A: android:name(0x01010003)="android.intent.action.MAIN"
        XE: (line=34)

That tells you the name of the main activity (MainWindow), and you can now run

adb shell am start -a android.intent.action.MAIN -n com.anonymous/.MainWindow

Calling another different view from the controller using ASP.NET MVC 4

You have to specify the name of the custom view and its related model in Controller Action method.

public ActionResult About()
{            
   return View("NameOfViewYouWantToReturn",Model); 
}

malloc an array of struct pointers

I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.

The code uses the ms visual studio leak detector so you can experiment with the potential leaks.

#include "stdafx.h"

#include <string.h>
#include "msc-lzw.h"

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h> 



// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
    return (key + try_num) % max;  // the hash fun returns a number bounded by the number of slots.
}


// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
    int key; // use this field as the key
    char *pValue;  // use this field to store a variable length string
};


struct hash_table {
    int max;
    int number_of_elements;
    struct key_value_pair **elements;  // This is an array of pointers to mystruct objects
};


int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {

    int try_num, hash;
    int max_number_of_retries = hash_table->max;


    if (hash_table->number_of_elements >= hash_table->max) {
        return 0; // FULL
    }

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(data->key, try_num, hash_table->max);

        if (NULL == hash_table->elements[hash]) { // an unallocated slot
            hash_table->elements[hash] = data;
            hash_table->number_of_elements++;
            return RC_OK;
        }
    }
    return RC_ERROR;
}


// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {

    unsigned int try_num, hash;
    unsigned int max_number_of_retries = hash_table->max;

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(key, try_num, hash_table->max);

        if (hash_table->elements[hash] == 0) {
            return NULL; // Nothing found
        }

        if (hash_table->elements[hash]->key == key) {
            return hash_table->elements[hash];
        }
    }
    return NULL;
}


// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter.  It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {

    int num_keys = 0;

    *ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );

    for (int i = 0; i < pHashTable->max; i++) {
        if (NULL != pHashTable->elements[i]) {
            (*ppKeys)[num_keys] = pHashTable->elements[i]->key;
            num_keys++;
        }
    }
    return num_keys;
}

// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {


    // Allocate the hash table slots
    pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair));  // allocate max number of key_value_pair entries
    for (int i = 0; i < pHashTable->max; i++) {
        pHashTable->elements[i] = NULL;
    }



    // alloc all the slots
    //struct key_value_pair *pa_slot;
    //for (int i = 0; i < pHashTable->max; i++) {
    //  // all that he could see was babylon
    //  pa_slot = (struct key_value_pair *)  malloc(sizeof(struct key_value_pair));
    //  if (NULL == pa_slot) {
    //      printf("alloc of slot failed\n");
    //      while (1);
    //  }
    //  pHashTable->elements[i] = pa_slot;
    //  pHashTable->elements[i]->key = 0;
    //}

    return RC_OK;
}


// This will make a dictionary entry where
//   o  key is an int
//   o  value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {

    // determine the len of the buffer assuming it is a string
    int len = strlen(buffer);

    // alloc the buffer to hold the string
    pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
    if (NULL == pMyStruct->pValue) {
        printf("Failed to allocate the buffer for the dictionary string value.");
        return RC_ERROR;
    }
    strcpy(pMyStruct->pValue, buffer);
    pMyStruct->key = a_key;

    return RC_OK;
}


// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {

    int rc;
    struct key_value_pair *pKeyValuePair;

    if (NULL == pHashTable) {
        printf("Hash table is null.\n");
        return RC_ERROR;
    }

    // Allocate the dictionary key value pair struct
    pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
    if (NULL == pKeyValuePair) {
        printf("Failed to allocate key value pair struct.\n");
        return RC_ERROR;
    }


    rc = make_dict_entry(key, pBuff, pKeyValuePair);  // a_hash_table[1221] = "abba"
    if (RC_ERROR == rc) {
        printf("Failed to add buff to key value pair struct.\n");
        return RC_ERROR;
    }


    rc = hash_insert(pKeyValuePair, pHashTable);
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }

    return RC_OK;
}


void dump_hash_table(struct hash_table *pHashTable) {

    // Iterate the dictionary by keys
    char * pValue;
    struct key_value_pair *pMyStruct;
    int *pKeyList;
    int num_keys;

    printf("i\tKey\tValue\n");
    printf("-----------------------------\n");
    num_keys = keys(pHashTable, &pKeyList);
    for (int i = 0; i < num_keys; i++) {
        pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
        pValue = pMyStruct->pValue;
        printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
    }

    // Free the key list
    free(pKeyList);

}

int main(int argc, char *argv[]) {

    int rc;
    int i;


    struct hash_table a_hash_table;
    a_hash_table.max = 20;   // The dictionary can hold at most 20 entries.
    a_hash_table.number_of_elements = 0;  // The intial dictionary has 0 entries.
    allocate_the_dictionary(&a_hash_table);

    rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }



    // Iterate the dictionary by keys
    dump_hash_table(&a_hash_table);

    // Free the individual slots
    for (i = 0; i < a_hash_table.max; i++) {
        // all that he could see was babylon
        if (NULL != a_hash_table.elements[i]) {
            free(a_hash_table.elements[i]->pValue);  // free the buffer in the struct
            free(a_hash_table.elements[i]);  // free the key_value_pair entry
            a_hash_table.elements[i] = NULL;
        }
    }


    // Free the overall dictionary
    free(a_hash_table.elements);


    _CrtDumpMemoryLeaks();
    return 0;
}

How to check what version of jQuery is loaded?

if (typeof jQuery != 'undefined') {  
    // jQuery is loaded => print the version
    alert(jQuery.fn.jquery);
}

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.