Programs & Examples On #Plyr

plyr is an R package with tools to solve a variety of problems using the split-apply-combine strategy

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Aggregate a dataframe on a given column and display another column

I don't have a high enough reputation to comment on Gavin Simpson's answer, but I wanted to warn that there seems to be a difference in the default treatment of missing values between the standard syntax and the formula syntax for aggregate.

#Create some data with missing values 
a<-data.frame(day=rep(1,5),hour=c(1,2,3,3,4),val=c(1,NA,3,NA,5))
  day hour val
1   1    1   1
2   1    2  NA
3   1    3   3
4   1    3  NA
5   1    4   5

#Standard syntax
aggregate(a$val,by=list(day=a$day,hour=a$hour),mean,na.rm=T)
  day hour   x
1   1    1   1
2   1    2 NaN
3   1    3   3
4   1    4   5

#Formula syntax.  Note the index for hour 2 has been silently dropped.
aggregate(val ~ hour + day,data=a,mean,na.rm=T)
  hour day val
1    1   1   1
2    3   1   3
3    4   1   5

Count number of rows by group using dplyr

There's a special function n() in dplyr to count rows (potentially within groups):

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

But dplyr also offers a handy count function which does exactly the same with less typing:

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

How to select the rows with maximum values in each group with dplyr?

Try this:

result <- df %>% 
             group_by(A, B) %>%
             filter(value == max(value)) %>%
             arrange(A,B,C)

Seems to work:

identical(
  as.data.frame(result),
  ddply(df, .(A, B), function(x) x[which.max(x$value),])
)
#[1] TRUE

As pointed out in the comments, slice may be preferred here as per @RoyalITS' answer below if you strictly only want 1 row per group. This answer will return multiple rows if there are multiple with an identical maximum value.

Check if a value is in an array (C#)

Add using System.Linq; at the top of your file. Then you can do:

if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{

}  

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

Main differences between SOAP and RESTful web services in Java

REST vs. SOAP Web Services

I am seeing a lot of new web services are implemented using a REST style architecture these days rather than a SOAP one. Lets step back a second and explain what REST is.

What is a REST web service?

The acronym REST stands for representational state transfer, and this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).

Who's using REST?

All of Yahoo's web services use REST, including Flickr and Delicious.

APIs use it, pubsub, bloglines, Technorati, and both eBay, and Amazon have web services for both REST and SOAP.

Who's using SOAP?

Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.

REST vs. SOAP

As you may have noticed the companies I mentioned that are using REST APIs haven't been around for very long, and their APIs came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (lets face it you use soap to wash, and you rest when your tired). The main advantages of REST web services are:

  • Lightweight - not a lot of extra XML markup Human Readable Results

  • Easy to build - no toolkits required. SOAP also has some advantages:

Easy to consume - sometimes Rigid - type checking, adheres to a contract Development tools For consuming web services, its sometimes a toss up between which is easier. For instance Google's AdWords web service is really hard to consume (in ColdFusion anyway), it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon's REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

Whichever architecture you choose make sure its easy for developers to access it, and well documented.

Freitag, P. (2005). "REST vs SOAP Web Services". Retrieved from http://www.petefreitag.com/item/431.cfm on June 13, 2010

How to match "anything up until this sequence of characters" in a regular expression?

I believe you need subexpressions. If I remember right you can use the normal () brackets for subexpressions.

This part is From grep manual:

 Back References and Subexpressions
       The back-reference \n, where n is a single digit, matches the substring
       previously matched  by  the  nth  parenthesized  subexpression  of  the
       regular expression.

Do something like ^[^(abc)] should do the trick.

Remove HTML tags from string including &nbsp in C#

I have used the @RaviThapliyal & @Don Rolling's code but made a little modification. Since we are replacing the &nbsp with empty string but instead &nbsp should be replaced with space, so added an additional step. It worked for me like a charm.

public static string FormatString(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>", "").Trim();
    var step2 = Regex.Replace(step1, @"&nbsp;", " ");
    var step3 = Regex.Replace(step2, @"\s{2,}", " ");
    return step3;
}

Used &nbps without semicolon because it was getting formatted by the Stack Overflow.

Eliminating duplicate values based on only one column of the table

This is where the window function row_number() comes in handy:

SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
     (select h.*, row_number() over (partition by siteName order by date desc) as seqnum
      from history h
     ) h
    ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

Angular - Can't make ng-repeat orderBy work

orderby works on arrays that contain objects with immidiate values which can be used as filters, ie

controller.images = [{favs:1,name:"something"},{favs:0,name:"something else"}];

When the above array is repeated, you may use | orderBy:'favs' to refer to that value immidiately, or use a minus in front to order descending

<div class="timeline-image" ng-repeat="image in controller.images | orderBy:'-favs'">
    <img ng-src="{{ images.name }}"/>
</div>

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Factory method: You have a factory that creates objects that derive from a particular base class

Abstract factory: You have a factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don't just want to create a single object (as with Factory method) - rather, you want to create a collection of related objects.

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

Remove tracking branches no longer on remote

If you are using zsh shell with Oh My Zsh installed then the easiest way to do this safely is to use the built in autocomplete.

First determine which branches you want to delete with:

~ git branch --merged

  branch1
  branch2
  branch3
* master

this will show you a list of already merged branches

After you know a few you want to delete then type:

~ git branch -d 

All you have to do is hit [tab] and it will show you a list of local branches. Use tab-complete or just hit [tab] again and you can cycle through them to select a branch with [enter].

Tab Select the branches over and over again until you have a list of branches you wnat to delete:

~ git branch -d branch1 branch2 branch3

Now just press enter to delete your collection of branches.

If you aren't using zsh on your terminal... Get it here.

How to use enums as flags in C++?

Currently there is no language support for enum flags, Meta classes might inherently add this feature if it would ever be part of the c++ standard.

My solution would be to create enum-only instantiated template functions adding support for type-safe bitwise operations for enum class using its underlying type:

File: EnumClassBitwise.h

#pragma once
#ifndef _ENUM_CLASS_BITWISE_H_
#define _ENUM_CLASS_BITWISE_H_

#include <type_traits>

//unary ~operator    
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator~ (Enum& val)
{
    val = static_cast<Enum>(~static_cast<std::underlying_type_t<Enum>>(val));
    return val;
}

// & operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator& (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
}

// &= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator&= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

//| operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator| (Enum lhs, Enum rhs)
{
    return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
}
//|= operator

template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator|= (Enum& lhs, Enum rhs)
{
    lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
    return lhs;
}

#endif // _ENUM_CLASS_BITWISE_H_

For convenience and for reducing mistakes, you might want to wrap your bit flags operations for enums and for integers as well:

File: BitFlags.h

#pragma once
#ifndef _BIT_FLAGS_H_
#define _BIT_FLAGS_H_

#include "EnumClassBitwise.h"

 template<typename T>
 class BitFlags
 {
 public:

     constexpr inline BitFlags() = default;
     constexpr inline BitFlags(T value) { mValue = value; }
     constexpr inline BitFlags operator| (T rhs) const { return mValue | rhs; }
     constexpr inline BitFlags operator& (T rhs) const { return mValue & rhs; }
     constexpr inline BitFlags operator~ () const { return ~mValue; }
     constexpr inline operator T() const { return mValue; }
     constexpr inline BitFlags& operator|=(T rhs) { mValue |= rhs; return *this; }
     constexpr inline BitFlags& operator&=(T rhs) { mValue &= rhs; return *this; }
     constexpr inline bool test(T rhs) const { return (mValue & rhs) == rhs; }
     constexpr inline void set(T rhs) { mValue |= rhs; }
     constexpr inline void clear(T rhs) { mValue &= ~rhs; }

 private:
     T mValue;
 };
#endif //#define _BIT_FLAGS_H_

Possible usage:

#include <cstdint>
#include <BitFlags.h>
void main()
{
    enum class Options : uint32_t
    { 
          NoOption = 0 << 0
        , Option1  = 1 << 0
        , Option2  = 1 << 1
        , Option3  = 1 << 2
        , Option4  = 1 << 3
    };

    const uint32_t Option1 = 1 << 0;
    const uint32_t Option2 = 1 << 1;
    const uint32_t Option3 = 1 << 2;
    const uint32_t Option4 = 1 << 3;

   //Enum BitFlags
    BitFlags<Options> optionsEnum(Options::NoOption);
    optionsEnum.set(Options::Option1 | Options::Option3);

   //Standard integer BitFlags
    BitFlags<uint32_t> optionsUint32(0);
    optionsUint32.set(Option1 | Option3); 

    return 0;
}

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

I am running windows container and I need to look inside the docker container for files and folder created and copied.

In order to do that I used following docker entrypoint command to get the command prompt running inside the container or attach to the container.

ENTRYPOINT ["C:\\Windows\\System32\\cmd.exe", "-D", "FOREGROUND"]

That helped me both to the command prompt attach to container and to keep the container a live. :)

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How to pass a value from one Activity to another in Android?

in the first Activity:

Intent i=new Intent(getApplicationContext,secondActivity.class);

i.putExtra("key",value);

startActivity(i);

and in the SecondActivity:

String value=getIntent.getStringExtra("Key");

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Visual Studio Code Automatic Imports

In the tsconfig.app.json, a standard Angular 10 app has:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

Once I changed the include like to be:

  "include": [
    "src/**/*.d.ts",
    "src/**/*.ts"
  ]

It worked for me It worked for me

How to pull specific directory with git

It's not possible. You need pull all repository or nothing.

Inserting line breaks into PDF

$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);

In every Column, before you set the X Position indicate first the Y position, so it became like this

Column 1

$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);

Column 2

$pdf->SetY($Y_Fields_Name_position);
$pdf->SetX(#);
$pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);

How to run composer from anywhere?

For running it from other location you can use the composer program that come with the program. It is basically a bash script. If you don't have it you can create one by simply copying the following code into a text file

#!/bin/sh

