Programs & Examples On #Web analytics tools

Saving a select count(*) value to an integer (SQL Server)

[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.

How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.

Sorry everyone...thanks for your help.

count number of characters in nvarchar column

Doesn't SELECT LEN(column_name) work?

Center image in div horizontally

A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

.top_image img { margin:0 auto; }

More information and examples from W3C.

Which icon sizes should my Windows application's icon include?

Not 96x96, use 64x64 instead. I usually use:

  • 16 - status/titlebar button
  • 32 - desktop icon
  • 48 - folder view
  • 64/128 - Additional sizes

256 works as well on XP, however, old resource compilers sometimes complained about "out of memory" errors.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

In my case this very same error was caused by the way I was importing my custom component from the caller class i.e. I was doing

import {MyComponent} from './components/MyComponent'

instead of

import MyComponent from './components/MyComponent'

using the latter solved the issue.

Determining the last row in a single column

This may be another way to go around lastrow. You may need to play around with the code to suit your needs

    function fill() {
      var spreadsheet = SpreadsheetApp.getActive();
      spreadsheet.getRange('a1').activate();
      var lsr = spreadsheet.getLastRow();
      lsr=lsr+1;
      lsr="A1:A"+lsr;

      spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
};

CSS: stretching background image to 100% width and height of screen?

I would recommend background-size: cover; if you don't want your background to lose its proportions: JS Fiddle

html { 
  background: url(image/path) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Source: http://css-tricks.com/perfect-full-page-background-image/

In c++ what does a tilde "~" before a function name signify?

It's the destructor. This method is called when the instance of your class is destroyed:

Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;

jQuery "blinking highlight" effect on div?

If you are not already using the Jquery UI library and you want to mimic the effect what you can do is very simple

$('#blinkElement').fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100);

you can also play around with the numbers to get a faster or slower one to fit your design better.

This can also be a global jquery function so you can use the same effect across the site. Also note that if you put this code in a for loop you can have 1 milion pulses so therefore you are not restricted to the default 6 or how much the default is.

EDIT: Adding this as a global jQuery function

$.fn.Blink = function (interval = 100, iterate = 1) {
    for (i = 1; i <= iterate; i++)
        $(this).fadeOut(interval).fadeIn(interval);
}

Blink any element easily from your site using the following

$('#myElement').Blink(); // Will Blink once

$('#myElement').Blink(500); // Will Blink once, but slowly

$('#myElement').Blink(100, 50); // Will Blink 50 times once

How to access /storage/emulated/0/

If you are using a simulator in Android Studio on Mac you can go to View -> Tool Windows -> Device File Explorer. Here you can use a finder-like structure.

Why emulator is very slow in Android Studio?

The Best Solution is to use Android Emulator with Intel Virtualization Technology.

Now if your system have a Processor that have a feature called as Intel Virtualization Technology, then Intel X86 images will be huge benefit for you. because it supports Intel® Hardware Accelerated Execution Manager (Intel® HAXM).

To check that your processor support HAXM or not : Click Here

You need to manually install the Intel HAXM in your system. Follow these steps for that.

  • First of all go to - adt -> extras -> intel -> Hardware_Accelerated_Execution_Manager
  • Make sure that Intel Virtualization is enabled from BIOS Settings.
  • Now install Intel HAXM in your system and select amount of memory(i prefer to set it as default value).
  • After installation create new Android Virtual Device (AVD) which should have a Target of API Level xx
  • Now set the CPU/ABI as Intel Atom(x86).
  • If you are on Windows then do not set RAM value more than 768 MB while setting up an emulator.
  • Run the emulator. It will be blazing fast then ordinary one.

Hope it will be helpful for you. :) Thanks.

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

scrollTop jquery, scrolling to div with id?

try this

    $('#div_id').animate({scrollTop:0}, '500', 'swing');

IIS w3svc error

Go to Task Manager --> Processes and manually stop the W3SVC process. After doing this the process should start normally when restarting IIS

how to display a javascript var in html body

You can do the same on document ready event like below

<script>
$(document).ready(function(){
 var number = 112;
    $("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>

or you can simply do it using document.write(number);.

Is it possible to clone html element objects in JavaScript / JQuery?

You need to select "#foo2" as your selector. Then, get it with html().

Here is the html:

<div id="foo1">

</div>
<div id="foo2">
    <div>Foo Here</div>
</div>?

Here is the javascript:

$("#foo2").click(function() {
    //alert("clicked");
    var value=$(this).html();
    $("#foo1").html(value);
});?

Here is the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

Is the NOLOCK (Sql Server hint) bad practice?

As a professional Developer I'd say it depends. But I definitely follow GATS and OMG Ponies advice. Know What You are doing, know when it helps and when it hurts and

read hints and other poor ideas

what might make You understand the sql server deeper. I generally follow the rule that SQL Hints are EVIL, but unfortunately I use them every now and then when I get fed up with forcing SQL server do things... But these are rare cases.

luke

What is JSONP, and why was it created?

It's actually not too complicated...

Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:

http://www.example.net/sample.aspx?callback=mycallback

Without JSONP, this might return some basic JavaScript object, like so:

{ foo: 'bar' }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
  alert(data.foo);
};

And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.

These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

How to secure database passwords in PHP?

An additional trick is to use a PHP separate configuration file that looks like that :

<?php exit() ?>

[...]

Plain text data including password

This does not prevent you from setting access rules properly. But in the case your web site is hacked, a "require" or an "include" will just exit the script at the first line so it's even harder to get the data.

Nevertheless, do not ever let configuration files in a directory that can be accessed through the web. You should have a "Web" folder containing your controler code, css, pictures and js. That's all. Anything else goes in offline folders.

Add inline style using Javascript

Use cssText

nFilter.style.cssText +=';width:330px;float:left;';

Remove Item from ArrayList

How about this? Just give it a thought-

import java.util.ArrayList;

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

             ArrayList<String> List_Of_Array = new ArrayList<String>();
             List_Of_Array.add("A");
             List_Of_Array.add("B");
             List_Of_Array.add("C");
             List_Of_Array.add("D");
             List_Of_Array.add("E");
             List_Of_Array.add("F");
             List_Of_Array.add("G");
             List_Of_Array.add("H");

             int i[] = {1,3,5};

             for (int j = 0; j < i.length; j++) {
                 List_Of_Array.remove(i[j]-j);
             }

             System.out.println(List_Of_Array);

        }


}

And the output was-

[A, C, E, G, H]

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

