Programs & Examples On #Brew framework

BREW is an application framework for mobile phones created by Qualcomm in 2001. This is not related to the macOS package manager (Homebrew).

How to make a local variable (inside a function) global

You could use module scope. Say you have a module called utils:

f_value = 'foo'

def f():
    return f_value

f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:

>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'

Note that you can import the function by name:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'

But not the attribute:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'

This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

How to print the array?

You could try this:

#include <stdio.h>

int main() 
{  
  int i,j;
  int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
  for(i = 0; i < 3; i++) 
  {
       for(j = 0; j < 3; j++) 
       {
         printf("%d ", my_array[i][j]);
       }
    printf("\n");
  } 
  return 0;
}

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I'd consider the patterns you are using for your system, the naming conventions / cataloguing / grouping of classes of tends to be defined by the pattern used. Personally, I stick to these naming conventions as they are the most likely way for another person to be able to pick up my code and run with it.

For example UserRecordsClerk might be better explained as extending a generic RecordsClerk interface that both UserRecordsClerk and CompanyRecordsClerk implement and then specialise on, meaning one can look at the methods in the interface to see what the its subclasses do / are generally for.

See a book such as Design Patterns for info, it's an excellent book and might help you clear up where you're aiming to be with your code - if you aren't already using it! ;o)

I reckon so long as your pattern is well chosen and used as far as is appropriate, then pretty uninventive straightforward class names should suffice!

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

Fixing npm path in Windows 8 and 10

This worked for me: 1. npm root -g (to see the current npm is installed) 2. npm config set prefix (to change the path)

state machines tutorials

I prefer using function pointers over gigantic switch statements, but in contrast to qrdl's answer I normally don't use explicit return codes or transition tables.

Also, in most cases you'll want a mechanism to pass along additional data. Here's an example state machine:

#include <stdio.h>

struct state;
typedef void state_fn(struct state *);

struct state
{
    state_fn * next;
    int i; // data
};

state_fn foo, bar;

void foo(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = bar;
}

void bar(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = state->i < 10 ? foo : 0;
}

int main(void)
{
    struct state state = { foo, 0 };
    while(state.next) state.next(&state);
}

java.util.NoSuchElementException - Scanner reading user input

The problem is

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Thus scan.close() closes System.in.

To fix it you can make

Scanner scan static and do not close it in PromptCustomerQty. Code below works.

public static void main (String[] args) {   

// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");

// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);

// Define internal variables 
// ## DONT CHANGE 
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output

// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);

// Ask users for quantities 
PromptCustomerQty(customer, ProductList);

// Ask user for payment method
PromptCustomerPayment(customer);

// Create the header
PrintHeader(customer, formatString);

// Create Body
PrintBody(ProductList, formatString);   
}

static Scanner scan;

public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)               {
// Initiate a Scanner
scan = new Scanner(System.in);

// **** VARIABLES ****
int qty = 0;

// Greet Customer
System.out.println("Hello " + customer.getName());

// Loop through each item and ask for qty desired
for (Product p : ProductList) {

    do {
    // Ask user for qty
    System.out.println("How many would you like for product: " + p.name);
    System.out.print("> ");

    // Get input and set qty for the object
    qty = scan.nextInt();

    }
    while (qty < 0); // Validation

    p.setQty(qty); // Set qty for object
    qty = 0; // Reset count
}

// Cleanup

}

public static void PromptCustomerPayment (Customer customer) {
// Variables
String payment = "";

// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");

payment = scan.next();

} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));

// Check/set result
if (payment.toLowerCase() == "yes") {
    customer.setPaidInFull(true);
}
else {
    customer.setPaidInFull(false);
}
}

On a side note, you shouldn't use == for String comparision, use .equals instead.

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

Connecting to local SQL Server database using C#

If you're using SQL Server express, change

SqlConnection conn = new SqlConnection("Server=localhost;" 
       + "Database=Database1;");

to

SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;" 
       + "Database=Database1;");

That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

Set focus to field in dynamically loaded DIV

Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.

The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.

Instead of:

$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );

Try this:

setTimeout( function() { $( '#header' ).focus() }, 500 );

In my code, testing passing the argument, this didn't work, the timeout was ignored:

setTimeout( alert( 'Hello, '+name ), 1000 );

This works, the timeout ticks:

setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );

It sucks that w3schools doesn't mention it.

Credits go to: makemineatriple.com.

Hopefully, this helps somebody who comes here.

psql: could not connect to server: No such file or directory (Mac OS X)

My problem ended up being that I was using Gas Mask (a hosts file manager for Mac), and I didn't have an entry for localhost in the hosts file I was using.

I added:

127.0.0.1 localhost

And that resolved my problem.

2D array values C++

The proper way to initialize a multidimensional array in C or C++ is

int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};

You can use this same trick to initialize even higher-dimensional arrays if you want.

Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!

get UTC time in PHP

date("Y-m-d H:i:s", time() - date("Z"))

How to write trycatch in R

Well then: welcome to the R world ;-)

Here you go

Setting up the code

urls <- c(
    "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
    "http://en.wikipedia.org/wiki/Xz",
    "xxxxx"
)
readUrl <- function(url) {
    out <- tryCatch(
        {
            # Just to highlight: if you want to use more than one 
            # R expression in the "try" part then you'll have to 
            # use curly brackets.
            # 'tryCatch()' will return the last evaluated expression 
            # in case the "try" part was completed successfully

            message("This is the 'try' part")

            readLines(con=url, warn=FALSE) 
            # The return value of `readLines()` is the actual value 
            # that will be returned in case there is no condition 
            # (e.g. warning or error). 
            # You don't need to state the return value via `return()` as code 
            # in the "try" part is not wrapped inside a function (unlike that
            # for the condition handlers for warnings and error below)
        },
        error=function(cond) {
            message(paste("URL does not seem to exist:", url))
            message("Here's the original error message:")
            message(cond)
            # Choose a return value in case of error
            return(NA)
        },
        warning=function(cond) {
            message(paste("URL caused a warning:", url))
            message("Here's the original warning message:")
            message(cond)
            # Choose a return value in case of warning
            return(NULL)
        },
        finally={
        # NOTE:
        # Here goes everything that should be executed at the end,
        # regardless of success or error.
        # If you want more than one expression to be executed, then you 
        # need to wrap them in curly brackets ({...}); otherwise you could
        # just have written 'finally=<expression>' 
            message(paste("Processed URL:", url))
            message("Some other message at the end")
        }
    )    
    return(out)
}

Applying the code

> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory

Investigating the output

> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"      
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"      
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"             
[5] "</head><body>"                                                          
[6] ""    

> length(y)
[1] 3

> y[[3]]
[1] NA

Additional remarks

tryCatch

tryCatch returns the value associated to executing expr unless there's an error or a warning. In this case, specific return values (see return(NA) above) can be specified by supplying a respective handler function (see arguments error and warning in ?tryCatch). These can be functions that already exist, but you can also define them within tryCatch() (as I did above).

The implications of choosing specific return values of the handler functions

As we've specified that NA should be returned in case of error, the third element in y is NA. If we'd have chosen NULL to be the return value, the length of y would just have been 2 instead of 3 as lapply() will simply "ignore" return values that are NULL. Also note that if you don't specify an explicit return value via return(), the handler functions will return NULL (i.e. in case of an error or a warning condition).

"Undesired" warning message

As warn=FALSE doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use

suppressWarnings(readLines(con=url))

instead of

readLines(con=url, warn=FALSE)

Multiple expressions

Note that you can also place multiple expressions in the "actual expressions part" (argument expr of tryCatch()) if you wrap them in curly brackets (just like I illustrated in the finally part).

How to uncheck a radio button?

Rewrite of Igor's code as plugin.

Use:

$('input[type=radio]').uncheckableRadio();

Plugin:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

How do you detect the clearing of a "search" HTML5 input?

I believe this is the only answer that fires ONLY when the x is clicked.

However, it is a bit hacky and ggutenberg's answer will work for most people.

$('#search-field').on('click', function(){
  $('#search-field').on('search', function(){
    if(!this.value){
      console.log("clicked x");
      // Put code you want to run on clear here
    }
  });
  setTimeout(function() {
    $('#search-field').off('search');
  }, 1);
});