dir=$(d=$(dirname "$0"); cd "$d" && pwd)

if command -v 'cygpath' >/dev/null 2>&1; then
  dir=$(cygpath -m $dir);
fi

dir=$(echo $dir | sed 's/ /\ /g')
php "${dir}/composer.phar" $*

Then save the file inside your bin folder and name it composer without any file extension. Then add the bin folder to your environment variable f

How do I consume the JSON POST data in an Express application

I think you're conflating the use of the response object with that of the request.

The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

For earlier versions of Express (< 4)

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

Test along the lines of:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

Updated for Express 4+

Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

var express = require('express')
  , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Update for Express 4.16+

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

What is a simple C or C++ TCP server and client example?

I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.

Copy files from one directory into an existing directory

What you want is:

cp -R t1/. t2/

The dot at the end tells it to copy the contents of the current directory, not the directory itself. This method also includes hidden files and folders.

Locking pattern for proper use of .NET MemoryCache

public interface ILazyCacheProvider : IAppCache
{
    /// <summary>
    /// Get data loaded - after allways throw cached result (even when data is older then needed) but very fast!
    /// </summary>
    /// <param name="key"></param>
    /// <param name="getData"></param>
    /// <param name="slidingExpiration"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    T GetOrAddPermanent<T>(string key, Func<T> getData, TimeSpan slidingExpiration);
}

/// <summary>
/// Initialize LazyCache in runtime
/// </summary>
public class LazzyCacheProvider: CachingService, ILazyCacheProvider
{
    private readonly Logger _logger = LogManager.GetLogger("MemCashe");
    private readonly Hashtable _hash = new Hashtable();
    private readonly List<string>  _reloader = new List<string>();
    private readonly ConcurrentDictionary<string, DateTime> _lastLoad = new ConcurrentDictionary<string, DateTime>();  


    T ILazyCacheProvider.GetOrAddPermanent<T>(string dataKey, Func<T> getData, TimeSpan slidingExpiration)
    {
        var currentPrincipal = Thread.CurrentPrincipal;
        if (!ObjectCache.Contains(dataKey) && !_hash.Contains(dataKey))
        {
            _hash[dataKey] = null;
            _logger.Debug($"{dataKey} - first start");
            _lastLoad[dataKey] = DateTime.Now;
            _hash[dataKey] = ((object)GetOrAdd(dataKey, getData, slidingExpiration)).CloneObject();
            _lastLoad[dataKey] = DateTime.Now;
           _logger.Debug($"{dataKey} - first");
        }
        else
        {
            if ((!ObjectCache.Contains(dataKey) || _lastLoad[dataKey].AddMinutes(slidingExpiration.Minutes) < DateTime.Now) && _hash[dataKey] != null)
                Task.Run(() =>
                {
                    if (_reloader.Contains(dataKey)) return;
                    lock (_reloader)
                    {
                        if (ObjectCache.Contains(dataKey))
                        {
                            if(_lastLoad[dataKey].AddMinutes(slidingExpiration.Minutes) > DateTime.Now)
                                return;
                            _lastLoad[dataKey] = DateTime.Now;
                            Remove(dataKey);
                        }
                        _reloader.Add(dataKey);
                        Thread.CurrentPrincipal = currentPrincipal;
                        _logger.Debug($"{dataKey} - reload start");
                        _hash[dataKey] = ((object)GetOrAdd(dataKey, getData, slidingExpiration)).CloneObject();
                        _logger.Debug($"{dataKey} - reload");
                        _reloader.Remove(dataKey);
                    }
                });
        }
        if (_hash[dataKey] != null) return (T) (_hash[dataKey]);

        _logger.Debug($"{dataKey} - dummy start");
        var data = GetOrAdd(dataKey, getData, slidingExpiration);
        _logger.Debug($"{dataKey} - dummy");
        return (T)((object)data).CloneObject();
    }
}

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Angular2: child component access parent class variable/function

Basically you can't access variables from parent directly. You do this by events. Component's output property is responsible for this. I would suggest reading https://angular.io/docs/ts/latest/guide/template-syntax.html#input-and-output-properties

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

Extending an Object in Javascript

People who are still struggling for the simple and best approach, you can use Spread Syntax for extending object.

_x000D_
_x000D_
var person1 = {_x000D_
      name: "Blank",_x000D_
      age: 22_x000D_
    };_x000D_
_x000D_
var person2 = {_x000D_
      name: "Robo",_x000D_
      age: 4,_x000D_
      height: '6 feet'_x000D_
    };_x000D_
// spread syntax_x000D_
let newObj = { ...person1, ...person2 };_x000D_
console.log(newObj.height);
_x000D_
_x000D_
_x000D_

Note: Remember that, the property is farthest to the right will have the priority. In this example, person2 is at right side, so newObj will have name Robo in it.

Switch case with conditions

A switch works by comparing what is in switch() to every case.

switch (cnt) {
    case 1: ....
    case 2: ....
    case 3: ....
}

works like:

if (cnt == 1) ...
if (cnt == 2) ...
if (cnt == 3) ...

Therefore, you can't have any logic in the case statements.

switch (cnt) {
    case (cnt >= 10 && cnt <= 20): ...
}

works like

if (cnt == (cnt >= 10 && cnt <= 20)) ...

and that's just nonsense. :)

Use if () { } else if () { } else { } instead.

What is the difference between encrypting and signing in asymmetric encryption?

Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.

Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.

Predicate in Java

You can view the java doc examples or the example of usage of Predicate here

Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:

 // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    resultset.beforeFirst();
    resultset.setFilter(filter);

jQuery remove options from select

$('.ct option').each(function() {
    if ( $(this).val() == 'X' ) {
        $(this).remove();
    }
});

Or just

$('.ct option[value="X"]').remove();

Main point is that find takes a selector string, by feeding it x you are looking for elements named x.

How to print Two-Dimensional Array like table

This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.

public static void display(int x[][])   // So we allow the method to take as input Multidimensional arrays
    {
        //Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
        for(int rreshti = 0; rreshti < x.length; rreshti++)     // Loop for the rows
        {
            for(int kolona = 0; kolona < x[rreshti].length;kolona++)        // Loop for the columns
            {
                System.out.print(x[rreshti][kolona] + "\t");            // the \t simply spaces out the elements for a clear view   
            }
            System.out.println();   // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look 
        }
    }

After you complete creating this method, you simply put this into your main method:

display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)

NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)

Source: enter link description here

PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Is there any kind of hash code function in JavaScript?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

you can use Es6 symbol to create unique key and access object. Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

var obj = {};