After perusing this myself (Using the Text Color Classes in Connor Leech's answer)

Be warned to pay careful attention to the "navbar-text" class.

To get green text on the navbar for example, you might be tempted to do this:

<p class="navbar-text text-success">Some Text Here</p>

This will NOT work!! "navbar-text" overrides the color and replaces it with the standard navbar text color.

The correct way to do it is to nest the text in a second element, EG:

<p class="navbar-text"><span class="text-success">Some Text Here</span></p>

or in my case (as I wanted emphasized text)

<p class="navbar-text"><strong class="text-success">Some Text Here</strong></p>

When you do it this way, you get properly aligned text with the height of the navbar and you get to change the color too.

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

How can I completely uninstall nodejs, npm and node in Ubuntu

In my case, I have tried to uninstall the node to use the other version of node but when i check node -v , it gives me same version again and again,

found a solution :- search your desired package:

brew search node

you can install the desired version if not install:

brew install node@10

node package already installed you need to unlink it first:

brew unlink node

And then you can link a different version:

brew link node@10 

if required to link them with the --force and --overwrite

brew link --force --overwrite node@10

jQuery selector regular expressions

You can use the filter function to apply more complicated regex matching.

Here's an example which would just match the first three divs:

_x000D_
_x000D_
$('div')_x000D_
  .filter(function() {_x000D_
    return this.id.match(/abc+d/);_x000D_
  })_x000D_
  .html("Matched!");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="abcd">Not matched</div>_x000D_
<div id="abccd">Not matched</div>_x000D_
<div id="abcccd">Not matched</div>_x000D_
<div id="abd">Not matched</div>
_x000D_
_x000D_
_x000D_

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

I had this error message with boot2docker on windows with the docker-oracle-xe-11g image (https://registry.hub.docker.com/u/wnameless/oracle-xe-11g/).

The reason was that the virtual box disk was full (check with boot2docker.exe ssh df). Deleting old images and restarting the container solved the problem.

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

PDF Editing in PHP?

The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.

IF...THEN...ELSE using XML

Perhaps another way to code conditional constructs in XML:

<rule>
    <if>
        <conditions>
            <condition var="something" operator="&gt;">400</condition>
            <!-- more conditions possible -->
        </conditions>
        <statements>
            <!-- do something -->
        </statements>
    </if>
    <elseif>
        <conditions></conditions>
        <statements></statements>
    </elseif>
    <else>
        <statements></statements>
    </else>
</rule>

How to create a remote Git repository from a local one?

In order to initially set up any Git server, you have to export an existing repository into a new bare repository — a repository that doesn’t contain a working directory. This is generally straightforward to do. In order to clone your repository to create a new bare repository, you run the clone command with the --bare option. By convention, bare repository directories end in .git, like so:

$ git clone --bare my_project my_project.git
Initialized empty Git repository in /opt/projects/my_project.git/

This command takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone.

Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. Let’s say you’ve set up a server called git.example.com that you have SSH access to, and you want to store all your Git repositories under the /opt/git directory. You can set up your new repository by copying your bare repository over:

$ scp -r my_project.git [email protected]:/opt/git

At this point, other users who have SSH access to the same server which has read-access to the /opt/git directory can clone your repository by running

$ git clone [email protected]:/opt/git/my_project.git

If a user SSHs into a server and has write access to the /opt/git/my_project.git directory, they will also automatically have push access. Git will automatically add group write permissions to a repository properly if you run the git init command with the --shared option.

$ ssh [email protected]
$ cd /opt/git/my_project.git
$ git init --bare --shared

It is very easy to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. Now you’re ready to collaborate on the same project.

What is PECS (Producer Extends Consumer Super)?

PECS (Producer extends and Consumer super)

mnemonic ? Get and Put principle.

This principle states that:

  • Use an extends wildcard when you only get values out of a structure.
  • Use a super wildcard when you only put values into a structure.
  • And don’t use a wildcard when you both get and put.

Example in Java:

class Super {
        Number testCoVariance() {
            return null;
        }
        void testContraVariance(Number parameter) {
        } 
    }
    
    class Sub extends Super {
        @Override
        Integer testCoVariance() {
            return null;
        } //compiles successfully i.e. return type is don't care(Integer is subtype of Number)
        @Override
        void testContraVariance(Integer parameter) {
        } //doesn't support even though Integer is subtype of Number
    }

The Liskov Substitution Principle (LSP) states that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.

Within the type system of a programming language, a typing rule

  • covariant if it preserves the ordering of types (=), which orders types from more specific to more generic;
  • contravariant if it reverses this ordering;
  • invariant or nonvariant if neither of these applies.

Covariance and contravariance

  • Read-only data types (sources) can be covariant;
  • write-only data types (sinks) can be contravariant.
  • Mutable data types which act as both sources and sinks should be invariant.

To illustrate this general phenomenon, consider the array type. For the type Animal we can make the type Animal[]

  • covariant: a Cat[] is an Animal[];
  • contravariant: an Animal[] is a Cat[];
  • invariant: an Animal[] is not a Cat[] and a Cat[] is not an Animal[].

Java Examples:

Object name= new String("prem"); //works
List<Number> numbers = new ArrayList<Integer>();//gets compile time error

Integer[] myInts = {1,2,3,4};
Number[] myNumber = myInts;
myNumber[0] = 3.14; //attempt of heap pollution i.e. at runtime gets java.lang.ArrayStoreException: java.lang.Double(we can fool compiler but not run-time)

List<String> list=new ArrayList<>();
list.add("prem");
List<Object> listObject=list; //Type mismatch: cannot convert from List<String> to List<Object> at Compiletime  

more examples

enter image description here Image src

bounded(i.e. heading toward somewhere) wildcard : There are 3 different flavours of wildcards:

  • In-variance/Non-variance: ? or ? extends Object - Unbounded Wildcard. It stands for the family of all types. Use when you both get and put.
  • Co-variance: ? extends T (the family of all types that are subtypes of T) - a wildcard with an upper bound. T is the upper-most class in the inheritance hierarchy. Use an extends wildcard when you only Get values out of a structure.
  • Contra-variance: ? super T ( the family of all types that are supertypes of T) - a wildcard with a lower bound. T is the lower-most class in the inheritance hierarchy. Use a super wildcard when you only Put values into a structure.

Note: wildcard ? means zero or one time, represents an unknown type. The wildcard can be used as the type of a parameter, never used as a type argument for a generic method invocation, a generic class instance creation.(i.e. when used wildcard that reference not used in elsewhere in program like we use T)

enter image description here

 import java.util.ArrayList;
import java.util.List;

class Shape { void draw() {}}

class Circle extends Shape {void draw() {}}

class Square extends Shape {void draw() {}}

class Rectangle extends Shape {void draw() {}}

public class Test {

    public static void main(String[] args) {
        //? extends Shape i.e. can use any sub type of Shape, here Shape is Upper Bound in inheritance hierarchy
        List<? extends Shape> intList5 = new ArrayList<Shape>();
        List<? extends Shape> intList6 = new ArrayList<Cricle>();
        List<? extends Shape> intList7 = new ArrayList<Rectangle>();
        List<? extends Shape> intList9 = new ArrayList<Object>();//ERROR.


        //? super Shape i.e. can use any super type of Shape, here Shape is Lower Bound in inheritance hierarchy
        List<? super Shape> inList5 = new ArrayList<Shape>();
        List<? super Shape> inList6 = new ArrayList<Object>();
        List<? super Shape> inList7 = new ArrayList<Circle>(); //ERROR.

        //-----------------------------------------------------------
        Circle circle = new Circle();
        Shape shape = circle; // OK. Circle IS-A Shape

        List<Circle> circles = new ArrayList<>();
        List<Shape> shapes = circles; // ERROR. List<Circle> is not subtype of List<Shape> even when Circle IS-A Shape

        List<? extends Circle> circles2 = new ArrayList<>();
        List<? extends Shape> shapes2 = circles2; // OK. List<? extends Circle> is subtype of List<? extends Shape>


        //-----------------------------------------------------------
        Shape shape2 = new Shape();
        Circle circle2= (Circle) shape2; // OK. with type casting

        List<Shape> shapes3 = new ArrayList<>();
        List<Circle> circles3 = shapes3; //ERROR. List<Circle> is not subtype of  List<Shape> even Circle is subetype of Shape

        List<? super Shape> shapes4 = new ArrayList<>();
        List<? super Circle> circles4 = shapes4; //OK.
    }

    
    
    /*
     * Example for an upper bound wildcard (Get values i.e Producer `extends`)
     *
     * */
    public void testCoVariance(List<? extends Shape> list) {
        list.add(new Object());//ERROR
        list.add(new Shape()); //ERROR
        list.add(new Circle()); // ERROR
        list.add(new Square()); // ERROR
        list.add(new Rectangle()); // ERROR
        Shape shape= list.get(0);//OK so list act as produces only
    /*
     * You can't add a Shape,Circle,Square,Rectangle to a List<? extends Shape>
     * You can get an object and know that it will be an Shape
     */
    }
    
    
    /*
     * Example for  a lower bound wildcard (Put values i.e Consumer`super`)
     * */
    public void testContraVariance(List<? super Shape> list) {
        list.add(new Object());//ERROR
        list.add(new Shape());//OK
        list.add(new Circle());//OK
        list.add(new Square());//OK
        list.add(new Rectangle());//OK
        Shape shape= list.get(0); // ERROR. Type mismatch, so list acts only as consumer
        Object object= list.get(0); //OK gets an object, but we don't know what kind of Object it is.
        /*
         * You can add a Shape,Circle,Square,Rectangle to a List<? super Shape>
         * You can't get an Shape(but can get Object) and don't know what kind of Shape it is.
         */
    }
}

generics and examples

Covariance and contravariance determine compatibility based on types. In either case, variance is a directed relation. Covariance can be translated as "different in the same direction," or with-different, whereas contravariance means "different in the opposite direction," or against-different. Covariant and contravariant types are not the same, but there is a correlation between them. The names imply the direction of the correlation.

jQuery How to Get Element's Margin and Padding?

If the element you're analyzing does not have any margin, border or whatsoever defined you won't be able to return it. At tops you'll be able to get 'auto' which is normally the default.

From your example I can see that you have margT as variable. Not sure if're trying to get margin-top. If that's the case you should be using .css('margin-top').

You're also trying to get the stylization from 'img' which will result (if you have more than one) in an array.

What you should do is use the .each() jquery method.

For example:

jQuery('img').each(function() {
    // get margin top
    var margT = jQuery(this).css('margin-top');

    // Do something with margT
});

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

How to get selected value of a dropdown menu in ReactJS

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

Multiple files upload in Codeigniter

I change upload method with images[] according to @Denmark.

    private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

"Please provide a valid cache path" error in laravel

Check if the following folders exists, if not create these folders.

  • storage/framework/cache
  • storage/framework/sessions
  • storage/framework/testing
  • storage/framework/views

How can I implement custom Action Bar with custom buttons in Android?

enter image description here

This is pretty much as close as you'll get if you want to use the ActionBar APIs. I'm not sure you can place a colorstrip above the ActionBar without doing some weird Window hacking, it's not worth the trouble. As far as changing the MenuItems goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.

<style name="MyTheme" parent="android:Theme.Holo.Light">
    <item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>

<style name="MyActionButtonStyle" parent="Widget.ActionButton">
    <item name="android:minWidth">28dip</item>
</style>

Here's how to inflate and add the custom layout to your ActionBar.

    // Inflate your custom layout
    final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
            R.layout.action_bar,
            null);

    // Set up your ActionBar
    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(actionBarLayout);

    // You customization
    final int actionBarColor = getResources().getColor(R.color.action_bar);
    actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

    final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
    actionBarTitle.setText("Index(2)");

    final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
    actionBarSent.setText("Sent");

    final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
    actionBarStaff.setText("Staff");

    final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
    actionBarLocations.setText("HIPPA Locations");

Here's the custom layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:orientation="horizontal"
    android:paddingEnd="8dip" >

    <Button
        android:id="@+id/action_bar_title"
        style="@style/ActionBarButtonWhite" />

    <Button
        android:id="@+id/action_bar_sent"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_staff"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_locations"
        style="@style/ActionBarButtonOffWhite" />

</LinearLayout>

Here's the color strip layout: To use it, just use merge in whatever layout you inflate in setContentView.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/colorstrip"
    android:background="@android:color/holo_blue_dark" />

Here are the Button styles:

<style name="ActionBarButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@null</item>
    <item name="android:ellipsize">end</item>
    <item name="android:singleLine">true</item>
    <item name="android:textSize">@dimen/text_size_small</item>
</style>

<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/white</item>
</style>

<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/off_white</item>
</style>

Here are the colors and dimensions I used:

<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>

<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>

<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>

If you want to customize it more than this, you may consider not using the ActionBar at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.

If you choose to forgo the ActionBar and use your own layout instead, you should be sure to add action-able Toasts when users long press your "MenuItems". This can be easily achieved using this Gist.

How to check iOS version?

I always keep those in my Constants.h file:

#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES) 
#define IS_OS_5_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
#define IS_OS_6_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
#define IS_OS_7_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define IS_OS_8_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

MySQL Server has gone away when importing large sql file

For GoDaddy shared hosting

On GoDaddy shared hosting accounts, it is tricky to tweak the PHP.ini etc files. However, there is another way and it just worked perfectly for me. (I just successfully uploaded a 3.8Mb .sql text file, containing 3100 rows and 145 cols. Using the IMPORT command in phpMyAdmin, I was getting the dreaded MySQL server has gone away error, and no further information.)

I found that Matt Butcher had the right answer. Like Matt, I had tried all kinds of tricks, from exporting MySQL databases in bite-sized chunks, to writing scripts that break large imports into smaller ones. But here is what worked:

(1) CPANEL ---> FILES (group) ---> BACKUP

(2a) Under "Partial Backups" heading...
(2b) Under "Download a MySQL Database Backup"
(2c) Choose your database and download a backup (this step optional, but wise)

(3a) Directly to the right of 2b, under heading "Restore a MySQL Database Backup"
(3b) Choose the .SQL import file from your local drive
(3c) True happiness will be yours (shortly....) Mine took about 5 seconds

I was able to use this method to import a single table. Nothing else in my database was affected -- but that is what step (2) above is intended to protect against.

Notes:
a. If you are unsure how to create a .SQL import file, use phpMyAdmin to export a table and modify that file structure.

SOURCE: Matt Butcher 2010 Article

Redirect stderr to stdout in C shell

What about just

xxx >& /dev/stdout

???

Dilemma: when to use Fragments vs Activities:

Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.

However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.

I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.

I've created a post about this dillema here, if you wish to read some further.

Representing null in JSON

null is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.

There is only one way to represent null in JSON. Per the specs (RFC 4627 and json.org):

2.1.  Values

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

  false null true

enter image description here

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

How to get exact browser name and version?

I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).

