Programs & Examples On #Cllocationdistance

Part of the Core Location Data Types. This is a distance measurement (in meters) from an existing location.

Failed to load ApplicationContext from Unit Test: FileNotFound

I added the spring folder to the build path and, after clean&build, it worked.

Select count(*) from multiple tables

As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.

Is there a destructor for Java?

I agree with most of the answers.

You should not depend fully on either finalize or ShutdownHook

finalize

  1. The JVM does not guarantee when this finalize() method will be invoked.

  2. finalize() gets called only once by GC thread. If an object revives itself from finalizing method, then finalize will not be called again.

  3. In your application, you may have some live objects, on which garbage collection is never invoked.

  4. Any Exception that is thrown by the finalizing method is ignored by the GC thread

  5. System.runFinalization(true) and Runtime.getRuntime().runFinalization(true) methods increase the probability of invoking finalize() method but now these two methods have been deprecated. These methods are very dangerous due to lack of thread safety and possible deadlock creation.

shutdownHooks

public void addShutdownHook(Thread hook)

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  1. The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

  2. The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

  3. A shutdown hook is simply an initialized but non-started thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled.

  4. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if the shutdown was initiated by invoking the exit method.

  5. Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit.

    But even Oracle documentation quoted that

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly

This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

Conclusion : use try{} catch{} finally{} blocks appropriately and release critical resources in finally(} block. During release of resources in finally{} block, catch Exception and Throwable.

"getaddrinfo failed", what does that mean?

Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust

Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.

You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings

Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.

Click Ok Come back to anaconda terminal and you can try install commands

How to compare two Dates without the time portion?

If you just want to compare only two dates without time, then following code might help you:

final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date dLastUpdateDate = dateFormat.parse(20111116);
Date dCurrentDate = dateFormat.parse(dateFormat.format(new Date()));
if (dCurrentDate.after(dLastUpdateDate))
{
   add your logic
}

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

For me the issue was in the php.ini file. The property mysql.default_socket was pointing to file in a non-existent directory. The property was pointing to /var/mysql/mysql.sock but in OSX, the file was located in /tmp/mysql.sock.

Once I updated the entry in php.ini and restarted the webserver, the issue was resolved.

JQuery DatePicker ReadOnly

During initialization you have to set to false the option enableOnReadonly which by default is true.

$('#datepicker').datepicker({
    enableOnReadonly: false
});

Then, you need to make the field readonly

$('#datepicker').prop('readonly', true);

See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly

How to compare numbers in bash?

If you have floats you can write a function and then use that e.g.

#!/bin/bash

function float_gt() {
    perl -e "{if($1>$2){print 1} else {print 0}}"
}

x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
    echo "do stuff with x"
else
    echo "do stuff with y"
fi

Git mergetool generates unwanted .orig files

The option to save the .orig file can be disabled by configuring KDiff3

KDiff3 Backup file .orig option

Getting a slice of keys from a map

I made a sketchy benchmark on the three methods described in other responses.

Obviously pre-allocating the slice before pulling the keys is faster than appending, but surprisingly, the reflect.ValueOf(m).MapKeys() method is significantly slower than the latter:

? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s

Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)

Creating Threads in python

Python 3 has the facility of Launching parallel tasks. This makes our work easier.

It has for thread pooling and Process pooling.

The following gives an insight:

ThreadPoolExecutor Example

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

Another Example

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

How to execute powershell commands from a batch file?

This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.

pros:

  • can be run like standard .cmd file
  • only one file for batch and powershell script
  • powershell script may be multi-line (easy to read script)
  • allows the standard console input (use the Read-Host cmdlet by standard way)

cons:

  • requires powershell version 2.0+

Commented and runable example of batch-ps-script.cmd:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

Snippet for .cmd file:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

How to show matplotlib plots in python

Save the plot as png

plt.savefig("temp.png")

How do I make this file.sh executable via double click?

Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

How can I convert string to datetime with format specification in JavaScript?

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

function ParseDate(dateString) {
    //dd.mm.yyyy, or dd.mm.yy
    var dateArr = dateString.split(".");
    if (dateArr.length == 1) {
        return null;    //wrong format
    }
    //parse time after the year - separated by space
    var spacePos = dateArr[2].indexOf(" ");
    if(spacePos > 1) {
        var timeString = dateArr[2].substr(spacePos + 1);
        var timeArr = timeString.split(":");
        dateArr[2] = dateArr[2].substr(0, spacePos);
        if (timeArr.length == 2) {
            //minutes only
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
        } else {
            //including seconds
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
        }
    } else {
        //gotcha at months - January is at 0, not 1 as one would expect
        return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
    }
}

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

Faced with the same situation playing with Javascript . Unfortunately Chrome doesn't allow to access javascript workers stored in a local file.

One kind of workaround below using a local storage is to running Chrome with --allow-file-access-from-files (with s at the end), but only one instance of Chrome is allowed, which is not too convenient for me. For this reason i'm using Chrome Canary, with file access allowed.

BTW in Firefox there is no such an issue.

Delete a row from a table by id

to Vilx-:

var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
    table = table.parentNode;

and what if row.parentNode is TBODY?

You should check it out first, and after that do while by .tBodies, probably

What are valid values for the id attribute in HTML?

Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and JQuery. The following should work but it must be unique throughout the page and also must start with a letter [A-Za-z].

Working with colons and periods needs a bit more work but you can do it as the following example shows.

<html>
<head>
<title>Cake</title>
<style type="text/css">
    #i\.Really\.Like\.Cake {
        color: green;
    }
    #i\:Really\:Like\:Cake {
        color: blue;
    }
</style>
</head>
<body>
    <div id="i.Really.Like.Cake">Cake</div>
    <div id="testResultPeriod"></div>

    <div id="i:Really:Like:Cake">Cake</div>
    <div id="testResultColon"></div>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            var testPeriod = $("#i\\.Really\\.Like\\.Cake");
            $("#testResultPeriod").html("found " + testPeriod.length + " result.");

            var testColon = $("#i\\:Really\\:Like\\:Cake");
            $("#testResultColon").html("found " + testColon.length + " result.");
        });
    </script>
</body>
</html>

Comparing HTTP and FTP for transferring files

Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.

I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.

Heres another good comparison of individual characteristics of each protocol.

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How can I wait for set of asynchronous callback functions?

Use an control flow library like after

after.map(array, function (value, done) {
    // do something async
    setTimeout(function () {
        // do something with the value
        done(null, value * 2)
    }, 10)
}, function (err, mappedArray) {
    // all done, continue here
    console.log(mappedArray)
})

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

Get number days in a specified month using JavaScript?

Another possible option would be to use Datejs

Then you can do

Date.getDaysInMonth(2009, 9)     

Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I'm working on Windows Server 2012. .NET Extensibility 4.5 feature is on. WebDAVModule removed. I was still getting 500.21 error on ASP.NET route '/docs'.

Changing 'skipManagedModules' to false fixed the problem.

<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
        <add initializationPage="/docs" />    
</applicationInitialization>

Thanks to https://groups.google.com/forum/#!topic/bonobo-git-server/GbdMXdDO4tI

Getting the thread ID from a thread