Where '#search-field' is the jQuery selector for your input. Use 'input[type=search]' to select all search inputs. Works by checking for a search event (Pauan's answer) immediately after a click on the field.

How to subtract/add days from/to a date?

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

Simple way to repeat a string

Simple loop

public static String repeat(String string, int times) {
    StringBuilder out = new StringBuilder();
    while (times-- > 0) {
        out.append(string);
    }
    return out.toString();
}

get unique machine id

There are two ways possible to this that I know:

  1. Get the Processor id of the system:

    public string getCPUId()
    {
        string cpuInfo = string.Empty;
        ManagementClass mc = new ManagementClass("win32_processor");
        ManagementObjectCollection moc = mc.GetInstances();
    
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo == "")
            {
                //Get only the first CPU's ID
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
        }
        return cpuInfo;
    }
    
  2. Get UUID of the system:

    public string getUUID()
    {
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "CMD.exe";
            startInfo.Arguments = "/C wmic csproduct get UUID";
            process.StartInfo = startInfo;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();
            return output;
    }
    

Purpose of __repr__ method?

An example to see the differences between them (I copied from this source),

>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'

The returns of repr() and str() are identical for int x, but there's a difference between the return values for str y -- one is formal and the other is informal. One of the most important differences between the formal and informal representations is that the default implementation of __repr__ for a str value can be called as an argument to eval, and the return value would be a valid string object, like this:

>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True

If you try to call the return value of __str__ as an argument to eval, the result won't be valid.

Angular2 change detection: ngOnChanges not firing for nested object

When you are manipulating the data like:

this.data.profiles[i].icon.url = '';

Then you should use in order to detect changes:

let array = this.data.profiles.map(x => Object.assign({}, x)); // It will detect changes

Since angular ngOnchanges not be able to detect changes in array, objects then we have to assign a new reference. Works everytime!

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

You have to change MySQL settings. Edit my.cnf file and put this setting in mysqld section:

[mysqld]
default_authentication_plugin= mysql_native_password

Then run following command:

FLUSH PRIVILEGES;

Above command will bring into effect the changes of default authentication mechanism.

How to use System.Net.HttpClient to post a complex type?

Note that if you are using a Portable Class Library, HttpClient will not have PostAsJsonAsync method. To post a content as JSON using a Portable Class Library, you will have to do this:

HttpClient client = new HttpClient();
HttpContent contentPost = new StringContent(argsAsJson, Encoding.UTF8, 
"application/json");

await client.PostAsync(new Uri(wsUrl), contentPost).ContinueWith(
(postTask) => postTask.Result.EnsureSuccessStatusCode());

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

How to Exit a Method without Exiting the Program?

If the function is a void, ending the function will return. Otherwise, you need to do an explicit return someValue. As Mark mentioned, you can also throw an exception. What's the context of your question? Do you have a larger code sample with which to show you some ways to exit the function?

Can I install Python 3.x and 2.x on the same Windows computer?

You can have both installed.

You should write this in front of your script:

#!/bin/env python2.7

or, eventually...

#!/bin/env python3.6

Update

My solution works perfectly with Unix, after a quick search on Google, here is the Windows solution:

#!c:/Python/python3_6.exe -u

Same thing: in front of your script.

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

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

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

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

Dark color scheme for Eclipse

I've created my own dark color scheme (based on Oblivion from gedit), which I think is very nice to work with.

Preview & details at: http://www.rogerdudler.com/?p=362

We're happy to announce the beta of eclipsecolorthemes.org, a new website to download, create and maintain Eclipse color themes / schemes. The theme editor allows you to copy an existing theme and edit the colors with a live preview of your changes on specific editors. The downloadable themes support a lot of editors (PHP, Java, SQL, Ant, text, HTML, CSS, and more to follow)

There's a growing list of themes already available on the site:

Screenshot of eclipsecolorthemes.org

You can read more about the launch here.

PHP memcached Fatal error: Class 'Memcache' not found

There are two extensions for memcached in PHP, "memcache" and "memcached".

It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

How to write logs in text file when using java.util.logging.Logger

A good library available named log4j for Java.
This will provide numerous feature. Go through link and you will find your solution.

mySQL :: insert into table, data from another table?

INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)  
SELECT campaign_id, from_number, received_msg, date_received
  FROM `received_txts`
 WHERE `campaign_id` = '8'

How do I get the last day of a month?

If you want the date, given a month and a year, this seems about right:

public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

SELECTING with multiple WHERE conditions on same column

Use:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(DISTINCT t.flag) = 2

The key thing is that the counting of t.flag needs to equal the number of arguments in the IN clause.

The use of COUNT(DISTINCT t.flag) is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:

  SELECT t.contactid
    FROM YOUR_TABLE t
   WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
  HAVING COUNT(t.flag) = 2

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

I'm using OS X (Yosemite) and this error happened to me when I upgraded from Mavericks to Yosemite. It was solved by using this command

sudo /usr/local/mysql/support-files/mysql.server start

Hiding and Showing TabPages in tabControl

I think the answer is much easier.

To hide the tab you just can use the way you already tried or adressing the TabPage itself.

TabControl1.TabPages.Remove(TabPage1) 'Could be male
TabControl1.TabPages.Remove(TabPage2) 'Could be female

a.s.o.

Removing the TabPage does not destroy it and the controls on it. To show the corresponding tab again just use the following code

TabControl1.TabPages.Insert(0, TabPage1) 'Show male
TabControl1.TabPages.Insert(1, TabPage2) 'Show female

Javascript variable access in HTML

In raw javascript, you'll want to put an id on your anchor tag and do this:

<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];

function insertText(){
    document.getElementById('someId').InnerHTML = splitText;}
</script>

<body onload="insertText()">
<a href = test.html id="someId">I need the value of "splitText" variable here</a>
</body>
</html>

Linux/Unix command to determine if process is running?

You SHOULD know the PID !

Finding a process by trying to do some kind of pattern recognition on the process arguments (like pgrep "mysqld") is a strategy that is doomed to fail sooner or later. What if you have two mysqld running? Forget that approach. You MAY get it right temporarily and it MAY work for a year or two but then something happens that you haven't thought about.

Only the process id (pid) is truly unique.

Always store the pid when you launch something in the background. In Bash this can be done with the $! Bash variable. You will save yourself SO much trouble by doing so.

How to determine if process is running (by pid)

So now the question becomes how to know if a pid is running.

Simply do:

ps -o pid= -p <pid>

This is POSIX and hence portable. It will return the pid itself if the process is running or return nothing if the process is not running. Strictly speaking the command will return a single column, the pid, but since we've given that an empty title header (the stuff immediately preceding the equals sign) and this is the only column requested then the ps command will not use header at all. Which is what we want because it makes parsing easier.

This will work on Linux, BSD, Solaris, etc.

Another strategy would be to test on the exit value from the above ps command. It should be zero if the process is running and non-zero if it isn't. The POSIX spec says that ps must exit >0 if an error has occurred but it is unclear to me what constitutes 'an error'. Therefore I'm not personally using that strategy although I'm pretty sure it will work as well on all Unix/Linux platforms.

How can I get enum possible values in a MySQL database?

MySQL Reference

If you want to determine all possible values for an ENUM column, use SHOW COLUMNS FROM tbl_name LIKE enum_col and parse the ENUM definition in the Type column of the output.

You would want something like:

$sql = "SHOW COLUMNS FROM `table` LIKE 'column'";
$result = $db->query($sql);
$row = $result->fetchRow();
$type = $row['Type'];
preg_match('/enum\((.*)\)$/', $type, $matches);
$vals = explode(',', $matches[1]);

This will give you the quoted values. MySQL always returns these enclosed in single quotes. A single quote in the value is escaped by a single quote. You can probably safely call trim($val, "'") on each of the array elements. You'll want to convert '' into just '.

The following will return $trimmedvals array items without quotes:

$trimmedvals = array();
foreach($vals as $key => $value) {
$value=trim($value, "'");
$trimmedvals[] = $value;
}

Thymeleaf: Concatenation - Could not parse as expression

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

Filter df when values matches part of a string in pyspark

pyspark.sql.Column.contains() is only available in pyspark version 2.2 and above.

df.where(df.location.contains('google.com'))

PHP Echo a large block of text

One option is to get out of the php block and just write HTML.

With your code, after the opening curly brace of your if statement, end the PHP:

if (is_single()) { ?>

Then remove the echo ' and the ';

After all your html and css, before the closing }, write:

<? } else {

If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Create WordPress Page that redirects to another URL

(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)

I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php all the time, or fiddle around with your server settings on each addition (I do not like both).

TLTR

You can add a filter on the actual WP permalink function you need (for me it was post_link, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.

This is ok, because the post is an alias, so you won't need the content anyways.

First step is to open the alias post and put the ID of the referenced post as content (and nothing else):

enter image description here

Next, open your functions.php and add:

function prefix_filter_post_permalink($url, $post) {
    // if the content of the post to get the permalink for is just a number...
    if (is_numeric($post->post_content)) {
        // instead, return the permalink for the post that has this ID
        return get_the_permalink((int)$post->post_content);
    }
    return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );

That's it

Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.

This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP code is far from ideal, but like this for making the point readable.

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

SQL - Update multiple records in one query

Execute the code below to update n number of rows, where Parent ID is the id you want to get the data from and Child ids are the ids u need to be updated so it's just u need to add the parent id and child ids to update all the rows u need using a small script.

    UPDATE [Table]
 SET couloumn1= (select couloumn1 FROM Table WHERE IDCouloumn = [PArent ID]),
     couloumn2= (select couloumn2 FROM Table WHERE IDCouloumn = [PArent ID]),
     couloumn3= (select couloumn3 FROM Table WHERE IDCouloumn = [PArent ID]),
     couloumn4= (select couloumn4 FROM Table WHERE IDCouloumn = [PArent ID]),
 WHERE IDCouloumn IN ([List of child Ids])

Programmatically find the number of cores on a machine

This functionality is part of the C++11 standard.

#include <thread>

unsigned int nthreads = std::thread::hardware_concurrency();

For older compilers, you can use the Boost.Thread library.

#include <boost/thread.hpp>

unsigned int nthreads = boost::thread::hardware_concurrency();

In either case, hardware_concurrency() returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
       Macro
    End If

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Mix Razor and Javascript code

Inside a code block (eg, @foreach), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag.

Inside the markup contexts, you need to surround code with code blocks (@{ ... } or @if, ...)

AngularJS : How to watch service variables?

You can insert the service in $rootScope and watch:

myApp.run(function($rootScope, aService){
    $rootScope.aService = aService;
    $rootScope.$watch('aService', function(){
        alert('Watch');
    }, true);
});

In your controller:

myApp.controller('main', function($scope){
    $scope.aService.foo = 'change';
});

Other option is to use a external library like: https://github.com/melanke/Watch.JS

Works with: IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Node.JS , Rhino 1.7+

You can observe the changes of one, many or all object attributes.

Example:

var ex3 = {
    attr1: 0,
    attr2: "initial value of attr2",
    attr3: ["a", 3, null]
};   
watch(ex3, function(){
    alert("some attribute of ex3 changes!");
});
ex3.attr3.push("new value");?

How to upload a file to directory in S3 bucket using boto

If you have the aws command line interface installed on your system you can make use of pythons subprocess library. For example:

import subprocess
def copy_file_to_s3(source: str, target: str, bucket: str):
   subprocess.run(["aws", "s3" , "cp", source, f"s3://{bucket}/{target}"])

Similarly you can use that logics for all sort of AWS client operations like downloading or listing files etc. It is also possible to get return values. This way there is no need to import boto3. I guess its use is not intended that way but in practice I find it quite convenient that way. This way you also get the status of the upload displayed in your console - for example:

Completed 3.5 GiB/3.5 GiB (242.8 MiB/s) with 1 file(s) remaining

To modify the method to your wishes I recommend having a look into the subprocess reference as well as to the AWS Cli reference.

Note: This is a copy of my answer to a similar question.

How to add a Try/Catch to SQL Stored Procedure

yep - you can even nest the try catch statements as:

BEGIN TRY
SET @myFixDte = CONVERT(datetime, @myFixDteStr,101)
END TRY
BEGIN CATCH
    BEGIN TRY
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,103)
END TRY
BEGIN CATCH
    BEGIN TRY
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,104)
    END TRY
    BEGIN CATCH
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,105)
    END CATCH
END CATCH END CATCH

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How do I get the current date in JavaScript?

This is good to get formatted date

_x000D_
_x000D_
let date = new Date().toLocaleDateString("en", {year:"numeric", day:"2-digit", month:"2-digit"});_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

How to read from stdin line by line in Node

You can use the readline module to read from stdin line by line:

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log(line);
})

Count the number of items in my array list

You want to count the number of itemids in your array. Simply use:

int counter=list.size();

Less code increases efficiency. Do not re-invent the wheel...

change the date format in laravel view page

In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting

In your Model just set:

protected $casts = [
    'my_custom_datetime_field' => 'datetime'
];

And then in your blade template you can use the format() method:

{{ $my_custom_datetime_field->format('d. m. Y') }}

ElasticSearch: Unassigned Shards, how to fix?

Maybe it helps someone, but I had the same issue and it was due to a lack of storage space caused by a log getting way too big.

Hope it helps someone! :)

How to hide Soft Keyboard when activity starts

You can set config on AndroidManifest.xml

Example:

<activity
    android:name="Activity"
    android:configChanges="orientation|keyboardHidden"
    android:theme="@*android:style/Theme.NoTitleBar"
    android:launchMode="singleTop"
    android:windowSoftInputMode="stateHidden"/>

How to cast from List<Double> to double[] in Java?

You can convert to a Double[] by calling frameList.toArray(new Double[frameList.size()]), but you'll need to iterate the list/array to convert to double[]

Save Dataframe to csv directly to s3 Python

I use AWS Data Wrangler. For example:

import awswrangler as wr
import pandas as pd

# read a local dataframe
df = pd.read_parquet('my_local_file.gz')

# upload to S3 bucket
wr.s3.to_parquet(df=df, path='s3://mys3bucket/file_name.gz')

The same applies to csv files. Instead of read_parquet and to_parquet, use read_csv and to_csv with the proper file extension.

sorting a List of Map<String, String>

There are many ways to solve the same. One of the easiest ways to solve using Java 8 is given below :

As per your requirement, To sort in alphabetical order based on the map's key name

1st way :

list = list.stream()
           .sorted((a,b)-> (a.get("name")).compareTo(b.get("name")))
           .collect(Collectors.toList());

Or,

list = list.stream()
           .sorted(Comparator.comparing(map->map.get("name")))
           .collect(Collectors.toList());

2nd way :

Collections.sort(list, Comparator.comparing(map -> map.get("name")));

3rd way :

list.sort(Comparator.comparing(map-> map.get("name")));

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I got the same problem and I just added the content of ~/.ssh/id_rsa.pub to my account in GitHub. After that just try again git push origin master, it should work.

Select current date by default in ASP.Net Calendar control

Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      DateTime dt = DateTime.Now.AddDays(-1);
      Calendar1.VisibleDate = dt;
      Calendar1.SelectedDate = dt;
      Calendar1.TodaysDate = dt;
      ...
    }
 }

In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

XPath: Get parent node from child node

New, improved answer to an old, frequently asked question...

How could I get its parent? Result should be the store node.

Use a predicate rather than the parent:: or ancestor:: axis

Most answers here select the title and then traverse up to the targeted parent or ancestor (store) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent:: or ancestor:: axes:

//*[book/title = "50"]

Should the intervening elements vary in name:

//*[*/title = "50"]

Or, in name and depth:

//*[.//title = "50"]

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

How to check a radio button with jQuery?

Use prop() mehtod

enter image description here

Source Link

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>

Java URL encoding of query string parameters

In android I would use this code:

Uri myUI = Uri.parse ("http://example.com/query").buildUpon().appendQueryParameter("q","random word A3500 bank 24").build();

Where Uri is a android.net.Uri

How to display line numbers in 'less' (GNU)

If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS doesn't include 'n'.

Turning off line numbers by default (for example, setting LESS=n) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.