function getBrowserInfo(){
    $browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');

    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $ub = 'Unknown';
    $version = "";
    $platform = 'Unknown';

    $deviceType='Desktop';

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){

        $deviceType='Mobile';

    }

    if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
        $deviceType='Tablet';
    }

    if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
        $deviceType='Tablet';
    }

    //$detect = new Mobile_Detect();
    
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';

    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';

    } elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the user agent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'IE'; 
        $ub = "MSIE";

    } else if(preg_match('/Firefox/i',$u_agent))
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 

    } else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Chrome'; 
        $ub = "Chrome"; 

    } else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Safari'; 
        $ub = "Safari"; 

    } else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 

    } else if(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 

    } else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
    {
        $bname = 'Internet Explorer'; 
        $ub = 'Internet Explorer'; 
    } 
    

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];

        } else {
            $version= @$matches['version'][1];
        }

    } else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'user_agent' => $u_agent,
        'browser'      => $bname,
        'browser_version'   => $version,
        'os_platform'  => $platform,
        'pattern'   => $pattern,
        'device'    => $deviceType
    );
}

This solved my problem of browser detection, I hope, this will also help you. Thank you.

Call Jquery function

calling a function is simple ..

 myFunction();

so your code will be something like..

 $(function(){
     $('#elementID').click(function(){
         myFuntion();  //this will call your function
    });
 });

  $(function(){
     $('#elementID').click( myFuntion );

 });

or with some condition

if(something){
   myFunction();  //this will call your function
}

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

How to avoid using Select in Excel VBA

The main reason never to use Select or Activesheet is because most people will have at least another couple of workbooks open (sometimes dozens) when they run your macro, and if they click away from your sheet while your macro is running and click on some other book they have open, then the "Activesheet" changes, and the target workbook for an unqualified "Select" command changes as well.

At best, your macro will crash, at worst you might end up writing values or changing cells in the wrong workbook with no way to "Undo" them.

I have a simple golden rule that I follow: Add variables named "wb" and "ws" for a Workbook object and a Worksheet object and always use those to refer to my macro book. If I need to refer to more than one book, or more than one sheet, I add more variables.

For example,

Dim wb as Workbook
Dim ws as Worksheet
Set wb = ThisWorkBook
Set ws = wb.sheets("Output")

The "Set wb = ThisWorkbook" command is absolutely key. "ThisWorkbook" is a special value in Excel, and it means the workbook that your VBA code is currently running from. A very helpful shortcut to set your Workbook variable with.

After you've done that at the top of your Sub, using them could not be simpler, just use them wherever you would use "Selection":

So to change the value of cell "A1" in "Output" to "Hello", instead of:

Sheets("Output").Activate
ActiveSheet.Range("A1").Select
Selection.Value = "Hello"

We can now do this:

ws.Range("A1").Value = "Hello"

Which is not only much more reliable and less likely to crash if the user is working with multiple spreadsheets; it's also much shorter, quicker and easier to write.

As an added bonus, if you always name your variables "wb" and "ws", you can copy and paste code from one book to another and it will usually work with minimal changes needed, if any.

How do I set the request timeout for one controller action in an asp.net mvc application

I had to add "Current" using .NET 4.5:

HttpContext.Current.Server.ScriptTimeout = 300;

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

How to reliably open a file in the same directory as a Python script

After trying all of this solutions, I still had different problems. So what I found the simplest way was to create a python file: config.py, with a dictionary containing the file's absolute path and import it into the script. something like

import config as cfg 
import pandas as pd 
pd.read_csv(cfg.paths['myfilepath'])

where config.py has inside:

paths = {'myfilepath': 'home/docs/...'}

It is not automatic but it is a good solution when you have to work in different directory or different machines.

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

How to detect the device orientation using CSS media queries?

I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:

For Mobile

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.

}


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

For Tablet

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

Desktop

make as per your design requirement enjoy...(:

Thanks, Jitu

On - window.location.hash - Change?

I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.

path.js NPM

path.js GitHub

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

Check if string begins with something?

Have a look at JavaScript substring() method.

What is the best way to find the users home directory in Java?

As I was searching for Scala version, all I could find was McDowell's JNA code above. I include my Scala port here, as there currently isn't anywhere more appropriate.

import com.sun.jna.platform.win32._
object jna {
    def getHome: java.io.File = {
        if (!com.sun.jna.Platform.isWindows()) {
            new java.io.File(System.getProperty("user.home"))
        }
        else {
            val pszPath: Array[Char] = new Array[Char](WinDef.MAX_PATH)
            new java.io.File(Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, ShlObj.CSIDL_MYDOCUMENTS, false) match {
                case true => new String(pszPath.takeWhile(c => c != '\0'))
                case _    => System.getProperty("user.home")
            })
        }
    }
}

As with the Java version, you will need to add Java Native Access, including both jar files, to your referenced libraries.

It's nice to see that JNA now makes this much easier than when the original code was posted.

Updating .class file in jar

Editing properties/my_app.properties file inside jar:

"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.

What process is listening on a certain port on Solaris?

I found this script somewhere. I don't remember where, but it works for me:

#!/bin/ksh

line='---------------------------------------------'
pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')

if [ $# -eq 0 ]; then
   read ans?"Enter port you would like to know pid for: "
else
   ans=$1
fi

for f in $pids
do
   /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans"
   if [ $? -eq 0 ]; then
      echo $line
      echo "Port: $ans is being used by PID:\c"
      /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f
   fi
done
exit 0

Edit: Here is the original source: [Solaris] Which process is bound to a given port ?

how to display excel sheet in html page

Maybe you might try the web to send the file with proper Content-Type header and with the header like this:

Content-Disposition: inline; filename="xxx.xxx"

Here is a discussion about these headers: How to force files to open in browser instead of download (pdf)?

Or just search on google for content-disposition.

What are Unwind segues for and how do you use them?

In a Nutshell

An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.

When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.

Objective-C:

- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}