For those about to hack:

    public static int GetNativeThreadId(Thread thread)
    {
        var f = typeof(Thread).GetField("DONT_USE_InternalThread",
            BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

        var pInternalThread = (IntPtr)f.GetValue(thread);
        var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 548 : 348); // found by analyzing the memory
        return nativeId;
    }

React-Native: Module AppRegistry is not a registered callable module

If you are using some of the examples they might not work

Here is my version for scroll view

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image
} from 'react-native';

class AwesomeProject extends Component {
  render() {
    return (
        <View>
          <ScrollView
            ref={(scrollView) => { _scrollView = scrollView; }}
            automaticallyAdjustContentInsets={false}
            onScroll={() => { console.log('onScroll!'); }}
            scrollEventThrottle={200}
            style={styles.scrollView}>
            {THUMBS.map(createThumbRow)}
          </ScrollView>
          <TouchableOpacity
            style={styles.button}
            onPress={() => { _scrollView.scrollTo({y: 0}); }}>
            <Text>Scroll to top</Text>
          </TouchableOpacity>
        </View>
    );
  }
}

var Thumb = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
    return false;
  },
  render: function() {
    return (
      <View style={styles.button}>
        <Image style={styles.img} source={{uri:this.props.uri}} />
      </View>
    );
  }
});

var THUMBS = [
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1
];

THUMBS = THUMBS.concat(THUMBS); // double length of THUMBS
var createThumbRow = (uri, i) => <Thumb key={i} uri={uri} />;

var styles = StyleSheet.create({
  scrollView: {
    backgroundColor: '#6A85B1',
    height: 600,
  },
  horizontalScrollView: {
    height: 120,
  },
  containerPage: {
    height: 50,
    width: 50,
    backgroundColor: '#527FE4',
    padding: 5,
  },
  text: {
    fontSize: 20,
    color: '#888888',
    left: 80,
    top: 20,
    height: 40,
  },
  button: {
    margin: 7,
    padding: 5,
    alignItems: 'center',
    backgroundColor: '#eaeaea',
    borderRadius: 3,
  },
  buttonContents: {
    flexDirection: 'row',
    width: 64,
    height: 64,
  },
  img: {
    width: 321,
    height: 200,
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

What is the <leader> in a .vimrc file?

The <Leader> key is mapped to \ by default. So if you have a map of <Leader>t, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader variable, see

:help leader

To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used.  It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead.  
Example:
    :map <Leader>A  oanother line <Esc>
Works like:
    :map \A  oanother line <Esc>
But after:
    :let mapleader = ","
It works like:
    :map ,A  oanother line <Esc>

Note that the value of "mapleader" is used at the moment the mapping is
defined.  Changing "mapleader" after that has no effect for already defined
mappings.


LaTeX Optional Arguments

Example from the guide:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

Mutex lock threads

What you need to do is to call pthread_mutex_lock to secure a mutex, like this:

pthread_mutex_lock(&mutex);

Once you do this, any other calls to pthread_mutex_lock(mutex) will not return until you call pthread_mutex_unlock in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will be able to (incorrectly) use the shared resource. You should call pthread_mutex_lock from within your fooAPI function, and that will cause the function to wait until the shared resource is available.

So you would have something like this:

#include <pthread.h>
#include <stdio.h>

int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* fooAPI(void* param)
{
    pthread_mutex_lock(&mutex);
    printf("Changing the shared resource now.\n");
    sharedResource = 42;
    pthread_mutex_unlock(&mutex);
    return 0;
}

int main()
{
    pthread_t thread;

    // Really not locking for any reason other than to make the point.
    pthread_mutex_lock(&mutex);
    pthread_create(&thread, NULL, fooAPI, NULL);
    sleep(1);
    pthread_mutex_unlock(&mutex);

    // Now we need to lock to use the shared resource.
    pthread_mutex_lock(&mutex);
    printf("%d\n", sharedResource);
    pthread_mutex_unlock(&mutex);
}

Edit: Using resources across processes follows this same basic approach, but you need to map the memory into your other process. Here's an example using shmem:

#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>

struct shared {
    pthread_mutex_t mutex;
    int sharedResource;
};

int main()
{
    int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600);
    ftruncate(fd, sizeof(struct shared));

    struct shared *p = (struct shared*)mmap(0, sizeof(struct shared),
        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    p->sharedResource = 0;

    // Make sure it can be shared across processes
    pthread_mutexattr_t shared;
    pthread_mutexattr_init(&shared);
    pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED);

    pthread_mutex_init(&(p->mutex), &shared);

    int i;
    for (i = 0; i < 100; i++) {
        pthread_mutex_lock(&(p->mutex));
        printf("%d\n", p->sharedResource);
        pthread_mutex_unlock(&(p->mutex));
        sleep(1);
    }

    munmap(p, sizeof(struct shared*));
    shm_unlink("/foo");
}

Writing the program to make changes to p->sharedResource is left as an exercise for the reader. :-)

Forgot to note, by the way, that the mutex has to have the PTHREAD_PROCESS_SHARED attribute set, so that pthreads will work across processes.

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

What are the differences between the BLOB and TEXT datatypes in MySQL?

A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field

L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.

Reference: http://dev.mysql.com/doc/refman/5.0/en/blob.html

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

How to set image on QPushButton?

Just use this code

QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);

Note that:"path_to_icon" is the path of image icon in file .qrc of your project You can find how to add .qrc file here

How can I run multiple npm scripts in parallel?

npm install npm-run-all --save-dev

package.json:

"scripts": {
  "start-watch": "...",
  "wp-server": "...",
  "dev": "npm-run-all --parallel start-watch wp-server"
}

More info: https://github.com/mysticatea/npm-run-all/blob/master/docs/npm-run-all.md

Java String remove all non numeric characters

Try this code:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");

Now str will contain "12.334.78".

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

This is an inverted version of @Jeff's answer* where a hidden character (U+115F, U+1160 or U+3164) is used to create variables that look like 1, 2 and 3.

_x000D_
_x000D_
var  a = 1;_x000D_
var ?1 = a;_x000D_
var ?2 = a;_x000D_
var ?3 = a;_x000D_
console.log( a ==?1 && a ==?2 && a ==?3 );
_x000D_
_x000D_
_x000D_

* That answer can be simplified by using zero width non-joiner (U+200C) and zero width joiner (U+200D). Both of these characters are allowed inside identifiers but not at the beginning:

_x000D_
_x000D_
var a = 1;_x000D_
var a? = 2;_x000D_
var a? = 3;_x000D_
console.log(a == 1 && a? == 2 && a? == 3);_x000D_
_x000D_
/****_x000D_
var a = 1;_x000D_
var a\u200c = 2;_x000D_
var a\u200d = 3;_x000D_
console.log(a == 1 && a\u200c == 2 && a\u200d == 3);_x000D_
****/
_x000D_
_x000D_
_x000D_