I typically run with LESS=RSXin (escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less as needed.

Why am I getting Unknown error in line 1 of pom.xml?

Got this error on eclipse IDE version 4.10, Spring boot 2.2.0.M4, changed the Spring boot version to 2.2.0.M2 (after many other solutions recommended and it solved the error). Maybe something missing or broken in the latest version of Spring boot starter project module maven POM.

Swap two items in List<T>

If order matters, you should keep a property on the "T" objects in your list that denotes sequence. In order to swap them, just swap the value of that property, and then use that in the .Sort(comparison with sequence property)

Export table from database to csv file

Some ideas:

From SQL Server Management Studio

 1. Run a SELECT statement to filter your data
 2. Click on the top-left corner to select all rows
 3. Right-click to copy all the selected
 4. Paste the copied content on Microsoft Excel
 5. Save as CSV

Using SQLCMD (Command Prompt)

Example:

From the command prompt, you can run the query and export it to a file:

sqlcmd -S . -d DatabaseName -E -s, -W -Q "SELECT * FROM TableName" > C:\Test.csv

Do not quote separator use just -s, and not quotes -s',' unless you want to set quote as separator.

More information here: ExcelSQLServer

Notes:

  • This approach will have the "Rows affected" information in the bottom of the file, but you can get rid of this by using the "SET NOCOUNT ON" in the query itself.

  • You may run a stored procedure instead of the actual query (e.g. "EXEC Database.dbo.StoredProcedure")

  • You can use any programming language or even a batch file to automate this

Using BCP (Command Prompt)

Example:

bcp "SELECT * FROM Database.dbo.Table" queryout C:\Test.csv -c -t',' -T -S .\SQLEXPRESS

It is important to quote the comma separator as -t',' vs just -t,

More information here: bcp Utility

Notes:

  • As per when using SQLCMD, you can run stored procedures instead of the actual queries
  • You can use any programming language or a batch file to automate this

Hope this helps.

Properties file with a list as the value for an individual key

Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH

casting Object array to Integer array error

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
    c[i] = (Integer) a[i];
}

Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects can be anything besides Integers, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).

However, you can cast a subtype array to a supertype array (e.g. Integer[] to Object[])!

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

How can I revert a single file to a previous version?

You can take a diff that undoes the changes you want and commit that.

E.g. If you want to undo the changes in the range from..to, do the following

git diff to..from > foo.diff  # get a reverse diff
patch < foo.diff
git commit -a -m "Undid changes from..to".

How can I override the OnBeforeUnload dialog and replace it with my own?

What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.

$(window).one("beforeunload", BeforeUnload);

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

Shell script to get the process ID on Linux

As a start there is no need to do a ps -aux | grep... The command pidof is far better to use. And almost never ever do kill -9 see here

to get the output from a command in bash, use something like

pid=$(pidof ruby)

or use pkill directly.

Detect if a page has a vertical scrollbar?

try this:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll variable will contain true or false.

If you need to do a more thorough check, add the following to the code above:

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");

Is there a way to collapse all code blocks in Eclipse?

If you always want the code collapsed by default, go to Windows > Preferences. Search for "folding". Then check all the items under "Initially fold these elements".

enter image description here

How to add a hook to the application context initialization event?

I had a single page application on entering URL it was creating a HashMap (used by my webpage) which contained data from multiple databases. I did following things to load everything during server start time-

1- Created ContextListenerClass

public class MyAppContextListener implements ServletContextListener
    @Autowired

    private  MyDataProviderBean myDataProviderBean; 

    public MyDataProviderBean getMyDataProviderBean() {

        return MyDataProviderBean;

    }

    public void setMyDataProviderBean(MyDataProviderBean MyDataProviderBean) {

        this.myDataProviderBean = MyDataProviderBean;

    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("ServletContextListener destroyed");

    }


    @Override

    public void contextInitialized(ServletContextEvent context) {

        System.out.println("ServletContextListener started");

        ServletContext sc = context.getServletContext();

        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc);

        MyDataProviderBean MyDataProviderBean = (MyDataProviderBean)springContext.getBean("myDataProviderBean");

        Map<String, Object> myDataMap = MyDataProviderBean.getDataMap();

        sc.setAttribute("myMap", myDataMap);

    }

2- Added below entry in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
<listener>
    <listener-class>com.context.listener.MyAppContextListener</listener-class>
</listener>

3- In my Controller Class updated code to first check for Map in servletContext

    @RequestMapping(value = "/index", method = RequestMethod.GET)
        public String index(@ModelAttribute("model") ModelMap model) {

            Map<String, Object> myDataMap = new HashMap<String, Object>();
            if (context != null && context.getAttribute("myMap")!=null)
            {

                myDataMap=(Map<String, Object>)context.getAttribute("myMap");
            }

            else
            {

                myDataMap = myDataProviderBean.getDataMap();
            }

            for (String key : myDataMap.keySet())
            {
                model.addAttribute(key, myDataMap.get(key));
            }
            return "myWebPage";

        }

With this much change when I start my tomcat it loads dataMap during startTime and puts everything in servletContext which is then used by Controller Class to get results from already populated servletContext .

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How can I change the version of npm using nvm?

In windows, run your terminal as admin (in case there are permission issues as I had). Then use a specific node version (say 7.8.0) by

nvm use 7.8.0

then update your npm to desired specific version by

npm install -g [email protected]

Pointer to a string in C?

The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.

How to browse localhost on Android device?

Easier way to check is in browser of emulator type 10.0.2.2 instead of localhost.

Reference for localhost

Hope that helps! :)

ngrok command not found

In shorts,ngrok should be in same directory in which you are running ngrok command.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

Simple but usefull way:

$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
        return $query;

Eclipse Workspaces: What for and why?

Basically the scope of workspace(s) is divided in two points.

First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.

And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.

Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!

SonarQube Exclude a directory

This worked for me:

sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css

It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).

MySQL table is marked as crashed and last (automatic?) repair failed

I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".

  • Server type: MySQL
  • Server version: 5.7.23 - MySQL Community Server (GPL)
  • phpMyAdmin: Version information: 4.7.7

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

What are .tpl files? PHP, web design