Swift:

@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}

The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue: method of UIViewController.

iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.

An Example

Let us have a storyboard with a navigation controller and three child view controllers:

enter image description here

From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:

Objective-C:

@implementation RedViewController

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}

@end

Swift:

@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}

After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:

enter image description here

You must select the action which is defined in the view controller you want to unwind to:

enter image description here

You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.

Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:

Objective-C:

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
    UIViewController* sourceViewController = unwindSegue.sourceViewController;

    if ([sourceViewController isKindOfClass:[BlueViewController class]])
    {
        NSLog(@"Coming from BLUE!");
    }
    else if ([sourceViewController isKindOfClass:[GreenViewController class]])
    {
        NSLog(@"Coming from GREEN!");
    }
}

Swift:

@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
    if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
        println("Coming from BLUE")
    }
    else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
        println("Coming from RED")
    }
}

Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:

enter image description here

Unwinding from Code

When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:

enter image description here

Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:

enter image description here

After this, the unwind segue can be performed from code just like any other segue:

Objective-C:

[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];

Swift:

performSegueWithIdentifier("UnwindToRedSegueID", sender: self)

Find (and kill) process locking port 3000 on Mac

Nothing above worked for me. Anyone else with my experience could try the following (worked for me):

Run:

lsof -i :3000 (where 3000 is your current port in use)

then check status of the reported PID :

ps ax | grep <PID>

finally, "begone with it":

kill -QUIT <PID>

"The page you are requesting cannot be served because of the extension configuration." error message

I fixed that on my Windows 10:

  1. Go to Control Panel - Programs and Features - Turn Windows features on or off.

  2. Select .NET Framework 4.6 Advanced Services - WCF Services

  3. Check HTTP Activation.

  4. OK done.

How to convert FormData (HTML5 object) to JSON

In my case form Data was data , fire base was expecting an object but data contains object as well as all other stuffs so i tried data.value it worked!!!

Reading a date using DataReader

Try as given below:

while (MyReader.Read())
{
    TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}

in ToString() method you can change data format as per your requirement.

What is the C# Using block and why should I use it?

Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass())
{
  mine.Action();
}

would do the same as:

MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}

Using using is way shorter and easier to read.

Changing MongoDB data store directory

Copy the contents of /var/lib/mongodb to /data/db. The files you should be looking for should have names like your_db_name.ns and your_dbname.n where n is a number starting with 0. If you do not see such files under /var/lib/mongodb, search for them on your filesystem.

Once copied over, use --dbpath=/data/db when starting MongoDB via the mongod command.

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

How do I access call log for android?

Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en

Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.

This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.

I wish you good luck of cause with your applications guys but be careful.

How to read fetch(PDO::FETCH_ASSOC);

Loop through the array like any other Associative Array:

while($data = $datas->fetch( PDO::FETCH_ASSOC )){ 
     print $data['title'].'<br>'; 
}

or

$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);

echo '<pre>'.$resultset.'</pre>';

How to make link not change color after visited?

Text decoration affects the underline, not the color.

To set the visited color to the same as the default, try:

a { 
    color: blue;
}

Or

a {
    text-decoration: none;
}
a:link, a:visited {
    color: blue;
}
a:hover {
    color: red;
}

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

Static linking vs dynamic linking

One reason to do a statically linked build is to verify that you have full closure for the executable, i.e. that all symbol references are resolved correctly.

As a part of a large system that was being built and tested using continuous integration, the nightly regression tests were run using a statically linked version of the executables. Occasionally, we would see that a symbol would not resolve and the static link would fail even though the dynamically linked executable would link successfully.

This was usually occurring when symbols that were deep seated within the shared libs had a misspelt name and so would not statically link. The dynamic linker does not completely resolve all symbols, irrespective of using depth-first or breadth-first evaluation, so you can finish up with a dynamically linked executable that does not have full closure.

jQuery won't parse my JSON from AJAX query

I was struggling with this, and spent a few hours trying to figure this out, until I used firebug to show the data object.

var data = eval("(" + data.responseText + ")");
console.log(data.count);

How can I check that two objects have the same set of property names?

2 Here a short ES6 variadic version:

function objectsHaveSameKeys(...objects) {
   const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
   const union = new Set(allKeys);
   return objects.every(object => union.size === Object.keys(object).length);
}

A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):

var x = {};
var y = {};

for (var i = 0; i < 5000000; ++i) {
    x[i] = i;
    y[i] = i;
}

Results:

objectsHaveSameKeys(x, y) // took  4996 milliseconds
compareKeys(x, y)               // took 14880 milliseconds
hasSameProps(x,y)               // after 10 minutes I stopped execution

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

How to see the proxy settings on windows?

You can use a tool called: NETSH

To view your system proxy information via command line:

netsh.exe winhttp show proxy

Another way to view it is to open IE, then click on the "gear" icon, then Internet options -> Connections tab -> click on LAN settings

How to remove all line breaks from a string

A linebreak in regex is \n, so your script would be

var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));

Retrieve version from maven pom.xml in code

Assuming you're using Java, you can:

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

  2. Set the value of some property in your .properties file using the standard Maven property for project version:

    foo.bar=${project.version}
    
  3. In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).

  4. In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>   
    </build>
    

You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.

How do I activate a virtualenv inside PyCharm's terminal?

I had the same problem with venv in PyCharm. But It is not big problem! Just do:

  1. enter in your terminal venv directory( cd venv/Scripts/ )
  2. You will see activate.bat
  3. Just enter activate.bat in your terminal after this you will see YOUR ( venv )

How do I pass along variables with XMLHTTPRequest

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
const params = new URLSearchParams();_x000D_
params.set('var1', 'foo');_x000D_
params.set('var2', 'bar');_x000D_
target.search = params.toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

Or to convert an entire object's worth of parameters:

_x000D_
_x000D_
const paramsObject = {_x000D_
  var1: 'foo',_x000D_
  var2: 'bar'_x000D_
};_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
target.search = new URLSearchParams(paramsObject).toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

How to make a cross-module variable?

I could achieve cross-module modifiable (or mutable) variables by using a dictionary:

# in myapp.__init__
Timeouts = {} # cross-modules global mutable variables for testing purpose
Timeouts['WAIT_APP_UP_IN_SECONDS'] = 60

# in myapp.mod1
from myapp import Timeouts

def wait_app_up(project_name, port):
    # wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']
    # ...

# in myapp.test.test_mod1
from myapp import Timeouts

def test_wait_app_up_fail(self):
    timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']
    Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3
    with self.assertRaises(hlp.TimeoutException) as cm:
        wait_app_up(PROJECT_NAME, PROJECT_PORT)
    self.assertEqual("Timeout while waiting for App to start", str(cm.exception))
    Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak

When launching test_wait_app_up_fail, the actual timeout duration is 3 seconds.

jQuery - select all text from a textarea

To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus event, not the click event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select() method in a focus event handler) from working.

jsFiddle: http://jsfiddle.net/NM62A/

Code:

<textarea id="foo">Some text</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("foo");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

jQuery version:

$("#foo").focus(function() {
    var $this = $(this);
    $this.select();

    // Work around Chrome's little problem
    $this.mouseup(function() {
        // Prevent further mouseup intervention
        $this.unbind("mouseup");
        return false;
    });
});

How to check if BigDecimal variable == 0 in java?

Alternatively, I think it is worth mentioning that the behavior of equals and compareTo methods in the class BigDecimal are not consistent with each other.

This basically means that:

BigDecimal someValue = new BigDecimal("0.00");
System.out.println(someValue.compareTo(BigDecimal.ZERO) == 0); // true
System.out.println(someValue.equals(BigDecimal.ZERO)); // false

Therefore, you have to be very careful with the scale in your someValue variable, otherwise you would get unexpected result.

How to force R to use a specified factor level as reference in a regression?

You can also manually tag the column with a contrasts attribute, which seems to be respected by the regression functions:

contrasts(df$factorcol) <- contr.treatment(levels(df$factorcol),
   base=which(levels(df$factorcol) == 'RefLevel'))

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

The chart seem to be async so you will probably need to provide a callback when the animation has finished or else the canvas will be empty.

var options = {
    bezierCurve : false,
    onAnimationComplete: done  /// calls function done() {} at end
};

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

What is the difference between String and StringBuffer in Java?

String is immutable, meaning that when you perform an operation on a String you are really creating a whole new String.

StringBuffer is mutable, and you can append to it as well as reset its length to 0.

In practice, the compiler seems to use StringBuffer during String concatenation for performance reasons.

How to install grunt and how to build script with it

You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.

Install grunt-cli with npm i -D grunt-cli instead of installing it globally with -g.

//package.json

...

"scripts": {
  "build": "grunt"
}

