Programs & Examples On #Jmenupopup

drag drop files into standard html file input

In theory, you could add an element overlaying the <input/>, and then use it's drop event to capture the files (using the File API) and pass them to input files array.

Except that a file input is read-only. This is an old problem.

You can however, bypass the form control completely and upload via XHR (not sure about the support for that):

You could also use an element in the surrounding area to cancel the drop event in Chrome, and prevent the default behaviour of loading the file.

Dropping multiple files over the input already works in Safari and Firefox.

Calling a function from a string in C#

This code works in my console .Net application
class Program
{
    static void Main(string[] args)
    {
        string method = args[0]; // get name method
        CallMethod(method);
    }
    
    public static void CallMethod(string method)
    {
        try
        {
            Type type = typeof(Program);
            MethodInfo methodInfo = type.GetMethod(method);
            methodInfo.Invoke(method, null);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            Console.ReadKey();
        }
    }
    
    public static void Hello()
    {
        string a = "hello world!";
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

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.

ng-model for `<input type="file"/>` (with directive DEMO)

This is an addendum to @endy-tjahjono's solution.

I ended up not being able to get the value of uploadme from the scope. Even though uploadme in the HTML was visibly updated by the directive, I could still not access its value by $scope.uploadme. I was able to set its value from the scope, though. Mysterious, right..?

As it turned out, a child scope was created by the directive, and the child scope had its own uploadme.

The solution was to use an object rather than a primitive to hold the value of uploadme.

In the controller I have:

$scope.uploadme = {};
$scope.uploadme.src = "";

and in the HTML:

 <input type="file" fileread="uploadme.src"/>
 <input type="text" ng-model="uploadme.src"/>

There are no changes to the directive.

Now, it all works like expected. I can grab the value of uploadme.src from my controller using $scope.uploadme.

SOAP vs REST (differences)

First of all: officially, the correct question would be web services + WSDL + SOAP vs REST.

Because, although the web service, is used in the loose sense, when using the HTTP protocol to transfer data instead of web pages, officially it is a very specific form of that idea. According to the definition, REST is not "web service".

In practice however, everyone ignores that, so let's ignore it too

There are already technical answers, so I'll try to provide some intuition.

Let's say you want to call a function in a remote computer, implemented in some other programming language (this is often called remote procedure call/RPC). Assume that function can be found at a specific URL, provided by the person who wrote it. You have to (somehow) send it a message, and get some response. So, there are two main questions to consider.

  • what is the format of the message you should send
  • how should the message be carried back and forth

For the first question, the official definition is WSDL. This is an XML file which describes, in detailed and strict format, what are the parameters, what are their types, names, default values, the name of the function to be called, etc. An example WSDL here shows that the file is human-readable (but not easily).

For the second question, there are various answers. However, the only one used in practice is SOAP. Its main idea is: wrap the previous XML (the actual message) into yet another XML (containing encoding info and other helpful stuff), and send it over HTTP. The POST method of the HTTP is used to send the message, since there is always a body.

The main idea of this whole approach is that you map a URL to a function, that is, to an action. So, if you have a list of customers in some server, and you want to view/update/delete one, you must have 3 URLS:

  • myapp/read-customer and in the body of the message, pass the id of the customer to be read.
  • myapp/update-customer and in the body, pass the id of the customer, as well as the new data
  • myapp/delete-customer and the id in the body

The REST approach sees things differently. A URL should not represent an action, but a thing (called resource in the REST lingo). Since the HTTP protocol (which we are already using) supports verbs, use those verbs to specify what actions to perform on the thing.

So, with the REST approach, customer number 12 would be found on URL myapp/customers/12. To view the customer data, you hit the URL with a GET request. To delete it, the same URL, with a DELETE verb. To update it, again, the same URL with a POST verb, and the new content in the request body.

For more details about the requirements that a service has to fulfil to be considered truly RESTful, see the Richardson maturity model. The article gives examples, and, more importantly, explains why a (so-called) SOAP service, is a level-0 REST service (although, level-0 means low compliance to this model, it's not offensive, and it is still useful in many cases).

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

This error can be seen for a number of reasons:

  1. As mentioned above, starting the parenthesis on a new line.

Error:

render() {
  return  
  (
    <div>I am demo data</div>
  )
}

Correct way to implement render:

render() {
  return (
    <div>I am demo html</div>
  );
}

In the above example, the semicolon at the end of the return statement will not make any difference.

  1. It can also be caused due to the wrong brackets used in the routing:

Error:

export default () => {
  <BrowserRouter>
    <Switch>
      <Route exact path='/' component={ DemoComponent } />
    </Switch>
  </BrowserRouter>
}

Correct way:

export default () => (
  <BrowserRouter>
    <Switch>
      <Route exact path='/' component={ DemoComponent } />
    </Switch>
  </BrowserRouter>
)

In the error example, we have used curly braces but we have to use round brackets instead. This also gives the same error.

Where to place the 'assets' folder in Android Studio?

right click on app folder->new->folder->Assets folder->set Target Source set->click on finish button

"undefined" function declared in another file?

I ran into the same issue with Go11, just wanted to share how I did solve it for helping others just in case they run into the same issue.

I had my Go project outside $GOPATH, so I had to turned on GO111MODULE=on without this option turned on, it will give you this issue; even if you you try to build or test the whole package or directory it won't be solved without GO111MODULE=on

Java parsing XML document gives "Content not allowed in prolog." error

You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

Razor MVC Populating Javascript array with Model Array

The valid syntax with named fields:

  var array = [];

     @foreach (var item in model.List)
     {
        @:array.push({ 
                       "Project": "@item.Project",
                       "ProjectOrgUnit": "@item.ProjectOrgUnit"
                     });
     }

Curl not recognized as an internal or external command, operable program or batch file

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

How to center a component in Material-UI and make it responsive?

All you have to do is wrap your content inside a Grid Container tag, specify the spacing, then wrap the actual content inside a Grid Item tag.

 <Grid container spacing={24}>
    <Grid item xs={8}>
      <leftHeaderContent/>
    </Grid>

    <Grid item xs={3}>
      <rightHeaderContent/>
    </Grid>
  </Grid>

Also, I've struggled with material grid a lot, I suggest you checkout flexbox which is built into CSS automatically and you don't need any addition packages to use. Its very easy to learn.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Form Submission without page refresh

Just catch the submit event and prevent that, then do ajax

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

How to get value of a div using javascript

You can try this:

var theValue = document.getElementById("demo").getAttribute("value");

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

How to loop over a Class attributes in Java?

Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.

Why does multiplication repeats the number several times?

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

Convert binary to ASCII and vice versa

This is my way to solve your task:

str = "0b110100001100101011011000110110001101111"
str = "0" + str[2:]
message = ""
while str != "":
    i = chr(int(str[:8], 2))
    message = message + i
    str = str[8:]
print message

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.

C++ create string of text and variables

You can also use sprintf:

char str[1024];
sprintf(str, "somtext %s sometext %s", somevar, somevar);

Date format in dd/MM/yyyy hh:mm:ss

CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)

RETURNS VARCHAR(24) 
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END

Import text file as single character string

It seems your solution is not much ugly. You can use functions and make it proffesional like these ways

  • first way
new.function <- function(filename){
  readChar(filename, file.info(filename)$size)
}

new.function('foo.txt')
  • second way
new.function <- function(){
  filename <- 'foo.txt'
  return (readChar(filename, file.info(filename)$size))
}

new.function()

What does a lazy val do?

I understand that the answer is given but I wrote a simple example to make it easy to understand for beginners like me:

var x = { println("x"); 15 }
lazy val y = { println("y"); x + 1 }
println("-----")
x = 17
println("y is: " + y)

Output of above code is:

x
-----
y
y is: 18

As it can be seen, x is printed when it's initialized, but y is not printed when it's initialized in same way (I have taken x as var intentionally here - to explain when y gets initialized). Next when y is called, it's initialized as well as value of last 'x' is taken into consideration but not the old one.

Hope this helps.

Maintain model of scope when changing between views in AngularJS

Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons

UI Router & UI Router Extras

These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.

Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.

Pandas "Can only compare identically-labeled DataFrame objects" error

You can also try dropping the index column if it is not needed to compare:

print(df1.reset_index(drop=True) == df2.reset_index(drop=True))

I have used this same technique in a unit test like so:

from pandas.util.testing import assert_frame_equal

assert_frame_equal(actual.reset_index(drop=True), expected.reset_index(drop=True))

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

Auto reloading python Flask app upon code changes

Use this method:

app.run(debug=True)

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
   return "Hello World"


if __name__ == '__main__':
  app.run(debug=True)

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.

Cannot call getSupportFragmentManager() from activity

This worked for me. Running android API 19 and above.

FragmentManager fragMan = getFragmentManager();

Is there any WinSCP equivalent for linux?

Just use gnome, just type in the address and away you go!

Using ping in c#

private async void Ping_Click(object sender, RoutedEventArgs e)
{
    Ping pingSender = new Ping();
    string host = @"stackoverflow.com";
    await Task.Run(() =>{
         PingReply reply = pingSender.Send(host);
         if (reply.Status == IPStatus.Success)
         {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
         }
         else
         {
            Console.WriteLine("Address: {0}", reply.Status);
         }
   });           
}

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

nodejs get file name from absolute path?

To get the file name portion of the file name, the basename method is used:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);

console.log(file); // 'python.exe'

If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);