Number 3 hit on Google for "tpl file" (even though it's one of those annoying "Fix TPL errors now", "Scan TPL files with our virus scanner", sell-you-everything-under-the-sun-with-flashy-ugly-ads-when-all-you-wanted-was-the-file-description sites) is:

Used by PHP web development and PHP web applications as a template file. Mostly used by Smarty template engine. Template is a common text file (like .html file) and contains user defined variables that are replaced by user defined output content when PHP web application parsing a template file.

CSS customized scroll bar in div

Like many people, I was looking for something that was:

  • Consistently styled and functional across most modern browsers
  • Not some ridiculous 3000-line bloated jQuery extension cr*p

...But alas - nothing!

Well if a job's worth doing... I was able to get something up and running in about 30 mins. Disclaimer: there's quite a few known (and probably a few as yet unknown) problems with it, but it makes me wonder what on Earth the other 2920 lines of JS are there for in many offerings!

_x000D_
_x000D_
(window => {

  let initCoords;

  const coords_update = e => {
    if (initCoords) {
      const elem = initCoords.bar.closest('.scrollr');
      const eSuffix = initCoords.axis.toUpperCase();
      const sSuffix = initCoords.axis == 'x' ? 'Left' : 'Top';
      const dSuffix = initCoords.axis == 'x' ? 'Width' : 'Height';
      const max = elem['scroll' + dSuffix] - elem['client' + dSuffix];
      const room = elem['client' + dSuffix] - initCoords.bar['client' + dSuffix];
      const delta = e['page' + eSuffix] - initCoords.abs;
      const abs = initCoords.p0 + delta;
      elem['scroll' + sSuffix] = max * abs / room;
    }
  };

  const scrollr_resize = elem => {
    const xBar = elem.querySelector('.track.x .bar');
    const yBar = elem.querySelector('.track.y .bar');
    const xRel = elem.clientWidth / elem.scrollWidth;
    const yRel = elem.clientHeight / elem.scrollHeight;
    xBar.style.width = (100 * xRel).toFixed(2) + '%';
    yBar.style.height = (100 * yRel).toFixed(2) + '%';
  };

  const scrollr_init = elem => {
    const xTrack = document.createElement('span');
    const yTrack = document.createElement('span');
    const xBar = document.createElement('span');
    const yBar = document.createElement('span');
    xTrack.className = 'track x';
    yTrack.className = 'track y';
    xBar.className = 'bar';
    yBar.className = 'bar';
    xTrack.appendChild(xBar);
    yTrack.appendChild(yBar);
    elem.appendChild(xTrack);
    elem.appendChild(yTrack);
    elem.addEventListener('wheel', scrollr_OnWheel);
    elem.addEventListener('scroll', scrollr_OnScroll);
    xTrack.addEventListener('wheel', xTrack_OnWheel);
    xTrack.addEventListener('click', xTrack_OnClick);
    xTrack.addEventListener('mouseover', () => xTrack.classList.add('active'));
    xTrack.addEventListener('mouseout', () => {
      if (!initCoords) xTrack.classList.remove('active');
    });
    yTrack.addEventListener('click', yTrack_OnClick);
    yTrack.addEventListener('mouseover', () => yTrack.classList.add('active'));
    yTrack.addEventListener('mouseout', () => {
      if (!initCoords) yTrack.classList.remove('active');
    });
    xBar.addEventListener('click', bar_OnClick);
    xBar.addEventListener('mousedown', xBar_OnMouseDown);
    yBar.addEventListener('click', bar_OnClick);
    yBar.addEventListener('mousedown', yBar_OnMouseDown);

    scrollr_resize(elem);
  };

  window.addEventListener('load', e => {
    const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
    scrollrz.forEach(scrollr_init);
  });

  window.addEventListener('resize', e => {
    const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
    scrollrz.forEach(scrollr_resize);
  });

  window.addEventListener('mousemove', coords_update);
  window.addEventListener('mouseup', e => {
    initCoords = null;
    Array.from(document.querySelectorAll('.track.active'))
      .forEach(elem => elem.classList.remove('active'));
  });

  function xBar_OnMouseDown(e) {
    const p0 = this.offsetLeft;
    initCoords = {
      axis: 'x',
      abs: e.pageX,
      bar: this,
      p0
    };
  }

  function yBar_OnMouseDown(e) {
    const p0 = this.offsetTop;
    initCoords = {
      axis: 'y',
      abs: e.pageY,
      bar: this,
      p0
    };
  }

  function bar_OnClick(e) {
    e.stopPropagation();
  }

  function xTrack_OnClick(e) {
    const elem = this.closest('.scrollr');
    const xBar = this.querySelector('.bar');
    let unit = elem.clientWidth - 30;
    if (e.offsetX <= xBar.offsetLeft) unit *= -1;
    elem.scrollLeft += unit;
  }

  function yTrack_OnClick(e) {
    const elem = this.closest('.scrollr');
    const yBar = this.querySelector('.bar');
    let unit = elem.clientHeight - 30;
    if (e.offsetY <= yBar.offsetTop) unit *= -1;
    elem.scrollTop += unit;
  }

  function xTrack_OnWheel(e) {
    e.stopPropagation();
    const elem = this.closest('.scrollr');
    const left0 = elem.scrollLeft;
    const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
    elem.scrollLeft += delta;
    const moved = left0 !== elem.scrollLeft;
    if (moved) e.preventDefault();
  }

  function scrollr_OnWheel(e) {
    const left0 = this.scrollLeft;
    const top0 = this.scrollTop;
    this.scrollLeft += e.deltaX;
    this.scrollTop += e.deltaY;
    const moved = left0 !== this.scrollLeft || top0 !== this.scrollTop;
    if (moved) e.preventDefault();
  }

  function scrollr_OnScroll(e) {
    const xTrack = this.querySelector('.track.x');
    const yTrack = this.querySelector('.track.y');
    const xBar = xTrack.querySelector('.bar');
    const yBar = yTrack.querySelector('.bar');

    const xMax = this.scrollWidth - this.clientWidth;
    const yMax = this.scrollHeight - this.clientHeight;
    const xFrac = this.scrollLeft / xMax;
    const yFrac = this.scrollTop / yMax;
    const xAbs = xFrac * (this.clientWidth - xBar.clientWidth);
    const yAbs = yFrac * (this.clientHeight - yBar.clientHeight);

    xTrack.style.left = this.scrollLeft + 'px';
    xTrack.style.bottom = -this.scrollTop + 'px';
    xBar.style.left = xAbs + 'px';

    yTrack.style.top = this.scrollTop + 'px';
    yTrack.style.right = -this.scrollLeft + 'px';
    yBar.style.top = yAbs + 'px';
  };

})(window);
_x000D_
.scrollr {
  overflow: hidden;
  position: relative;
}

.track {
  position: absolute;
  cursor: pointer;
  transition: background-color .3s;
  user-select: none;
}

.track.x {
  left: 0;
  bottom: 0;
  width: 100%;
  height: 10px;
}

.track.y {
  top: 0;
  right: 0;
  height: 100%;
  width: 10px;
}

.bar {
  position: absolute;
  background-color: yellow;
  transition: background-color .3s, opacity .3s, width .3s, height .3s, margin .3s;
  display: block;
  width: 100%;
  height: 100%;
  opacity: .7;
}

.track.x .bar {
  min-width: 25px;
  height: 3px;
  margin: 5px 0 2px 0;
}

.track.y .bar {
  min-height: 25px;
  width: 3px;
  margin: 0 2px 0 5px;
}

.track.active {
  background-color: #ccc;
}

.track.active .bar {
  background-color: #999;
  margin: 0;
  opacity: 1;
}

.track.x.active .bar {
  height: 10px;
}

.track.y.active .bar {
  width: 10px;
}


/* Custom client stuff */

.content {
  background: red;
}

.content p {
  width: 450px;
  margin: 0;
}

.scrollr {
  max-width: 350px;
  max-height: 150px;
}
_x000D_
<div class="scrollr content">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
</div>
_x000D_
_x000D_
_x000D_

How to return JSON data from spring Controller using @ResponseBody

I was facing same issue. I did not put @ResponseBody since I was using @RestController. But still I was getting error because I did not put the getter/setter method for the Company class. So after putting the getter/setter my problem was resolved.

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Describe table structure

For SQL Server use exec sp_help

USE db_name;
exec sp_help 'dbo.table_name'

For MySQL, use describe

DESCRIBE table_name;

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

inline conditionals in angular.js

So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )

This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}

{{vm.StateName === "AA" ? "ALL" : vm.StateName}}

What is the default scope of a method in Java?

Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

What is Dependency Injection?

Let's try simple example with Car and Engine classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.

public class Car
{
    public Car()
    {
        GasEngine engine = new GasEngine();
        engine.Start();
    }
}

public class GasEngine
{
    public void Start()
    {
        Console.WriteLine("I use gas as my fuel!");
    }
}

And to instantiate the Car class we will use next code:

Car car = new Car();

The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine.

In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:

    public interface IEngine
    {
        void Start();
    }

    public class GasEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I use gas as my fuel!");
        }
    }

    public class ElectricityEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I am electrocar");
        }
    }

    public class Car
    {
        private readonly IEngine _engine;
        public Car(IEngine engine)
        {
            _engine = engine;
        }

        public void Run()
        {
            _engine.Start();
        }
    }

Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine. Now, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where Dependency Injection comes in.

   Car gasCar = new Car(new GasEngine());
   gasCar.Run();
   Car electroCar = new Car(new ElectricityEngine());
   electroCar.Run();

Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.

The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.

So in the end Dependency injection is just a technique for achieving loose coupling between objects and their dependencies. Rather than directly instantiating dependencies that class needs in order to perform its actions, dependencies are provided to the class (most often) via constructor injection.

Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the IEngine dependency should be mapped to the GasEngine class and when we ask the IoC container for an instance of our Car class, it will automatically construct our Car class with a GasEngine dependency passed in.

UPDATE: Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

MATLAB error: Undefined function or method X for input arguments of type 'double'

Also, name it divrat.m, not divrat.M. This shouldn't matter on most OSes, but who knows...

You can also test whether matlab can find a function by using the which command, i.e.

which divrat

ASP.NET MVC 3 Razor - Adding class to EditorFor

No need to create custom template for MVC 4. Use TextBox instead of EditFor here special html attributes are not supported, it is only supported from MVC 5. TextBox is should support for MVC 4, I don't know about other version.

@Html.TextBox("test", "", new { @id = "signupform", @class = "form-control", @role = "form",@placeholder="Name" })

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

As for second question - you can use Fiddler filters to set response X-Frame-Options header manually to something like ALLOW-FROM *. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

jQuery Remove string from string

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];      
$("h1").text(name);

jsfiddle example

Postgresql: Scripting psql execution with password

PGPASSWORD=[your password] psql -Umyuser < myscript.sql

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".

You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.

Maven dependency of "spring-boot-starter-web" will look like

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to call Base Class's __init__ method from the child class?

You can call the super class's constructor like this

class A(object):
    def __init__(self, number):
        print "parent", number

class B(A):
    def __init__(self):
        super(B, self).__init__(5)

b = B()

NOTE:

This will work only when the parent class inherits object