Then use npm run build to fire off grunt.

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)

or

  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create module-info.java file

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

Try this if key/values are ICloneable:

    public static Dictionary<K,V> CloneDictionary<K,V>(Dictionary<K,V> dict) where K : ICloneable where V : ICloneable
    {
        Dictionary<K, V> newDict = null;

        if (dict != null)
        {
            // If the key and value are value types, just use copy constructor.
            if (((typeof(K).IsValueType || typeof(K) == typeof(string)) &&
                 (typeof(V).IsValueType) || typeof(V) == typeof(string)))
            {
                newDict = new Dictionary<K, V>(dict);
            }
            else // prepare to clone key or value or both
            {
                newDict = new Dictionary<K, V>();

                foreach (KeyValuePair<K, V> kvp in dict)
                {
                    K key;
                    if (typeof(K).IsValueType || typeof(K) == typeof(string))
                    {
                        key = kvp.Key;
                    }
                    else
                    {
                        key = (K)kvp.Key.Clone();
                    }
                    V value;
                    if (typeof(V).IsValueType || typeof(V) == typeof(string))
                    {
                        value = kvp.Value;
                    }
                    else
                    {
                        value = (V)kvp.Value.Clone();
                    }

                    newDict[key] = value;
                }
            }
        }

        return newDict;
    }

What is the worst real-world macros/pre-processor abuse you've ever come across?

By a classmate who failed to understand the rules about magic numbers:
#define TWO_HUNDRED_AND_EIGHTY_THREE_POINT_ONE 283.1

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

Append values to query string

This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri as obsolete.

Anyway, probably a better way to manipulate relative Uris is to give it what it wants:

var requestUri = new Uri("x://x").MakeRelativeUri(
   new UriBuilder("x://x") { Path = path, Query = query }.Uri);

You can use the other answers to actually build the query string.

How to plot data from multiple two column text files with legends in Matplotlib?

I feel the simplest way would be

 from matplotlib import pyplot;
 from pylab import genfromtxt;  
 mat0 = genfromtxt("data0.txt");
 mat1 = genfromtxt("data1.txt");
 pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
 pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
 pyplot.legend();
 pyplot.show();
  1. label is the string that is displayed on the legend
  2. you can plot as many series of data points as possible before show() to plot all of them on the same graph This is the simple way to plot simple graphs. For other options in genfromtxt go to this url.

Open two instances of a file in a single Visual Studio session

You can use the Windows ? New Window option to duplicate the current window. See more at: Why I like Visual Studio 2010? Undock Windows

How do I run a spring boot executable jar in a Production environment?

If you are using gradle you can just add this to your build.gradle

springBoot {
    executable = true
}

You can then run your application by typing ./your-app.jar

Also, you can find a complete guide here to set up your app as a service

56.1.1 Installation as an init.d service (System V)

http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

cheers

Target class controller does not exist - Laravel 8

In laravel 8 you just add your controller namespace in routes\web.php

use App\Http\Controllers\InvoiceController; // InvoiceController is controller name Route::get('invoice',[InvoiceController::class, 'index']);

Or

go `app\Providers\RouteServiceProvider.php` path and remove comments

protected $namespace = 'App\\Http\\Controllers';

How do you get the file size in C#?

Size on disk might be different, if you move the file to another filesystem (FAT16, NTFS, EXT3, etc)

As other answerers have said, this will give you the size in bytes, not the size on disk.

Docker Error bind: address already in use

For Linux/Unix:

Simple search for linux utility using following command

netstat -nlp | grep 8888

It'll show processing running at this port, then kill that process using PID (look for a PID in row) of that process.

kill PID

Python: Removing spaces from list objects

result = map(str.strip, hello)

How to create text file and insert data to that file on Android

If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt


         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) 
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);


                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }

How to add hyperlink in JLabel?

Just put window.open(website url), it works every time.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

I made some changes in above code to look for a location fix by both GPS and Network for about 5sec and give me the best known location out of it.

public class LocationService implements LocationListener {

    boolean isGPSEnabled = false;

    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    final static long MIN_TIME_INTERVAL = 60 * 1000L;

    Location location;


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

    protected LocationManager locationManager;

    private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {

        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
            stopUsingGPS();
        }
    };

    public LocationService() {
        super(R.id.gps_service_id);
    }


    public void start() {
        if (Utils.isNetworkAvailable(context)) {

            try {


                timer.start();


                locationManager = (LocationManager) context
                        .getSystemService(Context.LOCATION_SERVICE);

                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }
                if (isGPSEnabled) {

                    locationManager.requestSingleUpdate(
                            LocationManager.GPS_PROVIDER, this, null);
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }

            } catch (Exception e) {
                onTaskError(e.getMessage());
                e.printStackTrace();
            }
        } else {
            onOfflineResponse(requestData);
        }
    }

    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(LocationService.this);
        }
    }

    public boolean canGetLocation() {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGPSEnabled || isNetworkEnabled;
    }

    @Override
    public void onLocationChanged(Location location) {

        if (location != null
                && isBetterLocation(location, this.location)) {

            this.location = location;

        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public Object getResponseObject(Object location) {
        return location;
    }

    public static boolean isBetterLocation(Location location,
            Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
        boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location,
        // use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must
            // be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
                .getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and
        // accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider) {
            return true;
        }
        return false;
    }

}

In the above class, I am registering a location listener for both GPS and network, so an onLocationChanged call back can be called by either or both of them multiple times and we just compare the new location fix with the one we already have and keep the best one.

Difference between variable declaration syntaxes in Javascript (including global variables)?

In global scope there is no semantic difference.

But you really should avoid a=0 since your setting a value to an undeclared variable.

Also use closures to avoid editing global scope at all

(function() {
   // do stuff locally

   // Hoist something to global scope
   window.someGlobal = someLocal
}());

Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.

As @AvianMoncellor mentioned there is an IE bug with var a = foo only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.

So stick to window.globalName = someLocalpointer

How to create a HTTP server in Android?

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

https://github.com/weeChanc/AndroidHttpServer

https://github.com/ktorio/ktor

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too

PowerShell: Create Local User Account

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account." 

How to use a switch case 'or' in PHP

I suggest you to go through switch (manual).

switch ($your_variable)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

Explanation

Like for the value you want to execute a single statement for, you can put it without a break as as until or unless break is found. It will go on executing the code and if a break found, it will come out of the switch case.

How to switch to the new browser window, which opens after click on the button?

You can switch between windows as below:

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)

How to insert newline in string literal?

If you are working with Web application you can try this.

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help
  2. Install New Software ---> Add
  3. inside Add Repository write the Name: ADT (or whatever you want)
  4. and Location: https://dl-ssl.google.com/android/eclipse/
  5. after loading you should get Developer Tools and NDK Plugins
  6. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  7. click Next
  8. Finish

How can I make a JPA OneToOne relation lazy

In native Hibernate XML mappings, you can accomplish this by declaring a one-to-one mapping with the constrained attribute set to true. I am not sure what the Hibernate/JPA annotation equivalent of that is, and a quick search of the doc provided no answer, but hopefully that gives you a lead to go on.

Why doesn't java.io.File have a close method?

Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

How to get week numbers from dates?

I understand the need for packages in certain situations, but the base language is so elegant and so proven (and debugged and optimized).

Why not:

dt <- as.Date("2014-03-16")
dt2 <- as.POSIXlt(dt)
dt2$yday
[1] 74

And then your choice whether the first week of the year is zero (as in indexing in C) or 1 (as in indexing in R).

No packages to learn, update, worry about bugs in.

Use of #pragma in C

To sum it up, #pragma tells the compiler to do stuff. Here are a couple of ways I use it:

  • #pragma can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:

    #pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
    

    An older version of libportable does this portably.

  • #pragma once, when written at the top of a header file, will cause said header file to be included once. libportable checks for pragma once support.

How to get URI from an asset File?

Please try this code working fine

 Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));

    /* 2) Create a new Intent */
    Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
            .setData(imageUri)
            .build();

How do I turn off autocommit for a MySQL client?

This is useful to check the status of autocommit;

select @@autocommit;

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

Iterate two Lists or Arrays with one ForEach statement in C#

This method would work for a list implementation and could be implemented as an extension method.

public void TestMethod()
{
    var first = new List<int> {1, 2, 3, 4, 5};
    var second = new List<string> {"One", "Two", "Three", "Four", "Five"};

    foreach(var value in this.Zip(first, second, (x, y) => new {Number = x, Text = y}))
    {
        Console.WriteLine("{0} - {1}",value.Number, value.Text);
    }
}

public IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(List<TFirst> first, List<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
    if (first.Count != second.Count)
        throw new Exception();  

    for(var i = 0; i < first.Count; i++)
    {
        yield return selector.Invoke(first[i], second[i]);
    }
}

Java: Check if command line arguments are null

The arguments can never be null. They just wont exist.

In other words, what you need to do is check the length of your arguments.

public static void main(String[] args)
{
    // Check how many arguments were passed in
    if(args.length == 0)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}