Other tricks are possible using the same idea e.g. by using Unicode variation selectors to create variables that look exactly alike (a? = 1; a? = 2; a? == 1 && a? == 2; // true).

What is a serialVersionUID and why should I use it?

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.

Specifying one gives more control, though JVM does generate one if you don't specify. The value generated can differ between different compilers. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects [backward incompatibility], and in this case you just have to change the serialVersionUID.

The javadocs for Serializable say:

the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Therefore, you must declare serialVersionUID because it give us more control.

This article has some good points on the topic.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation

The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.

Hope this saves somebody else some time, and teaches the search engines about this open source gem :)

AngularJS not detecting Access-Control-Allow-Origin header?

It's a bug in chrome for local dev. Try other browser. Then it'll work.

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to configure custom PYTHONPATH with VM and PyCharm?

In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.

Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.

See e.g. this SO question for more details on .pth files....

PHP Redirect to another page after form submit

First give your input type submit a name, like this name='submitform'.

and then put this in your php file

if (isset($_POST['submitform']))
    {   
    ?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>      
    <?php
    }

Don't forget to change the url to yours.

How should I remove all the leading spaces from a string? - swift

I'd use this extension, to be flexible and mimic how other collections do it:

extension String {
    func filter(pred: Character -> Bool) -> String {
        var res = String()
        for c in self.characters {
            if pred(c) {
                res.append(c)
            }
        }
        return res
    }
}

"this is a String".filter { $0 != Character(" ") } // "thisisaString"

Why aren't programs written in Assembly more often?

I can only answer why I personally don't write programs in assembly more often, and the main reason is that it's more tedious to do. Also, I think that it is easier to get things subtly wrong without noticing immediately. E.g., you might change the way you use a register in one routine but forget to change this in one place. It'll assemble fine and you may not notice until much later.

That said, I do think there are still valid uses for assembly. For instance, I have a number of pretty optimised assembly routines for processing large amounts of data, using SIMD and following the paranoid "every bit is sacred"[quote V.Stob] approach. (But note that naive assembly implementations are often a lot worse than what a compiler would generate for you.)

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Virtual member call in a constructor

In C#, a base class' constructor runs before the derived class' constructor, so any instance fields that a derived class might use in the possibly-overridden virtual member are not initialized yet.

Do note that this is just a warning to make you pay attention and make sure it's all-right. There are actual use-cases for this scenario, you just have to document the behavior of the virtual member that it can not use any instance fields declared in a derived class below where the constructor calling it is.

How to write a simple Java program that finds the greatest common divisor between two numbers?

One way to do it is the code below:

        int gcd = 0;
        while (gcdNum2 !=0 && gcdNum1 != 0 ) {
        if(gcdNum1 % gcdNum2 == 0){
            gcd = gcdNum2;
        }
            int aux = gcdNum2; 
            gcdNum2 = gcdNum1 % gcdNum2;
            gcdNum1 = aux;
    }

You do not need recursion to do this.

And be careful, it says that when a number is zero, then the GCD is the number that is not zero.

    while (gcdNum1 == 0) {
    gcdNum1 = 0;
}

You should modify this to fulfill the requirement.

I am not going to tell you how to modify your code entirely, only how to calculate the gcd.

JavaScriptSerializer - JSON serialization of enum as string

This is an old question but I thought I'd contribute just in case. In my projects I use separate models for any Json requests. A model would typically have same name as domain object with "Json" prefix. Models are mapped using AutoMapper. By having the json model declare a string property that is an enum on domain class, AutoMapper will resolve to it's string presentation.

In case you are wondering, I need separate models for Json serialized classes because inbuilt serializer comes up with circular references otherwise.

Hope this helps someone.

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

Get week number (in the year) from a date PHP

To get the week number for a date in North America I do like this:

function week_number($n)
{
    $w = date('w', $n);
    return 1 + date('z', $n + (6 - $w) * 24 * 3600) / 7;
}

$n = strtotime('2022-12-27');
printf("%s: %d\n", date('D Y-m-d', $n), week_number($n));

and get:

Tue 2022-12-27: 53

How to trigger checkbox click event even if it's checked through Javascript code?

You can use the jQuery .trigger() method. See http://api.jquery.com/trigger/

E.g.:

$('#foo').trigger('click');

Select tableview row programmatically

There are two different methods for iPad and iPhone platforms, so you need to implement both:

  • selection handler and
  • segue.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    // Selection handler (for horizontal iPad)
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    
    // Segue (for iPhone and vertical iPad)
    [self performSegueWithIdentifier:"showDetail" sender:self];
    

What is the difference between ports 465 and 587?

587 vs. 465

These port assignments are specified by the Internet Assigned Numbers Authority (IANA):

  • Port 587: [SMTP] Message submission (SMTP-MSA), a service that accepts submission of email from email clients (MUAs). Described in RFC 6409.
  • Port 465: URL Rendezvous Directory for SSM (entirely unrelated to email)

Historically, port 465 was initially planned for the SMTPS encryption and authentication “wrapper” over SMTP, but it was quickly deprecated (within months, and over 15 years ago) in favor of STARTTLS over SMTP (RFC 3207). Despite that fact, there are probably many servers that support the deprecated protocol wrapper, primarily to support older clients that implemented SMTPS. Unless you need to support such older clients, SMTPS and its use on port 465 should remain nothing more than an historical footnote.

The hopelessly confusing and imprecise term, SSL, has often been used to indicate the SMTPS wrapper and TLS to indicate the STARTTLS protocol extension.

For completeness: Port 25

  • Port 25: Simple Mail Transfer (SMTP-MTA), a service that accepts submission of email from other servers (MTAs or MSAs). Described in RFC 5321.

Sources:

What does the 'L' in front a string mean in C++?

It means that it is a wide character, wchar_t.

Similar to 1L being a long value.

Start service in Android

Intent serviceIntent = new Intent(this,YourActivity.class);

startService(serviceIntent);

add service in manifist

<service android:enabled="true" android:name="YourActivity.class" />

for running service on oreo and greater devices use for ground service and show notification to user

or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

You can use [FromBody] but you need to set the Content-Type header of your request to application/json, i.e.

Content-Type: application/json

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

How to open a new window on form submit

The code you have given, needs to be corrected. In form tag you have to enclosed the onClick attribute value in double quote:

"window.open('google.htm','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');"

You also need to take care that first parameter of window.open should also be enclosed using quotes.

How to fully clean bin and obj folders within Visual Studio?

Check out Ron Jacobs fantastic open source CleanProject It even takes care of the zipping if you like.

Here is the CodePlex link

How do you automatically set the focus to a textbox when a web page loads?

IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

$(document).ready(function() {
  $('input:text[value=""]:visible:enabled:first').focus();
});

Hope that helps...

Thanks...

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

Redirecting to a new page after successful login

First of all, move all your PHP code to the top. Without it, my code below wont work.

To do the redirect, use:

header('Location: http://www.example.com/');

Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.

Here you can find useful links to free books: https://stackoverflow.com/tags/php/info

Using PHP variables inside HTML tags?

You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:

echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";

echo '<a href="http://www.whatever.com/' . $param . '">Click Here</a>';

Notice that I escaped the double quotes inside my first example using a backslash.

Regular expression that matches valid IPv6 addresses

Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed, as you can see from some of these answers.

The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.