obj[Symbol('a')] = 'a';
obj[Symbol.for('b')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

get string value from HashMap depending on key name

This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:

        Map<Integer, String> testKeyset = new HashMap<Integer, String>();

        testKeyset.put(1, "first");
        testKeyset.put(2, "second");
        testKeyset.put(3, "third");
        testKeyset.put(4, "fourth");

        // Print a single value relevant to a specified Key. (uses keySet())
        for(int mapKey: testKeyset.keySet())
            System.out.println(testKeyset.get(mapKey));

        // Print all values regardless of the key.
        for(String mapVal: testKeyset.values())
            System.out.println(mapVal.trim());

        // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
        System.out.println(testKeyset.entrySet());

what is Promotional and Feature graphic in Android Market/Play Store?

In market client on phones at least featured apps with high ratings get to display the promotional graphic.

This is the one that shows up on top even before you start searching the market for a specific app.

See this answer from Android market forum.

Edited: One of the google employee gives some clarifications here

Update: Both links above are now broken but the detailed information can be found here

Selected applications have the ability to be featured atop their respective categories. This is not a guaranteed feature, but uploading promotional graphics is something that we recommend.

Difference between staticmethod and classmethod

First let's start with an example code that we'll use to understand both concepts:

class Employee:

    NO_OF_EMPLOYEES = 0
  
    def __init__(self, first_name, last_name, salary):
        self.first_name = first_name
        self.last_name = last_name
        self.salary = salary
        self.increment_employees()

    def give_raise(self, amount):
        self.salary += amount

    @classmethod
    def employee_from_full_name(cls, full_name, salary):
        split_name = full_name.split(' ')
        first_name = split_name[0]
        last_name = split_name[1]
        return cls(first_name, last_name, salary)

    @classmethod
    def increment_employees(cls):
        cls.NO_OF_EMPLOYEES += 1

    @staticmethod
    def get_employee_legal_obligations_txt():
        legal_obligations = """
        1. An employee must complete 8 hours per working day
        2. ...
        """
        return legal_obligations

Class method

A class method accepts the class itself as an implicit argument and -optionally- any other arguments specified in the definition. It’s important to understand that a class method, does not have access to object instances (like instance methods do). Therefore, class methods cannot be used to alter the state of an instantiated object but instead, they are capable of changing the class state which is shared amongst all the instances of that class. Class methods are typically useful when we need to access the class itself — for example, when we want to create a factory method, that is a method that creates instances of the class. In other words, class methods can serve as alternative constructors.

In our example code, an instance of Employee can be constructed by providing three arguments; first_name , last_name and salary.

employee_1 = Employee('Andrew', 'Brown', 85000)
print(employee_1.first_name)
print(employee_1.salary)

'Andrew'
85000

Now let’s assume that there’s a chance that the name of an Employee can be provided in a single field in which the first and last names are separated by a whitespace. In this case, we could possibly use our class method called employee_from_full_name that accepts three arguments in total. The first one, is the class itself, which is an implicit argument which means that it won’t be provided when calling the method — Python will automatically do this for us:

employee_2 = Employee.employee_from_full_name('John Black', 95000)
print(employee_2.first_name)
print(employee_2.salary)

'John'
95000

Note that it is also possible to call employee_from_full_name from object instances although in this context it doesn’t make a lot of sense:

employee_1 = Employee('Andrew', 'Brown', 85000)
employee_2 = employee_1.employee_from_full_name('John Black', 95000)

Another reason why we might want to create a class method, is when we need to change the state of the class. In our example, the class variable NO_OF_EMPLOYEES keeps track of the number of employees currently working for the company. This method is called every time a new instance of Employee is created and it updates the count accordingly:

employee_1 = Employee('Andrew', 'Brown', 85000)
print(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')
employee_2 = Employee.employee_from_full_name('John Black', 95000)
print(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')

Number of employees: 1
Number of employees: 2

Static methods

On the other hand, in static methods neither the instance (i.e. self) nor the class itself (i.e. cls) is passed as an implicit argument. This means that such methods, are not capable of accessing the class itself or its instances. Now one could argue that static methods are not useful in the context of classes as they can also be placed in helper modules instead of adding them as members of the class. In object oriented programming, it is important to structure your classes into logical chunks and thus, static methods are quite useful when we need to add a method under a class simply because it logically belongs to the class. In our example, the static method named get_employee_legal_obligations_txt simply returns a string that contains the legal obligations of every single employee of a company. This function, does not interact with the class itself nor with any instance. It could have been placed into a different helper module however, it is only relevant to this class and therefore we have to place it under the Employee class.

A static method can be access directly from the class itself

print(Employee.get_employee_legal_obligations_txt())


    1. An employee must complete 8 hours per working day
    2. ...

or from an instance of the class:

employee_1 = Employee('Andrew', 'Brown', 85000)
print(employee_1.get_employee_legal_obligations_txt())


    1. An employee must complete 8 hours per working day
    2. ...

References

Most Useful Attributes

My vote would be for Conditional

[Conditional("DEBUG")]
public void DebugOnlyFunction()
{
    // your code here
}

You can use this to add a function with advanced debugging features; like Debug.Write, it is only called in debug builds, and so allows you to encapsulate complex debug logic outside the main flow of your program.

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

How to force cp to overwrite without confirmation

By default cp has aliase to cp -i. You can check it, type alias and you can see some like:

alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'

To solve this problem just use /bin/cp /from /to command instead cp /from /to

When should I create a destructor?

Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

Setting width as a percentage using jQuery

Using the width function:

$('div#somediv').width('70%');

will turn:

<div id="somediv" />

into:

<div id="somediv" style="width: 70%;"/>

How to handle screen orientation change when progress dialog and background thread active?

This is a very old question that came up on the sidebar for some reason.

If the background task only needs to survive while the activity is in the foreground, the "new" solution is to host the background thread (or, preferably, AsyncTask) in a retained fragment, as described in this developer guide and numerous Q&As.

A retained fragment survives if the activity is destroyed for a configuration change, but not when the activity is destroyed in the background or back stack. Therefore, the background task should still be interrupted if isChangingConfigurations() is false in onPause().

How do I base64 encode (decode) in C?

This solution is based on schulwitz answer (encoding/decoding using OpenSSL), but it is for C++ (well, original question was about C, but there are already another C++ answers here) and it uses error checking (so it's safer to use):

#include <openssl/bio.h>

std::string base64_encode(const std::string &input)
{
    BIO *p_bio_b64 = nullptr;
    BIO *p_bio_mem = nullptr;

    try
    {
        // make chain: p_bio_b64 <--> p_bio_mem
        p_bio_b64 = BIO_new(BIO_f_base64());
        if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
        BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less

        p_bio_mem = BIO_new(BIO_s_mem());
        if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
        BIO_push(p_bio_b64, p_bio_mem);

        // write input to chain
        // write sequence: input -->> p_bio_b64 -->> p_bio_mem
        if (BIO_write(p_bio_b64, input.c_str(), input.size()) <= 0)
            { throw std::runtime_error("BIO_write failed"); }

        if (BIO_flush(p_bio_b64) <= 0)
            { throw std::runtime_error("BIO_flush failed"); }

        // get result
        char *p_encoded_data = nullptr;
        auto  encoded_len    = BIO_get_mem_data(p_bio_mem, &p_encoded_data);
        if (!p_encoded_data) { throw std::runtime_error("BIO_get_mem_data failed"); }

        std::string result(p_encoded_data, encoded_len);

        // clean
        BIO_free_all(p_bio_b64);

        return result;
    }
    catch (...)
    {
        if (p_bio_b64) { BIO_free_all(p_bio_b64); }
        throw;
    }
}

std::string base64_decode(const std::string &input)
{
    BIO *p_bio_mem = nullptr;
    BIO *p_bio_b64 = nullptr;

    try
    {
        // make chain: p_bio_b64 <--> p_bio_mem
        p_bio_b64 = BIO_new(BIO_f_base64());
        if (!p_bio_b64) { throw std::runtime_error("BIO_new failed"); }
        BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines

        p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
        if (!p_bio_mem) { throw std::runtime_error("BIO_new failed"); }
        BIO_push(p_bio_b64, p_bio_mem);

        // read result from chain
        // read sequence (reverse to write): buf <<-- p_bio_b64 <<-- p_bio_mem
        std::vector<char> buf((input.size()*3/4)+1);
        std::string result;
        for (;;)
        {
            auto nread = BIO_read(p_bio_b64, buf.data(), buf.size());
            if (nread  < 0) { throw std::runtime_error("BIO_read failed"); }
            if (nread == 0) { break; } // eof

            result.append(buf.data(), nread);
        }

        // clean
        BIO_free_all(p_bio_b64);

        return result;
    }
    catch (...)
    {
        if (p_bio_b64) { BIO_free_all(p_bio_b64); }
        throw;
    }
}

Note that base64_decode returns empty string, if input is incorrect base64 sequence (openssl works in such way).

IllegalArgumentException or NullPointerException for a null parameter?

As a subjective question this should be closed, but as it's still open:

This is part of the internal policy used at my previous place of employment and it worked really well. This is all from memory so I can't remember the exact wording. It's worth noting that they did not use checked exceptions, but that is beyond the scope of the question. The unchecked exceptions they did use fell into 3 main categories.

NullPointerException: Do not throw intentionally. NPEs are to be thrown only by the VM when dereferencing a null reference. All possible effort is to be made to ensure that these are never thrown. @Nullable and @NotNull should be used in conjunction with code analysis tools to find these errors.

IllegalArgumentException: Thrown when an argument to a function does not conform to the public documentation, such that the error can be identified and described in terms of the arguments passed in. The OP's situation would fall into this category.

IllegalStateException: Thrown when a function is called and its arguments are either unexpected at the time they are passed or incompatible with the state of the object the method is a member of.

For example, there were two internal versions of the IndexOutOfBoundsException used in things that had a length. One a sub-class of IllegalStateException, used if the index was larger than the length. The other a subclass of IllegalArgumentException, used if the index was negative. This was because you could add more items to the object and the argument would be valid, while a negative number is never valid.

As I said, this system works really well, and it took someone to explain why the distinction is there: "Depending on the type of error it is quite straightforward for you to figure out what to do. Even if you can't actually figure out what went wrong you can figure out where to catch that error and create additional debugging information."

NullPointerException: Handle the Null case or put in an assertion so that the NPE is not thrown. If you put in an assertion is just one of the other two types. If possible, continue debugging as if the assertion was there in the first place.

IllegalArgumentException: you have something wrong at your call site. If the values being passed in are from another function, find out why you are receiving an incorrect value. If you are passing in one of your arguments propagate the error checks up the call stack until you find the function that is not returning what you expect.

IllegalStateException: You have not called your functions in the correct order. If you are using one of your arguments, check them and throw an IllegalArgumentException describing the issue. You can then propagate the cheeks up against the stack until you find the issue.

Anyway, his point was that you can only copy the IllegalArgumentAssertions up the stack. There is no way for you to propagate the IllegalStateExceptions or NullPointerExceptions up the stack because they had something to do with your function.

Combining two lists and removing duplicates, without removing duplicates in original list

Simplest to me is:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

merged_list = list(set(first_list+second_list))
print(merged_list)

#prints [1, 2, 5, 7, 9]

How to set image for bar button with swift?

Swift 4.

@IBOutlet weak var settingBarBtn: UIBarButtonItem! {
    didSet {
        let imageSetting = UIImageView(image: UIImage(named: "settings"))
        imageSetting.image = imageSetting.image!.withRenderingMode(.alwaysOriginal)
        imageSetting.tintColor = UIColor.clear
        settingBarBtn.image = imageSetting.image
    }
}

How can I refresh c# dataGridView after update ?

You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():

    private void RefreshGridView()
    {
        if (dataGridView1.InvokeRequired)
        {
            dataGridView1.Invoke((MethodInvoker)delegate ()
            {
                RefreshGridView();
            });
        }
        else
            dataGridView1.Refresh();
    }  

Play sound on button click android

there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.

Nice!

MediaActionSound

A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs

use like:

fun playBeepSound() {
    val sound = MediaActionSound()
    sound.play(MediaActionSound.START_VIDEO_RECORDING)
}

How to show full height background image?

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

In Java what is the syntax for commenting out multiple lines?

/* 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
*/

Calculating powers of integers

Guava's math libraries offer two methods that are useful when calculating exact integer powers:

pow(int b, int k) calculates b to the kth the power, and wraps on overflow

checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow

Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).

If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.

keycode and charcode

keyCode and which represent the actual keyboard key pressed in the form of a numeric value. The reason both exist is that keyCode is available within Internet Explorer while which is available in W3C browsers like FireFox.

charCode is similar, but in this case you retrieve the Unicode value of the character pressed. For example, the letter "A."

The JavaScript expression:

var keyCode = e.keyCode ? e.keyCode : e.charCode;

Essentially says the following:

If the e.keyCode property exists, set variable keyCode to its value. Otherwise, set variable keyCode to the value of the e.charCode property.

Note that retrieving the keyCode or charCode properties typically involve figuring out differences between the event models in IE and in W3C. Some entails writing code like the following:

/*
 get the event object: either window.event for IE 
 or the parameter e for other browsers
*/
var evt = window.event ? window.event : e;
/*
 get the numeric value of the key pressed: either 
 event.keyCode for IE for e.which for other browsers
*/
var keyCode = evt.keyCode ? evt.keyCode : e.which;

EDIT: Corrections to my explanation of charCode as per Tor Haugen's comments.

Which MySQL data type to use for storing boolean values

If you use the BOOLEAN type, this is aliased to TINYINT(1). This is best if you want to use standardised SQL and don't mind that the field could contain an out of range value (basically anything that isn't 0 will be 'true').

ENUM('False', 'True') will let you use the strings in your SQL, and MySQL will store the field internally as an integer where 'False'=0 and 'True'=1 based on the order the Enum is specified.

In MySQL 5+ you can use a BIT(1) field to indicate a 1-bit numeric type. I don't believe this actually uses any less space in the storage but again allows you to constrain the possible values to 1 or 0.

All of the above will use approximately the same amount of storage, so it's best to pick the one you find easiest to work with.

Make sure that the controller has a parameterless public constructor error

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Turning off SSL seems like a profoundly bad idea. npm's blog explains that they no longer support their self-signed cert. They suggest upgrading npm via npm install npm -g, but I of course got the same SELF_SIGNED_CERT_IN_CHAIN error. So I just updated node, which updated npm along with it. Exact procedure depends on how you installed node in the first place.

Get TimeZone offset value from TimeZone without TimeZone name

We can easily get the millisecond offset of a TimeZone with only a TimeZone instance and System.currentTimeMillis(). Then we can convert from milliseconds to any time unit of choice using the TimeUnit class.

Like so:

public static int getOffsetHours(TimeZone timeZone) {
    return (int) TimeUnit.MILLISECONDS.toHours(timeZone.getOffset(System.currentTimeMillis()));
}

Or if you prefer the new Java 8 time API

public static ZoneOffset getOffset(TimeZone timeZone) { //for using ZoneOffsett class
    ZoneId zi = timeZone.toZoneId();
    ZoneRules zr = zi.getRules();
    return zr.getOffset(LocalDateTime.now());
}

public static int getOffsetHours(TimeZone timeZone) { //just hour offset
    ZoneOffset zo = getOffset(timeZone);
    TimeUnit.SECONDS.toHours(zo.getTotalSeconds());
}

Standard Android menu icons, for example refresh

Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:

"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
plot(c(1:10),
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

How can the size of an input text box be defined in HTML?

You can set the width in pixels via inline styling:

<input type="text" name="text" style="width: 195px;">

You can also set the width with a visible character length:

<input type="text" name="text" size="35">

How can I enable or disable the GPS programmatically on Android?

the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.

here's some example code i use

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.

private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

How can I access global variable inside class in Python

I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing). I ran into the same problem with declaring global variables and figured it out with some experiments.

The reason that g_c was not changed by the run function within your class is that the referencing to the global name within g_c was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c has two effects:

  1. Preconditions the entrance of the key "g_c" into the dictionary accessible by the built-in function, globals(). However, the key will not appear in the dictionary until after a value is assigned to it.

  2. (Potentially) alters the way Python looks for the variable g_c within the current method.

The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c occurs within the method, then Python defaults to searching for it among the globals(). This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.

However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:

UnboundLocalError: local variable 'g_c' referenced before assignment

Now, if the declaration global g_c occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:

SyntaxWarning: name 'g_c' is used prior to global declaration

If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.

Here is a code that summarizes what I just said (with a few more observations):

g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
      + str("g_c" in globals()))

class TestClass():
    def direct_print(self):
        print("Directly printing g_c without declaration or modification: "
              + str(g_c))
        #Without any local reference to the name
        #Python defaults to search for the variable in globals()
        #This of course happens for all the module names you import

    def mod_without_dec(self):
        g_c = 1
        #A local assignment without declaring reference to global variable
        #makes Python default to access local name
        print ("After mod_without_dec, local g_c=" + str(g_c))
        print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))


    def mod_with_late_dec(self):
        g_c = 2
        #Even with a late declaration, the global variable is accessed
        #However, a syntax warning will be issued
        global g_c
        print ("After mod_with_late_dec, local g_c=" + str(g_c))
        print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))

    def mod_without_dec_error(self):
        try:
            print("This is g_c" + str(g_c))
        except:
            print("Error occured while accessing g_c")
            #If you try to access g_c without declaring it global
            #but within the method you also alter it at some point
            #then Python will not search for the name in globals()
            #!!!!!Even if the assignment command occurs later!!!!!
        g_c = 3

    def sound_practice(self):
        global g_c
        #With correct declaration within the method
        #The local name g_c becomes an alias for globals()["g_c"]
        g_c = 4
        print("In sound_practice, the name g_c points to: " + str(g_c))