console.log(file); // 'python'

Content Type text/xml; charset=utf-8 was not supported by service

In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:29495/IntegrationService.asmx"
                binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
                contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>

Both my client and server use basicHttpBinding. I hope this helps the others :)

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

range() for floats

Eagerly evaluated (2.x range):

[x * .5 for x in range(10)]

Lazily evaluated (2.x xrange, 3.x range):

itertools.imap(lambda x: x * .5, xrange(10)) # or range(10) as appropriate

Alternately:

itertools.islice(itertools.imap(lambda x: x * .5, itertools.count()), 10)
# without applying the `islice`, we get an infinite stream of half-integers.

Android - SMS Broadcast receiver

I tried your code and found it wasn't working.

I had to change

if (intent.getAction() == SMS_RECEIVED) {

to

if (intent.getAction().equals(SMS_RECEIVED)) {

Now it's working. It's just an issue with java checking equality.

What are the differences between struct and class in C++?

While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.

This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).

Converting a date in MySQL from string field

This:

STR_TO_DATE(t.datestring, '%d/%m/%Y')

...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:

DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')

If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE call to convert the string to a DateTime data type.

What is the total amount of public IPv4 addresses?

Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).

How to parse JSON to receive a Date object in JavaScript?

//
// formats a .net date into a javascript compatible date
//
function FormatJsonDate(jsonDt) 
{              
    var MIN_DATE = -62135578800000; // const

    var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));                                                       
    return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear(); 
}

Can I use GDB to debug a running process?

Yes you can. Assume a process foo is running...

ps -elf | grep foo

look for the PID number

gdb -a {PID number}

How to compile and run C/C++ in a Unix console/Mac terminal?

For running c++ files run below command, Assuming file name is "main.cpp"

1.Compile to make object file from c++ file.

g++ -c main.cpp -o main.o

2.Since #include <conio.h> does not support in MacOS so we should use its alternative which supports in Mac that is #include <curses.h>. Now object file needs to be converted to executable file. To use curses.h we have to use library -lcurses.

g++ -o main main.o -lcurses

3.Now run the executable.

./main

How can I mix LaTeX in with Markdown?

Hey, this might not be the most ideal solution, but it works for me. I ended up creating a Python-Markdown LaTeX extension.

https://github.com/justinvh/Markdown-LaTeX

It adds support for inline math and text expressions using a $math$ and %text% syntax. The extension is a preprocessor that will use latex/dvipng to generate pngs for the respective equations/text and then base64 encode the data to inline the images directly, rather than have external images.

The data is then put in a simple-delimited cache file that encodes the expression to the base64 representation. This limits the number of times latex actually has to be run.

Here is an example:

%Hello, world!% This is regular text, but this: $y = mx + b$ is not.

The output:

$ markdown -x latex test.markdown
<p><img class='latex-inline math-false' alt='Hello, world!' id='Helloworld' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAAAQBAMAAABpWwV8AAAAMFBMVEX///8iIiK6urpUVFTu7u6YmJgQEBDc3NxERESqqqqIiIgyMjJ2dnZmZmbMzMwAAAAbX03YAAAAAXRSTlMAQObYZgAAAVpJREFUKM9jYICDOgb2BwzYAVji8AQg8fb/PZ79u4AMvv0Mrz/gUA6W8F7AmcLAsJuBYT7Y1PcMfLiUgyWYF/B8Z2DYAVReABKrZ2DHpZwdopzrA0nKOeHKj66CKOcKPQJWwJo2NVFhfwCQyymhYwCUYD0avIApgYFh2927/QUcE3gDwMpvMhRCDJzNMIPhKZg7UW8DUOIMg9sCPgGo6e8ZODeAlAP9xLEArNy/IIwhAMx9D3IM+3cgi70BqnxZaNQFkHJWAQbeBrByjgURExaAuc9AyjnB5hjAlEO9ygVXzrplpskEMPchQvkBmGMcGApgjjkAVs7yhyWVAcwFK2f/AlJeAI0m5gMsEK+aMhQ6aDuA1DcDIZirBg7IOwxlB5g2QBJBF8OZVUz95hqfC3hOXWGYrwBSHskwk4EByGXab8QAlOBaGizFKYAtUlgUGEgBTCSpZnDCLQUA+y6MXeYnPDgAAAAASUVORK5CYII='> This is regular text, but this: <img class='latex-inline math-true' alt='y = mx + b' id='ymxb' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFIAAAAOBAMAAABOTlYkAAAAMFBMVEX///9ERETu7u4yMjK6urp2dnZUVFSIiIjMzMwQEBDc3NwiIiJmZmaYmJiqqqoAAADS00rKAAAAAXRSTlMAQObYZgAAAOtJREFUKM9jYCAACsCk4wYGgiABTLInEKuS+QGxKvkVGBj47jBwI8tcffI84e45BoZ7GVcLECo9751iWLeSoRPITBQEggMMDBy9sxj2MDgz8DIE8yCpPMxwjWFBGUMMkpFcbAEMvxjKGLgYxIE8NkHBiYIyQMY+hmoGhi0Mdsi2czawbGCQBTJ+ILvzE0MaA9MHIIWwnWE9A+sBpk8LGDgmMCnAVXJNYPgCJHhRQvUiA/cDXoECZx4DXoSZTBtYgaaEPw5AVnkOGBRc5xTcbsReQrL9+nWwyxbgC88DcJZ+QygDcYD1+QPiFAIAtLA8KPZOGFEAAAAASUVORK5CYII='> is not.</p>

As you can see it is a verbose output, but that really isn't an issue since you're already using Markdown :)

Getting a timestamp for today at midnight?

In more object way:

$today = new \DateTimeImmutable('today');