Code example:

        try {
            IPAddressString str = new IPAddressString("::1");
            IPAddress addr = str.toAddress();
            if(addr.isIPv6() || addr.isIPv6Convertible()) {
                IPv6Address ipv6Addr = addr.toIPv6();
            }
            //use address
        } catch(AddressStringException e) {
            //e.getMessage has validation error
        }

Linq select to new object

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

Determining the size of an Android view at runtime

You can check this question. You can use the View's post() method.

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

How to allow download of .json file with ASP.NET

Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config and I was able to add in the correct "mime map" there.

Appending to an object

jQuery $.extend(obj1, obj2) would merge 2 objects for you, but you should really be using an array.

var alertsObj = {
    1: {app:'helloworld','message'},
    2: {app:'helloagain',message:'another message'}
};

var alertArr = [
    {app:'helloworld','message'},
    {app:'helloagain',message:'another message'}
];

var newAlert = {app:'new',message:'message'};

$.extend(alertsObj, newAlert);
alertArr.push(newAlert);

Is a GUID unique 100% of the time?

For more better result the best way is to append the GUID with the timestamp (Just to make sure that it stays unique)

Guid.NewGuid().ToString() + DateTime.Now.ToString();

git status (nothing to commit, working directory clean), however with changes commited

git status output tells you three things by default:

  1. which branch you are on
  2. What is the status of your local branch in relation to the remote branch
  3. If you have any uncommitted files

When you did git commit , it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.

If you find the output of git status verbose and difficult to comprehend, try using git status -sb this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:

master...origin/master [ahead 1]

git status is pretty useful, in the workflow you described do a git status -sb: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.

Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.

SSH configuration: override the default username

Create a file called config inside ~/.ssh. Inside the file you can add:

Host *
    User buck

Or add

Host example
    HostName example.net
    User buck

The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net; ssh example will be enough.

compression and decompression of string data in java

Client send some messages need be compressed, server (kafka) decompress the string meesage

Below is my sample:

compress:

   public static String compress(String str, String inEncoding) {
        if (str == null || str.length() == 0) {
            return str;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(inEncoding));
            gzip.close();
            return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

decompress:

    public static String decompress(String str, String outEncoding) {
        if (str == null || str.length() == 0) {
            return str;
        }

        try {
            String decode = URLDecoder.decode(str, "UTF-8");

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(outEncoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Shortcut for changing font size

Ctrl + Alt + MouseWheel will work in Visual Studio 2015.

What charset does Microsoft Excel use when saving files?

From memory, Excel uses the machine-specific ANSI encoding. So this would be Windows-1252 for a EN-US installation, 1251 for Russian, etc.

Make an html number input always display 2 decimal places

What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">

JS

function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };

Breaking a list into multiple columns in Latex

Another option to avoid nesting two different environments (like multicols and enumerate).

The environment called tasks from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).

This code:

\documentclass{article}
\usepackage{tasks}

%\settasks{style=itemize}

\begin{document}
Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.

\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}    

Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.
\end{document}

produces this output

tasks

The package tasks was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.

Hidden features of Windows batch files

Variable substrings:

> set str=0123456789
> echo %str:~0,5%
01234
> echo %str:~-5,5%
56789
> echo %str:~3,-3%
3456

How to make background of table cell transparent

It is possible
You just also need to apply the color to 'tbody' element as that's the table body that's been causing our trouble by peeking underneath.
table, tbody, tr, th, td{ background-color: rgba(0, 0, 0, 0.0) !important; }

How to modify a text file?

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

This is an operating system thing, not a Python thing. It is the same in all languages.

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

How to pause javascript code execution for 2 seconds

Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note: The above code is NOT recommended.

Is it better to use path() or url() in urls.py for django 2.0?

The new django.urls.path() function allows a simpler, more readable URL routing syntax. For example, this example from previous Django releases:

url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive)

could be written as:

path('articles/<int:year>/', views.year_archive)

The django.conf.urls.url() function from previous versions is now available as django.urls.re_path(). The old location remains for backwards compatibility, without an imminent deprecation. The old django.conf.urls.include() function is now importable from django.urls so you can use:

from django.urls import include, path, re_path

in the URLconfs. For further reading django doc

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

Chrome hangs after certain amount of data transfered - waiting for available socket

simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...

if you use jplayer then replace preload:"metadata" to preload:"none" from jplayer JS file ...

preload:"metadata" is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error

Timing a command's execution in PowerShell

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1  
$command = Get-History -Count 1  
$command.EndExecutionTime - $command.StartExecutionTime

Create PDF from a list of images

The best answer already exists !!! I am just improving the answer a little bit. Here's the code :

from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames you can create using os module by iterating all the files in a folder or by specifying their name
for image in imagelist:
    pdf.add_page()
    pdf.image(image,x=0,y=0,w=210,h=297) # for A4 size because some people said that every other page is blank
pdf.output("yourfile.pdf", "F")

You'll need to install FPDF for this purpose.

pip install FPDF

"Could not find or load main class" Error while running java program using cmd prompt

Create a folder org/tij/exercises and then move HelloWorld.java file. Then run below command

javac -cp . org/tij/exercises/HelloWorld.java

AND

java -cp . org/tij/exercises/HelloWorld

How to print instances of a class using print()?

Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

Given this class definition:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we'll get:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

But, as I said in my last comment: more info is just here!

Execute a shell function with timeout

Putting my comment to Tiago Lopo's answer into more readable form:

I think it's more readable to impose a timeout on the most recent subshell, this way we don't need to eval a string and the whole script can be highlighted as shell by your favourite editor. I simply put the commands after the subshell with eval has spawned into a shell-function (tested with zsh, but should work with bash):

timeout_child () {
    trap -- "" SIGTERM
    child=$!
    timeout=$1
    (
            sleep $timeout
            kill $child
    ) &
    wait $child
}

Example usage:

( while true; do echo -n .; sleep 0.1; done) & timeout_child 2

And this way it also works with a shell function (if it runs in the background):

 print_dots () {
     while true
     do
         sleep 0.1
         echo -n .
     done
 }


 > print_dots & timeout_child 2
 [1] 21725
 [3] 21727
 ...................[1]    21725 terminated  print_dots
 [3]  + 21727 done       ( sleep $timeout; kill $child; )

How to change color in circular progress bar?

For API 21 and Higher. Simply set the indeterminateTint property. Like:

android:indeterminateTint="@android:color/holo_orange_dark"

To support pre-API 21 devices:

mProgressSpin.getIndeterminateDrawable()
                .setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), PorterDuff.Mode.SRC_IN );

How to change the background color of a UIButton while it's highlighted?

Here is the code in Swift to select for button state:

func imageWithColor(color:UIColor) -> UIImage {
    let rect:CGRect = CGRectMake(0.0, 0.0, 1.0, 1.0)
     UIGraphicsBeginImageContext(rect.size)
    let context:CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    return image;
}

Example:

    self.button.setImage(self.imageWithColor(UIColor.blackColor()), forState: .Highlighted)

Currency format for display

You can use string.Format("{0:c}", value).

See also here:

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

Git reset single file in feature branch to be the same as in master

you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:

git checkout master -- filename

Note that the differences will be cached; so if you want to see the differences you obtained; use

git diff --cached