Why Anaconda does not recognize conda command?

It's not recommended to add conda.exe path directly into the System Environment Variables at stated by anaconda installer :

enter image description here

For Windows Users, Open Conda Prompt Shortcut and change the Target into the Correct Address :

enter image description here

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

Instead of using substring with a fixed index, you'd better use replace :

$("#date").html(function(t){
    return t.replace(/^([^\/]*\/)/, '<span>$1</span><br>')
});

One advantage is that it would still work if the first / is at a different position.

Another advantage of this construct is that it would be extensible to more than one elements, for example to all those implementing a class, just by changing the selector.

Demonstration (note that I had to select jQuery in the menu in the left part of jsfiddle's window)

Is it possible to use argsort in descending order?

An elegant way could be as follows -

ids = np.flip(np.argsort(avgDists))

This will give you indices of elements sorted in descending order. Now you can use regular slicing...

top_n = ids[:n]

How do I update Node.js?

On Windows you can use Chocolatey to install and update Node.js (and lots of other packages).

Install Node

cinst nodejs.install

Update Node

cup nodejs.install

Note: You will need to install Chocolatey before you can use cinst and cup.

anaconda update all possible packages?

if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there

How do I erase an element from std::vector<> by index?

If you work with large vectors (size > 100,000) and want to delete lots of elements, I would recommend to do something like this:

int main(int argc, char** argv) {

    vector <int> vec;
    vector <int> vec2;

    for (int i = 0; i < 20000000; i++){
        vec.push_back(i);}

    for (int i = 0; i < vec.size(); i++)
    {
        if(vec.at(i) %3 != 0)
            vec2.push_back(i);
    }

    vec = vec2;
    cout << vec.size() << endl;
}

The code takes every number in vec that can't be divided by 3 and copies it to vec2. Afterwards it copies vec2 in vec. It is pretty fast. To process 20,000,000 elements this algorithm only takes 0.8 sec!

I did the same thing with the erase-method, and it takes lots and lots of time:

Erase-Version (10k elements)  : 0.04 sec
Erase-Version (100k elements) : 0.6  sec
Erase-Version (1000k elements): 56   sec
Erase-Version (10000k elements): ...still calculating (>30 min)

Print all day-dates between two dates

import datetime

begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)

next_day = begin
while True:
    if next_day > end:
        break
    print next_day
    next_day += datetime.timedelta(days=1)

How to maintain aspect ratio using HTML IMG tag

Try this:

<img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">

Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

Resolving require paths with webpack

If you're using create-react-app, you can simply add a .env file containing

NODE_PATH=src/

Source: https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

Common CSS Media Queries Break Points

I always use Desktop first, mobile first doesn't have highest priority does it? IE< 8 will show mobile css..

normal css here: 

@media screen and (max-width: 768px) {}

@media screen and (max-width: 480px) {}

sometimes some custom sizes. I don't like bootstrap etc.

Selecting data frame rows based on partial string match in a column

I notice that you mention a function %like% in your current approach. I don't know if that's a reference to the %like% from "data.table", but if it is, you can definitely use it as follows.

Note that the object does not have to be a data.table (but also remember that subsetting approaches for data.frames and data.tables are not identical):

library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]

If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.


If you don't want to load a package, you can try using grep() to search for the string you're matching. Here's an example with the mtcars dataset, where we are matching all rows where the row names includes "Merc":

mtcars[grep("Merc", rownames(mtcars)), ]
             mpg cyl  disp  hp drat   wt qsec vs am gear carb
# Merc 240D   24.4   4 146.7  62 3.69 3.19 20.0  1  0    4    2
# Merc 230    22.8   4 140.8  95 3.92 3.15 22.9  1  0    4    2
# Merc 280    19.2   6 167.6 123 3.92 3.44 18.3  1  0    4    4
# Merc 280C   17.8   6 167.6 123 3.92 3.44 18.9  1  0    4    4
# Merc 450SE  16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
# Merc 450SL  17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
# Merc 450SLC 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3

And, another example, using the iris dataset searching for the string osa:

irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

For your problem try:

selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Logical Operators, || or OR?

I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.

EDIT: As others have pointed out there is indeed a difference between the two.

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

"Cannot update paths and switch to branch at the same time"

You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master. To the best of my knowledge, you can control --depth via .travis.yml but not the --branch. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.

Before:

$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master

The fix:

$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch

After:

$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master

Prepend line to beginning of a file

with open("fruits.txt", "r+") as file:
    file.write("bab111y")
    file.seek(0)
    content = file.read()
    print(content)

How to print in C

To print those numbers in C do the following:

printf("%d", addNumbers(a,b));

How to generate entire DDL of an Oracle schema (scriptable)?

There is a problem with objects such as PACKAGE_BODY:

SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';


ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ??  "SYS.DBMS_METADATA", line 4018
ORA-06512: ??  "SYS.DBMS_METADATA", line 5843
ORA-06512: ??  line 1
31600. 00000 -  "invalid input value %s for parameter %s in function %s"
*Cause:    A NULL or invalid value was supplied for the parameter.
*Action:   Correct the input value and try the call again.



SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
  FROM all_OBJECTS 
  WHERE (OWNER = 'OWNER1');

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

By any chance have you tried POST vs post? This support article suggests it can cause problems with IIS: http://support.microsoft.com/?id=828726

How to print the full NumPy array, without truncation?

A slight modification: (since you are going to print a huge list)

import numpy as np
np.set_printoptions(threshold=np.inf, linewidth=200)

x = np.arange(1000)
print(x)

This will increase the number of characters per line (default linewidth of 75). Use any value you like for the linewidth which suits your coding environment. This will save you from having to go through huge number of output lines by adding more characters per line.

Set selected item of spinner programmatically

The optimal solution is:

    public String[] items= new String[]{"item1","item2","item3"};
    // here you can use array or list 
    ArrayAdapter adapter= new ArrayAdapter(Your_Context, R.layout.support_simple_spinner_dropdown_item, items);
    final Spinner itemsSpinner= (Spinner) findViewById(R.id.itemSpinner);
itemsSpinner.setAdapter(adapter);

To get the position of the item automatically add the following statement

itemsSpinner.setSelection(itemsSpinner.getPosition("item2"));

How do I run a command on an already existing Docker container?

I usually use this:

    docker exec -it my-container-name bash

to continuously interact with a running container.

Select N random elements from a List<T> in C#

This is the best I could come up with on a first cut:

public List<String> getRandomItemsFromList(int returnCount, List<String> list)
{
    List<String> returnList = new List<String>();
    Dictionary<int, int> randoms = new Dictionary<int, int>();

    while (randoms.Count != returnCount)
    {
        //generate new random between one and total list count
        int randomInt = new Random().Next(list.Count);

        // store this in dictionary to ensure uniqueness
        try
        {
            randoms.Add(randomInt, randomInt);
        }
        catch (ArgumentException aex)
        {
            Console.Write(aex.Message);
        } //we can assume this element exists in the dictonary already 

        //check for randoms length and then iterate through the original list 
        //adding items we select via random to the return list
        if (randoms.Count == returnCount)
        {
            foreach (int key in randoms.Keys)
                returnList.Add(list[randoms[key]]);

            break; //break out of _while_ loop
        }
    }

    return returnList;
}

Using a list of randoms within a range of 1 - total list count and then simply pulling those items in the list seemed to be the best way, but using the Dictionary to ensure uniqueness is something I'm still mulling over.

Also note I used a string list, replace as needed.

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

Bootstrap 3 .col-xs-offset-* doesn't work?

Remove the dot in front of your class so it looks like this:

<div class="col-xs-2 col-xs-offset-1">col</div>

How do I get the total Json record count using JQuery?

What you're looking for is

j.d.length

The d is the key. At least it is in my case, I'm using a .NET webservice.

 $.ajax({
            type: "POST",
            url: "CantTellU.asmx",
            data: "{'userID' : " + parseInt($.query.get('ID')) + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                ApplyTemplate(msg);
                alert(msg.d.length);
            }
        });

Two dimensional array in python

x=3#rows
y=3#columns
a=[]#create an empty list first
for i in range(x):
    a.append([0]*y)#And again append empty lists to original list
    for j in range(y):
         a[i][j]=input("Enter the value")

How to solve a timeout error in Laravel 5

In Laravel:

Add set_time_limit(0) line on top of query.

set_time_limit(0);

$users = App\User::all();

It helps you in different large queries but you should need to improve query optimise.

What is the difference between atomic / volatile / synchronized?

volatile:

volatile is a keyword. volatile forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.

AtomicXXX:

AtomicXXX classes support lock-free thread-safe programming on single variables. These AtomicXXX classes (like AtomicInteger) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.

When to use: Multiple threads can read and modify data.

synchronized:

synchronized is keyword used to guard a method or code block. By making method as synchronized has two effects:

  1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

  2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations

AtomicXXX is equivalent of volatile + synchronized even though the implementation is different. AmtomicXXX extends volatile variables + compareAndSet methods but does not use synchronization.

Related SE questions:

Difference between volatile and synchronized in Java

Volatile boolean vs AtomicBoolean

Good articles to read: ( Above content is taken from these documentation pages)

https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

Use this in procedure

declare cu cursor for SELECT [name] FROM sys.Tables where [name] like 'tbl_%'
declare @table varchar(100)
declare @sql nvarchar(1000)

OPEN cu  
FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @sql = N'delete from ' + @table
    EXEC sp_executesql @sql
    FETCH NEXT FROM cu INTO @table 
END   
CLOSE cu;  
DEALLOCATE cu;

WPF: Grid with column/row margin/padding?

Though you can't add margin or padding to a Grid, you could use something like a Frame (or similar container), that you can apply it to.

That way (if you show or hide the control on a button click say), you won't need to add margin on every control that may interact with it.

Think of it as isolating the groups of controls into units, then applying style to those units.

Unable to import a module that is definitely installed

I had similar problem (on Windows) and the root cause in my case was ANTIVIRUS software! It has "Auto-Containment" feature, that wraps running process with some kind of a virtual machine. Symptoms are: pip install somemodule works fine in one cmd-line window and import somemodule fails when executed from another process with the error

ModuleNotFoundError: No module named 'somemodule'

I hope it will save some time to somebody :)

Can I add extension methods to an existing static class?

I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.

PHP - how to create a newline character?

Strings between double quotes "" interpolate, meaning they convert escaped characters to printable characters.

Strings between single quotes '' are literal, meaning they are treated exactly as the characters are typed in.

You can have both on the same line:

echo '$clientid $lastname ' . "\r\n";
echo "$clientid $lastname \r\n";

outputs:

$clientid $lastname
1 John Doe

How to decode a Base64 string?

There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.

Important:

  • Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).

  • Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.

Ergo:

  • on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.

  • on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.

Examples:

Note:

  • The following examples convert to and from UTF-8 encoded strings:

  • To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode for [Text.Encoding]::UTF8

Convert TO Base64:

PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==

Convert FROM Base64:

PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead

MongoDB not equal to

From the Mongo docs:

The $not operator only affects other operators and cannot check fields and documents independently. So, use the $not operator for logical disjunctions and the $ne operator to test the contents of fields directly.

Since you are testing the field directly $ne is the right operator to use here.

Edit:

A situation where you would like to use $not is:

db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

That would select all documents where:

  • The price field value is less than or equal to 1.99 or the price
  • Field does not exist

How can one use multi threading in PHP applications

The Thread class is available since PECL pthreads = 2.0.0.

where is gacutil.exe?

  1. Open Developer Command prompt.
  2. type

where gacutil

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

Stateless vs Stateful

I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.

Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.

Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.

Regex pattern including all special characters

For people (like me) looking for an answer for special characters like Ä etc. just use this pattern:

  • Only text (or a space): "[A-Za-zÀ-? ]"

  • Text and numbers: "[A-Za-zÀ-?0-9 ]"

  • Text, numbers and some special chars: "[A-Za-zÀ-?0-9(),-_., ]"

Regex just starts at the ascii index and checks if a character of the string is in within both indexes [startindex-endindex].

So you can add any range.

Eventually you can play around with a handy tool: https://regexr.com/

Good luck;)

Jquery to open Bootstrap v3 modal of remote url

From Bootstrap's docs about the remote option;

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

If a remote URL is provided, content will be loaded one time via jQuery's load method and injected into the .modal-content div. If you're using the data-api, you may alternatively use the href attribute to specify the remote source. An example of this is shown below:

<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

That's the .modal-content div, not .modal-body. If you want to put content inside .modal-body then you need to do that with custom javascript.

So I would call jQuery.load programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.

To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal event to load content into the .modal-body div.

HTML Link/Button

<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>

jQuery

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

Infinite Recursion with Jackson JSON and Hibernate JPA issue

For some reason, in my case, it wasn't working with Set. I had to change it to List and use @JsonIgnore and @ToString.Exclude to get it working.

Replace Set with List:

//before
@OneToMany(mappedBy="client")
private Set<address> addressess;

//after
@OneToMany(mappedBy="client")
private List<address> addressess;

And add @JsonIgnore and @ToString.Exclude annotations:

@ManyToOne
@JoinColumn(name="client_id", nullable = false)
@JsonIgnore
@ToString.Exclude
private Client client;

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

No you can't; datetime will be stored in default format only while creating table and then you can change the display format in you select query the way you want using the Mysql Date Time Functions

jQuery get textarea text

the best way: $('#myTextBox').val('new value').trim();

Clear and reset form input fields

I don't know if this is still relevant. But when I had similar issue this is how I resolved it.

Where you need to clear an uncontrolled form you simply do this after submission.

this.<ref-name-goes-here>.setState({value: ''});

Hope this helps.

Recursive sub folder search and return files in a list python

You can use the "recursive" setting within glob module to search through subdirectories

For example:

import glob
glob.glob('//Mypath/folder/**/*',recursive = True)

The second line would return all files within subdirectories for that folder location (Note, you need the '**/*' string at the end of your folder string to do this.)

If you specifically wanted to find text files deep within your subdirectories, you can use

glob.glob('//Mypath/folder/**/*.txt',recursive = True)

Case insensitive comparison NSString

if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
  // strings are equal except for possibly case
}

The documentation is located at Search and Comparison Methods

Opening A Specific File With A Batch File?

You can simply call

program "file"

from the batch file for the vast majority of programs. Don't mess with start unless you absolutely need it; it has various weird side-effects that make your life only harder.

The The point here is that pretty much every program that does something with files allows passing the name of the file to do something with in the command line. If that weren't the case, then you couldn't double-click files in the graphical shell to open them, for example.

If the program you're executing is a console application, then it will run in the current console window and the batch file will continue afterwards. If the program is a GUI program (i.e. not a console program; that's a distinction in the EXE) then the batch file will continue immediately after starting it.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This happens when you declared the JSF Managed Bean as

@RequestScoped;

when you should declare as

@SessionScoped;

Regards;

How can we generate getters and setters in Visual Studio?

In Visual Studio Community Edition 2015 you can select all the fields you want and then press Ctrl + . to automatically generate the properties.

You have to choose if you want to use the property instead of the field or not.

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

How to filter by string in JSONPath?

Drop the quotes:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

Using "If cell contains" in VBA excel

Requirement:
Find a cell containing the word TOTAL then to enter a dash in the cell below it.

Solution: This solution uses the Find method of the Range object, as it seems appropriate to use it rather than brute force (For…Next loop). For explanation and details about the method see Range.Find method (Excel)

Implementation:
In order to provide flexibility the Find method is wrapped in this function:

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean

Where:
sWhat: contains the string to search for
rTrg: is the range to be searched

The function returns True if any match is found, otherwise it returns False

Additionally, every time the function finds a match it passes the resulting range to the procedure Range_Find_Action to execute the required action, (i.e. "enter a dash in the cell below it"). The "required action" is in a separated procedure to allow for customization and flexibility.

This is how the function is called:

This test is searching for "total" to show the effect of the MatchCase:=False. The match can be made case sensitive by changing it to MatchCase:=True

Sub Range_Find_Action_TEST()
Dim sWhat As String, rTrg As Range
Dim sMsgbdy As String
    sWhat = "total"                                             'String to search for (update as required)
    Rem Set rTrg = ThisWorkbook.Worksheets("Sht(0)").UsedRange  'Range to Search (use this to search all used cells)
    Set rTrg = ThisWorkbook.Worksheets("Sht(0)").Rows(6)        'Range to Search (update as required)
    sMsgbdy = IIf(Range_ƒFind_Action(sWhat, rTrg), _
        "Cells found were updated successfully", _
        "No cells were found.")
    MsgBox sMsgbdy, vbInformation, "Range_ƒFind_Action"
    End Sub