sendUserActionEvent() is null

I solved this problem on my Galaxy S4 phone by replacing context.startActivity(addAccountIntent); with startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

How to load local html file into UIWebView

Here's Swift 3:

    if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
        do{
            let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
            messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
        }
        catch _ {
        }
    }

Async/Await Class Constructor

If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:

async function buildA(...) {
  const data = await fetch(...);
  return {
    getData: function() {
      return data;
    }
  }
}

and simple use it as

const a = await buildA(...);

If you're using typescript or flow, you can even enforce the interface of the constructors

Interface A {
  getData: object;
}

async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...

Copy multiple files with Ansible

Use the following source code for copy multiple files on your client machine.


 - name: Copy data to the client machine
   hosts: hostname
   become_method: sudo
   become_user: root
   become: true
   tasks: 
     # Copy twice as sometimes files get skipped (mostly only one file skipped from a folder if the folder does not exist)
     - name: Copy UFO-Server 
       copy:
         src: "source files path"
         dest: "destination file path"
         owner: root
         group: root
         mode: 0644
         backup: yes
       ignore_errors: true

Note:

If you are passing multiple paths by using variable then

src: "/root/{{ item }}"

If you are passing path by using a variable for different items then

src: "/root/{{ item.source_path }}"

How can I execute Python scripts using Anaconda's version of Python?

don't know windows 8 but you can probably set the default prog for a specific extension, for example on windows 7 you do right click => open with, then you select the prog you want and select 'use this prog as default', or you can remove your old version of python from your path and add the one of the anaconda

Use grep to report back only line numbers

I recommend the answers with sed and awk for just getting the line number, rather than using grep to get the entire matching line and then removing that from the output with cut or another tool. For completeness, you can also use Perl:

perl -nE '/pattern/ && say $.' filename

or Ruby:

ruby -ne 'puts $. if /pattern/' filename

How do I kill an Activity when the Back button is pressed?

Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause() is called when another activity gains focus, and onStop() is called when the activity is no longer visible.

From what I have learned yet, you can call finish() only from the activity which is active and/or has the focus. If you're calling finish() from the onPause() method that means you're calling it when the activity is no longer active. thus an exception is thrown.

When you're calling finish() from onStop() then the activity is being sent to background, thus will no longer be visible, then this exception.

When you press the back button, onStop() is called.

Most probably, Android will automatically do for you what you are currently wanting to do.

Android ImageView Zoom-in and Zoom-Out

I know it is a bit late for this answer, but I hope it helps someone.

I was looking for the same thing (Zoom using pinch, and dragging image) and I found this Android Developers Blog link.

Works perfect. No artifacts or what so ever. It uses ScaleGestureDetector.

How to automatically generate N "distinct" colors?

For the sake of generations to come I add here the accepted answer in Python.

import numpy as np
import colorsys

def _get_colors(num_colors):
    colors=[]
    for i in np.arange(0., 360., 360. / num_colors):
        hue = i/360.
        lightness = (50 + np.random.rand() * 10)/100.
        saturation = (90 + np.random.rand() * 10)/100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
    return colors

Remove pattern from string with gsub

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

JPA getSingleResult() or null

Spring has a utility method for this:

TypedQuery<Profile> query = em.createNamedQuery(namedQuery, Profile.class);
...
return org.springframework.dao.support.DataAccessUtils.singleResult(query.getResultList());

define() vs. const

I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.

As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:

  • Consts cannot be defined from an expression. const FOO = 4 * 3; doesn't work, but define('CONST', 4 * 3); does.
  • The name passed to define must include the namespace to be defined within that namespace.

The code below should illustrate the differences.

namespace foo 
{
    const BAR = 1;
    define('BAZ', 2);
    define(__NAMESPACE__ . '\\BAZ', 3);
}

namespace {
    var_dump(get_defined_constants(true));
}

The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3].

=== UPDATE ===

The upcoming PHP 5.6 will allow a bit more flexibility with const. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:

const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;

You still won't be able to define consts in terms of variables or function returns though, so

const RND = mt_rand();
const CONSTVAR = $var;

will still be out.

Auto-expanding layout with Qt-Designer

Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".

Gradle does not find tools.jar

I solved problem on this way:

Maven Install on Mac OS X

If you don't want to install Homebrew only for install Maven you could simply do this:

  1. Download the binary Maven and extract the zip

  2. Launch the Terminal and type this command:

    sudo ln -s /path_to_maven_folder/bin/mvn /usr/bin/mvn

You can find more details on this post.

Sort & uniq in Linux shell

Using sort -u does less I/O than sort | uniq, but the end result is the same. In particular, if the file is big enough that sort has to create intermediate files, there's a decent chance that sort -u will use slightly fewer or slightly smaller intermediate files as it could eliminate duplicates as it is sorting each set. If the data is highly duplicative, this could be beneficial; if there are few duplicates in fact, it won't make much difference (definitely a second order performance effect, compared to the first order effect of the pipe).

Note that there times when the piping is appropriate. For example:

sort FILE | uniq -c | sort -n

This sorts the file into order of the number of occurrences of each line in the file, with the most repeated lines appearing last. (It wouldn't surprise me to find that this combination, which is idiomatic for Unix or POSIX, can be squished into one complex 'sort' command with GNU sort.)

There are times when not using the pipe is important. For example:

sort -u -o FILE FILE

This sorts the file 'in situ'; that is, the output file is specified by -o FILE, and this operation is guaranteed safe (the file is read before being overwritten for output).

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If you want to ignore the certificate all together then take a look at the answer here: Ignore self-signed ssl cert using Jersey Client

Although this will make your app vulnerable to man-in-the-middle attacks.

Or, try adding the cert to your java store as a trusted cert. This site may be helpful. http://blog.icodejava.com/tag/get-public-key-of-ssl-certificate-in-java/

Here's another thread showing how to add a cert to your store. Java SSL connect, add server cert to keystore programmatically

The key is:

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(someCert);
ks.setEntry("someAlias", newEntry, null);

JAX-WS - Adding SOAP Headers

I struggled with all the answers here, starting with Pascal's solution, which is getting harder with the Java compiler not binding against rt.jar by default any more (and using internal classes makes it specific to that runtime implementation).

The answer from edubriguenti brought me close. The way the handler is hooked up in the final bit of code didn't work for me, though - it was never called.

I ended up using a variation of his handler class, but wired it into the javax.xml.ws.Service instance like this:

Service service = Service.create(url, qname); service.setHandlerResolver( portInfo -> Collections.singletonList(new SOAPHeaderHandler(handlerArgs)) );

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

TypeError: 'float' object is not callable

You have forgotten a * between -3.7 and (prof[x]).

Thus:

for x in range(len(prof)):
    PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))

Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

The name of the file should be Dockerfile and not .Dockerfile. The file should not have any extension.

HTML Entity Decode

To do it in pure javascript without jquery or predefining everything you can cycle the encoded html string through an elements innerHTML and innerText(/textContent) properties for every decode step that is required:

<html>
  <head>
    <title>For every decode step, cycle through innerHTML and innerText </title>
    <script>
function decode(str) {
  var d = document.createElement("div");
  d.innerHTML = str; 
  return typeof d.innerText !== 'undefined' ? d.innerText : d.textContent;
}
    </script>
  </head>
  <body>
    <script>
var encodedString = "&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style=\"font-size:xx-small;\"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;";
    </script>
    <input type=button onclick="document.body.innerHTML=decode(encodedString)"/>
  </body>
</html>

How to insert a text at the beginning of a file?

Another solution with aliases. Add to your init rc/ env file:

addtail () { find . -type f ! -path "./.git/*" -exec sh -c "echo $@ >> {}" \; }
addhead () { find . -type f ! -path "./.git/*" -exec sh -c  "sed -i '1s/^/$@\n/' {}" \; }

Usage:

addtail "string to add at the beginning of file"
addtail "string to add at the end of file"

jQuery check if an input is type checkbox?

Use this function:

function is_checkbox(selector) {
    var $result = $(selector);
    return $result[0] && $result[0].type === 'checkbox';
};

Or this jquery plugin:

$.fn.is_checkbox = function () { return this.is(':checkbox'); };

Cannot make a static reference to the non-static method fxn(int) from the type Two

You cannot refer non-static members from a static method.

Non-Static members (like your fxn(int y)) can be called only from an instance of your class.

Example:

You can do this:

       public class A
       {
           public   int fxn(int y) {
              y = 5;
              return y;
          }
       }


  class Two {
public static void main(String[] args) {
    int x = 0;
    A a = new A();
    System.out.println("x = " + x);
    x = a.fxn(x);
    System.out.println("x = " + x);
}

or you can declare you method as static.

Reverse order of foreach list items

You can use usort function to create own sorting rules

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Android SDK location

Try to open the Android Sdk manager and the path would be displayed on the status bar.

enter image description here

How to programmatically empty browser cache?

Imagine the .js files are placed in /my-site/some/path/ui/js/myfile.js

So normally the script tag would look like:

<script src="/my-site/some/path/ui/js/myfile.js"></script>

Now change that to:

<script src="/my-site/some/path/ui-1111111111/js/myfile.js"></script>

Now of course that will not work. To make it work you need to add one or a few lines to your .htaccess The important line is: (entire .htaccess at the bottom)

RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]

So what this does is, it kind of removes the 1111111111 from the path and links to the correct path.

So now if you make changes you just have to change the number 1111111111 to whatever number you want. And however you include your files you can set that number via a timestamp when the js-file has last been modified. So cache will work normally if the number does not change. If it changes it will serve the new file (YES ALWAYS) because the browser get's a complete new URL and just believes that file is so new he must go get it.

You can use this for CSS, favicons and what ever gets cached. For CSS just use like so

<link href="http://my-domain.com/my-site/some/path/ui-1492513798/css/page.css" type="text/css" rel="stylesheet">

And it will work! Simple to update, simple to maintain.

The promised full .htaccess

If you have no .htaccess yet this is the minimum you need to have there:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>

Where will log4net create this log file?

For the log folder and file stuff, go with @Bens answer.

I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:

ILog logger = LogManager.GetLogger(typeof(CCController));

because it is short and concise.

That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

How to force a line break in a long word in a DIV?

CSS word-wrap:break-word;, tested in FireFox 3.6.3

How do I view executed queries within SQL Server Management Studio?

If you want SSMS to maintain a query history, use the SSMS Tool Pack add on.

If you want to monitor the SQL Server for currently running queries, use SQL PRofiler as other have already suggested.

How do I use a PriorityQueue?

As an alternative to using Comparator, you can also have the class you're using in your PriorityQueue implement Comparable (and correspondingly override the compareTo method).

Note that it's generally best to only use Comparable instead of Comparator if that ordering is the intuitive ordering of the object - if, for example, you have a use case to sort Person objects by age, it's probably best to just use Comparator instead.

import java.lang.Comparable;
import java.util.PriorityQueue;

class Test
{
    public static void main(String[] args)
    {
        PriorityQueue<MyClass> queue = new PriorityQueue<MyClass>();
        queue.add(new MyClass(2, "short"));
        queue.add(new MyClass(2, "very long indeed"));
        queue.add(new MyClass(1, "medium"));
        queue.add(new MyClass(1, "very long indeed"));
        queue.add(new MyClass(2, "medium"));
        queue.add(new MyClass(1, "short"));
        while (queue.size() != 0)
            System.out.println(queue.remove());
    }
}
class MyClass implements Comparable<MyClass>
{
    int sortFirst;
    String sortByLength;

    public MyClass(int sortFirst, String sortByLength)
    {
        this.sortFirst = sortFirst;
        this.sortByLength = sortByLength;
    }

    @Override
    public int compareTo(MyClass other)
    {
        if (sortFirst != other.sortFirst)
            return Integer.compare(sortFirst, other.sortFirst);
        else
            return Integer.compare(sortByLength.length(), other.sortByLength.length());
    }

    public String toString()
    {
        return sortFirst + ", " + sortByLength;
    }
}

Output:

1, short
1, medium
1, very long indeed
2, short
2, medium
2, very long indeed

Group query results by month and year in postgresql

Postgres has few types of timestamps:

timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.

timestamp with timezone - The timezone offset is already included in the timestamp.

In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g. https://www.timeanddate.com/time/zone/romania/bucharest)

To add timezone you can use this example and replace the timezone offset with yours.

"your_date_column" at time zone '+03'

To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.

If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:

SELECT 
    "id", "Product", "Sale",
    date_trunc('month', 
        CASE WHEN 
            Extract(month from t."date") > 03 AND
            Extract(day from t."date") > 26 AND
            Extract(hour from t."date") > 3 AND
            Extract(month from t."date") < 10 AND
            Extract(day from t."date") < 29 AND
            Extract(hour from t."date") < 4
        THEN 
            t."date" at time zone '+03' -- Romania TimeZone offset + DST
        ELSE
            t."date" at time zone '+02' -- Romania TimeZone offset 
        END) as "date"
FROM 
    public."Table" AS t
WHERE 1=1
    AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
    AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month', 
    CASE WHEN 
        Extract(month from t."date") > 03 AND
        Extract(day from t."date") > 26 AND
        Extract(hour from t."date") > 3 AND
        Extract(month from t."date") < 10 AND
        Extract(day from t."date") < 29 AND
        Extract(hour from t."date") < 4
    THEN 
        t."date" at time zone '+03' -- Romania TimeZone offset + DST
    ELSE
        t."date" at time zone '+02' -- Romania TimeZone offset 
    END)

How do I get first element rather than using [0] in jQuery?

With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
 $("#grid_GridHeader").get(0)
 $("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
 ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

How to copy and edit files in Android shell?

Also if the goal is only to access the files on the phone. There is a File Explorer that is accessible from the Eclipse DDMS perspective. It lets you copy file from and to the device. So you can always get the file, modify it and put it back on the device. Of course it enables to access only the files that are not read protected.

If you don't see the File Explorer, from the DDMS perspective, go in "Window" -> "Show View" -> "File Explorer".

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

How to change package name of an Android Application

I found the easiest solution was to use Regexxer to replace "com.package.name" with "com.newpackage.name", then rename the directories properly. Super easy, super fast.

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

Create patch or diff file from git repository and apply it to another different git repository

To produce patch for several commits, you should use format-patch git command, e.g.

git format-patch -k --stdout R1..R2

This will export your commits into patch file in mailbox format.

To generate patch for the last commit, run:

git format-patch -k --stdout HEAD^

Then in another repository apply the patch by am git command, e.g.

git am -3 -k file.patch

See: man git-format-patch and git-am.

Lists: Count vs Count()

If you by any chance wants to change the type of your collection you are better served with the Count() extension. This way you don't have to refactor your code (to use Length for instance).

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

Laravel Eloquent - Get one Row

Try with it

$color = \App\Color::take(1)->first();

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

How different is Scrum practice from Agile Practice?

Comparision of Agile to Scrum is similar to comparision of organism to one organ.

Scrum suggests the way of management while it doesn't prescribe everything what is necessary to do to be able to react fast on changes. Only by adding other agile techniques like continuous integration, extreme programming, test driven development your teams will be able to deliver products not just fast, but also product that customer wants with great quality.

add a temporary column with a value

I giving you an example in wich the TABLE registrofaena doesn't have the column called minutos. Minutos is created and it content is a result of divide demora/60, in other words, i created a column to show the values of the delay in minutes.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

Sum one number to every element in a list (or array) in Python

If you don't want list comprehensions:

a = [1,1,1,1,1]
b = []
for i in a:
    b.append(i+1)

How to print a number with commas as thousands separators in JavaScript

You can use for loops to add commas to the number

function convertNumber(){
    var _cash = cash.toString()
    var _formattedCash = ''
    var count = 0

    for (let i = _cash.length; i >= 0; i--) {
        _formattedCash += _cash.substring(i,i+1)

        if(count == 3 && i > 0){
            _formattedCash += ','
            count = 0
        }
        count++
    }

    var _format = ''

    for (let i = _formattedCash.length; i >= 0; i--) {
        _format += _formattedCash.substring(i, i + 1)
    }

    return 'Ksh ' + _format;
}

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

In my case issue occurred after following:

I selected proxy settings from Android Studio settings when I was working in a network behind a proxy. When I disconnected from that network and connected to home network which doesn't have a proxy, I removed the proxy settings from Android Studio, but gradle seemed to take the old proxy settings.

The problem was that gradle had also saved the proxy settings in following file when I set proxy settings in Android Studio, but it hasn't got removed when I removed proxy settings from Android Studio.

%HOME%\.gradle\gradle.properties

When I removed the proxy settings from this file, gradle sync worked again.

Chmod 777 to a folder and all contents

You can also use chmod 777 *

This will give permissions to all files currently in the folder and files added in the future without giving permissions to the directory itself.

NOTE: This should be done in the folder where the files are located. For me it was an images that had an issue so I went to my images folder and did this.

C++ Double Address Operator? (&&)

I believe that is is a move operator. operator= is the assignment operator, say vector x = vector y. The clear() function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.

This way,

std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
    std::cout << b[i] << ' ';
}