t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()

Background color for Tk in Python

I know this is kinda an old question but:

root["bg"] = "black"

will also do what you want and it involves less typing.

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

Uninstall mongoDB from ubuntu

use command with sudo,

sudo apt-get autoremove --purge mongodb

OR

sudo apt-get remove mongodb* --purge

It will remove complete mongodb

How do I get the XML SOAP request of an WCF Web service request?

OperationContext.Current.RequestContext.RequestMessage 

this context is accesible server side during processing of request. This doesn`t works for one-way operations

Create table variable in MySQL

They don't exist in MySQL do they? Just use a temp table:

CREATE PROCEDURE my_proc () BEGIN 

CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100)); 
INSERT INTO TempTable SELECT tblid, tblfield FROM Table1; 

/* Do some more stuff .... */

From MySQL here

"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"

How do I create a readable diff of two spreadsheets using git diff?

Do you use TortoiseSVN for doing your commits and updates in subversion? It has a diff tool, however comparing Excel files is still not really user friendly. In my environment (Win XP, Office 2007), it opens up two excel files for side by side comparison.

Right click document > Tortoise SVN > Show Log > select revision > right click for "Compare with working copy".

how to update spyder on anaconda

Use this conda install spyder=4.0.0 This will not mess up your anaconda dependencies. https://github.com/spyder-ide/spyder/releases

How to generate unique ID with node.js

I am using the following and it is working fine plus without any third-party dependencies.

const {
  randomBytes
} = require('crypto');

const uid = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();

Change Tomcat Server's timeout in Eclipse

The issue is also created if you have setup breakpoints in the code and trying to start tomcat in debug mode post some code overhaul.

Solution is to clear all the breakpoints.

Comparing arrays in C#

For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

Create two-dimensional arrays and access sub-arrays in Ruby

There are some problems with 2 dimensional Arrays the way you implement them.

a= [[1,2],[3,4]]
a[0][2]= 5 # works
a[2][0]= 6 # error

Hash as Array

I prefer to use Hashes for multi dimensional Arrays

a= Hash.new
a[[1,2]]= 23
a[[5,6]]= 42

This has the advantage, that you don't have to manually create columns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash does not become too big.

You can even set a default value for all not specified elements

a= Hash.new(0)

So now about how to get subarrays

(3..5).to_a.product([2]).collect { |index| a[index] }
[2].product((3..5).to_a).collect { |index| a[index] }

(a..b).to_a runs in O(n). Retrieving an element from an Hash is almost O(1), so the collect runs in almost O(n). There is no way to make it faster than O(n), as copying n elements always is O(n).

Hashes can have problems when they are getting too big. So I would think twice about implementing a multidimensional Array like this, if I knew my amount of data is getting big.

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

https://stackoverflow.com/a/1320708/969984

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Restrict varchar() column to specific values?

Personally, I'd code it as tinyint and:

  • Either: change it to text on the client, check constraint between 1 and 4
  • Or: use a lookup table with a foreign key

Reasons:

  • It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.

  • What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.

  • Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.

How to view DB2 Table structure

php example for iSeries (as400) db2, yes this worked!

$i5 = db2_connect($database, $user, $password, array("i5_lib"=>"qsys2"));

$querydesc = "select * from qsys2.syscolumns where table_schema = '".$library."' and table_name = '".$table_name."' ";

$result = db2_exec($i5, $querydesc);

also if you just want to list all tables with their descriptions

$query = "select TABLE_NAME, TABLE_TEXT from systables where table_schema = '$library' ";

$result = db2_exec($i5, $query);

Accessing bash command line args $@ vs $*

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

Meaning of @classmethod and @staticmethod for beginner?

A little compilation

@staticmethod A way to write a method inside a class without reference to the object it is being called on. So no need to pass implicit argument like self or cls. It is written exactly the same how written outside the class, but it is not of no use in python because if you need to encapsulate a method inside a class since this method needs to be the part of that class @staticmethod is comes handy in that case.

@classmethod It is important when you want to write a factory method and by this custom attribute(s) can be attached in a class. This attribute(s) can be overridden in the inherited class.

A comparison between these two methods can be as below

Table

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Found a likely answer in /jstillwell's posts here: https://github.com/stefanocudini/leaflet-gps/issues/15 basically this feature will not be supported (in Chrome only?) in the future, but only for HTTP sites. HTTPS will still be ok, and there are no plans to create an equivalent replacement for HTTP use.

What is memoization and how can I use it in Python?

Let's not forget the built-in hasattr function, for those who want to hand-craft. That way you can keep the mem cache inside the function definition (as opposed to a global).

def fact(n):
    if not hasattr(fact, 'mem'):
        fact.mem = {1: 1}
    if not n in fact.mem:
        fact.mem[n] = n * fact(n - 1)
    return fact.mem[n]

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How do I convert an object to an array?

You can also use array_values() method of php

Dump all tables in CSV format using 'mysqldump'

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

"id","login","password","folder","email" "8","mariana","xxxxxxxxxx","mariana","" "3","squaredesign","xxxxxxxxxxxxxxxxx","squaredesign","[email protected]" "4","miedziak","xxxxxxxxxx","miedziak","[email protected]" "5","Sarko","xxxxxxxxx","Sarko","" "6","Logitrans Poland","xxxxxxxxxxxxxx","LogitransPoland","" "7","Amos","xxxxxxxxxxxxxxxxxxxx","Amos","" "9","Annabelle","xxxxxxxxxxxxxxxx","Annabelle","" "11","Brandfathers and Sons","xxxxxxxxxxxxxxxxx","BrandfathersAndSons","" "12","Imagine Group","xxxxxxxxxxxxxxxx","ImagineGroup","" "13","EduSquare.pl","xxxxxxxxxxxxxxxxx","EduSquare.pl","" "101","tmp","xxxxxxxxxxxxxxxxxxxxx","_","[email protected]"

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it's only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

How to compare arrays in C#?

The Equals method does a reference comparison - if the arrays are different objects, this will indeed return false.

To check if the arrays contain identical values (and in the same order), you will need to iterate over them and test equality on each.

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

Font scaling based on width of container

I was very frustrated trying to achieve a fitty-like tight text wrapping so I ended up using a canvas-based method which I arrived at by unsuccessfully trying other methods. What I was aiming for looks like the attached which turns out to be surprisingly difficult (for me). Hopefully one day we will have a simple CSS-only way of doing this. Downsides of this approach is the text is treated more like an image, but for some use cases this is fine.

https://codesandbox.io/s/create-a-canvas-tightly-holding-a-word-st2h1?file=/index.html

This image is a screenshot of a CSS Grid layout of four full-bleed canvases.

enter image description here

Date object to Calendar [Java]

something like

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

Processing $http response in service

I had the same problem, but when I was surfing on the internet I understood that $http return back by default a promise, then I could use it with "then" after return the "data". look at the code:

 app.service('myService', function($http) {
       this.getData = function(){
         var myResponseData = $http.get('test.json').then(function (response) {
            console.log(response);.
            return response.data;
          });
         return myResponseData;

       }
});    
 app.controller('MainCtrl', function( myService, $scope) {
      // Call the getData and set the response "data" in your scope.  
      myService.getData.then(function(myReponseData) {
        $scope.data = myReponseData;
      });
 });

Serializing PHP object to JSON

json_encode() will only encode public member variables. so if you want to include the private once you have to do it by yourself (as the others suggested)

CSS full screen div with text in the middle

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>?

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}?

Using Html.ActionLink to call action on different controller

I would recommend writing these helpers using named parameters for the sake of clarity as follows:

@Html.ActionLink(
    linkText: "Details",
    actionName: "Details",
    controllerName: "Product",
    routeValues: new {
        id = item.ID
    },
    htmlAttributes: null
)

How to make layout with View fill the remaining space?

If you use RelativeLayout, you can do it something like this:

<RelativeLayout
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <ImageView
        android:id = "@+id/my_image"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop ="true" />
    <RelativeLayout
        android:id="@+id/layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height = "50dp"
        android:layout_alignParentBottom = "true">
        <Button
            android:id = "@+id/but_left"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&lt;"
            android:layout_alignParentLeft = "true"/>
        <TextView
            android:layout_width = "fill_parent"
            android:layout_height = "wrap_content"
            android:layout_toLeftOf = "@+id/but_right"
            android:layout_toRightOf = "@id/but_left" />
        <Button
            android:id = "@id/but_right"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&gt;"
            android:layout_alignParentRight = "true"/>
    </RelativeLayout>
</RelativeLayout>

Static nested class in Java, why?

To my mind, the question ought to be the other way round whenever you see an inner class - does it really need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?

Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)

Maintain model of scope when changing between views in AngularJS

I took a bit of time to work out what is the best way of doing this. I also wanted to keep the state, when the user leaves the page and then presses the back button, to get back to the old page; and not just put all my data into the rootscope.

The final result is to have a service for each controller. In the controller, you just have functions and variables that you dont care about, if they are cleared.

The service for the controller is injected by dependency injection. As services are singletons, their data is not destroyed like the data in the controller.

In the service, I have a model. the model ONLY has data - no functions -. That way it can be converted back and forth from JSON to persist it. I used the html5 localstorage for persistence.

Lastly i used window.onbeforeunload and $rootScope.$broadcast('saveState'); to let all the services know that they should save their state, and $rootScope.$broadcast('restoreState') to let them know to restore their state ( used for when the user leaves the page and presses the back button to return to the page respectively).

Example service called userService for my userController :

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''
        },

        SaveState: function () {
            sessionStorage.userService = angular.toJson(service.model);
        },

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);
        }
    }

    $rootScope.$on("savestate", service.SaveState);
    $rootScope.$on("restorestate", service.RestoreState);

    return service;
}]);

userController example

function userCtrl($scope, userService) {
    $scope.user = userService;
}

The view then uses binding like this

<h1>{{user.model.name}}</h1>

And in the app module, within the run function i handle the broadcasting of the saveState and restoreState

$rootScope.$on("$routeChangeStart", function (event, next, current) {
    if (sessionStorage.restorestate == "true") {
        $rootScope.$broadcast('restorestate'); //let everything know we need to restore state
        sessionStorage.restorestate = false;
    }
});

//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
    $rootScope.$broadcast('savestate');
};

As i mentioned this took a while to come to this point. It is a very clean way of doing it, but it is a fair bit of engineering to do something that i would suspect is a very common issue when developing in Angular.

I would love to see easier, but as clean ways to handle keeping state across controllers, including when the user leaves and returns to the page.

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

In PHPStorm, it's a bit easier: you can just search for NPM in settings or:

File > Settings > Language & Frameworks > Node.js and NPM

Then click the enable button (apparently in new versions, it is called "Coding assistance for Node").

Why does JSHint throw a warning if I am using const?

If you are using Grunt configuration, You need to do the following steps

Warning message in Jshint:

enter image description here

Solution:

  1. Set the jshint options and map the .jshintrc.js file

enter image description here

  1. Create the .jshintrc.js file in that file add the following code
{  
  "esversion": 6  
} 

After configured this, Run again It will skip the warning,

enter image description here

How do I read a specified line in a text file?

Read five lines each time, just put your statement in if statement , thats it

        String str1 = @"C:\Users\TEMP\Desktop\StaN.txt";   

        System.IO.StreamReader file = new System.IO.StreamReader(str1);

        line = file.ReadLine();

        Int32 ctn=0;

        try
        {

            while ((line = file.ReadLine()) != null)
            {

                    if (Counter == ctn)
                    {
                        MessageBox.Show("I am here");
                        ctn=ctn+5;
                        continue;
                    }
                    else
                    {
                        Counter++;
                        //MessageBox.Show(Counter.ToString());
                        MessageBox.Show(line.ToString());
                    } 
                }

            file.Close();
        }
        catch (Exception er)
        {

        }

How to implement static class member functions in *.cpp file?

Yes you can define static member functions in *.cpp file. If you define it in the header, compiler will by default treat it as inline. However, it does not mean separate copies of the static member function will exist in the executable. Please follow this post to learn more about this: Are static member functions in c++ copied in multiple translation units?

Remove space above and below <p> tag HTML

In case anyone wishes to do this with bootstrap, version 4 offers the following:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Where property is one of:

m - for classes that set margin
p - for classes that set padding

Where sides is one of:

t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto

For example:

.mt-0 {
  margin-top: 0 !important;
}

.ml-1 {
  margin-left: ($spacer * .25) !important;
}

.px-2 {
  padding-left: ($spacer * .5) !important;
  padding-right: ($spacer * .5) !important;
}

.p-3 {
  padding: $spacer !important;
}

Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi from 'node-v0.10.33-x86.msi' and it is working well for me!

http://blog.nodejs.org/2014/06/16/node-v0-10-29-stable/

Making an svg image object clickable with onclick, avoiding absolute positioning

I got this working accross the latest versions of Firefox, Chrome, Safari and Opera.

It relies on a transparent div before the object that has absolute position and set width and height so it covers the object tag below.

Here it is, I've been a bit lazy and used inline styes:

<div id="toolbar" style="width: 600px; height: 100px; position: absolute; z-index: 1;"></div>
<object data="interface.svg" width="600" height="100" type="image/svg+xml">
</object>

I used the following JavaScript to hook up an event to it:

<script type="text/javascript">
    var toolbar = document.getElementById("toolbar");
    toolbar.onclick = function (e) {
        alert("Hello");
    };
</script>

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:

If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).

EDIT:

From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.

How to update a value, given a key in a hashmap?

The simplified Java 8 way:

map.put(key, map.getOrDefault(key, 0) + 1);

This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').

This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)

How to get value of selected radio button?

My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.

var Anodes = document.getElementsByName('A'),
    AValue = Array.from(Anodes)
       .filter(node => node.checked)
       .map(node => node.value)
       .pop();
console.log(AValue);

Note that I'm using arrow functions. See this fiddle for a working example.

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Compare dates in MySQL

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

How do you format code on save in VS Code

No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

Create a folder if it doesn't already exist

if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}

Java says FileNotFoundException but file exists

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.
  • Calling file.isDirectory() will test if it is a directory.
  • Calling file.canRead() will test if it is a readable file.
  • This line will tell you what the current directory is:

    System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:

    System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

node.js, socket.io with SSL

On the same note, if your server supports both http and https you can connect using:

var socket = io.connect('//localhost');

to auto detect the browser scheme and connect using http/https accordingly. when in https, the transport will be secured by default, as connecting using

var socket = io.connect('https://localhost');

will use secure web sockets - wss:// (the {secure: true} is redundant).

for more information on how to serve both http and https easily using the same node server check out this answer.

Batch: Remove file extension

Without looping

I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):

for %%f in ("%filename%") do set filename=%%~nf

If you want to strip the extension from a full path, use %%dpnf instead:

for %%f in ("%path%") do set path=%%~dpnf

Example:

(Use directly in the console)

@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf

OUTPUT:

file name
C:\Dir\file

Detach (move) subdirectory into separate Git repository

Update: This process is so common, that the git team made it much simpler with a new tool, git subtree. See here: Detach (move) subdirectory into separate Git repository


You want to clone your repository and then use git filter-branch to mark everything but the subdirectory you want in your new repo to be garbage-collected.

  1. To clone your local repository:

    git clone /XYZ /ABC
    

    (Note: the repository will be cloned using hard-links, but that is not a problem since the hard-linked files will not be modified in themselves - new ones will be created.)

  2. Now, let us preserve the interesting branches which we want to rewrite as well, and then remove the origin to avoid pushing there and to make sure that old commits will not be referenced by the origin:

    cd /ABC
    for i in branch1 br2 br3; do git branch -t $i origin/$i; done
    git remote rm origin
    

    or for all remote branches:

    cd /ABC
    for i in $(git branch -r | sed "s/.*origin\///"); do git branch -t $i origin/$i; done
    git remote rm origin
    
  3. Now you might want to also remove tags which have no relation with the subproject; you can also do that later, but you might need to prune your repo again. I did not do so and got a WARNING: Ref 'refs/tags/v0.1' is unchanged for all tags (since they were all unrelated to the subproject); additionally, after removing such tags more space will be reclaimed. Apparently git filter-branch should be able to rewrite other tags, but I could not verify this. If you want to remove all tags, use git tag -l | xargs git tag -d.

  4. Then use filter-branch and reset to exclude the other files, so they can be pruned. Let's also add --tag-name-filter cat --prune-empty to remove empty commits and to rewrite tags (note that this will have to strip their signature):

    git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC -- --all
    

    or alternatively, to only rewrite the HEAD branch and ignore tags and other branches:

    git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC HEAD
    
  5. Then delete the backup reflogs so the space can be truly reclaimed (although now the operation is destructive)

    git reset --hard
    git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
    git reflog expire --expire=now --all
    git gc --aggressive --prune=now
    

    and now you have a local git repository of the ABC sub-directory with all its history preserved.

Note: For most uses, git filter-branch should indeed have the added parameter -- --all. Yes that's really --space-- all. This needs to be the last parameters for the command. As Matli discovered, this keeps the project branches and tags included in the new repo.

Edit: various suggestions from comments below were incorporated to make sure, for instance, that the repository is actually shrunk (which was not always the case before).

How to check a string against null in java?

There are two ways to do it..Say String==null or string.equals()..

public class IfElse {

    public int ifElseTesting(String a){
        //return null;
        return (a== null)? 0: a.length();
    }

}

public class ShortCutifElseTesting {

    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        System.out.println("enter the string please:");
        String a=scanner.nextLine();
        /*
        if (a.equals(null)){
            System.out.println("you are not correct");
        }
        else if(a.equals("bangladesh")){
            System.out.println("you are right");
        }
        else
            System.out.println("succesful tested");

        */
        IfElse ie=new IfElse();
        int result=ie.ifElseTesting(a);
        System.out.println(result);

    }

}

Check this example..Here is an another example of shortcut version of If Else..

Hidden Columns in jqGrid

This feature is built into jqGrid.

setup your grid function as follows.

$('#myGrid').jqGrid({
   ...
   colNames: ['Manager', 'Name', 'HiddenSalary'],
   colModel: [               
               { name: 'Manager', editable: true },
               { name: 'Price', editable: true },
               { name: 'HiddenSalary', hidden: true , editable: true, 
                  editrules: {edithidden:true} 
               }
             ],
   ...
};

There are other editrules that can be applied but this basic setup would hide the manager's salary in the grid view but would allow editing when the edit form was displayed.

filemtime "warning stat failed for"

Shorter version for those who like short code:

// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)


function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {

    // $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age

    foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) { 

        if (is_writable($f) && filemtime($f) < (time() - $timeout))
            unlink($f);

    }

}

Two Decimal places using c#

In some tests here, it worked perfectly this way:

Decimal.Round(value, 2);

Hope this helps

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

How to style the parent element when hovering a child element?

As mentioned previously "there is no CSS selector for selecting a parent of a selected child".

So you either:


Here is the example for the javascript/jQuery solution

On the javascript side:

$('#my-id-selector-00').on('mouseover', function(){
  $(this).parent().addClass('is-hover');
}).on('mouseout', function(){
  $(this).parent().removeClass('is-hover');
})

And on the CSS side, you'd have something like this:

.is-hover {
  background-color: red;
}

How do I tell Gradle to use specific JDK version?

I added this line in my GRADLE_HOME/bin/gradle file - export JAVA_HOME=/path/to/java/version

How to import other Python files?

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.

Add/remove class with jquery based on vertical scroll?

For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.

jQuery(document.body).scroll(function() {
        var scroll = jQuery(document.body).scrollTop();

        if (scroll >= 300) {
            //alert();
            header.addClass("sticky");
        } else {
            header.removeClass('sticky');
        }
    });

This code worked for me. Hope it will help you.

Simple DatePicker-like Calendar

jquery ui has a great datepicker you can find it here

http://jqueryui.com/demos/datepicker/

you can use

http://jqueryui.com/demos/datepicker/#event-onSelect

to make your own actions when a date is picked

and if you want it to open without a form you could create a form that's hidden and then bind a click event to it like this

$("button").click(function() {
    $(inputselector).datepicker('show');
});

How to implement a FSM - Finite State Machine in Java

Here is a SUPER SIMPLE implementation/example of a FSM using just "if-else"s which avoids all of the above subclassing answers (taken from Using Finite State Machines for Pattern Matching in Java, where he is looking for a string which ends with "@" followed by numbers followed by "#"--see state graph here):

public static void main(String[] args) {
    String s = "A1@312#";
    String digits = "0123456789";
    int state = 0;
    for (int ind = 0; ind < s.length(); ind++) {
        if (state == 0) {
            if (s.charAt(ind) == '@')
                state = 1;
        } else {
            boolean isNumber = digits.indexOf(s.charAt(ind)) != -1;
            if (state == 1) {
                if (isNumber)
                    state = 2;
                else if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            } else if (state == 2) {
                if (s.charAt(ind) == '#') {
                    state = 3;
                } else if (isNumber) {
                    state = 2;
                } else if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            } else if (state == 3) {
                if (s.charAt(ind) == '@')
                    state = 1;
                else
                    state = 0;
            }
        }
    } //end for loop

    if (state == 3)
        System.out.println("It matches");
    else
        System.out.println("It does not match");
}

P.S: Does not answer your question directly, but shows you how to implement a FSM very easily in Java.

How to change value of ArrayList element in java

The list is maintaining an object reference to the original value stored in the list. So when you execute this line:

Integer x = i.next();

Both x and the list are storing a reference to the same object. However, when you execute:

x = Integer.valueOf(9);

nothing has changed in the list, but x is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as

list.set(index, Integer.valueof(9))

Note: this has nothing to do with the immutability of Integer, as others are suggesting. This is just basic Java object reference behaviour.


Here's a complete example, to help explain the point. Note that this makes use of the ListIterator class, which supports removing/setting items mid-iteration:

import java.util.*;

public class ListExample {

  public static void main(String[] args) {

    List<Foo> fooList = new ArrayList<Foo>();
    for (int i = 0; i < 9; i++)
      fooList.add(new Foo(i, i));

    // Standard iterator sufficient for altering elements
    Iterator<Foo> iterator = fooList.iterator();

    if (iterator.hasNext()) {
      Foo foo = iterator.next();
      foo.x = 99;
      foo.y = 42;
    }

    printList(fooList);    

    // List iterator needed for replacing elements
    ListIterator<Foo> listIterator = fooList.listIterator();

    if (listIterator.hasNext()) {
      // Need to call next, before set.
      listIterator.next();
      // Replace item returned from next()
      listIterator.set(new Foo(99,99));
    }

    printList(fooList);
  }

  private static void printList(List<?> list) {
    Iterator<?> iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
    System.out.println();
  }

  private static class Foo {
    int x;
    int y;

    Foo(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public String toString() {
      return String.format("[%d, %d]", x, y);
    }
  }
}

This will print:

[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]

Test if remote TCP port is open from a shell script

check ports using bash

Example

$ ./test_port_bash.sh 192.168.7.7 22

the port 22 is open

Code

HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi

Why does z-index not work?

If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

So with following html

_x000D_
_x000D_
div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }_x000D_
#el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }
_x000D_
<div id="el1" style="z-index: 5"></div>_x000D_
<div id="el2" style="z-index: 3">_x000D_
  <div id="el3" style="z-index: 8"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

If you want to check stacking contexts of parent elements, you can use this:

var el = document.getElementById("#yourElement"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex, el);
} while(el.parentElement && (el = el.parentElement));

There is a great article about stacking contexts on MDN

Difference between DataFrame, Dataset, and RDD in Spark

Apache Spark – RDD, DataFrame, and DataSet

Spark RDD

An RDD stands for Resilient Distributed Datasets. It is Read-only partition collection of records. RDD is the fundamental data structure of Spark. It allows a programmer to perform in-memory computations on large clusters in a fault-tolerant manner. Thus, speed up the task.

Spark Dataframe

Unlike an RDD, data organized into named columns. For example a table in a relational database. It is an immutable distributed collection of data. DataFrame in Spark allows developers to impose a structure onto a distributed collection of data, allowing higher-level abstraction.

Spark Dataset

Datasets in Apache Spark are an extension of DataFrame API which provides type-safe, object-oriented programming interface. Dataset takes advantage of Spark’s Catalyst optimizer by exposing expressions and data fields to a query planner.

Static Block in Java

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

How to find if an array contains a specific string in JavaScript/jQuery?

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I experienced the same issues as Harry Johnston has mentioned. rmdir /s /q would complain that a directory was not empty even though /s is meant to do the emptying for you! I think it's a bug in Windows, personally.

My workaround is to del everything in the directory before deleting the directory itself:

del /f /s /q mydir 1>nul
rmdir /s /q mydir

(The 1>nul hides the standard output of del because otherwise, it lists every single file it deletes.)

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

two divs the same line, one dynamic width, one fixed

I'd go with @sandeep's display: table-cell answer if you don't care about IE7.

Otherwise, here's an alternative, with one downside: the "right" div has to come first in the HTML.

See: http://jsfiddle.net/thirtydot/qLTMf/
and exactly the same, but with the "right div" removed: http://jsfiddle.net/thirtydot/qLTMf/1/

#parent {
    overflow: hidden;
    border: 1px solid red
}
.right {
    float: right;
    width: 100px;
    height: 100px;
    background: #888;
}
.left {
    overflow: hidden;
    height: 100px;
    background: #ccc
}
<div id="parent">
    <div class="right">right</div>
    <div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper porta sem, at ultrices ante interdum at. Donec condimentum euismod consequat. Ut viverra lorem pretium nisi malesuada a vehicula urna aliquet. Proin at ante nec neque commodo bibendum. Cras bibendum egestas lacus, nec ullamcorper augue varius eget.</div>
</div>

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

Shell script to capture Process ID and kill it if exist

PID=`ps -ef | grep syncapp 'awk {print $2}'`

if [[ -z "$PID" ]] then
**Kill -9 $PID**
fi

How to embed PDF file with responsive width

Simply do this:

<object data="resume.pdf" type="application/pdf" width="100%" height="800px"> 
  <p>It appears you don't have a PDF plugin for this browser.
   No biggie... you can <a href="resume.pdf">click here to
  download the PDF file.</a></p>  
</object>

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

How to select the nth row in a SQL database table?

Oracle:

select * from (select foo from bar order by foo) where ROWNUM = x

Private class declaration

To answer your question:

If we can have inner private class then why can't we have outer private class...?

You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.

Entity Framework rollback and remove bad migration

I am using EF Core with ASP.NET Core V2.2.6. @Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.

So, For those using EF Core with ASP.NET Core V2.2.6 +...

instead of

Update-Database <Name of last good migration>

I had to use:

dotnet ef database update <Name of last good migration>

And instead of

Remove-Migration

I had to use:

dotnet ef migrations remove

For --help i had to use :

dotnet ef migrations --help


Usage: dotnet ef migrations [options] [command]

Options:
  -h|--help        Show help information
  -v|--verbose     Show verbose output.
  --no-color       Don't colorize output.
  --prefix-output  Prefix output with level.

Commands:
  add     Adds a new migration.
  list    Lists available migrations.
  remove  Removes the last migration.
  script  Generates a SQL script from migrations.

Use "migrations [command] --help" for more information about a command.

This let me role back to the stage where my DB worked as expected, and start from beginning.

How to count the occurrence of certain item in an ndarray?

A general and simple answer would be:

numpy.sum(MyArray==x)   # sum of a binary list of the occurence of x (=0 or 1) in MyArray

which would result into this full code as exemple

import numpy
MyArray=numpy.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])  # array we want to search in
x=0   # the value I want to count (can be iterator, in a list, etc.)
numpy.sum(MyArray==0)   # sum of a binary list of the occurence of x in MyArray

Now if MyArray is in multiple dimensions and you want to count the occurence of a distribution of values in line (= pattern hereafter)

MyArray=numpy.array([[6, 1],[4, 5],[0, 7],[5, 1],[2, 5],[1, 2],[3, 2],[0, 2],[2, 5],[5, 1],[3, 0]])
x=numpy.array([5,1])   # the value I want to count (can be iterator, in a list, etc.)
temp = numpy.ascontiguousarray(MyArray).view(numpy.dtype((numpy.void, MyArray.dtype.itemsize * MyArray.shape[1])))  # convert the 2d-array into an array of analyzable patterns
xt=numpy.ascontiguousarray(x).view(numpy.dtype((numpy.void, x.dtype.itemsize * x.shape[0])))  # convert what you search into one analyzable pattern
numpy.sum(temp==xt)  # count of the searched pattern in the list of patterns

Can I mask an input text in a bat file?

Yes - I am 4 years late.

But I found a way to do this in one line without having to create an external script; by calling powershell commands from a batch file.

Thanks to TessellatingHeckler - without outputting to a text file (I set the powershell command in a variable, because it's pretty messy in one long line inside a for loop).

@echo off
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
echo %password%

Originally I wrote it to output to a text file, then read from that text file. But the above method is better. In one extremely long, near incomprehensible line:

@echo off
powershell -Command $pword = read-host "Enter password" -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt
echo %password%

I'll break this down - you can split it up over a few lines using caret ^, which is much nicer...

@echo off
powershell -Command $pword = read-host "Enter password" -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt 
set /p password=<.tmp.txt & del .tmp.txt
echo %password%

This article explains what the powershell commands are doing; essentially it gets input using Read-Host -AsSecureString - the following two lines convert that secure string back into plain text, the output (plaintext password) is then sent to a text file using >.tmp.txt. That file is then read into a variable and deleted.

Multi-Column Join in Hibernate/JPA Annotations

If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar owns them and Foo uses them to reference Bar) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar so the many-to-one relation doesn't become a many-to-many.

@Embeddable
public class AnEmbeddedObject
{
    @Column(name = "column_1")
    private Long column1;
    @Column(name = "column_2")
    private Long column2;
    @Column(name = "column_3")
    private Long column3;
    @Column(name = "column_4")
    private Long column4;
}

@Entity
public class Foo
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "column_1", referencedColumnName = "column_1"),
        @JoinColumn(name = "column_2", referencedColumnName = "column_2"),
        @JoinColumn(name = "column_3", referencedColumnName = "column_3"),
        @JoinColumn(name = "column_4", referencedColumnName = "column_4")
    })
    private Bar bar;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
    "column_1",
    "column_2",
    "column_3",
    "column_4"
}))
public class Bar
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
    private Long id;
    @Embedded
    private AnEmbeddedObject anEmbeddedObject;
}

Is there a minlength validation attribute in HTML5?

If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:

   // prefix="prefix_text"
   // If the user changes the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
       document.getElementById('myInput').value = prefix;

tr:hover not working

Your best bet is to use

table.YourClass tr:hover td {
background-color: #FEFEFE;
}

Rows aren't fully support for background color but cells are, using the combination of :hover and the child element will yield the results you need.

CSS how to make an element fade in and then fade out?

I found this link to be useful: css-tricks fade-in fade-out css.

Here's a summary of the csstricks post:

CSS classes:

.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
.m-fadeIn {
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

In React:

toggle(){
    if(true condition){
        this.setState({toggleClass: "m-fadeIn"});
    }else{
        this.setState({toggleClass: "m-fadeOut"});
    }
}

render(){
    return (<div className={this.state.toggleClass}>Element to be toggled</div>)
}

Java - How to convert type collection into ArrayList?

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

You can force update your master branch as follows:

git checkout upstreambranch  
git branch master upstreambranch -f    
git checkout master  
git push origin master -f

For the ones who have problem to merge into main branch (Which is the new default one in Github) you can use the following:

git checkout master  
git branch main master -f    
git checkout main  
git push origin main -f

The following command will force both branches to have the same history:

git branch [Branch1] [Branch2] -f 

How to loop and render elements in React.js without an array of objects to map?

You can still use map if you can afford to create a makeshift array:

{
    new Array(this.props.level).fill(0).map((_, index) => (
        <span className='indent' key={index}></span>
    ))
}

This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.

array-fill

Capturing standard out and error with Start-Process

I really had troubles with those examples from Andy Arismendi and from LPG. You should always use:

$stdout = $p.StandardOutput.ReadToEnd()

before calling

$p.WaitForExit()

A full example is:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

Stretch Image to Fit 100% of Div Height and Width

Instead of setting absolute widths and heights, you can use percentages:

#mydiv img {
    height: 100%;
    width: 100%;
}

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

Display text from .txt file in batch file

Here is a good date and time code:

@echo off
if %date:~4,2%==01 set month=January
if %date:~4,2%==02 set month=February
if %date:~4,2%==03 set month=March
if %date:~4,2%==04 set month=April
if %date:~4,2%==05 set month=May
if %date:~4,2%==06 set month=June
if %date:~4,2%==07 set month=July
if %date:~4,2%==08 set month=August
if %date:~4,2%==09 set month=September
if %date:~4,2%==10 set month=October
if %date:~4,2%==11 set month=November
if %date:~4,2%==12 set month=December

if %date:~0,3%==Mon set day=Monday
if %date:~0,3%==Tue set day=Tuesday
if %date:~0,3%==Wed set day=Wednesday
if %date:~0,3%==Thu set day=Thursday
if %date:~0,3%==Fri set day=Friday
if %date:~0,3%==Sat set day=Saturday
if %date:~0,3%==Sun set day=Sunday
echo.
echo The Date is %day%, %month% %date:~7,2%, %date:~10,4% the current time is: %time:~0,5%
pause

Outputs: The Date is Sunday, September 27, 2009 the current time is: 3:07

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

Self-explanatory code follows which first creates a std::tm corresponding to 10-10-2012 12:38:40, converts that to a std::chrono::system_clock::time_point, adds 0.123456 seconds, and then prints that out by converting back to a std::tm. How to handle the fractional seconds is in the very last step.

#include <iostream>
#include <chrono>
#include <ctime>

int main()
{
    // Create 10-10-2012 12:38:40 UTC as a std::tm
    std::tm tm = {0};
    tm.tm_sec = 40;
    tm.tm_min = 38;
    tm.tm_hour = 12;
    tm.tm_mday = 10;
    tm.tm_mon = 9;
    tm.tm_year = 112;
    tm.tm_isdst = -1;
    // Convert std::tm to std::time_t (popular extension)
    std::time_t tt = timegm(&tm);
    // Convert std::time_t to std::chrono::system_clock::time_point
    std::chrono::system_clock::time_point tp = 
                                     std::chrono::system_clock::from_time_t(tt);
    // Add 0.123456 seconds
    // This will not compile if std::chrono::system_clock::time_point has
    //   courser resolution than microseconds
    tp += std::chrono::microseconds(123456);
    
    // Now output tp

    // Convert std::chrono::system_clock::time_point to std::time_t
    tt = std::chrono::system_clock::to_time_t(tp);
    // Convert std::time_t to std::tm (popular extension)
    tm = std::tm{0};
    gmtime_r(&tt, &tm);
    // Output month
    std::cout << tm.tm_mon + 1 << '-';
    // Output day
    std::cout << tm.tm_mday << '-';
    // Output year
    std::cout << tm.tm_year+1900 << ' ';
    // Output hour
    if (tm.tm_hour <= 9)
        std::cout << '0';
    std::cout << tm.tm_hour << ':';
    // Output minute
    if (tm.tm_min <= 9)
        std::cout << '0';
    std::cout << tm.tm_min << ':';
    // Output seconds with fraction
    //   This is the heart of the question/answer.
    //   First create a double-based second
    std::chrono::duration<double> sec = tp - 
                                    std::chrono::system_clock::from_time_t(tt) +
                                    std::chrono::seconds(tm.tm_sec);
    //   Then print out that double using whatever format you prefer.
    if (sec.count() < 10)
        std::cout << '0';
    std::cout << std::fixed << sec.count() << '\n';
}

For me this outputs:

10-10-2012 12:38:40.123456

Your std::chrono::system_clock::time_point may or may not be precise enough to hold microseconds.

Update

An easier way is to just use this date library. The code simplifies down to (using C++14 duration literals):

#include "date.h"
#include <iostream>
#include <type_traits>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    static_assert(std::is_same<decltype(t),
                               time_point<system_clock, microseconds>>{}, "");
    std::cout << t << '\n';
}

which outputs:

2012-10-10 12:38:40.123456

You can skip the static_assert if you don't need to prove that the type of t is a std::chrono::time_point.

If the output isn't to your liking, for example you would really like dd-mm-yyyy ordering, you could:

#include "date.h"
#include <iomanip>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    using namespace std;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    auto dp = floor<days>(t);
    auto time = make_time(t-dp);
    auto ymd = year_month_day{dp};
    cout.fill('0');
    cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
         << '-' << ymd.year() << ' ' << time << '\n';
}

which gives exactly the requested output:

10-10-2012 12:38:40.123456

Update

Here is how to neatly format the current time UTC with milliseconds precision:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}

which just output for me:

2016-10-17 16:36:02.975

C++17 will allow you to replace time_point_cast<milliseconds> with floor<milliseconds>. Until then date::floor is available in "date.h".

std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));

Update C++20

In C++20 this is now simply:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto t = sys_days{10d/10/2012} + 12h + 38min + 40s + 123456us;
    std::cout << t << '\n';
}

Or just:

std::cout << std::chrono::system_clock::now() << '\n';

std::format will be available to customize the output.

How to locate the php.ini file (xampp)

For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder).

Under Linux, most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini.

It can be edited using a normal Text-Editor.

Clarification:

  • Xampp (X (for "some OS"), Apache, MySQL, Perl, PHP)
  • Lampp (Linux, Apache, MySQL, Perl, PHP)

in this context, they can be substituted for one another.

How do I get the coordinate position after using jQuery drag and drop?

Cudos accepted answer is great. However, the Draggable module also has a "drag" event that tells you the position while your dragging. So, in addition to the 'start' and 'stop' you could add the following event within your Draggable object:

    // Drag current position of dragged image.
    drag: function(event, ui) {

        // Show the current dragged position of image
        var currentPos = $(this).position();
        $("div#xpos").text("CURRENT: \nLeft: " + currentPos.left + "\nTop: " + currentPos.top);

    }

What do the terms "CPU bound" and "I/O bound" mean?

An application is CPU-bound when the arithmetic/logical/floating-point (A/L/FP) performance during the execution is mostly near the theoretical peak-performance of the processor (data provided by the manufacturer and determined by the characteristics of the processor: number of cores, frequency, registers, ALUs, FPUs, etc.).

The peek performance is very difficult to be achieved in real-world applications, for not saying impossible. Most of the applications access memory in different parts of the execution and the processor is not doing A/L/FP operations during several cycles. This is called Von Neumann Limitation due to the distance that exists between the memory and the processor.

If you want to be near the CPU peak-performance a strategy could be to try to reuse most of the data in the cache memory in order to avoid requiring data from the main memory. An algorithm that exploits this feature is the matrix-matrix multiplication (if both matrices can be stored in the cache memory). This happens because if the matrices are size n x n then you need to do about 2 n^3 operations using only 2 n^2 FP numbers of data. On the other hand matrix addition, for example, is a less CPU-bound or a more memory-bound application than the matrix multiplication since it requires only n^2 FLOPs with the same data.

In the following figure the FLOPs obtained with a naive algorithms for the matrix addition and the matrix multiplication in an Intel i5-9300H, is shown:

FLOPs comparison between Matrix Addition and Matrix Multiplication

Note that as expected the performance of the matrix multiplication in bigger than the matrix addition. These results can be reproduced by running test/gemm and test/matadd available in this repository.

I suggest also to see the video given by J. Dongarra about this effect.

Compare a string using sh shell

-eq is the shell comparison operator for comparing integers. For comparing strings you need to use =.

Is it possible to refresh a single UITableViewCell in a UITableView?

Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = @[indexPath] for a single object, or Paths = @[indexPath1, indexPath2,...] for multiple objects.

Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)

Just thought I'd throw this into the mix. Hope it helps.

How to grep Git commit diffs or contents for a certain word?

After a lot of experimentation, I can recommend the following, which shows commits that introduce or remove lines containing a given regexp, and displays the text changes in each, with colours showing words added and removed.

git log --pickaxe-regex -p --color-words -S "<regexp to search for>"

Takes a while to run though... ;-)

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

Convert a char to upper case using regular expressions (EditPad Pro)

You can do this in jEdit, by using the "Return value of a BeanShell snippet" option in jEdit's find and replace dialog. Just search for " [a-z]" and replace it by " _0.toUpperCase()" (without quotes)

How to read a file and write into a text file?

If you want to do it line by line:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

Git: list only "untracked" files (also, custom commands)

The accepted answer crashes on filenames with space. I'm at this point not sure how to update the alias command, so I'll put the improved version here:

git ls-files -z -o --exclude-standard | xargs -0 git add

Include PHP inside JavaScript (.js) files

Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.

Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.

Static Js File - Using http://api.jquery.com/jquery.getscript/ or http://api.jquery.com/load/

In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.

some file.php 1:

<?php
$somevar = "Some Dynamic Data";
?>

$('input').val(<?php echo $somevar?>);

or simply echo the script such as

echo "$('input').val(".$somevar.");";

File 2:somejsfile.js:

$("#result").load( "file.php" );

File 3 myhtml.html:

<script src="somejsfile.js"></script>

I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

What's the reason I can't create generic array types in Java?

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

How do you normalize a file path in Bash?

Old question, but there is much simpler way if you are dealing with full path names at the shell level:

   abspath="$( cd "$path" && pwd )"

As the cd happens in a subshell it does not impact the main script.

Two variations, supposing your shell built-in commands accept -L and -P, are:

   abspath="$( cd -P "$path" && pwd -P )"    #physical path with resolved symlinks
   abspath="$( cd -L "$path" && pwd -L )"    #logical path preserving symlinks

Personally, I rarely need this later approach unless I'm fascinated with symbolic links for some reason.

FYI: variation on obtaining the starting directory of a script which works even if the script changes it's current directory later on.

name0="$(basename "$0")";                  #base name of script
dir0="$( cd "$( dirname "$0" )" && pwd )"; #absolute starting dir

The use of CD assures you always have the absolute directory, even if the script is run by commands such as ./script.sh which, without the cd/pwd, often gives just .. Useless if the script does a cd later on.

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

  <img
    src="pond1.jpg"
    alt="pic id code"
    onClick="window.open(this.src)"
    role="button"
    tabIndex="0"
  />

How to remove line breaks from a file in Java?

Try doing this:

 textValue= textValue.replaceAll("\n", "");
 textValue= textValue.replaceAll("\t", "");
 textValue= textValue.replaceAll("\\n", "");
 textValue= textValue.replaceAll("\\t", "");
 textValue= textValue.replaceAll("\r", "");
 textValue= textValue.replaceAll("\\r", "");
 textValue= textValue.replaceAll("\r\n", "");
 textValue= textValue.replaceAll("\\r\\n", "");

How does java do modulus calculations with negative numbers?

The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of

-13 % 64

the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51 -13 - (-64) = -13 + 64 = 51

Java 32-bit vs 64-bit compatibility

The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

os.path.dirname(__file__) returns empty

can be used also like that:

dirname(dirname(abspath(__file__)))

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

How do I allow HTTPS for Apache on localhost?

I use ngrok (https://ngrok.com/) for this. ngrok is a command line tool and create a tunnel for localhost. It creates both http and https connection. After downloading it, following command needs to be run :

ngrok http 80

( In version 2, the syntax is : ngrok http 80 . In version 2, any port can be tunneled. )

After few seconds, it will give two urls :

http://a_hexadecimal_number.ngrok.com
https://a_hexadecimal_number.ngrok.com

Now, both the urls point to the localhost.

How do I create a user account for basic authentication?

in iis manager click directory to protect.

choose authorization rules.

add deny anonymous users rule.

add allow all users rule.

go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.

the directory is now protected. only people with user accounts can access the folder over the web.

When to use IList and when to use List

I don't think there are hard and fast rules for this type of thing, but I usually go by the guideline of using the lightest possible way until absolutely necessary.

For example, let's say you have a Person class and a Group class. A Group instance has many people, so a List here would make sense. When I declare the list object in Group I will use an IList<Person> and instantiate it as a List.

public class Group {
  private IList<Person> people;

  public Group() {
    this.people = new List<Person>();
  }
}

And, if you don't even need everything in IList you can always use IEnumerable too. With modern compilers and processors, I don't think there is really any speed difference, so this is more just a matter of style.

How do I create batch file to rename large number of files in a folder?

You don't need a batch file, just do this from powershell :

powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

How to Set OnClick attribute with value containing function in ie8?

You also can use:

element.addEventListener("click", function(){
    // call execute function here...
}, false);