example:

 echo (new \DateTimeImmutable('today'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 00:00:00

and:

echo (new \DateTimeImmutable())->format('Y-m-d H:i:s');
echo (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 14:00:35

.htaccess deny from all

Deny from all 

is an .htaccess command(the actual content of that file you are trying to view). Not a denial of being able to edit the file. Just reopen the .htaccess file in the text viewer of choice and make the alterations as you so desire, save it, then reupload it to your folder of choice.

Though I think inadvertently you are blocking even yourself from viewing said application once uploaded.

I would do something like:

order deny,allow
deny from all
allow from 127.0.0.1

which will deny everyone but the IP in the allow from line, which you would change the IP to match your IP which you can obtain from http://www.whatismyip.com/ or similar site.

better way to drop nan rows in pandas

Just in case commands in previous answers doesn't work, Try this: dat.dropna(subset=['x'], inplace = True)

How to get the current user's Active Directory details in C#

Alan already gave you the right answer - use the sAMAccountName to filter your user.

I would add a recommendation on your use of DirectorySearcher - if you only want one or two pieces of information, add them into the "PropertiesToLoad" collection of the DirectorySearcher.

Instead of retrieving the whole big user object and then picking out one or two items, this will just return exactly those bits you need.

Sample:

adSearch.PropertiesToLoad.Add("sn");  // surname = last name
adSearch.PropertiesToLoad.Add("givenName");  // given (or first) name
adSearch.PropertiesToLoad.Add("mail");  // e-mail addresse
adSearch.PropertiesToLoad.Add("telephoneNumber");  // phone number

Those are just the usual AD/LDAP property names you need to specify.

How can I add a hint or tooltip to a label in C# Winforms?

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip( Label1, "Label for Label1");

How often should you use git-gc?

Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.

So don’t be too much of a neat freak in your private clones. There’s little need for it.

OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.

How do you test your Request.QueryString[] variables?

Use int.TryParse instead to get rid of the try-catch block:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

When to use static classes in C#

If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.

It is more of a guideline than a rule, really...

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

Windows.history.back() + location.reload() jquery

window.history.back(); Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.

I would use this below function for go back with the refresh.

function GoBackWithRefresh(event) {
    if ('referrer' in document) {
        window.location = document.referrer;
        /* OR */
        //location.replace(document.referrer);
    } else {
        window.history.back();
    }
}

In your html, use:

<a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>`

For more customization you can use history.js plugins.

How do I display a ratio in Excel in the format A:B?

You are looking for the greatest common divisor (GCD).

You can calculate it recursively in VBA, like this:

Function GCD(numerator As Integer, denominator As Integer)
  If denominator = 0 Then
    GCD = numerator
  Else
    GCD = GCD(denominator, numerator Mod denominator)
  End If
End Function

And use it in your sheet like this:

   ColumnA   ColumnB   ColumnC
1  33        11        =A1/GCD(A1; B1) & ":" & B1/GCD(A1; B1)
2  25         5        =A2/GCD(A2; B2) & ":" & B2/GCD(A2; B2)

It is recommendable to store the result of the function call in a hidden column and use this result to avoid calling the function twice per row:

   ColumnA   ColumnB   ColumnC        ColumnD
1  33        11        =GCD(A1; B1)   =A1/C1 & ":" & B1/C1
2  25         5        =GCD(A2; B2)   =A2/C2 & ":" & B2/C2

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

The hash solution is nice but not really human readable when you want to know what version of file is sitting in your local web folder. The solution is to date/time stamp your version so you can easily compare it against your server file.

For example, if your .js or .css file is dated 2011-02-08 15:55:30 (last modification) then the version should equal to .js?v=20110208155530

Should be easy to read properties of any file in any language. In ASP.Net it's really easy...

".js?v=" + File.GetLastWriteTime(HttpContext.Current.Request.PhysicalApplicationPath + filename).ToString("yyMMddHHHmmss");

Of coz get it nicely refactored into properties/functions first and off you go. No more excuses.

Good luck, Art.

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

Run bash command on jenkins pipeline

If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:

Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)

Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

Close all infowindows in Google Maps API v3

I had a dynamic loop that was creating the infowindows and markers based on how many were input into the CMS, so I didn't want to create a new InfoWindow() on every event click and bog it down with requests, if that ever arose. Instead, I tried to know what the specific infowindow variable for each instance was going to be out of the set amount of locations I had, and then prompt Maps to close all of them before it opened the correct one.

My array of locations was called locations, so the PHP I set up before the actual maps initilization to get my infowindow variable names was:

for($k = 0; $k < count($locations); $k++) {
        $infowindows[] = 'infowindow' . $k; 
} 

Then after initialzing the map and so forth, in the script I had a PHP foreach loop creating the dynamic info windows using a counter:

//...javascript map initilization
<?php 
$i=0;
foreach($locations as $location) {

    ..//get latitudes, longitude, image, etc...

echo 'var mapMarker' . $i . ' = new google.maps.Marker({
          position: myLatLng' . $i . ',
          map: map,
          icon: image
      });';

echo 'var contentString' . $i . ' = "<h1>' . $title[$i] . '</h1><h2>' . $address[$i] . '</h2>' . $content[$i] .         '";'; 
echo 'infowindow' . $i . ' = new google.maps.InfoWindow({ ';
echo '    content: contentString' . $i . '
          });';

echo 'google.maps.event.addListener(mapMarker' . $i . ', "click", function() { ';   
    foreach($infowindows as $window) {  
        echo $window . '.close();'; 
    }
        echo 'infowindow' . $i . '.open(map,mapMarker'. $i . ');
      });';

$i++; 
}
?>
...//continue with Maps script... 

So, the point is, before I called the entire map script, I had an array with the names I knew were going to be outputted when an InfoWindow() was created, like infowindow0, infowindow1, infowindow2, etc...

Then, on the click event for each marker, the foreach loop goes through and says close all of them before you follow through with the next step of opening them. It turns out looking like this:

google.maps.event.addListener(mapMarker0, "click", function() {
    infowindow0.close();
    infowindow1.close();
    infowindow2.close();
    infowindow0.open(map,mapMarker0);
}

Just a different way of doing things I suppose... but I hope it helps someone.

How to export library to Jar in Android Studio?

Here's yet another, slightly different answer with a few enhancements.

This code takes the .jar right out of the .aar. Personally, that gives me a bit more confidence that the bits being shipped via .jar are the same as the ones shipped via .aar. This also means that if you're using ProGuard, the output jar will be obfuscated as desired.

I also added a super "makeJar" task, that makes jars for all build variants.

task(makeJar) << {
    // Empty. We'll add dependencies for this task below
}

// Generate jar creation tasks for all build variants
android.libraryVariants.all { variant ->
    String taskName = "makeJar${variant.name.capitalize()}"

    // Create a jar by extracting it from the assembled .aar
    // This ensures that products distributed via .aar and .jar exactly the same bits
    task (taskName, type: Copy) {
        String archiveName = "${project.name}-${variant.name}"
        String outputDir = "${buildDir.getPath()}/outputs"

        dependsOn "assemble${variant.name.capitalize()}"
        from(zipTree("${outputDir}/aar/${archiveName}.aar"))
        into("${outputDir}/jar/")
        include('classes.jar')
        rename ('classes.jar', "${archiveName}-${variant.mergedFlavor.versionName}.jar")
    }

    makeJar.dependsOn tasks[taskName]
}

For the curious reader, I struggled to determine the correct variables and parameters that the com.android.library plugin uses to name .aar files. I finally found them in the Android Open Source Project here.

How do I 'foreach' through a two-dimensional array?

Using LINQ you can do it like this:

var table_enum = table

    // Convert to IEnumerable<string>
    .OfType<string>()

    // Create anonymous type where Index1 and Index2
    // reflect the indices of the 2-dim. array
    .Select((_string, _index) => new {
        Index1 = (_index / 2),
        Index2 = (_index % 2), // ? I added this only for completeness
        Value = _string
    })

    // Group by Index1, which generates IEnmurable<string> for all Index1 values
    .GroupBy(v => v.Index1)

    // Convert all Groups of anonymous type to String-Arrays
    .Select(group => group.Select(v => v.Value).ToArray());

// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
    // …
}

This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.

Why am I getting "Thread was being aborted" in ASP.NET?

ASP.NET spawns and kills worker processes all the time as needed. Your thread may just be getting shut down by ASP.NET.

Old Answer:

Known issue: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Response.Redirect ("bla.aspx", false);

or

try
{
    Response.Redirect("bla.aspx");
}
catch (ThreadAbortException ex)
{
}

Reading in from System.in - Java

In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

After this statement executes, br is a character-based stream that is linked to the console through System.in.

This is taken from the book Java- The Complete Reference by Herbert Schildt

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

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

How to add a "confirm delete" option in ASP.Net Gridview?

I love the JavaScript solution and have some updates to work with dynamic ajax loading:

     $(document).on("click", "a", function () {
        if (this.innerHTML.indexOf("Delete") == 0) {
            return confirm("Are you sure you want to delete this record?");
        }
    });

Hope it help ;)

How to get a random number between a float range?

random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.

How to select data of a table from another database in SQL Server?

Try using OPENDATASOURCE The syntax is like this:

select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable    

How to make parent wait for all child processes to finish?

POSIX defines a function: wait(NULL);. It's the shorthand for waitpid(-1, NULL, 0);, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid indicates wait for any child process to end.

In your case, have the parent call it from within your else branch.

Download File Using Javascript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();

How can I view live MySQL queries?

Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';

The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.

You can also add conditions to make it more specific just any SQL query.

e.g. Shows all queries running for 5 seconds or more:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;

e.g. Show all running UPDATEs:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';

For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html

Updating a java map entry

You just use the method

public Object put(Object key, Object value)

if the key was already present in the Map then the previous value is returned.

IOS: verify if a point is inside a rect

I'm starting to learn how to code with Swift and was trying to solve this too, this is what I came up with on Swift's playground:

// Code
var x = 1
var y = 2
var lowX = 1
var lowY = 1
var highX = 3
var highY = 3


if (x, y) >= (lowX, lowY) && (x, y) <= (highX, highY ) {
    print("inside")
} else {
    print("not inside")
}

It prints inside

Convert a tensor to numpy array in Tensorflow?

You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.

new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();

simply add wait();

and them in the OnClickListener start the class again with notify() something like this

@Override
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
        **notify**();
        dialog.cancel();
    }

the same workaround goes 4 toasts and other async calls in android

Is it possible to save HTML page as PDF using JavaScript or jquery?

You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

Example code:

phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf

How to create a new schema/new user in Oracle Database 11g?

SQL> select Username from dba_users
  2  ;

USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS

USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

16 rows selected.

SQL> create user testdb identified by password;

User created.

SQL> select username from dba_users;

USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL

USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

17 rows selected.

SQL> grant create session to testdb;

Grant succeeded.

SQL> create tablespace testdb_tablespace
  2  datafile 'testdb_tabspace.dat'
  3  size 10M autoextend on;

Tablespace created.

SQL> create temporary tablespace testdb_tablespace_temp
  2  tempfile 'testdb_tabspace_temp.dat'
  3  size 5M autoextend on;

Tablespace created.

SQL> drop user testdb;

User dropped.

SQL> create user testdb
  2  identified by password
  3  default tablespace testdb_tablespace
  4  temporary tablespace testdb_tablespace_temp;

User created.

SQL> grant create session to testdb;

Grant succeeded.

SQL> grant create table to testdb;

Grant succeeded.

SQL> grant unlimited tablespace to testdb;

Grant succeeded.

SQL>

POST data with request module on Node.JS

I highly recommend axios https://www.npmjs.com/package/axios install it with npm or yarn

const axios = require('axios');

axios.get('http://your_server/your_script.php')
    .then( response => {
    console.log('Respuesta', response.data);
    })
    .catch( response => {
        console.log('Error', response);
    })
    .finally( () => {
        console.log('Finalmente...');
    });

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

   <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter device name"
        android:maxLength="10"
        android:inputType="textFilter"
        android:singleLine="true"/>

InputType has to set "textFilter"

        android:inputType="textFilter"

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Easy pretty printing of floats in python?

To control the number of significant digits, use the format specifier %g.

Let's name Emile's solution prettylist2f. Here is the modified one:

prettylist2g = lambda l : '[%s]' % ', '.join("%.2g" % x for x in l)

Usage:

>>> c_e_alpha_eps0 = [299792458., 2.718281828, 0.00729735, 8.8541878e-12]
>>> print(prettylist2f(c_e_alpha_eps0)) # [299792458.00, 2.72, 0.01, 0.00]
>>> print(prettylist2g(c_e_alpha_eps0)) # [3e+08, 2.7, 0.0073, 8.9e-12]

If you want flexibility in the number of significant digits, use f-string formatting instead:

prettyflexlist = lambda p, l : '[%s]' % ', '.join(f"{x:.{p}}" for x in l)
print(prettyflexlist(3,c_e_alpha_eps0)) # [3e+08, 2.72, 0.0073, 8.85e-12]

C++ int float casting

You are performing calculations on integers and assigning its result to float. So compiler is implicitly converting your integer result into float

Loop inside React JSX

If numrows is an array, as the other answers, the best way is the map method. If it's not and you only access it from JSX, you can also use this ES6 method:

<tbody>
    {
      [...Array(numrows).fill(0)].map((value,index)=><ObjectRow key={index} />)
    }
</tbody>

Why is semicolon allowed in this python snippet?

Python uses the ; as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.

How to check if ping responded or not in a batch file

I've seen three results to a ping - The one we "want" where the IP replies, "Host Unreachable" and "timed out" (not sure of exact wording).

The first two return ERRORLEVEL of 0.

Timeout returns ERRORLEVEL of 1.

Are the other results and error levels that might be returned? (Besides using an invalid switch which returns the allowable switches and an errorlevel of 1.)

Apparently Host Unreachable can use one of the previously posted methods (although it's hard to figure out when someone replies which case they're writing code for) but does the timeout get returned in a similar manner that it can be parsed?

In general, how does one know what part of the results of the ping can be parsed? (Ie, why might Sent and/or Received and/or TTL be parseable, but not host unreachable?

Oh, and iSid, maybe there aren't many upvotes because the people that read this don't have enough points. So they get their question answered (or not) and leave.

I wasn't posting the above as an answer. It should have been a comment but I didn't see that choice.

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Node.js: Gzip compression?

Generally speaking, for a production web application, you will want to put your node.js app behind a lightweight reverse proxy such as nginx or lighttpd. Among the many benefits of this setup, you can configure the reverse proxy to do http compression or even tls compression, without having to change your application source code.

Throughput and bandwidth difference?

In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".

All you need to know in MOST cases is this:

"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.

Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.

Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.

Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.

So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).

Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.

A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.

To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).

For whatever it's worth.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

I faced the same problem but I successfully solved the problem by changing the version of compileSdkVersion to the latest which is 29 and change the version of targetSdkVersion to the latest which is 29.

Go to the gradile.build file and change the compilesdkversion and targetsdkversion.

CSS table layout: why does table-row not accept a margin?

There is a pretty simple fix for this, the border-spacing and border-collapse CSS attributes work on display: table.

You can use the following to get padding/margins in your cells.

_x000D_
_x000D_
.container {_x000D_
  width: 850px;_x000D_
  padding: 0;_x000D_
  display: table;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 15px;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.home_1 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_2 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_3 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_4 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
    <div class="home_3">Foo</div>_x000D_
    <div class="home_4">Foo</div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you have to have

border-collapse: separate;

Otherwise it will not work.

Is there a way to make a DIV unselectable?

Use

onselectstart="return false"

it prevents copying your content.

How to get char from string by index?

Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Create Carriage Return in PHP String?

PHP_EOL returns a string corresponding to the line break on the platform(LF, \n ou #10 sur Unix, CRLF, \n\r ou #13#10 sur Windows).

echo "Hello World".PHP_EOL;

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

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

AppStore - App status is ready for sale, but not in app store

I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.

For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.

The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.

After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.

Then, I unchecked the countries the App is available on and checked them all again and hit Save.

The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.

I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).

Difference between npx and npm?

Here's an example of NPX in action: npx cowsay hello

If you type that into your bash terminal you'll see the result. The benefit of this is that npx has temporarily installed cowsay. There is no package pollution since cowsay is not permanently installed. This is great for one off packages where you want to avoid package pollution.

As mentioned in other answers, npx is also very useful in cases where (with npm) the package needs to be installed then configured before running. E.g. instead of using npm to install and then configure the json.package file and then call the configured run command just use npx instead. A real example: npx create-react-app my-app

What do two question marks together mean in C#?

As correctly pointed in numerous answers that is the "null coalescing operator" (??), speaking of which you might also want to check out its cousin the "Null-conditional Operator" (?. or ?[) that is an operator that many times it is used in conjunction with ??

Null-conditional Operator

Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

For example:

// if 'customers' or 'Order' property or 'Price' property  is null,
// dollarAmount will be 0 
// otherwise dollarAmount will be equal to 'customers.Order.Price'

int dollarAmount = customers?.Order?.Price ?? 0; 

the old way without ?. and ?? of doing this is

int dollarAmount = customers != null 
                   && customers.Order!=null
                   && customers.Order.Price!=null 
                    ? customers.Order.Price : 0; 

which is more verbose and cumbersome.

How can I stop the browser back button using JavaScript?

I create one HTML page (index.html). I also create a one (mechanism.js) inside a script folder / directory. Then, I lay all my content inside of (index.html) using form, table, span, and div tags as needed. Now, here's the trick that will make back / forward do nothing!

First, the fact that you have only one page! Second, the use of JavaScript with span / div tags to hide and display content on the same page when needed via regular links!

Inside 'index.html':

<td width="89px" align="right" valign="top" style="letter-spacing:1px;">
    <small>
        <b>
            <a href="#" class="traff" onClick="DisplayInTrafficTable();">IN</a>&nbsp;
        </b>
    </small>
    [&nbsp;<span id="inCountSPN">0</span>&nbsp;]
</td>

Inside 'mechanism.js':

function DisplayInTrafficTable()
{
    var itmsCNT = 0;
    var dsplyIn = "";
    for (i=0; i<inTraffic.length; i++)
    {
        dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
    }
    document.getElementById('inOutSPN').innerHTML =
        "" +
        "<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" +
        DateStamp() +
        "&nbsp;&nbsp;-&nbsp;&nbsp;<small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" +
        dsplyIn.toUpperCase() +
        "</table>" +
        "";
    return document.getElementById('inOutSPN').innerHTML;
}

It looks hairy, but note the function names and calls, embedded HTML, and the span tag id calls. This was to show how you can inject different HTML into same span tag on same page! How can Back/Forward affect this design? It cannot, because you are hiding objects and replacing others all on the same page!

How can we hide and display? Here goes:

Inside functions in ' mechanism.js ' as needed, use:

document.getElementById('textOverPic').style.display = "none"; //hide
document.getElementById('textOverPic').style.display = "";     //display

Inside ' index.html ' call functions through links:

<img src="images/someimage.jpg" alt="" />
<span class="textOverPic" id="textOverPic"></span>

and

<a href="#" style="color:#119;font-size:11px;text-decoration:none;letter-spacing:1px;" onclick="HiddenTextsManager(1);">Introduction</a>

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

How do I crop an image in Java?

You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package.

For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel.

Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged method...

For a mousedragged action, you will get the coordinate of the rectangle form by the drag...

Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....

And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!

How do I set a checkbox in razor view?

You should set the AllowRating property to true, preferably in the controller or model.
Like other inputs, the checkbox's state reflects the value of the property.

how to use the Box-Cox power transformation in R

If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:

library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)

Can you have multiline HTML5 placeholder text in a <textarea>?

React:

If you are using React, you can do it as follows:

placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}

Fastest way to iterate over all the chars in a String

Despite @Saint Hill's answer if you consider the time complexity of str.toCharArray(),

the first one is faster even for very large strings. You can run the code below to see it for yourself.

        char [] ch = new char[1_000_000_00];
    String str = new String(ch); // to create a large string

    // ---> from here
    long currentTime = System.nanoTime();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = str.charAt(i);
    }
    // ---> to here
    System.out.println("str.charAt(i):"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

    /**
     *   ch = str.toCharArray() itself takes lots of time   
     */
    // ---> from here
    currentTime = System.nanoTime();
    ch = str.toCharArray();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = ch[i];
    }
    // ---> to  here
    System.out.println("ch = str.toCharArray() + c = ch[i] :"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

output:

str.charAt(i):5.492102 (ms)
ch = str.toCharArray() + c = ch[i] :79.400064 (ms)

How to make VS Code to treat other file extensions as certain language?

This, for example, will make files ending in .variables and .overrides being treated just like any other LESS file. In terms of code coloring, in terms of (auto) formatting. Define in user settings or project settings, as you like.

(Semantic UI uses these weird extensions, in case you wonder)

Use grep to report back only line numbers

try:

grep -n "text to find" file.ext | cut -f1 -d:

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

As the creator of ElasticSearch, maybe I can give you some reasoning on why I went ahead and created it in the first place :).

Using pure Lucene is challenging. There are many things that you need to take care for if you want it to really perform well, and also, its a library, so no distributed support, it's just an embedded Java library that you need to maintain.

In terms of Lucene usability, way back when (almost 6 years now), I created Compass. Its aim was to simplify using Lucene and make everyday Lucene simpler. What I came across time and time again is the requirement to be able to have Compass distributed. I started to work on it from within Compass, by integrating with data grid solutions like GigaSpaces, Coherence, and Terracotta, but it's not enough.

At its core, a distributed Lucene solution needs to be sharded. Also, with the advancement of HTTP and JSON as ubiquitous APIs, it means that a solution that many different systems with different languages can easily be used.

This is why I went ahead and created ElasticSearch. It has a very advanced distributed model, speaks JSON natively, and exposes many advanced search features, all seamlessly expressed through JSON DSL.

Solr is also a solution for exposing an indexing/search server over HTTP, but I would argue that ElasticSearch provides a much superior distributed model and ease of use (though currently lacking on some of the search features, but not for long, and in any case, the plan is to get all Compass features into ElasticSearch). Of course, I am biased, since I created ElasticSearch, so you might need to check for yourself.

As for Sphinx, I have not used it, so I can't comment. What I can refer you is to this thread at Sphinx forum which I think proves the superior distributed model of ElasticSearch.

Of course, ElasticSearch has many more features than just being distributed. It is actually built with a cloud in mind. You can check the feature list on the site.

Locking a file in Python

The other solutions cite a lot of external code bases. If you would prefer to do it yourself, here is some code for a cross-platform solution that uses the respective file locking tools on Linux / DOS systems.

try:
    # Posix based file locking (Linux, Ubuntu, MacOS, etc.)
    #   Only allows locking on writable files, might cause
    #   strange results for reading.
    import fcntl, os
    def lock_file(f):
        if f.writable(): fcntl.lockf(f, fcntl.LOCK_EX)
    def unlock_file(f):
        if f.writable(): fcntl.lockf(f, fcntl.LOCK_UN)
except ModuleNotFoundError:
    # Windows file locking
    import msvcrt, os
    def file_size(f):
        return os.path.getsize( os.path.realpath(f.name) )
    def lock_file(f):
        msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))
    def unlock_file(f):
        msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, file_size(f))


# Class for ensuring that all file operations are atomic, treat
# initialization like a standard call to 'open' that happens to be atomic.
# This file opener *must* be used in a "with" block.
class AtomicOpen:
    # Open the file with arguments provided by user. Then acquire
    # a lock on that file object (WARNING: Advisory locking).
    def __init__(self, path, *args, **kwargs):
        # Open the file and acquire a lock on the file before operating
        self.file = open(path,*args, **kwargs)
        # Lock the opened file
        lock_file(self.file)

    # Return the opened file object (knowing a lock has been obtained).
    def __enter__(self, *args, **kwargs): return self.file

    # Unlock the file and close the file object.
    def __exit__(self, exc_type=None, exc_value=None, traceback=None):        
        # Flush to make sure all buffered contents are written to file.
        self.file.flush()
        os.fsync(self.file.fileno())
        # Release the lock on the file.
        unlock_file(self.file)
        self.file.close()
        # Handle exceptions that may have come up during execution, by
        # default any exceptions are raised to the user.
        if (exc_type != None): return False
        else:                  return True        

Now, AtomicOpen can be used in a with block where one would normally use an open statement.

WARNINGS:

  • If running on Windows and Python crashes before exit is called, I'm not sure what the lock behavior would be.
  • The locking provided here is advisory, not absolute. All potentially competing processes must use the "AtomicOpen" class.
  • As of (Nov 9th, 2020) this code only locks writable files on Posix systems. At some point after the posting and before this date, it became illegal to use the fcntl.lock on read-only files.

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;
}

Would override all link styles and make all the states the colour blue.

"Unable to acquire application service" error while launching Eclipse

The accepted answer above is correct, except for it's not completely clear.

You need to add the following line to the bottom of the eclipse.ini file:

-Dosgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@

Mocking HttpClient in unit tests

To add my 2 cents. To mock specific http request methods either Get or Post. This worked for me.

mockHttpMessageHandler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(a => a.Method == HttpMethod.Get), ItExpr.IsAny<CancellationToken>())
                                                .Returns(Task.FromResult(new HttpResponseMessage()
                                                {
                                                    StatusCode = HttpStatusCode.OK,
                                                    Content = new StringContent(""),
                                                })).Verifiable();

Fluid width with equally spaced DIVs

The easiest way to do this now is with a flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The CSS is then simply:

#container {
    display: flex;
    justify-content: space-between;
}

demo: http://jsfiddle.net/QPrk3/

However, this is currently only supported by relatively recent browsers (http://caniuse.com/flexbox). Also, the spec for flexbox layout has changed a few times, so it's possible to cover more browsers by additionally including an older syntax:

http://css-tricks.com/old-flexbox-and-new-flexbox/

http://css-tricks.com/using-flexbox/

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Change an image with onclick()

function chkicon(num,allsize) {
    var  flagicon = document.getElementById("flagicon"+num).value;

    if(flagicon=="plus"){
         //alert("P== "+flagicon);

         for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }


         document.images["pic"+num].src = "../images/minus.gif";
         document.getElementById("flagicon"+num).value = "minus";

    }else if(flagicon=="minus"){
         //alert("M== "+flagicon);

          document.images["pic"+num].src  = "../images/plus.gif";    
          document.getElementById("flagicon"+num).value = "plus";

    }else{
          for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }
    }
}

Can I access variables from another file?

This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)

Find if listA contains any elements not in listB

listA.Except(listB) will give you all of the items in listA that are not in listB

Why is Spring's ApplicationContext.getBean considered bad?

It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:

public class AutowireThisDriver {

    private MySpringBean mySpringBean;    

    public static void main(String[] args) {
       AutowireThisDriver atd = new AutowireThisDriver(); //get instance

       ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                  "/WEB-INF/applicationContext.xml"); //get Spring context 

       //the magic: auto-wire the instance with all its dependencies:
       ctx.getAutowireCapableBeanFactory().autowireBeanProperties(atd,
                  AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        

       // code that uses mySpringBean ...
       mySpringBean.doStuff() // no need to instantiate - thanks to Spring
    }

    public void setMySpringBean(MySpringBean bean) {
       this.mySpringBean = bean;    
    }
}

I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

Deleting all records in a database table

If you mean delete every instance of all models, I would use

ActiveRecord::Base.connection.tables.map(&:classify)
  .map{|name| name.constantize if Object.const_defined?(name)}
  .compact.each(&:delete_all)

Perform Button click event when user press Enter key in Textbox

in the html code only, add a panel that contains the page's controls. Inside the panel, add a line DefaultButton = "buttonNameThatClicksAtEnter". See the example below, there should be nothing else required.

<asp:Panel runat="server" DefaultButton="Button1"> //add this!
  //here goes all the page controls and the trigger button
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
</asp:Panel> //and this too!

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Using LINQ to concatenate strings

quick performance data for the StringBuilder vs Select & Aggregate case over 3000 elements:

Unit test - Duration (seconds)
LINQ_StringBuilder - 0.0036644
LINQ_Select.Aggregate - 1.8012535

    [TestMethod()]
    public void LINQ_StringBuilder()
    {
        IList<int> ints = new List<int>();
        for (int i = 0; i < 3000;i++ )
        {
            ints.Add(i);
        }
        StringBuilder idString = new StringBuilder();
        foreach (int id in ints)
        {
            idString.Append(id + ", ");
        }
    }
    [TestMethod()]
    public void LINQ_SELECT()
    {
        IList<int> ints = new List<int>();
        for (int i = 0; i < 3000; i++)
        {
            ints.Add(i);
        }
        string ids = ints.Select(query => query.ToString())
                         .Aggregate((a, b) => a + ", " + b);
    }

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

How can I use NSError in my iPhone App?

Objective-C

NSError *err = [NSError errorWithDomain:@"some_domain"
                                   code:100
                               userInfo:@{
                                           NSLocalizedDescriptionKey:@"Something went wrong"
                               }];

Swift 3

let error = NSError(domain: "some_domain",
                      code: 100,
                  userInfo: [NSLocalizedDescriptionKey: "Something went wrong"])

What is your single most favorite command-line trick using Bash?

cd -

It's the command-line equivalent of the back button (takes you to the previous directory you were in).

Maximum number of rows in an MS Access database engine table?

It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.

Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.

How do I get row id of a row in sql server

There is a pseudocolumn called %%physloc%% that shows the physical address of the row.

See Equivalent of Oracle's RowID in SQL Server

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

Storing a Key Value Array into a compact JSON string

To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.

{
    "keyvaluelist": {
        "slide0001.html": "Looking Ahead",
        "slide0008.html": "Forecast",
        "slide0021.html": "Summary"
    },
    "otherdata": {
        "one": "1",
        "two": "2",
        "three": "3"
    },
    "anotherthing": "thing1",
    "onelastthing": "thing2"
}

I read this as

a JSON object with four elements
    element 1 is a map of key/value pairs named "keyvaluelist",
    element 2 is a map of key/value pairs named "otherdata",
    element 3 is a string named "anotherthing",
    element 4 is a string named "onelastthing"

The first element or second element could alternatively be described as objects themselves, of course, with three elements each.

How to get xdebug var_dump to show full object/array

I'd like to recommend var_export($array) - it doesn't show types, but it generates syntax you can use in your code :)

Using .htaccess to make all .html pages to run as .php files?

I think this is the best way to run php script on html and htm pages:

AddType application/x-httpd-php5 .html .htm

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Bottom Line

Use either COUNT(field) or COUNT(*), and stick with it consistently, and if your database allows COUNT(tableHere) or COUNT(tableHere.*), use that.

In short, don't use COUNT(1) for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)

Use count(*) for counting

Use * for all your queries that need to count everything, even for joins, use *

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But don't use COUNT(*) for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table

SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Don't be fooled by those advising that when using * in COUNT, it fetches entire row from your table, saying that * is slow. The * on SELECT COUNT(*) and SELECT * has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *.

An alternate syntax

In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere) the same semantics as COUNT(*). Example:

For counting rows we could have this:

SELECT COUNT(emp) FROM emp

And they could make it simpler:

SELECT COUNT() FROM emp

And for LEFT JOINs, we could have this:

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But they cannot do that (COUNT(tableNameHere)) since SQL standard permits naming a field with the same name as its table name:

CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name, 
                and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)

Counting with null

And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit field. This will not count all rows, it will only yield 3, not 4

SELECT count(fruit) FROM fruit

Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But that could cause confusion later if we will add a subordinate field in the table, as it will count the field(which could be nullable), not the table rows.

So to be on the safe side, use:

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

count(1): The one-trick pony

In particular to COUNT(1), it is a one-trick pony, it works well only on one table query:

SELECT COUNT(1) FROM tbl

But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

So what's the meaning of COUNT(1) here?

SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Is it this...?

-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Or this...?

-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

By careful thought, you can infer that COUNT(1) is the same as COUNT(*), regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1) to work as: COUNT(subordinate.boss_id), COUNT(subordinate.*)

So just use either of the following:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Works on Postgresql, it's clear that you want to count the cardinality of the set

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7

select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You cannot do this: http://www.sqlfiddle.com/#!1/98515/8

select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9

select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Laravel supports aliases on tables and columns with AS. Try

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

Let's see it in action with an awesome tinker tool

$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
//   0 => object(stdClass)(
//     'uid' => '1'
//   )
// )

How to set layout_gravity programmatically?

This question is old but I just had the same problem and solved it like this

LayoutParams lay = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)
lay.gravity = Gravity.CENTER;

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

Python Save to file

In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

with open('Failed.py','w',encoding = 'utf-8') as f:
   f.write("Write what you want to write in\n")
   f.write("this file\n\n")

This program will create a new file named Failed.py in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Check for special characters (/*-+_@&$#%) in a string?

Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:

[a-zA-Z0-9 ]

MySQL Cannot Add Foreign Key Constraint

Please ensure that both the tables are in InnoDB format. Even if one is in MyISAM format, then, foreign key constraint wont work.

Also, another thing is that, both the fields should be of the same type. If one is INT, then the other should also be INT. If one is VARCHAR, the other should also be VARCHAR, etc.

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I found Integer.toHexString to be a little slow. If you are converting many bytes, you may want to consider building an array of Strings containing "00".."FF" and use the integer as the index. I.e.

hexString.append(hexArray[0xFF & messageDigest[i]]);

This is faster and ensures the correct length. Just requires the array of strings:

String[] hexArray = {
"00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
"10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
"20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
"30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
"40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
"50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
"60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
"70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
"80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
"90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
"A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
"B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
"C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
"D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
"E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
"F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};

How do I create and access the global variables in Groovy?

Could not figure out what you want, but you need something like this ? :

?def a = { b -> b = 1 }
?bValue = a()
println b // prints 1

Now bValue contains the value of b which is a variable in the closure a. Now you can do anything with bValue Let me know if i have misunderstood your question

How to reformat JSON in Notepad++?

Universal Indent GUI plugin for Notepad++ will turn your sample into:

{
    "menu" : {
        "id" : "file", "value" : "File", "popup" : {
            "menuitem" : [ {
                "value" : "New", "onclick" : "CreateNewDoc()";
            }
            , {
                "value" : "Open", "onclick" : "OpenDoc()";
            }
            , {
                "value" : "Close", "onclick" : "CloseDoc()";
            }
            ];
        }
    }
}

Using numpy to build an array of all combinations of two arrays

Here's a pure-numpy implementation. It's about 5× faster than using itertools.


import numpy as np

def cartesian(arrays, out=None):
    """
    Generate a cartesian product of input arrays.

    Parameters
    ----------
    arrays : list of array-like
        1-D arrays to form the cartesian product of.
    out : ndarray
        Array to place the cartesian product in.

    Returns
    -------
    out : ndarray
        2-D array of shape (M, len(arrays)) containing cartesian products
        formed of input arrays.

    Examples
    --------
    >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
    array([[1, 4, 6],
           [1, 4, 7],
           [1, 5, 6],
           [1, 5, 7],
           [2, 4, 6],
           [2, 4, 7],
           [2, 5, 6],
           [2, 5, 7],
           [3, 4, 6],
           [3, 4, 7],
           [3, 5, 6],
           [3, 5, 7]])

    """

    arrays = [np.asarray(x) for x in arrays]
    dtype = arrays[0].dtype

    n = np.prod([x.size for x in arrays])
    if out is None:
        out = np.zeros([n, len(arrays)], dtype=dtype)

    m = n / arrays[0].size
    out[:,0] = np.repeat(arrays[0], m)
    if arrays[1:]:
        cartesian(arrays[1:], out=out[0:m, 1:])
        for j in xrange(1, arrays[0].size):
            out[j*m:(j+1)*m, 1:] = out[0:m, 1:]
    return out

RelativeLayout center vertical

Adding both android:layout_centerInParent and android:layout_centerVertical work for me to center ImageView both vertical and horizontal:

<ImageView
    ..
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    />

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

How to custom switch button?

<Switch android:layout_width="wrap_content" 
                    android:layout_height="wrap_content"
                    android:thumb="@drawable/custom_switch_inner_holo_light"
                    android:track="@drawable/custom_switch_track_holo_light"
                    android:textOn="@string/yes"
                    android:textOff="@string/no"/>

drawable/custom_switch_inner_holo_light.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/custom_switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/custom_switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/custom_switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/custom_switch_thumb_holo_light" />
</selector>

drawable/custom_switch_track_holo_light.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"  android:drawable="@drawable/custom_switch_bg_focused_holo_light" />
    <item                               android:drawable="@drawable/custom_switch_bg_holo_light" />
</selector>

Next images are 9.paths drawables and they must be in different density (mdpi, hdpi, xhdpi, xxhdpi). As example I give xxhdpi (you can resize they if u needed):

drawable/custom_switch_thumb_disabled_holo_light

custom_switch_thumb_disabled_holo_light

drawable/custom_switch_thumb_pressed_holo_light

custom_switch_thumb_pressed_holo_light

drawable/custom_switch_thumb_activated_holo_light

custom_switch_thumb_activated_holo_light

drawable/custom_switch_thumb_holo_light

custom_switch_thumb_holo_light

drawable/custom_switch_bg_focused_holo_light

custom_switch_bg_focused_holo_light

drawable/custom_switch_bg_holo_light

enter image description here

Disable EditText blinking cursor

If you want to ignore the Edittext from the starting of activity, android:focusable and android:focusableInTouchMode will help you inshallah.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout7" android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:focusable="true" android:focusableInTouchMode="true">

This LinearLayout with your Edittext.

"Too many characters in character literal error"

I faced the same issue. String.Replace('\\.','') is not valid statement and throws the same error. Thanks to C# we can use double quotes instead of single quotes and following works String.Replace("\\.","")

100% Min Height CSS layout

Try this:

body{ height: 100%; }
#content { 
    min-height: 500px;
    height: 100%;
}
#footer {
    height: 100px;
    clear: both !important;
}

The div element below the content div must have clear:both.

Retrofit 2 - Dynamic URL

RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code and you can use different URLs, Headers and Params, in every Call.

Add multiple URLs in your application class like this :

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                    //api url
                .setBaseUrl("https://reqres.in/")
                    //you can set multiple urls
        //                .setUrl("example","http://ngrok.io/api/")
                    //set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                    //enable cache
                .enableCaching(this)
                    //add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  

And then use the URL you need in your call:

retrofitClient.Get<GetResponseModel>()
            //set base url
            .setBaseUrlKey("example")
            //set path
            .setPath("api/users/2")
            //set url params Key-Value or HashMap
            .setUrlParams("KEY","Value")
            .setResponseHandler(GetResponseModel::class.java,
                object : ResponseHandler<GetResponseModel>() {
                    override fun onSuccess(response: Response<GetResponseModel>) {
                        super.onSuccess(response)
                        //handle response
                    }
                }).run(this)

For more information see the documentation

How do I check if a variable is of a certain type (compare two types) in C?

As another answer mentioned, you can now do this in C11 with _Generic.

For example, here's a macro that will check if some input is compatible with another type:

#include <stdbool.h>
#define isCompatible(x, type) _Generic(x, type: true, default: false)

You can use the macro like so:

double doubleVar;
if (isCompatible(doubleVar, double)) {
    printf("doubleVar is of type double!\n");  // prints
}

int intVar;
if (isCompatible(intVar, double)) {
    printf("intVar is compatible with double too!\n");  // doesn't print
}

This can also be used on other types, including structs. E.g.

struct A {
    int x;
    int y;
};

struct B {
    double a;
    double b;
};

int main(void)
{    
    struct A AVar = {4, 2};
    struct B BVar = {4.2, 5.6};

    if (isCompatible(AVar, struct A)) {
        printf("Works on user-defined types!\n");  // prints
    }

    if (isCompatible(BVar, struct A)) {
        printf("And can differentiate between them too!\n");  // doesn't print
    }

    return 0;
}

And on typedefs.

typedef char* string;

string greeting = "Hello world!";
if (isCompatible(greeting, string)) {
    printf("Can check typedefs.\n");
}

However, it doesn't always give you the answer you expect. For instance, it can't distinguish between an array and a pointer.

int intArray[] = {4, -9, 42, 3};

if (isCompatible(intArray, int*)) {
    printf("Treats arrays like pointers.\n");
}

// The code below doesn't print, even though you'd think it would
if (isCompatible(intArray, int[4])) {
    printf("But at least this works.\n");
}

Answer borrowed from here: http://www.robertgamble.net/2012/01/c11-generic-selections.html

ORA-12560: TNS:protocol adaptor error

from command console, if you get this error you can avoid it by typing

c:\> sqlplus /nolog

then you can connect

SQL> conn user/pass @host:port/service

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

A related issue on the emulator is when there isn'y any space left in the /data partition.

For example,

% adb shell df

Filesystem             Size   Used   Free   Blksize
/dev                   252M    32K   252M   4096
/mnt/asec              252M     0K   252M   4096
/mnt/obb               252M     0K   252M   4096
/system                154M   154M     0K   4096
/data                   64M    57M     6M   4096
/cache                  64M     1M    62M   4096

Here is a sample view of the /data/app directory:

% adb shell ls -l /data/app

-rw-r--r-- system   system      19949 2011-10-12 17:09 CubeLiveWallpapers.apk
-rw-r--r-- system   system      27670 2011-10-12 17:09 GestureBuilder.apk
-rw-r--r-- system   system      34341 2011-10-12 17:09 SoftKeyboard.apk
-rw-r--r-- system   system      20151 2011-10-12 17:09 WidgetPreview.apk

I removed the extra APK files. It seems upon every install you get a new APK file. Just remove the extra APK files.

For example,

adb shell rm /data/app/com.brooklynmarathon.calendarapi2-1.apk

Java - remove last known item from ArrayList

It should be:

ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);

Or you can do

clients.remove(clients.size() - 1);

The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.

Simple insecure two-way data "obfuscation"?

I know you said you don't care about how secure it is, but if you chose DES you might as well take AES it is the more up-to-date encryption method.

Jquery asp.net Button Click Event via ajax

This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

$(document).ready(function() {
  $("input[id$='btnAwesome']").click(function() {
    // Do client side button click stuff here.
  });
});

The id$= is doing a regex match for an id ENDING with btnAwesome.

Edit:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.

Perl read line by line

In bash foo is the name of the variable, and $ is an operator which means 'get the value of'.

In perl $foo is the name of the variable.

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

Creating a new dictionary in Python

>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

Will add the value in the python dictionary.

font-weight is not working properly?

Most browsers don't fully support the numerical values for font-weight. Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.

If you need something bolder then you might want to try using a different font that's bolder than your existing one. Naturally, you could probably adjust the font size for a similar effect.

Python: Making a beep noise

I was searching for the same but for Linux shell.

The topic brought me to an answer, -thanks-

Maybe more pythonic manner :

import os
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
beep(3)

Notes :

  • the sleep value (here 0.2), depends on the length (seconds) of your default beep sound
  • I choosed to use os.system rather then subprocess.Popen for simplicity (it could be bad)
  • the '-n' for echo is to have no more display
  • the last ';' after sleep is necessary for the resulting text sequence (*x)
  • also tested through ssh on an X term

class << self idiom in Ruby

In fact if you write any C extensions for your Ruby projects there is really only one way to define a Module method.

rb_define_singleton_method

I know this self business just opens up all kinds of other questions so you could do better by searching each part.

Objects first.

foo = Object.new

Can I make a method for foo?

Sure

def foo.hello
 'hello'
end

What do I do with it?

foo.hello
 ==>"hello"

Just another object.

foo.methods

You get all the Object methods plus your new one.

def foo.self
 self
end

foo.self

Just the foo Object.

Try to see what happens if you make foo from other Objects like Class and Module. The examples from all the answers are nice to play with but you have to work with different ideas or concepts to really understand what is going on with the way the code is written. So now you have lots of terms to go look at.

Singleton, Class, Module, self, Object, and Eigenclass was brought up but Ruby doesn't name Object Models that way. It's more like Metaclass. Richard or __why shows you the idea here. http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html And if the blows you away then try looking up Ruby Object Model in search. Two videos that I know of on YouTube are Dave Thomas and Peter Cooper. They try to explain that concept too. It took Dave a long time to get it so don't worry. I'm still working on it too. Why else would I be here? Thanks for your question. Also take a look at the standard library. It has a Singleton Module just as an FYI.

This is pretty good. https://www.youtube.com/watch?v=i4uiyWA8eFk

Finding all objects that have a given property inside a collection

Use Google Guava.

final int lastSeq = myCollections.size();
Clazz target = Iterables.find(myCollections, new Predicate<Clazz>() {
    @Override
    public boolean apply(@Nullable Clazz input) {
      return input.getSeq() == lastSeq;
    }
});

I think to use this method.

Regex to remove all special characters from string?

This should do it:

[^a-zA-Z0-9]

Basically it matches all non-alphanumeric characters.

How to query GROUP BY Month in a Year

I am doing like this in MSSQL

Getting Monthly Data:

 SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month], 
     DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
    FROM pictures_table
    GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED), 
     DATENAME(MONTH, DATE_CREATED)
    ORDER BY 1,2

Getting Monthly Data using PIVOT:

SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year], 
       DATENAME(MONTH, DATE_CREATED) [Month], 
       SUM(Num_of_Pictures) [Pictures Count]
      FROM pictures_table
      GROUP BY YEAR(DATE_CREATED), 
      DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])   
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot

Clearing an HTML file upload field via JavaScript

I know it is quite old, but testing in the browser:

$0.value=null; // when $0 is the file upload element we talking about

erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)

Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.

Explanation:

As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property. Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)

How to install pip in CentOS 7?

Update 2019

I tried easy_install at first but it doesn't install packages in a clean and intuitive way. Also when it comes time to remove packages it left a lot of artifacts that needed to be cleaned up.

sudo yum install epel-release
sudo yum install python34-pip
pip install package

Was the solution that worked for me, it installs "pip3" as pip on the system. It also uses standard rpm structure so it clean in its removal. I am not sure what process you would need to take if you want both python2 and python3 package manager on your system.

Django: multiple models in one template using forms

This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.

if request.POST():
    a_valid = formA.is_valid()
    b_valid = formB.is_valid()
    c_valid = formC.is_valid()
    # we do this since 'and' short circuits and we want to check to whole page for form errors
    if a_valid and b_valid and c_valid:
        a = formA.save()
        b = formB.save(commit=False)
        c = formC.save(commit=False)
        b.foreignkeytoA = a
        b.save()
        c.foreignkeytoB = b
        c.save()

Here are the docs for custom validation.

Skip first entry in for loop in python?

If cars is a sequence you can just do

for car in cars[1:-1]:
    pass

How to use moment.js library in angular 2 typescript app?

The angular2-moment library has pipes like {{myDate | amTimeAgo}} to use in .html files.

Those same pipes can also be accessed as Typescript functions within a component class (.ts) file. First install the library as instructed:

npm install --save angular2-moment

In the node_modules/angular2-moment will now be ".pipe.d.ts" files like calendar.pipe.d.ts, date-format.pipe.d.ts and many more.

Each of those contains the Typescript function name for the equivalent pipe, for example, DateFormatPipe() is the function for amDateFormatPipe.

To use DateFormatPipe in your project, import and add it to your global providers in app.module.ts:

import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]

Then in any component where you want to use the function, import it on top, inject into the constructor and use:

import { DateFormatPipe } from "angular2-moment";
....
constructor(.......,  public dfp: DateFormatPipe) {
    let raw = new Date(2015, 1, 12);
    this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}

To use any of the functions follow this process. It would be nice if there was one way to gain access to all the functions, but none of the above solutions worked for me.

node.js hash string?

Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  md5sum.update(d);
});

s.on('end', function() {
  var d = md5sum.digest('hex');
  console.log(d + '  ' + filename);
});

Styling of Select2 dropdown select boxes

This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:

.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
    border-color: transparent transparent #fff transparent !important;
  }
  .select2-container--default .select2-selection--single .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent !important;
  }

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

CSS Printing: Avoiding cut-in-half DIVs between pages?

I have the same problem bu no solution yet. page-break-inside does not work on browsers but Opera. An alternative might be to use page-break-after: avoid; on all child elements of the div to keep togehter ... but in my tests, the avoid-Attribute does not work eg. in Firefox ...

What works in all ppular browsers are forced page breaks using eg. page-break-after: always

package android.support.v4.app does not exist ; in Android studio 0.8

In my case the problem was solved by appending the string cordova.system.library.2=com.android.support:support-v4:+ to platforms/android/project.properties file

Connect to mysql in a docker container from the host

I do this by running a temporary docker container against my server so I don't have to worry about what is installed on my host. First, I define what I need (which you should modify for your purposes):

export MYSQL_SERVER_CONTAINER=mysql-db
export MYSQL_ROOT_PASSWORD=pswd 
export DB_DOCKER_NETWORK=db-net
export MYSQL_PORT=6604

I always create a new docker network which any other containers will need:

docker network create --driver bridge $DB_DOCKER_NETWORK

Start a mySQL database server:

docker run --detach --name=$MYSQL_SERVER_CONTAINER --net=$DB_DOCKER_NETWORK --env="MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" -p ${MYSQL_PORT}:3306 mysql

Capture IP address of the new server container

export DBIP="$(docker inspect ${MYSQL_SERVER_CONTAINER} | grep -i 'ipaddress' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])')"

Open a command line interface to the server:

docker run -it -v ${HOST_DATA}:/data --net=$DB_DOCKER_NETWORK --link ${MYSQL_SERVER_CONTAINER}:mysql --rm mysql sh -c "exec mysql -h${DBIP} -uroot -p"

This last container will remove itself when you exit the mySQL interface, while the server will continue running. You can also share a volume between the server and host to make it easier to import data or scripts. Hope this helps!

pandas GroupBy columns with NaN (missing) values

One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan yields False, so the replace function doesn't actually do anything.

What worked for me was this:

df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)

(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pad zeroes to a string?

For zip codes saved as integers:

>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Source

So as others mentioned, it's a convention.

How to upload and parse a CSV file in php

You can try with this:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

How to detect installed version of MS-Office?

If you've installed 32-bit Office on a 64-bit machine, you may need to check for the presence of "SOFTWARE\Wow6432Node\Microsoft\Office\12.0\", substituting the 12.0 with the appropriate version. This is certainly the case for Office 2007 installed on 64-bit Windows 7.

Note that Office 2010 (== 14.0) is the first Office for which a 64-bit version exists.

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

How to convert integer to decimal in SQL Server query?

SELECT CAST(height AS DECIMAL(18,0)) / 10

Edit: How this works under the hood?

The result type is the same as the type of both arguments, or, if they are different, it is determined by the data type precedence table. You can therefore cast either argument to something non-integral.

Now DECIMAL(18,0), or you could equivalently write just DECIMAL, is still a kind of integer type, because that default scale of 0 means "no digits to the right of the decimal point". So a cast to it might in different circumstances work well for rounding to integers - the opposite of what we are trying to accomplish.

However, DECIMALs have their own rules for everything. They are generally non-integers, but always exact numerics. The result type of the DECIMAL division that we forced to occur is determined specially to be, in our case, DECIMAL(29,11). The result of the division will therefore be rounded to 11 places which is no concern for division by 10, but the rounding becomes observable when dividing by 3. You can control the amount of rounding by manipulating the scale of the left hand operand. You can also round more, but not less, by placing another ROUND or CAST operation around the whole expression.

Identical mechanics governs the simpler and nicer solution in the accepted answer:

  SELECT height / 10.0

In this case, the type of the divisor is DECIMAL(3,1) and the type of the result is DECIMAL(17,6). Try dividing by 3 and observe the difference in rounding.

If you just hate all this talk of precisions and scales, and just want SQL server to perform all calculations in good old double precision floating point arithmetics from some point on, you can force that, too:

SELECT height / CAST(10 AS FLOAT(53))

or equivalently just

SELECT height / CAST (10 AS FLOAT)

Specify path to node_modules in package.json

In short: It is not possible, and as it seems won't ever be supported (see here https://github.com/npm/npm/issues/775).

There are some hacky work-arrounds with using the CLI or ENV-Variables (see the current selected answer), .npmrc-Config-Files or npm link - what they all have in common: They are never just project-specific, but always some kind of global Solutions.

For me, none of those solutions are really clean because contributors to your project always need to create some special configuration or have some special knowledge - they can't just npm install and it works.

So: Either you will have to put your package.json in the same directory where you want your node_modules installed, or live with the fact that they will always be in the root-dir of your project.

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

What is callback in Android?

Callback can be very helpful in Java.

Using Callback you can notify another Class of an asynchronous action that has completed with success or error.

How to semantically add heading to a list

As Felipe Alsacreations has already said, the first option is fine.

If you want to ensure that nothing below the list is interpreted as belonging to the heading, that's exactly what the HTML5 sectioning content elements are for. So, for instance you could do

<h2>About Fruits</h2>
<section>
  <h3>Fruits I Like:</h3>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
  </ul>
</section>
<!-- anything here is part of the "About Fruits" section but does not 
     belong to the "Fruits I Like" section. -->

Bash foreach loop

Here is a while loop:

while read filename
do
    echo "Printing: $filename"
    cat "$filename"
done < filenames.txt

Computational complexity of Fibonacci Sequence

The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:

IN | OUT | TOT | LEAF | INT
 1 |   1 |   1 |   1  |   0
 2 |   1 |   1 |   1  |   0
 3 |   2 |   3 |   2  |   1
 4 |   3 |   5 |   3  |   2
 5 |   5 |   9 |   5  |   4
 6 |   8 |  15 |   8  |   7
 7 |  13 |  25 |  13  |  12
 8 |  21 |  41 |  21  |  20
 9 |  34 |  67 |  34  |  33
10 |  55 | 109 |  55  |  54

What immediately leaps out is that the number of leaf nodes is fib(n). What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1. Therefore the total number of nodes is 2 * fib(n) - 1.

Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n)).

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

I am using JDK 7 for maven project and I used -Dhttps.protocols=TLSv1.2 as argument in JRE. It has allowed to download all maven repository which were failing earlier.

how to instanceof List<MyType>?

You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List