Even though we gave vector a values, vector b has the values. It's the magic of the operator=()!

MSDN -- How to create a move constructor

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

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

In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:

@media print{
* {
    display:inline;
}
script, style { 
    display:none; 
}
div {
    page-break-inside:avoid;
}

}

It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.

Maybe someone could expand on this.

Fastest way to count exact number of rows in a very large table?

Put an index on some column. That should allow the optimizer to perform a full scan of the index blocks, instead of a full scan of the table. That will cut your IO costs way down. Look at the execution plan before and after. Then measure wall clock time both ways.

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

Insert Picture into SQL Server 2005 Image Field using only SQL

Create Table:

Create Table EmployeeProfile ( 
    EmpId int, 
    EmpName varchar(50) not null, 
    EmpPhoto varbinary(max) not null ) 
Go

Insert statement:

Insert EmployeeProfile 
   (EmpId, EmpName, EmpPhoto) 
   Select 1001, 'Vadivel', BulkColumn 
   from Openrowset( Bulk 'C:\Image1.jpg', Single_Blob) as EmployeePicture

This Sql Query Working Fine.

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

How can I break from a try/catch block without throwing an exception in Java

The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:

public void someMethod() {
    try {
        ...
        if (condition)
            return;
        ...
    } catch (SomeException e) {
        ...
    }
}

If the code involves lots of local variables, you may also consider using a break from a labeled block, as suggested by Stephen C:

label: try {
    ...
    if (condition)
        break label;
    ...
} catch (SomeException e) {
    ...
}

Collapsing Sidebar with Bootstrap

Via Angular: using ng-class of Angular, we can hide and show the side bar.

http://jsfiddle.net/DVE4f/359/

<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
    <div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
        Sidebar
    </div>
    <div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'"  id="colMain"  >
        <button  ng-click='toggle()' >Sidebar Toggle</a>
    </div>    
  </div>
</div>

.

function AppCtrl($scope) {
    $scope.showgraphSidebar = false;
    $scope.toggle = function() {
        $scope.showgraphSidebar = !$scope.showgraphSidebar;
    }
}

Pandas: rolling mean by time interval

This example seems to call for a weighted mean as suggested in @andyhayden's comment. For example, there are two polls on 10/25 and one each on 10/26 and 10/27. If you just resample and then take the mean, this effectively gives twice as much weighting to the polls on 10/26 and 10/27 compared to the ones on 10/25.

To give equal weight to each poll rather than equal weight to each day, you could do something like the following.

>>> wt = df.resample('D',limit=5).count()

            favorable  unfavorable  other
enddate                                  
2012-10-25          2            2      2
2012-10-26          1            1      1
2012-10-27          1            1      1

>>> df2 = df.resample('D').mean()

            favorable  unfavorable  other
enddate                                  
2012-10-25      0.495        0.485  0.025
2012-10-26      0.560        0.400  0.040
2012-10-27      0.510        0.470  0.020

That gives you the raw ingredients for doing a poll-based mean instead of a day-based mean. As before, the polls are averaged on 10/25, but the weight for 10/25 is also stored and is double the weight on 10/26 or 10/27 to reflect that two polls were taken on 10/25.

>>> df3 = df2 * wt
>>> df3 = df3.rolling(3,min_periods=1).sum()
>>> wt3 = wt.rolling(3,min_periods=1).sum()

>>> df3 = df3 / wt3  

            favorable  unfavorable     other
enddate                                     
2012-10-25   0.495000     0.485000  0.025000
2012-10-26   0.516667     0.456667  0.030000
2012-10-27   0.515000     0.460000  0.027500
2012-10-28   0.496667     0.465000  0.041667
2012-10-29   0.484000     0.478000  0.042000
2012-10-30   0.488000     0.474000  0.042000
2012-10-31   0.530000     0.450000  0.020000
2012-11-01   0.500000     0.465000  0.035000
2012-11-02   0.490000     0.470000  0.040000
2012-11-03   0.490000     0.465000  0.045000
2012-11-04   0.500000     0.448333  0.035000
2012-11-05   0.501429     0.450000  0.032857
2012-11-06   0.503333     0.450000  0.028333
2012-11-07   0.510000     0.435000  0.010000

Note that the rolling mean for 10/27 is now 0.51500 (poll-weighted) rather than 52.1667 (day-weighted).

Also note that there have been changes to the APIs for resample and rolling as of version 0.18.0.

rolling (what's new in pandas 0.18.0)

resample (what's new in pandas 0.18.0)

docker cannot start on windows

You can run "C:\Program Files\Docker\Docker\DockerCli.exe" -SwitchDaemon and point Docker CLI to either Linux or Windows containers. This worked for me.

The mysqli extension is missing. Please check your PHP configuration

I know this is a while ago but I encountered this and followed the other answers here but to no avail, I found the solution via this question (Stackoverflow Question)

Essentially just needed to edit the php.ini file (mine was found at c:\xampp\php\php.ini) and uncomment these lines...

;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

After restarting apache all was working as expected.

How can I put a database under git (version control)?

This question is pretty much answered but I would like to complement X-Istence's and Dana the Sane's answer with a small suggestion.

If you need revision control with some degree of granularity, say daily, you could couple the text dump of both the tables and the schema with a tool like rdiff-backup which does incremental backups. The advantage is that instead of storing snapshots of daily backups, you simply store the differences from the previous day.

With this you have both the advantage of revision control and you don't waste too much space.

In any case, using git directly on big flat files which change very frequently is not a good solution. If your database becomes too big, git will start to have some problems managing the files.

Reversing a String with Recursion in Java

You need to remember that you won't have just one call - you'll have nested calls. So when the "most highly nested" call returns immediately (when it finds just "o"), the next level up will take str.charAt(0) - where str is "lo" at that point. So that will return "ol".

Then the next level will receive "ol", execute str.charAt(0) for its value of str (which is "llo"), returning "oll" to the next level out.

Then the next level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "ello"), returning "olle" to the next level out.

Then the final level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "hello"), returning "olleh" to the original caller.

It may make sense to think of the stack as you go:

// Most deeply nested call first...
reverse("o") -> returns "o"
reverse("lo") -> adds 'l', returns "ol" 
reverse("llo") -> adds 'l', returns "oll" 
reverse("ello") -> adds 'e', returns "olle" 
reverse("hello") -> adds 'h', returns "olleh" 

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

There are some modules and packages only necessary for development, which are not needed in production. Like it says it in the documentation:

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use. In this case, it's best to list these additional items in a devDependencies hash.

Redirecting output to $null in PowerShell, but ensuring the variable remains set

using a function:

function run_command ($command)
{
    invoke-expression "$command *>$null"
    return $_
}

if (!(run_command "dir *.txt"))
{
    if (!(run_command "dir *.doc"))
    {
        run_command "dir *.*"
    }
}

or if you like one-liners:

function run_command ($command) { invoke-expression "$command  "|out-null; return $_ }

if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }

SQL Server - In clause with a declared variable

This is an example where I use the table variable to list multiple values in an IN clause. The obvious reason is to be able to change the list of values only one place in a long procedure.

To make it even more dynamic and alowing user input, I suggest declaring a varchar variable for the input, and then using a WHILE to loop trough the data in the variable and insert it into the table variable.

Replace @your_list, Your_table and the values with real stuff.

DECLARE @your_list TABLE (list varchar(25)) 
INSERT into @your_list
VALUES ('value1'),('value2376')

SELECT *  
FROM your_table 
WHERE your_column in ( select list from @your_list )

The select statement abowe will do the same as:

SELECT *  
FROM your_table 
WHERE your_column in ('value','value2376' )

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

How can I count the rows with data in an Excel sheet?

With formulas, what you can do is:

  • in a new column (say col D - cell D2), add =COUNTA(A2:C2)
  • drag this formula till the end of your data (say cell D4 in our example)
  • add a last formula to sum it up (e.g in cell D5): =SUM(D2:D4)