What does the "On Error Resume Next" statement do?

On Error Resume Next means that On Error, It will resume to the next line to resume.

e.g. if you try the Try block, That will stop the script if a error occurred

PHPExcel - set cell type before writing a value in it

I wanted the Number same as I get from database for example.

1) 00100.220000

2) 00123

3) 0000.0000100

So I modified the code as below

$objPHPExcel->getActiveSheet()
    ->setCellValue('A3', '00100.220000');
$objPHPExcel->getActiveSheet()
    ->getStyle('A3')
    ->getNumberFormat()
    ->setFormatCode('00000.000000');


$objPHPExcel->getActiveSheet()
    ->setCellValue('A4', '00123');
$objPHPExcel->getActiveSheet()
  ->getStyle('A4')
 ->getNumberFormat()
->setFormatCode('00000');


$objPHPExcel->getActiveSheet()
    ->setCellValue('A5', '0000.0000100');
$objPHPExcel->getActiveSheet()
  ->getStyle('A5')
 ->getNumberFormat()
->setFormatCode('0000.0000000');

Byte array to image conversion

One liner:

Image bmp = (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));

Adding POST parameters before submit

You can do a form.serializeArray(), then add name-value pairs before posting:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

Converting string to numeric

I suspect you are having a problem with factors. For example,

> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8

Some comments:

  • You mention that your vector contains the characters "Down" and "NoData". What do expect/want as.numeric to do with these values?
  • In read.csv, try using the argument stringsAsFactors=FALSE
  • Are you sure it's sep="/t and not sep="\t"
  • Use the command head(pitchman) to check the first fews rows of your data
  • Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") since I don't have access to the data set.

How to trigger an event after using event.preventDefault()

The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault(). Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events.

More details about this can be found in this link

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

  • JDK - Java Development Kit
  • JRE - Java Runtime Environment
  • Java SE - Java Standard Edition

SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).

The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.

Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).


Edited 2011-04-06: The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)


Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.

Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.

Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).

How to scroll page in flutter