This is the Find function

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean
Dim rCll As Range, s1st As String
    With rTrg

        Rem Set First Cell Found
        Set rCll = .Find(What:=sWhat, After:=.Cells(1), _
            LookIn:=xlFormulas, LookAt:=xlPart, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

        Rem Validate First Cell
        If rCll Is Nothing Then Exit Function
        s1st = rCll.Address

        Rem Perform Action
        Call Range_Find_Action(rCll)

        Do
            Rem Find Other Cells
            Set rCll = .FindNext(After:=rCll)
            Rem Validate Cell vs 1st Cell
            If rCll.Address <> s1st Then Call Range_Find_Action(rCll)

        Loop Until rCll.Address = s1st

    End With

    Rem Set Results
    Range_ƒFind_Action = True

    End Function

This is the Action procedure

Sub Range_Find_Action(rCll)
    rCll.Offset(1).Value2 = Chr(167)    'Update as required - Using `§` instead of "-" for visibilty purposes
    End Sub

enter image description here

How to escape special characters in building a JSON string?

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Image showing the definition of a string from the JSON spec

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by four-hex-digits

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

Rename multiple files based on pattern in Unix

There are many ways to do it (not all of these will work on all unixy systems):

  • ls | cut -c4- | xargs -I§ mv fgh§ jkl§

    The § may be replaced by anything you find convenient. You could do this with find -exec too but that behaves subtly different on many systems, so I usually avoid that

  • for f in fgh*; do mv "$f" "${f/fgh/jkl}";done

    Crude but effective as they say

  • rename 's/^fgh/jkl/' fgh*

    Real pretty, but rename is not present on BSD, which is the most common unix system afaik.

  • rename fgh jkl fgh*

  • ls | perl -ne 'chomp; next unless -e; $o = $_; s/fgh/jkl/; next if -e; rename $o, $_';

    If you insist on using Perl, but there is no rename on your system, you can use this monster.

Some of those are a bit convoluted and the list is far from complete, but you will find what you want here for pretty much all unix systems.

Find element in List<> that contains a value

You can use the Where to filter and Select to get the desired value.

MyList.Where(i=>i.name == yourName).Select(j=>j.value);

C/C++ Struct vs Class

Other that the differences in the default access (public/private), there is no difference.

However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."

Note that C unions work with C++, but not the other way around. For example

union WorksWithCppOnly{
    WorksWithCppOnly():a(0){}
    friend class FloatAccessor;
    int a;
private:
    float b;
};

And likewise

typedef union friend{
    int a;
    float b;
} class;

only works in C

Create a branch in Git from another branch

Various ways to create a branch in git from another branch:

This answer adds some additional insight, not already present in the existing answers, regarding just the title of the question itself (Create a branch in Git from another branch), but does not address the more narrow specifics of the question which already have sufficient answers here.

I'm adding this because I really needed to know how to do #1 below just now (create a new branch from a branch I do NOT have checked out), and it wasn't obvious how to do it, and Google searches led to here as a top search result. So, I'll share my findings here. This isn't touched upon well, if at all, by any other answer here.

While I'm at it, I'll also add my other most-common git branch commands I use in my regular workflow, below.

1. To create a new branch from a branch you do NOT have checked out:

Create branch2 from branch1 while you have any branch whatsoever checked out (ex: let's say you have master checked out):

git branch branch2 branch1

The general format is:

git branch <new_branch> [from_branch]

man git branch shows it as:

git branch [--track | --no-track] [-l] [-f] <branchname> [<start-point>]

2. To create a new branch from the branch you DO have checked out:

git branch new_branch

This is great for making backups before rebasing, squashing, hard resetting, etc.--before doing anything which could mess up your branch badly.

Ex: I'm on feature_branch1, and I'm about to squash 20 commits into 1 using git rebase -i master. In case I ever want to "undo" this, let's back up this branch first! I do this ALL...THE...TIME and find it super helpful and comforting to know I can always easily go back to this backup branch and re-branch off of it to try again in case I mess up feature_branch1 in the process:

git branch feature_branch1_BAK_20200814-1320hrs_about_to_squash

The 20200814-1120hrs part is the date and time in format YYYYMMDD-HHMMhrs, so that would be 13:20hrs (1:20pm) on 14 Aug. 2020. This way I have an easy way to find my backup branches until I'm sure I'm ready to delete them. If you don't do this and you mess up badly, you have to use git reflog to go find your branch prior to messing it up, which is much harder, more stressful, and more error-prone.

3. To create and check out a new branch from the branch you DO have checked out:

git checkout -b new_branch

4. To rename a branch

Just like renaming a regular file or folder in the terminal, git considered "renaming" to be more like a 'm'ove command, so you use git branch -m to rename a branch. Here's the general format:

git branch -m <old_name> <new_name>

man git branch shows it like this:

git branch (-m | -M) [<oldbranch>] <newbranch>

Example: let's rename branch_1 to branch_1.5:

git branch -m branch_1 branch_1.5

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
set(mylist2)

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

matplotlib: Group boxplots

Here is my version. It stores data based on categories.

import matplotlib.pyplot as plt
import numpy as np

data_a = [[1,2,5], [5,7,2,2,5], [7,2,5]]
data_b = [[6,4,2], [1,2,5,3,2], [2,3,5,1]]

ticks = ['A', 'B', 'C']

def set_box_color(bp, color):
    plt.setp(bp['boxes'], color=color)
    plt.setp(bp['whiskers'], color=color)
    plt.setp(bp['caps'], color=color)
    plt.setp(bp['medians'], color=color)

plt.figure()

bpl = plt.boxplot(data_a, positions=np.array(xrange(len(data_a)))*2.0-0.4, sym='', widths=0.6)
bpr = plt.boxplot(data_b, positions=np.array(xrange(len(data_b)))*2.0+0.4, sym='', widths=0.6)
set_box_color(bpl, '#D7191C') # colors are from http://colorbrewer2.org/
set_box_color(bpr, '#2C7BB6')

# draw temporary red and blue lines and use them to create a legend
plt.plot([], c='#D7191C', label='Apples')
plt.plot([], c='#2C7BB6', label='Oranges')
plt.legend()

plt.xticks(xrange(0, len(ticks) * 2, 2), ticks)
plt.xlim(-2, len(ticks)*2)
plt.ylim(0, 8)
plt.tight_layout()
plt.savefig('boxcompare.png')

I am short of reputation so I cannot post an image to here. You can run it and see the result. Basically it's very similar to what Molly did.

Note that, depending on the version of python you are using, you may need to replace xrange with range

Result of this code

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

This will work to both load and save a file into TXT from a HTML page with a save as choice

<html>
<body>

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>

<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

</script>

</body>
</html>

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

You probably want to create a type by using the Folding Pattern:

    // Here is the constructor section.
    var myType = function () {
        var N = {}, // Enclosed (private) members are here.
            X = this; // Exposed (public) members are here.

        (function ENCLOSED_FIELDS() {
            N.toggle = false;
            N.text = '';
        }());

        (function EXPOSED_FIELDS() {
            X.count = 0;
            X.numbers = [1, 2, 3];
        }());

        // The properties below have access to the enclosed fields.
        // Careful with functions exposed within the closure of the
        // constructor, each new instance will have it's own copy.
        (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
            Object.defineProperty(X, 'toggle', {
                get: function () {
                    var before = N.toggle;
                    N.toggle = !N.toggle;
                    return before;
                }
            });

            Object.defineProperty(X, 'text', {
                get: function () {
                    return N.text;
                },
                set: function (value) {
                    N.text = value;
                }
            });
        }());
    };

    // Here is the prototype section.
    (function PROTOTYPE() {
        var P = myType.prototype;

        (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
            Object.defineProperty(P, 'numberLength', {
                get: function () {
                    return this.numbers.length;
                }
            });
        }());

        (function EXPOSED_METHODS() {
            P.incrementNumbersByCount = function () {
                var i;
                for (i = 0; i < this.numbers.length; i++) {
                    this.numbers[i] += this.count;
                }
            };
            P.tweak = function () {
                if (this.toggle) {
                    this.count++;
                }
                this.text = 'tweaked';
            };
        }());
    }());

That code will give you a type called myType. It will have internal private fields called toggle and text. It will also have these exposed members: the fields count and numbers; the properties toggle, text and numberLength; the methods incrementNumbersByCount and tweak.

The Folding Pattern is fully detailed here: Javascript Folding Pattern

What's the difference between text/xml vs application/xml for webservice response

From the RFC (3023), under section 3, XML Media Types:

If an XML document -- that is, the unprocessed, source XML document -- is readable by casual users, text/xml is preferable to application/xml. MIME user agents (and web user agents) that do not have explicit support for text/xml will treat it as text/plain, for example, by displaying the XML MIME entity as plain text. Application/xml is preferable when the XML MIME entity is unreadable by casual users.

(emphasis mine)

How to load npm modules in AWS Lambda?

You can now use Lambda Layers for this matters. Simply add a layer containing the package you need and it will run perfectly.

Follow this post: https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

How to serialize an Object into a list of URL query parameters?

An elegant one: (assuming you are running a modern browser or node)

var str = Object.keys(obj).map(function(key) {
  return key + '=' + obj[key];
}).join('&');

And the ES2017 equivalent: (thanks to Lukas)

let str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');

Note: You probably want to use encodeURIComponent() if the keys/values are not URL encoded.

How do I count the number of rows and columns in a file using bash?

Alternatively to count columns, count the separators between columns. I find this to be a good balance of brevity and ease to remember. Of course, this won't work if your data include the column separator.

head -n1 myfile.txt | grep -o " " | wc -l

Uses head -n1 to grab the first line of the file. Uses grep -o to to count all the spaces, and output each space found on a new line. Uses wc -l to count the number of lines.

What are the true benefits of ExpandoObject?

After valueTuples, what's the use of ExpandoObject class? this 6 lines code with ExpandoObject:

dynamic T = new ExpandoObject();
T.x = 1;
T.y = 2;
T.z = new ExpandoObject();
T.z.a = 3;
T.b= 4;

can be written in one line with tuples:

var T = (x: 1, y: 2, z: (a: 3, b: 4));

besides with tuple syntax you have strong type inference and intlisense support