Wrap your widget tree inside a SingleChildScrollView

 body: SingleChildScrollView(
child: Stack(
    children: <Widget>[
      new Container(
        decoration: BoxDecoration(
            image: DecorationImage(...),
      new Column(children: [
        new Container(...),
        new Container(...... ),
        new Padding(
          child: SizedBox(
            child: RaisedButton(..),
        ),
....
...
 ); // Single child scroll view

Remember, SingleChildScrollView can only have one direct widget (Just like ScrollView in Android)

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Failed to Connect to MySQL at localhost:3306 with user root

At rigth side in Navigator -> Instance-> Click on Startup/Shutdown -> Click on Start Server

It will work surely

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

In Wordpress just replace

$(function(){...});

with

jQuery(function(){...});

How to set a default value for an existing column

ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

What is the difference between ng-if and ng-show/ng-hide

@EdSpencer is correct. If you have a lot of elements and you use ng-if to only instantiate the relevant ones, you are saving resources. @CodeHater is also somewhat correct, if you are going to remove and show an element very often, hiding it instead of removing it could improve performance.

The main use case I find for ng-if is that it allows me to cleanly validate and eliminte an element if the contents is illegal. For instance I could reference to a null image name variable and that will throw an error but if I ng-if and check if it's null, it's all good. If I did an ng-show, the error would still fire.

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

How to clear the Entry widget after a button is pressed in Tkinter?

After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height=42, width=42)
        self.entry = tk.Entry(self)
        self.entry.focus()
        self.entry.pack()
        self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
        self.clear_button.pack()

    def clear_text(self):
        self.entry.delete(0, 'end')

def main():
    root = tk.Tk()
    App(root).pack(expand=True, fill='both')
    root.mainloop()

if __name__ == "__main__":
    main()

MongoDB: Combine data from multiple collections into one..how?

If there is no bulk insert into mongodb, we loop all objects in the small_collection and insert them one by one into the big_collection:

db.small_collection.find().forEach(function(obj){ 
   db.big_collection.insert(obj)
});

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

In my case the problem was raised when I was trying to do some "weird" arithmetic expressions

eg (3.14/4)/5 or 3.15%2.55

So, I would suggest you to check all the arithmetic expressions in case some of them cannot be calculated by the Arduino.

Hope it helps.

How to send an HTTP request using Telnet

For posterity, your question was how to send an http request to https://stackoverflow.com/questions. The real answer is: you cannot with telnet, cause this is an https-only reachable url.

So, you might want to use openssl instead of telnet, like this for instance

$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com

This will give you the https response.

How to install Anaconda on RaspBerry Pi 3 Model B

I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3

Conda is now working. Hope this helps those of you interested in running conda on the pi zero!

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

How to properly create composite primary keys - MYSQL

Suppose you have already created a table now you can use this query to make composite primary key

alter table employee add primary key(emp_id,emp_name);

Detecting when Iframe content has loaded (Cross browser)

For those using React, detecting a same-origin iframe load event is as simple as setting onLoad event listener on iframe element.

<iframe src={'path-to-iframe-source'} onLoad={this.loadListener} frameBorder={0} />

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )


Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(as.data.table(text), "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(dplyr)
library(tidyr)

as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

How to remove square brackets in string using regex?

Use this regular expression to match square brackets or single quotes:

/[\[\]']+/g

Replace with the empty string.

_x000D_
_x000D_
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
_x000D_
_x000D_

Installing a dependency with Bower from URL and specify version

Installs package from git and save to your bower.json dependency block.

  1. bower register package-name git-endpoint#version
  2. install package-name --save

(--save will save the package name version in the bower.json file inside the dependency block).

Reference

Configuration with name 'default' not found. Android Studio

Step.1 $ git submodule update

Step.2 To be commented out the dependences of classpass

Best practice for instantiating a new Android Fragment

I disagree with yydi answer saying:

If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.

I think it is a solution and a good one, this is exactly the reason it been developed by Java core language.

Its true that Android system can destroy and recreate your Fragment. So you can do this:

public MyFragment() {
//  An empty constructor for Android System to use, otherwise exception may occur.
}

public MyFragment(int someInt) {
    Bundle args = new Bundle();
    args.putInt("someInt", someInt);
    setArguments(args);
}

It will allow you to pull someInt from getArguments() latter on, even if the Fragment been recreated by the system. This is more elegant solution than static constructor.

For my opinion static constructors are useless and should not be used. Also they will limit you if in the future you would like to extend this Fragment and add more functionality to the constructor. With static constructor you can't do this.

Update:

Android added inspection that flag all non-default constructors with an error.
I recommend to disable it, for the reasons mentioned above.

Disable the postback on an <ASP:LinkButton>

Just been through this, the correct way to do it is to use:

  1. OnClientClick
  2. return false

as in the following example line of code:

<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />

Laravel 5 - redirect to HTTPS

You can make it works with a Middleware class. Let me give you an idea.

namespace MyApp\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class HttpsProtocol {

    public function handle($request, Closure $next)
    {
            if (!$request->secure() && App::environment() === 'production') {
                return redirect()->secure($request->getRequestUri());
            }

            return $next($request); 
    }
}

Then, apply this middleware to every request adding setting the rule at Kernel.php file, like so:

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',

    // appending custom middleware 
    'MyApp\Http\Middleware\HttpsProtocol'       

];

At sample above, the middleware will redirect every request to https if:

  1. The current request comes with no secure protocol (http)
  2. If your environment is equals to production. So, just adjust the settings according to your preferences.

Cloudflare

I am using this code in production environment with a WildCard SSL and the code works correctly. If I remove && App::environment() === 'production' and test it in localhost, the redirection also works. So, having or not a installed SSL is not the problem. Looks like you need to keep a very hard attention to your Cloudflare layer in order to get redirected to Https protocol.

Edit 23/03/2015

Thanks to @Adam Link's suggestion: it is likely caused by the headers that Cloudflare is passing. CloudFlare likely hits your server via HTTP and passes a X-Forwarded-Proto header that declares it is forwarding a HTTPS request. You need add another line in your Middleware that say...

$request->setTrustedProxies( [ $request->getClientIp() ] ); 

...to trust the headers CloudFlare is sending. This will stop the redirect loop

Edit 27/09/2016 - Laravel v5.3

Just need to add the middleware class into web group in kernel.php file:

protected $middlewareGroups = [
    'web' => [
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,

        // here
        \MyApp\Http\Middleware\HttpsProtocol::class

    ],
];

Remember that web group is applied to every route by default, so you do not need to set web explicitly in routes nor controllers.

Edit 23/08/2018 - Laravel v5.7

  • To redirect a request depending the environment you can use App::environment() === 'production'. For previous version was env('APP_ENV') === 'production'.
  • Using \URL::forceScheme('https'); actually does not redirect. It just builds links with https:// once the website is rendered.

I want to use CASE statement to update some records in sql server 2005

This is also an alternate use of case-when...

UPDATE [dbo].[JobTemplates]
SET [CycleId] = 
    CASE [Id]
        WHEN 1376 THEN 44   --ACE1 FX1
        WHEN 1385 THEN 44   --ACE1 FX2
        WHEN 1574 THEN 43   --ACE1 ELEM1
        WHEN 1576 THEN 43   --ACE1 ELEM2
        WHEN 1581 THEN 41   --ACE1 FS1
        WHEN 1585 THEN 42   --ACE1 HS1
        WHEN 1588 THEN 43   --ACE1 RS1
        WHEN 1589 THEN 44   --ACE1 RM1
        WHEN 1590 THEN 43   --ACE1 ELEM3
        WHEN 1591 THEN 43   --ACE1 ELEM4
        WHEN 1595 THEN 44   --ACE1 SSTn     
        ELSE 0  
     END
WHERE
    [Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)

I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:

SELECT
     [Id]
    ,[QueueId]
    ,[BaseDimensionId]
    ,[ElastomerTypeId]
    ,CASE [CycleId]
        WHEN  29 THEN 44
        WHEN  30 THEN 43
        WHEN  31 THEN 43
        WHEN 101 THEN 41
        WHEN 102 THEN 43
        WHEN 116 THEN 42
        WHEN 120 THEN 44
        WHEN 127 THEN 44
        WHEN 129 THEN 44
        ELSE    0
     END                AS [CycleId]
INTO
    ##ACE1_PQPANominals_1
FROM 
    [dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
    [QueueId] = 3
ORDER BY 
    [BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)

UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET 
    [CycleId] = X.[CycleId]
FROM
    [dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
    SELECT  
        MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
    FROM 
        ##ACE1_PQPANominals_1
    GROUP BY    
        [QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
) AS X
ON
    [dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)

How to repair COMException error 80040154?

WORKAROUND:

The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)

ROOTCAUSE

The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

How to delete last character in a string in C#?

string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
    dest = source.Substring(0, source.Length - 1);
}

How to use basic authorization in PHP curl

Its Simple Way To Pass Header

function get_data($url) {

$ch = curl_init();
$timeout = 5;
$username = 'c4f727b9646045e58508b20ac08229e6';        // Put Username 
$password = '';                                        // Put Password
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");    // Add This Line
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = "https://storage.scrapinghub.com/items/397187/2/127";
$data = get_data($url);
echo '<pre>';`print_r($data_json);`die;    // For Print Value

Check My JSON Value

How to move from one fragment to another fragment on click of an ImageView in Android?

you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.

You can call another fragment by writing the code below:

        FragmentTransaction t = this.getFragmentManager().beginTransaction();
        Fragment mFrag = new MyFragment();
        t.replace(R.id.content_frame, mFrag);
        t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

you can also add the other fragment incase of replace.

Reading a string with spaces with sscanf

I guess this is what you want, it does exactly what you specified.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d cool %s", &age, buffer);
    printf("cool %s is %d years old\n", buffer, age);
    return 0;
}

The format expects: first a number (and puts it at where &age points to), then whitespace (zero or more), then the literal string "cool", then whitespace (zero or more) again, and then finally a string (and put that at whatever buffer points to). You forgot the "cool" part in your format string, so the format then just assumes that is the string you were wanting to assign to buffer. But you don't want to assign that string, only skip it.

Alternative, you could also have a format string like: "%d %s %s", but then you must assign another buffer for it (with a different name), and print it as: "%s %s is %d years old\n".

sql - insert into multiple tables in one query

I had the same problem. I solve it with a for loop.

Example:

If I want to write in 2 identical tables, using a loop

for x = 0 to 1

 if x = 0 then TableToWrite = "Table1"
 if x = 1 then TableToWrite = "Table2"
  Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT

either

ArrTable = ("Table1", "Table2")

for xArrTable = 0 to Ubound(ArrTable)
 Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT

If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

CSS Inset Borders

It's an old trick, but I still find the easiest way to do this is to use outline-offset with a negative value (example below uses -6px). Here's a fiddle of it—I've made the outer border red and the outline white to differentiate the two:

.outline-offset {
width:300px;
height:200px;
background:#333c4b;
border:2px solid red;
outline:2px #fff solid;
outline-offset:-6px;
}

<div class="outline-offset"></div>

How to reject in async/await syntax?

You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.

function safePromise(promise) {
  return promise.then(data => [ data ]).catch(error => [ null, error ]);
}

Use it like this in ES7 and in an async function:

async function checkItem() {
  const [ item, error ] = await safePromise(getItem(id));
  if (error) { return null; } // handle error and return
  return item; // no error so safe to use item
}

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I encountered the same issue today and found this post and others from Google. I think I may have a more direct solution as a modification of your code. The previous answer is correct in identifying the mismatch in versions.

I tried the proposed solutions to no avail. I found that the versions were correct on my computer. However, this mismatch error was not resulting from the actual versions installed on the computer, but rather the RSelenium code is seeking the "latest" version of Chrome/ChromeDriver by default argument. See ?rsDriver() help page for the arguments.

If you run the code binman::list_versions("chromedriver") as specified in the help documentation, then you can identify the versions of compatible with the function. In my case, I was able to use the following code to establish a connection.

driver <- rsDriver(browser=c("chrome"), chromever="73.0.3683.68", extraCapabilities = eCaps)

You should be able to specify your version of Chrome with the chromever= argument. I had to use the closest version, though (my chrome version was "73.0.3683.75").

Hope this helps!

Set proxy through windows command line including login parameters

The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.

Align printf output in Java

A simple solution that springs to mind is to have a String block of spaces:

String indent = "                  "; // 20 spaces.

When printing out a string, compute the actual indent and add it to the end:

String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);

This will mediate the number of spaces to the string, and put them all in the same column.

How to view log output using docker-compose run?

Update July 1st 2019

docker-compose logs <name-of-service>

From the documentation:

Usage: logs [options] [SERVICE...]

Options:

--no-color Produce monochrome output.

-f, --follow Follow log output.

-t, --timestamps Show timestamps.

--tail="all" Number of lines to show from the end of the logs for each container.

See docker logs

You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.

  1. Use docker-compose up -d to start all services in detached mode (-d) (you won't see any logs in detached mode)
  2. Use docker-compose logs -f -t to attach yourself to the logs of all running services, whereas -f means you follow the log output and the -t option gives you timestamps (See Docker reference)
  3. Use Ctrl + z or Ctrl + c to detach yourself from the log output without shutting down your running containers

If you're interested in logs of a single container you can use the docker keyword instead:

  1. Use docker logs -t -f <name-of-service>

Save the output

To save the output to a file you add the following to your logs command:

  1. docker-compose logs -f -t >> myDockerCompose.log

Passing parameters to a JDBC PreparedStatement

Do something like this, which also prevents SQL injection attacks

statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

Reversing a String with Recursion in Java

import java.util.*;

public class StringReverser
{
   static Scanner keyboard = new Scanner(System.in);

   public static String getReverser(String in, int i)
   {
      if (i < 0)
         return "";
      else
         return in.charAt(i) + getReverser(in, i-1);
   }

   public static void main (String[] args)
   {
      int index = 0;

      System.out.println("Enter a String");
      String input = keyboard.nextLine();


      System.out.println(getReverser(input, input.length()-1));
   }
}

Git: can't undo local changes (error: path ... is unmerged)

git checkout origin/[branch] .
git status

// Note dot (.) at the end. And all will be good

Merge Two Lists in R

merged = map(names(first), ~c(first[[.x]], second[[.x]])
merged = set_names(merged, names(first))

Using purrr. Also solves the problem of your lists not being in order.

How do I download code using SVN/Tortoise from Google Code?

Select Tortoise SVN - > Settings - > NetWork

Fill the required proxy if any and then check.

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

figure of imshow() is too small

Update 2020

as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.

This works with matplotlip 3.2.1:

from matplotlib import pyplot as plt
import random
import numpy as np

random = np.random.random ([8,90])

plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')

This plots:

enter image description here

To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).

What is the Regular Expression For "Not Whitespace and Not a hyphen"

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

how to get the cookies from a php curl into a variable

My understanding is that cookies from curl must be written out to a file (curl -c cookie_file). If you're running curl through PHP's exec or system functions (or anything in that family), you should be able to save the cookies to a file, then open the file and read them in.

How to import RecyclerView for Android L-preview

My dependencies;

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.1.0'

    //RecyclerView dependency
    compile 'com.android.support:recyclerview-v7:25.1.0'

    // Instrumentation dependencies use androidTestCompile
    // (as opposed to testCompile for local unit tests run in the JVM)
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support:support-annotations:25.1.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
}

I added only compile 'com.android.support:recyclerview-v7:25.1.0'. The important thing is to add RecycleView dependency which is as the same version as appcompat

Remove Select arrow on IE

I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.

Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.

Anyway, let's start with the modern browsers and then we will see the solution for the older ones.

Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+

For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.

To do so, you have to reset the browser's default style for the select tag and set new background rules (like suggested before).

select {
    /* you should keep these firsts rules in place to maintain cross-browser behaviour */
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background-image: url('<custom_arrow_image_url_here>');
    background-position: 98% center;
    background-repeat: no-repeat;
    outline: none;
    ...
}

The appearance rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.

The background rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).

In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.

Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font

This is the harder part... Or maybe not.

There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select CSS rule for more details about the inline SVG used).

The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html tag to recognize the older IE browser.

After that, every select in the HTML have to be wrapped by a div (or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.

<div class="selectTagWrapper prefix-icon-arrow-down-fill">
    ...
</div>

In easy words, this wrapper is used to simulate the select tag.

To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select.

Notice that we cannot use the select border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden rule applied to the select itself.

The custom arrow icon-font is placed in the pseudo class :before where the rule content contains the reference for the arrow (in this case it is a right parenthesis).

We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).

.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
    content: ")";
    position: absolute;
    top: 43%;
    left: 93%;
    font-size: 6px;
    ...
}

You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image rule or making a new icon font file by yourself.

How do I negate a test with regular expressions in a bash script?

Yes you can negate the test as SiegeX has already pointed out.

However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:

[[ ":$PATH:" != *":$1:"* ]]

(Source)

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

Disabling SSL Certificate Validation in Spring RestTemplate

@Bean
public RestTemplate restTemplate() 
                throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
 }

Flask example with POST

Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..

#libraries to include

import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
    def question():
    # request.args is to get urls arguments 


    if request.method == 'GET':
        start = request.args.get('start', default=0, type=int)
        limit_url = request.args.get('limit', default=20, type=int)
        questions = mongo.db.questions.find().limit(limit_url).skip(start);
        data = [doc for doc in questions]
        return jsonify(isError= False,
                    message= "Success",
                    statusCode= 200,
                    data= data), 200

# request.form to get form parameter

    if request.method == 'POST':
        average_time = request.form.get('average_time')
        choices = request.form.get('choices')
        created_by = request.form.get('created_by')
        difficulty_level = request.form.get('difficulty_level')
        question = request.form.get('question')
        topics = request.form.get('topics')

    ##Do something like insert in DB or Render somewhere etc. it's up to you....... :)

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

Your results make sense. Since FTP operates over a non-encrypted channel it is faster than SFTP (which is subsystem on top of the SSH version 2 protocol). Also remember that SFTP is a packet based protocol unlike FTP which is command based.

Each packet in SFTP is encrypted before being written to the outgoing socket from the client and subsequently decrypted when received by the server. This of-course leads to slow transfer rates but very secure transfer. Using compression such as zlib with SFTP improves the transfer time but still it won't be anywhere near plain text FTP. Perhaps a better comparison is to compare SFTP with FTPS which both use encryption?

Speed for SFTP depends on the cipher used for encryption/decryption, the compression used e.g. zlib, packet sizes and buffer sizes used for the socket connection.

Update records using LINQ

Yes. You can use foreach to update the records in linq.There is no performance degrade.

you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.

The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods

For instance,

var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
query = query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);

foreach (string name in result)   // Only now is the query executed!
   Console.WriteLine (name);

Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.

So no need to scare to use foreach for update the linq result.

In your case code sample given below will be useful to update many properties,

 var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);

//TO update using foreach

foreach(var person in persons)
{
//update property values
}  

I hope it helps...

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

How to get POSTed JSON in Flask?

To give another approach.

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/service', methods=['POST'])
def service():
    data = json.loads(request.data)
    text = data.get("text",None)
    if text is None:
        return jsonify({"message":"text not found"})
    else:
        return jsonify(data)

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

The remote end hung up unexpectedly while git cloning

Wasted a few hours trying some of these solutions but eventually traced this to a corporate IPS (Instrusion Protection System) dropping the connection after a certain amount of data is transferred.

Change first commit of project with Git?

git rebase -i allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.

# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`

# switch to a new branch pointing at the first commit
git checkout -b new-root root

# make any edits and then commit them with:
git commit --amend

# check out the previous branch (i.e. master)
git checkout @{-1}

# replace old root with amended version
git rebase --onto new-root root

# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue

# delete the branch "new-root"
git branch -d new-root

# delete the tag "root"
git tag -d root

What's the easy way to auto create non existing dir in ansible

To ensure success with a full path use recurse=yes

- name: ensure custom facts directory exists
    file: >
      path=/etc/ansible/facts.d
      recurse=yes
      state=directory

How do I paste multi-line bash codes into terminal and run it all at once?

I'm really surprised this answer isn't offered here, I was in search of a solution to this question and I think this is the easiest approach, and more flexible/forgiving...

If you'd like to paste multiple lines from a website/text editor/etc., into bash, regardless of whether it's commands per line or a function or entire script... simply start with a ( and end with a ) and Enter, like in the following example:

If I had the following blob

function hello {
    echo Hello!
}
hello

You can paste and verify in a terminal using bash by:

  1. Starting with (

  2. Pasting your text, and pressing Enter (to make it pretty)... or not

  3. Ending with a ) and pressing Enter

Example:

imac:~ home$ ( function hello {
>     echo Hello!
> }
> hello
> )
Hello!
imac:~ home$ 

The pasted text automatically gets continued with a prepending > for each line. I've tested with multiple lines with commands per line, functions and entire scripts. Hope this helps others save some time!

How to start an application using android ADB tools?

We can as well start an application by knowing application type and feeding it with data:

adb shell am start -d "file:///sdcard/sample.3gp" -t "video/3gp" -a android.intent.action.VIEW

This command displays available Video Players to play sample.3gp file

How to write multiple conditions in Makefile.am with "else if"

As you've discovered, you can't do that. You can do:

libtest_LIBS = 

...

if HAVE_CLIENT
libtest_LIBS += libclient.la
endif

if HAVE_SERVER
libtest_LIBS += libserver.la
endif

Forms authentication timeout vs sessionState timeout

From what I understand they are independent of one another. By keeping the session timeout less than or equal to the authentication timeout, you can make sure any user-specific session variables are not persisted after the authentication has timed out (if that is your concern, which I think is the normal one when asking this question). Of course, you'll have to manually handle the disposal of session variables upon log-out.

Here is a decent response that may answer your question or at least point you in the right direction:

Search for an item in a Lua list

function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 end
 if valid[data] then
  return false
 else
  return true
 end
end

Here's the function I use for checking if data is in an array.

Where can I download the jar for org.apache.http package?

You can add org.apache.http by using below code in app:Build gradle

dependencies {
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

How can I get a web site's favicon?

In 2020, using duckduckgo.com's service from the CLI

curl -v https://icons.duckduckgo.com/ip2/<website>.ico > favicon.ico

Example

curl -v https://icons.duckduckgo.com/ip2/www.cdc.gov.ico > favicon.ico

How to loop over grouped Pandas dataframe?

Here is an example of iterating over a pd.DataFrame grouped by the column atable. For this sample, "create" statements for an SQL database are generated within the for loop:

import pandas as pd

df1 = pd.DataFrame({
    'atable':     ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
    'column':     ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
    'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
    'is_null':    ['No', 'No', 'Yes', 'No', 'Yes'],
})

df1_grouped = df1.groupby('atable')

# iterate over each group
for group_name, df_group in df1_grouped:
    print('\nCREATE TABLE {}('.format(group_name))

    for row_index, row in df_group.iterrows():
        col = row['column']
        column_type = row['column_type']
        is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
        print('\t{} {} {},'.format(col, column_type, is_null))

    print(");")

What's the difference between an Angular component and module

https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-L9vDDYxu6nH7FVBtFFS%2F-LBvB_WpCSzgVF0c4R9W%2F-LBvCVC22B-3Ls3_nyuC%2Fangular-modules.jpg?alt=media&token=624c03ca-e24f-457d-8aa7-591d159e573c

A picture is worth a thousand words !

The concept of Angular is very simple. It propose to "build" an app with "bricks" -> modules.

This concept makes it possible to better structure the code and to facilitate reuse and sharing.

Be careful not to confuse the Angular modules with the ES2015 / TypeScript modules.

Regarding the Angular module, it is a mechanism for:

1- group components (but also services, directives, pipes etc ...)

2- define their dependencies

3- define their visibility.

An Angular module is simply defined with a class (usually empty) and the NgModule decorator.

How to horizontally center an unordered list of unknown width?

The solution, if your list items can be display: inline is quite easy:

#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }

However, many times you must use display:block on your <li>s. The following CSS will work, in this case:

#footer { width: 100%; overflow: hidden; }
#footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; }
#footer ul li { position: relative; float: left; display: block; right: 50%; }

Java get last element of a collection

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too.

ActiveRecord find and only return selected columns

In Rails 2

l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...

l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

In Rails 3 w/ActiveRecord Query Interface

l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

More than 1 row in <Input type="textarea" />

The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.

How to install pip for Python 3 on Mac OS X?

On Mac OS X Mojave python stands for python of version 2.7 and python3 for python of version 3. The same is pip and pip3. So, to upgrade pip for python 3 do this:

~$ sudo pip3 install --upgrade pip

How do I get the current time zone of MySQL?

The command mention in the description returns "SYSTEM" which indicated it takes the timezone of the server. Which is not useful for our query.

Following query will help to understand the timezone

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) as GMT_TIME_DIFF;

Above query will give you the time interval with respect to Coordinated Universal Time(UTC). So you can easily analyze the timezone. if the database time zone is IST the output will be 5:30

UTC_TIMESTAMP

In MySQL, the UTC_TIMESTAMP returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format depending on the usage of the function i.e. in a string or numeric context.

NOW()

NOW() function. MySQL NOW() returns the value of current date and time in 'YYYY-MM-DD HH:MM:SS' format or YYYYMMDDHHMMSS.uuuuuu format depending on the context (numeric or string) of the function. CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, LOCALTIMESTAMP() are synonyms of NOW().

Where is Developer Command Prompt for VS2013?

For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:

Using Windows Explorer, navigate to:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013

In that folder, you'll see a shortcut named Visual Studio Tools that maps to (assuming default installation):

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts

Double-click the shortcut (or go to the folder above).

From that folder, copy the shortcut named Developer Command Prompt for VS2013 (and any others you find useful) to the first directory (for the Start Menu). You'll likely be prompted for administrative access (do so).

Once you've done that, you'll now have an icon available for the 2013 command prompt.

How can I convert a string to a number in Perl?

As I understand it int() is not intended as a 'cast' function for designating data type it's simply being (ab)used here to define the context as an arithmetic one. I've (ab)used (0+$val) in the past to ensure that $val is treated as a number.