Programs & Examples On #Soapfault

The SOAP Fault element is defined as part of the W3C SOAP specification. The SOAP Fault element is used to carry error information within a SOAP message.

SOAP PHP fault parsing WSDL: failed to load external entity?

try this. works for me

$options = array(
    'cache_wsdl' => 0,
    'trace' => 1,
    'stream_context' => stream_context_create(array(
          'ssl' => array(
               'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
          )
    ));

$client = new SoapClient(url, $options);

SoapFault exception: Could not connect to host

This work for me

$opts = array(
  'ssl' => array('verify_peer' => false, 'verify_peer_name' => false)
);

if (!isset($this->soap_client)) {
  $this->soap_client = new SoapClient($this->WSDL, array(
    'soap_version'   => $this->soap_version,
    'location'       => $this->URL,
    'trace'          => 1,
    'exceptions'     => 0,
    'stream_context' => stream_context_create($opts)
  ));

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

In my apache error log, I saw:

[Tue Feb 16 14:55:02 2010] [notice] child pid 9985 exit signal File size limit exceeded (25)

So I, removed all the contents of my largest log file 2.1GB /var/log/system.log. Now everything works.

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

what does "dead beef" mean?

http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef

"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.

How to clear the interpreter console?

Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.

How can I open the interactive matplotlib window in IPython notebook?

A better solution for your problem might be the Charts library. It enables you to use the excellent Highcharts javascript library to make beautiful and interactive plots. Highcharts uses the HTML svg tag so all your charts are actually vector images.

Some features:

  • Vector plots which you can download in .png, .jpg and .svg formats so you will never run into resolution problems
  • Interactive charts (zoom, slide, hover over points, ...)
  • Usable in an IPython notebook
  • Explore hundreds of data structures at the same time using the asynchronous plotting capabilities.

Disclaimer: I'm the developer of the library

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

ExecuteReader: Connection property has not been initialized

You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

How to keep a git branch in sync with master

You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or mobiledevicesupport depending on their role.

Break or return from Java 8 stream forEach?

For maximal performance in parallel operations use findAny() which is similar to findFirst().

Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findAny();

However If a stable result is desired, use findFirst() instead.

Also note that matching patterns (anyMatch()/allMatch) will return only boolean, you will not get matched object.

Python | change text color in shell

I just described very popular library clint. Which has more features apart of coloring the output on terminal.

By the way it support MAC, Linux and Windows terminals.

Here is the example of using it:

Installing (in Ubuntu)

pip install clint

To add color to some string

colored.red('red string')

Example: Using for color output (django command style)

from django.core.management.base import BaseCommand
from clint.textui import colored


class Command(BaseCommand):
    args = ''
    help = 'Starting my own django long process. Use ' + colored.red('<Ctrl>+c') + ' to break.'

    def handle(self, *args, **options):
        self.stdout.write('Starting the process (Use ' + colored.red('<Ctrl>+c') + ' to break)..')
        # ... Rest of my command code ...

What is username and password when starting Spring Boot with Tomcat?

Try to take username and password from below code snipet in your project and login and hope this will work.

@Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("spring").password("spring").roles("USER").build());
        return new UserDetailsManager(users);
    }

Excel column number from column name

In my opinion the simpliest way to get column number is:
Sub Sample() ColName = ActiveCell.Column MsgBox ColName End Sub

Unable to add window -- token null is not valid; is your activity running?

I was getting this error while trying to show DatePicker from Fragment.

I changed

val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)

to

val datePickerDialog = DatePickerDialog(requireContext(), ...)

and it worked just fine.

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

.htaccess rewrite to redirect root URL to subdirectory

This seemed the simplest solution:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://www.example.com/store [R=301,L]

I was getting redirect loops with some of the other solutions.

How to validate a url in Python? (Malformed or not)

Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.

def get_domain_suffixes():
    import requests
    res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
    lst=set()
    for line in res.text.split('\n'):
        if not line.startswith('//'):
            domains=line.split('.')
            cand=domains[-1]
            if cand:
                lst.add('.'+cand)
    return tuple(sorted(lst))

domain_suffixes=get_domain_suffixes()

def reminds_url(txt:str):
    """
    >>> reminds_url('yandex.ru.com/somepath')
    True
    
    """
    ltext=txt.lower().split('/')[0]
    return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)

Add custom buttons on Slick Carousel

Why you cant use default CSS classes and add some your style?

.slick-next {
  /*my style*/
  background: url(my-image.png);
}

and

.slick-prev {
  /*my style*/
  background: url(my-image.png);
}

Are you used simple background css property?

in example: http://jsfiddle.net/BNvke/1/

You can use Font Awesome too. Don't forget about CSS pseudo elements.

And don't forget jQuery, you can replace elements, add classes, etc.

builder for HashMap

A simple map builder is trivial to write:

public class Maps {

    public static <Q,W> MapWrapper<Q,W> map(Q q, W w) {
        return new MapWrapper<Q, W>(q, w);
    }

    public static final class MapWrapper<Q,W> {
        private final HashMap<Q,W> map;
        public MapWrapper(Q q, W w) {
            map = new HashMap<Q, W>();
            map.put(q, w);
        }
        public MapWrapper<Q,W> map(Q q, W w) {
            map.put(q, w);
            return this;
        }
        public Map<Q,W> getMap() {
            return map;
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3).getMap();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to read a file in reverse order?

Accepted answer won't work for cases with large files that won't fit in memory (which is not a rare case).

As it was noted by others, @srohde answer looks good, but it has next issues:

  • openning file looks redundant, when we can pass file object & leave it to user to decide in which encoding it should be read,
  • even if we refactor to accept file object, it won't work for all encodings: we can choose file with utf-8 encoding and non-ascii contents like

    ?
    

    pass buf_size equal to 1 and will have

    UnicodeDecodeError: 'utf8' codec can't decode byte 0xb9 in position 0: invalid start byte
    

    of course text may be larger but buf_size may be picked up so it'll lead to obfuscated error like above,

  • we can't specify custom line separator,
  • we can't choose to keep line separator.

So considering all these concerns I've written separate functions:

  • one which works with byte streams,
  • second one which works with text streams and delegates its underlying byte stream to the first one and decodes resulting lines.

First of all let's define next utility functions:

ceil_division for making division with ceiling (in contrast with standard // division with floor, more info can be found in this thread)

def ceil_division(left_number, right_number):
    """
    Divides given numbers with ceiling.
    """
    return -(-left_number // right_number)

split for splitting string by given separator from right end with ability to keep it:

def split(string, separator, keep_separator):
    """
    Splits given string by given separator.
    """
    parts = string.split(separator)
    if keep_separator:
        *parts, last_part = parts
        parts = [part + separator for part in parts]
        if last_part:
            return parts + [last_part]
    return parts

read_batch_from_end to read batch from the right end of binary stream

def read_batch_from_end(byte_stream, size, end_position):
    """
    Reads batch from the end of given byte stream.
    """
    if end_position > size:
        offset = end_position - size
    else:
        offset = 0
        size = end_position
    byte_stream.seek(offset)
    return byte_stream.read(size)

After that we can define function for reading byte stream in reverse order like

import functools
import itertools
import os
from operator import methodcaller, sub


def reverse_binary_stream(byte_stream, batch_size=None,
                          lines_separator=None,
                          keep_lines_separator=True):
    if lines_separator is None:
        lines_separator = (b'\r', b'\n', b'\r\n')
        lines_splitter = methodcaller(str.splitlines.__name__,
                                      keep_lines_separator)
    else:
        lines_splitter = functools.partial(split,
                                           separator=lines_separator,
                                           keep_separator=keep_lines_separator)
    stream_size = byte_stream.seek(0, os.SEEK_END)
    if batch_size is None:
        batch_size = stream_size or 1
    batches_count = ceil_division(stream_size, batch_size)
    remaining_bytes_indicator = itertools.islice(
            itertools.accumulate(itertools.chain([stream_size],
                                                 itertools.repeat(batch_size)),
                                 sub),
            batches_count)
    try:
        remaining_bytes_count = next(remaining_bytes_indicator)
    except StopIteration:
        return

    def read_batch(position):
        result = read_batch_from_end(byte_stream,
                                     size=batch_size,
                                     end_position=position)
        while result.startswith(lines_separator):
            try:
                position = next(remaining_bytes_indicator)
            except StopIteration:
                break
            result = (read_batch_from_end(byte_stream,
                                          size=batch_size,
                                          end_position=position)
                      + result)
        return result

    batch = read_batch(remaining_bytes_count)
    segment, *lines = lines_splitter(batch)
    yield from reverse(lines)
    for remaining_bytes_count in remaining_bytes_indicator:
        batch = read_batch(remaining_bytes_count)
        lines = lines_splitter(batch)
        if batch.endswith(lines_separator):
            yield segment
        else:
            lines[-1] += segment
        segment, *lines = lines
        yield from reverse(lines)
    yield segment

and finally a function for reversing text file can be defined like:

import codecs


def reverse_file(file, batch_size=None, 
                 lines_separator=None,
                 keep_lines_separator=True):
    encoding = file.encoding
    if lines_separator is not None:
        lines_separator = lines_separator.encode(encoding)
    yield from map(functools.partial(codecs.decode,
                                     encoding=encoding),
                   reverse_binary_stream(
                           file.buffer,
                           batch_size=batch_size,
                           lines_separator=lines_separator,
                           keep_lines_separator=keep_lines_separator))

Tests

Preparations

I've generated 4 files using fsutil command:

  1. empty.txt with no contents, size 0MB
  2. tiny.txt with size of 1MB
  3. small.txt with size of 10MB
  4. large.txt with size of 50MB

also I've refactored @srohde solution to work with file object instead of file path.

Test script

from timeit import Timer

repeats_count = 7
number = 1
create_setup = ('from collections import deque\n'
                'from __main__ import reverse_file, reverse_readline\n'
                'file = open("{}")').format
srohde_solution = ('with file:\n'
                   '    deque(reverse_readline(file,\n'
                   '                           buf_size=8192),'
                   '          maxlen=0)')
azat_ibrakov_solution = ('with file:\n'
                         '    deque(reverse_file(file,\n'
                         '                       lines_separator="\\n",\n'
                         '                       keep_lines_separator=False,\n'
                         '                       batch_size=8192), maxlen=0)')
print('reversing empty file by "srohde"',
      min(Timer(srohde_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing empty file by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))

Note: I've used collections.deque class to exhaust generator.

Outputs

For PyPy 3.5 on Windows 10:

reversing empty file by "srohde" 8.31e-05
reversing empty file by "Azat Ibrakov" 0.00016090000000000028
reversing tiny file (1MB) by "srohde" 0.160081
reversing tiny file (1MB) by "Azat Ibrakov" 0.09594989999999998
reversing small file (10MB) by "srohde" 8.8891863
reversing small file (10MB) by "Azat Ibrakov" 5.323388100000001
reversing large file (50MB) by "srohde" 186.5338368
reversing large file (50MB) by "Azat Ibrakov" 99.07450229999998

For CPython 3.5 on Windows 10:

reversing empty file by "srohde" 3.600000000000001e-05
reversing empty file by "Azat Ibrakov" 4.519999999999958e-05
reversing tiny file (1MB) by "srohde" 0.01965560000000001
reversing tiny file (1MB) by "Azat Ibrakov" 0.019207699999999994
reversing small file (10MB) by "srohde" 3.1341862999999996
reversing small file (10MB) by "Azat Ibrakov" 3.0872588000000007
reversing large file (50MB) by "srohde" 82.01206720000002
reversing large file (50MB) by "Azat Ibrakov" 82.16775059999998

So as we can see it performs like original solution, but is more general and free of its disadvantages listed above.


Advertisement

I've added this to 0.3.0 version of lz package (requires Python 3.5+) that have many well-tested functional/iterating utilities.

Can be used like

 import io
 from lz.iterating import reverse
 ...
 with open('path/to/file') as file:
     for line in reverse(file, batch_size=io.DEFAULT_BUFFER_SIZE):
         print(line)

It supports all standard encodings (maybe except utf-7 since it is hard for me to define a strategy for generating strings encodable with it).

What’s the difference between Response.Write() andResponse.Output.Write()?

Nothing, they are synonymous (Response.Write is simply a shorter way to express the act of writing to the response output).

If you are curious, the implementation of HttpResponse.Write looks like this:

public void Write(string s)
{
    this._writer.Write(s);
}

And the implementation of HttpResponse.Output is this:

public TextWriter Output
{
    get
    {
        return this._writer;
    }
}

So as you can see, Response.Write and Response.Output.Write are truly synonymous expressions.

How can I count the occurrences of a list item?

Count of all elements with itertools.groupby()

Antoher possiblity for getting the count of all elements in the list could be by means of itertools.groupby().

With "duplicate" counts

from itertools import groupby

L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c']  # Input list

counts = [(i, len(list(c))) for i,c in groupby(L)]      # Create value-count pairs as list of tuples 
print(counts)

Returns

[('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]

Notice how it combined the first three a's as the first group, while other groups of a are present further down the list. This happens because the input list L was not sorted. This can be a benefit sometimes if the groups should in fact be separate.

With unique counts

If unique group counts are desired, just sort the input list:

counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
print(counts)

Returns

[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]

Note: For creating unique counts, many of the other answers provide easier and more readable code compared to the groupby solution. But it is shown here to draw a parallel to the duplicate count example.

How can we run a test method with multiple parameters in MSTest?

Not exactly the same as NUnit's Value (or TestCase) attributes, but MSTest has the DataSource attribute, which allows you to do a similar thing.

You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.

Clear all fields in a form upon going back with browser back button

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:

window.addEventListener("pageshow", () => {
  // update hidden input field
});

See more details for Gecko and WebKit implementations.

Use URI builder in Android or create URL with variables

Best answer: https://stackoverflow.com/a/19168199/413127

Example for

 http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7

Now with Kotlin

 val myUrl = Uri.Builder().apply {
        scheme("https")
        authority("www.myawesomesite.com")
        appendPath("turtles")
        appendPath("types")
        appendQueryParameter("type", "1")
        appendQueryParameter("sort", "relevance")
        fragment("section-name")
        build()            
    }.toString()

How can I extract all values from a dictionary in Python?

If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].

Is it possible to pull just one file in Git?

You can fetch and then check out only one file in this way:

git fetch
git checkout -m <revision> <yourfilepath>
git add <yourfilepath>
git commit

Regarding the git checkout command:

  • <revision> -- a branch name, i.e. origin/master
  • <yourfilepath> does not include the repository name (that you can get from clicking copy path button on a file page on GitHub), i.e. README.md

How to upgrade pip3?

You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running pip3 install --upgrade pip.

It might be a good idea to take some time and read about virtual environments in Python. It isn't a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/

Upload a file to Amazon S3 with NodeJS

Upload CSV/Excel

const fs = require('fs');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
    accessKeyId: XXXXXXXXX,
    secretAccessKey: XXXXXXXXX
});

const absoluteFilePath = "C:\\Project\\test.xlsx";

const uploadFile = () => {
  fs.readFile(absoluteFilePath, (err, data) => {
     if (err) throw err;
     const params = {
         Bucket: 'testBucket', // pass your bucket name
         Key: 'folderName/key.xlsx', // file will be saved in <folderName> folder
         Body: data
     };
      s3.upload(params, function (s3Err, data) {
                    if (s3Err) throw s3Err
                    console.log(`File uploaded successfully at ${data.Location}`);
                    debugger;
                });
  });
};

uploadFile();

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

An URL to a Windows shared folder

If you are allowed to go further then javascript/html facilities - I would use the apache web server to represent your directory listing via http.

If this solution is appropriate. these are the steps:

  1. download apache hhtp server from one of the mirrors http://httpd.apache.org/download.cgi

  2. unzip/install (if msi) it to the directory e.g C:\opt\Apache (the instruction is for windows)

  3. map the network forlder as a local drive on windows (\server\folder to let's say drive H:)

  4. open conf/httpd.conf file

  5. make sure the next line is present and not commented

    LoadModule autoindex_module modules/mod_autoindex.so

  6. Add directory configuration

<Directory "H:/path">

Options +Indexes

AllowOverride None

Order allow,deny

Allow from all

</Directory> 7. Start the web server and make sure the directory listingof the remote folder is available by http. hit localhost/path 8. use a frame inside your web page to access the listing

What is missed: 1. you mignt need more fancy configuration for the host name, refer to Apache Web Server docs. Register the host name in DNS server

  1. the mapping to the network drive might not work, i did not check. As a posible resolution - host your web server on the same machine as smb server.

Deserialize JSON into C# dynamic object?

JsonFx can deserialize JSON content into dynamic objects.

Serialize to/from dynamic types (default for .NET 4.0):

var reader = new JsonReader(); var writer = new JsonWriter();

string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}

Could not open a connection to your authentication agent

Using Git Bash on Win8.1E, my resolution was as follows:

eval $(ssh-agent) > /dev/null
ssh-add ~/.ssh/id_rsa

Filtering Table rows using Jquery

Adding one more approach :

value = $(this).val().toLowerCase();
$("#product-search-result tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});

Adb over wireless without usb cable at all for not rooted phones

type in Windows cmd.exe

    cd %userprofile%\.android
    dir
    copy adbkey.pub adb_keys
    dir

copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.

from: How to solve ADB device unauthorized in Android ADB host device?

now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.

from: How can I connect to Android with ADB over TCP?

Python: SyntaxError: keyword can't be an expression

I just got that problem when converting from % formatting to .format().

Previous code:

"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}

Problematic syntax:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)

The problem is that format is a function that needs parameters. They cannot be strings. That is one of worst python error messages I've ever seen.

Corrected code:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)

How to parse float with two decimal places in javascript?

For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.

To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.

MySQL SELECT query string matching

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

Get table column names in MySQL?

The following SQL statements are nearly equivalent:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'
  [AND table_schema = 'db_name']
  [AND column_name LIKE 'wild']

SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']

Reference: INFORMATION_SCHEMA COLUMNS

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

How to remove all non-alpha numeric characters from a string in MySQL?

The fastest way I was able to find (and using ) is with convert().

from Doc. CONVERT() with USING is used to convert data between different character sets.

Example:

convert(string USING ascii)

In your case the right character set will be self defined

NOTE from Doc. The USING form of CONVERT() is available as of 4.1.0.

Getting full-size profile picture

As noted above, it appears that the cover photo of the profile album is a hi-res profile picture. I would check for the album type of "profile" rather than the name though, as the name may not be consistent across different languages, but the type should be.

To reduce the number of requests / parsing, you can use this fql: "select cover_object_id from album where type='profile' and owner = user_id"

And then you can construct the image url with: "https://graph.facebook.com/" + cover_object_id + "/picture&type=normal&access_token=" + access_token

Looks like there is no "large" type for this image, but the "normal" one is still quite large.

As noted above, this photo may be less accessible than the public profile picture. You need the user_photos or friend_photos permission to access it.

How to convert hashmap to JSON object in Java

This solution works with complex JSONs:

public Object toJSON(Object object) throws JSONException {
    if (object instanceof HashMap) {
        JSONObject json = new JSONObject();
        HashMap map = (HashMap) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable) object)) {
            json.put(toJSON(value));
        }
        return json;
    }
    else {
        return object;
    }
}

How to change already compiled .class file without decompile?

Use a bytecode editor, like:

http://set.ee/jbe/

Be careful because you need a very good knowledge of the Java bytecode.

You can also change the class at runtime with bytecode weaving (like AspectJ).

Display HTML snippets in HTML

<textarea ><?php echo htmlentities($page_html); ?></textarea>

works fine for me..

"keeping in mind Alexander's suggestion, here is why I think this is a good approach"

if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.

using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.

There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)

Laravel Checking If a Record Exists

I think below way is the simplest way to achieving same :

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user doesn't exist!
    }

openCV video saving in python

import cv2

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        print(frame.shape)
        out.write(frame)
        cv2.imshow('Frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()`enter code here`

cv2.destroyAllWindows()

This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour

Android: Scale a Drawable or background image?

You can use one of following:

android:gravity="fill_horizontal|clip_vertical"

Or

android:gravity="fill_vertical|clip_horizontal"

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

How to copy data from one HDFS to another HDFS?

Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.

Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

Attempt to write a readonly database - Django w/ SELinux error

In short, it happens when the application which writes to the sqlite database does not have write permission.

This can be solved in three ways:

  1. Granting ownership of db.sqlite3 file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3 )
  2. Running the webserver (often gunicorn) as root user (run the command sudo -i before you run gunicorn or django runserver)
  3. Allowing read and write access to all users by running command chmod 777 db.sqlite3 (Dangerous option)

Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.

Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

Merge, update, and pull Git branches without using checkouts

The question is simple and the answer should be as simple. All the OP is asking is to merge the upstream origin/branchB into his current branch without switching branches.

TL;DR:

git fetch
git merge origin/branchB

The full answer:

git pull does a fetch + merge. It's roughly the the same the two commands below, where <remote> is usually origin (default), and the remote tracking branch starts with <remote>/ followed by the remote branch name:

git fetch [<remote>]
git merge @{u}

The @{u} notation is the configured remote tracking branch for the current branch. If branchB tracks origin/branchB then @{u} from branchB is the same as typing origin/branchB (see git rev-parse --help for more info).

Since you already merge with origin/branchB, all that is missing is the git fetch (which can run from any branch) to update that remote-tracking branch.

Note though that if there was any merge from the pull to include, you should rather merge branchB into branchA after having done a pull from branchB (and eventually push the changes to orign/branchB), but as long as they're fast-forward they would remain the same.

Keep in mind the local branchB will not be updated until you switch to it and do an actual pull, however as long as there are no local commits added to this branch it will just remain a fast-forward to the remote branch.

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

pandas: to_numeric for multiple columns

df[cols] = pd.to_numeric(df[cols].stack(), errors='coerce').unstack()

Set EditText cursor color

The only valid answer should be to change the theme of the activity: <item name="colorAccent">#000000</item> You should not use the android:textCursorDrawable to @null because this only concerns the cursor itself but not the pin below the cursor if you want to drag that cursor. The theming solution is the most serious one.

Resizing an image in an HTML5 canvas

Looking for another great simple solution?

var img=document.createElement('img');
img.src=canvas.toDataURL();
$(img).css("background", backgroundColor);
$(img).width(settings.width);
$(img).height(settings.height);

This solution will use the resize algorith of browser! :)

What key shortcuts are to comment and uncomment code?

"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding

specifying goal in pom.xml

The error message which you specified is nothing but you are not specifying goal for maven build.

you can specify any goal in your run configuration for maven build like clear, compile, install, package.

please following below step to resolve it.

  1. right click on your project.
  2. click 'Run as' and select 'Maven Build'
  3. edit Configuration window will open. write any goal but your problem specific write 'package' in Goal text box.
  4. click on 'Run'

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

In my case it was caused by two things (VS.2012):

1) One of the projects was configured for AnyCPU instead of x86

2) A project that was referenced had somehow the "Build" checkbox unchecked.

Do check your Build | Configuration Manager to get an overview of what is being built and for which platform. Also make sure you check it for both Debug & Release as they may have different settings.

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Copy all values from fields in one class to another through reflection

I didn't want to add dependency to another JAR file because of this, so wrote something which would suit my needs. I follow the convention of fjorm https://code.google.com/p/fjorm/ which means that my generally accessible fields are public and that I don't bother to write setters and getters. (in my opinion code is easier to manage and more readable actually)

So I wrote something (it's not actually much difficult) which suits my needs (assumes that the class has public constructor without args) and it could be extracted into utility class

  public Effect copyUsingReflection() {
    Constructor constructorToUse = null;
    for (Constructor constructor : this.getClass().getConstructors()) {
      if (constructor.getParameterTypes().length == 0) {
        constructorToUse = constructor;
        constructorToUse.setAccessible(true);
      }
    }
    if (constructorToUse != null) {
      try {
        Effect copyOfEffect = (Effect) constructorToUse.newInstance();
        for (Field field : this.getClass().getFields()) {
          try {
            Object valueToCopy = field.get(this);
            //if it has field of the same type (Effect in this case), call the method to copy it recursively
            if (valueToCopy instanceof Effect) {
              valueToCopy = ((Effect) valueToCopy).copyUsingReflection();
            }
            //TODO add here other special types of fields, like Maps, Lists, etc.
            field.set(copyOfEffect, valueToCopy);
          } catch (IllegalArgumentException | IllegalAccessException ex) {
            Logger.getLogger(Effect.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
        return copyOfEffect;
      } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        Logger.getLogger(Effect.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    return null;
  }

Proper use cases for Android UserManager.isUserAGoat()?

There is a similar call, isUserAMonkey(), that returns true if the MonkeyRunner tool is being used. The SDK explanation is just as curious as this one.

public static boolean isUserAMonkey(){}     

Returns true if the user interface is currently being messed with by a monkey.

Here is the source.

I expect that this was added in anticipation of a new SDK tool named something with a goat and will actually be functional to test for the presence of that tool.

Also see a similar question, Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?.

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

How to iterate through a table rows and get the cell values using jQuery

I got it and explained in below:

//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;

<table id="tableID" class="table table-condensed">
       <thead>
          <tr>
             <th><label>From Group</lable></th>
             <th><label>To Group</lable></th>
             <th><label>Level</lable></th>

           </tr>
       </thead>
         <tbody>
           <tr id="rowCount">
             <td>
               <select >
                 <option value="">select</option>
                 <option value="G1">G1</option>
                 <option value="G2">G2</option>
                 <option value="G3">G3</option>
                 <option value="G4">G4</option>
               </select>
            </td>
            <td>
              <input type="text" id="" value="" readonly="readonly" />
            </td>
            <td>
              <input type="text" value=""  readonly="readonly" />
            </td>
         </tr>
         <tr id="rowCount">
          <td>
            <select >
              <option value="">select</option>
              <option value="G1">G1</option>
              <option value="G2">G2</option>
              <option value="G3">G3</option>
              <option value="G4">G4</option>
           </select>
         </td>
         <td>
           <input type="text" id="" value="" readonly="readonly" />
         </td>
         <td>
           <input type="text" value=""  readonly="readonly" />
         </td>
      </tr>
  </tbody>
</table>

  <button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>


//call on click of Save button;
 $('#saveDtls').click(function(event) {

  var TableData = []; //initialize array;                           
  var data=""; //empty var;

  //Here traverse and  read input/select values present in each td of each tr, ;
  $("table#tableID > tbody > tr").each(function(row, tr) {

     TableData[row]={
        "fromGroup":  $('td:eq(0) select',this).val(),
        "toGroup": $('td:eq(1) input',this).val(),
        "level": $('td:eq(2) input',this).val()
 };

  //Convert tableData array to JsonData
  data=JSON.stringify(TableData)
  //alert('data'+data); 
  });
});

Could not load the Tomcat server configuration

I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.

The following instructions from this blog article helped me in the end:

cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

Validating IPv4 addresses with regexp

For number from 0 to 255 I use this regex:

(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))

Above regex will match integer number from 0 to 255, but not match 256.

So for IPv4 I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})$

It is in this structure: ^(N)((\.(N)){3})$ where N is the regex used to match number from 0 to 255.
This regex will match IP like below:

0.0.0.0
192.168.1.2

but not those below:

10.1.0.256
1.2.3.
127.0.1-2.3

For IPv4 CIDR (Classless Inter-Domain Routing) I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))$

It is in this structure: ^(N)((\.(N)){3})\/M$ where N is the regex used to match number from 0 to 255, and M is the regex used to match number from 0 to 32.
This regex will match CIDR like below:

0.0.0.0/0
192.168.1.2/32

but not those below:

10.1.0.256/16
1.2.3./24
127.0.0.1/33

And for list of IPv4 CIDR like "10.0.0.0/16", "192.168.1.1/32" I use this regex:

^("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))")((,([ ]*)("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))"))*)$

It is in this structure: ^(“C”)((,([ ]*)(“C”))*)$ where C is the regex used to match CIDR (like 0.0.0.0/0).
This regex will match list of CIDR like below:

“10.0.0.0/16”,”192.168.1.2/32”, “1.2.3.4/32”

but not those below:

“10.0.0.0/16” 192.168.1.2/32 “1.2.3.4/32”

Maybe it might get shorter but for me it is easy to understand so fine by me.

Hope it helps!

net::ERR_INSECURE_RESPONSE in Chrome

For me the answer to this was available here on StackOverflow:

ERR_INSECURE_RESPONSE caused by change to Fiddler's root certificate generation using CertEnroll for Windows 7 and later

Unfortunately, this change can cause problems for users who have previously trusted the Fiddler root certificate; the browser may show an error message like NET::ERR_CERT_AUTHORITY_INVALID or The certificate was not issued by a trusted certificate authority.

(Quote from the original source)

I had this ERR_CERT_AUTHORITY_INVALID error on the browser and ERR_INSECURE_RESPONSE shown in Developer Tools of Chrome.

How to use jQuery to show/hide divs based on radio button selection?

An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>  
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>

and have some page independent JavaScript that nicely uses functional programming:

function executeAutomaticVisibility(name) {
    $("[name="+name+"]:checked").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
    });
    $("[name="+name+"]:not(:checked)").each(function() {
        $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
    });
}

$(document).ready( function() {
    triggers = $("[automaticallyVisibleIfIdChecked]")
        .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
    $.unique(triggers);
    triggers.each( function() {
        executeAutomaticVisibility(this.name);
        $(this).change( function(){ executeAutomaticVisibility(this.name); } );
    });
});

Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.

Python function attributes - uses and abuses

Function attributes can be used to write light-weight closures that wrap code and associated data together:

#!/usr/bin/env python

SW_DELTA = 0
SW_MARK  = 1
SW_BASE  = 2

def stopwatch():
   import time

   def _sw( action = SW_DELTA ):

      if action == SW_DELTA:
         return time.time() - _sw._time

      elif action == SW_MARK:
         _sw._time = time.time()
         return _sw._time

      elif action == SW_BASE:
         return _sw._time

      else:
         raise NotImplementedError

   _sw._time = time.time() # time of creation

   return _sw

# test code
sw=stopwatch()
sw2=stopwatch()
import os
os.system("sleep 1")
print sw() # defaults to "SW_DELTA"
sw( SW_MARK )
os.system("sleep 2")
print sw()
print sw2()

1.00934004784

2.00644397736

3.01593494415

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...

  1. Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.

  2. Try using XAMPP Control panel "Admin" button instead of usual http://localhost or http://localhost/phpmyadmin

  3. Try direct link: http://localhost/phpmyadmin/main.php or http://127.0.0.1/phpmyadmin/main.php

  4. Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php

Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.

If this solution helped let me know.

How can I check if a string is null or empty in PowerShell?

Another way to accomplish this in a pure PowerShell way would be to do something like this:

("" -eq ("{0}" -f $val).Trim())

This evaluates successfully for null, empty string, and whitespace. I'm formatting the passed value into an empty string to handle null (otherwise a null will cause an error when the Trim is called). Then just evaluate equality with an empty string. I think I still prefer the IsNullOrWhiteSpace, but if you're looking for another way to do it, this will work.

$val = null    
("" -eq ("{0}" -f $val).Trim())
>True
$val = "      "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False

In a fit of boredom, I played with this some and made it shorter (albeit more cryptic):

!!(("$val").Trim())

or

!(("$val").Trim())

depending on what you're trying to do.

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

Pause in Python

There's no need to wait for input before closing, just change your command like so:

cmd /K python <script>

The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

Subtracting 2 lists in Python

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.

Otherwise, look for list comprehensions used with the zip builtin function:

[a_i - b_i for a_i, b_i in zip(a, b)]

Compare two MySQL databases

There is a useful tool written using perl called Maatkit. It has several database comparison and syncing tools among other things.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I realize this is not related to OSX, but on an embedded system (Beagle Bone Angstrom) I had the exact same error message. Installing the following ipk packages solved it.

opkg install python-setuptools
opkg install python-pip

proper hibernate annotation for byte[]

Thanks Justin, Pascal for guiding me to the right direction. I was also facing the same issue with Hibernate 3.5.3. Your research and pointers to the right classes had helped me identify the issue and do a fix.

For the benefit for those who are still stuck with Hibernate 3.5 and using oid + byte[] + @LoB combination, following is what I have done to fix the issue.

  1. I created a custom BlobType extending MaterializedBlobType and overriding the set and the get methods with the oid style access.

    public class CustomBlobType extends MaterializedBlobType {
    
    private static final String POSTGRESQL_DIALECT = PostgreSQLDialect.class.getName();
    
    /**
     * Currently set dialect.
     */
    private String dialect = hibernateConfiguration.getProperty(Environment.DIALECT);
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#set(java.sql.PreparedStatement, java.lang.Object, int)
     */
    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        byte[] internalValue = toInternalFormat(value);
    
        if (POSTGRESQL_DIALECT.equals(dialect)) {
            try {
    
    //I had access to sessionFactory through a custom sessionFactory wrapper.
    st.setBlob(index, Hibernate.createBlob(internalValue, sessionFactory.getCurrentSession()));
                } catch (SystemException e) {
                    throw new HibernateException(e);
                }
            } else {
                st.setBytes(index, internalValue);
            }
        }
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#get(java.sql.ResultSet, java.lang.String)
     */
    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        Blob blob = rs.getBlob(name);
        if (rs.wasNull()) {
            return null;
        }
        int length = (int) blob.length();
        return toExternalFormat(blob.getBytes(1, length));
      }
    }
    
    1. Register the CustomBlobType with Hibernate. Following is what i did to achieve that.

      hibernateConfiguration= new AnnotationConfiguration();
      Mappings mappings = hibernateConfiguration.createMappings();
      mappings.addTypeDef("materialized_blob", "x.y.z.BlobType", null);
      

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

How to preview selected image in input type="file" in popup using jQuery?

If your are using HTML5 then try following code snippet

<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

</script>

How to use log4net in Asp.net core 2.0

I am successfully able to log a file using the following code

public static void Main(string[] args)
{
    XmlDocument log4netConfig = new XmlDocument();
    log4netConfig.Load(File.OpenRead("log4net.config"));
    var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
               typeof(log4net.Repository.Hierarchy.Hierarchy));
    log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

    BuildWebHost(args).Run();
}

log4net.config in website root

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="C:\Temp\" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
</log4net>

How to get the first element of an array?

If you're chaining a view functions to the array e.g.

array.map(i => i+1).filter(i => i > 3)

And want the first element after these functions you can simply add a .shift() it doesn't modify the original array, its a nicer way then array.map(i => i+1).filter(=> i > 3)[0]

If you want the first element of an array without modifying the original you can use array[0] or array.map(n=>n).shift() (without the map you will modify the original. In this case btw i would suggest the ..[0] version.

Execute ssh with password authentication via windows command prompt

PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.

How do I get a list of all the duplicate items using pandas in python?

With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])

In [3]: df
Out[3]: 
       0
    0  a
    1  b
    2  c
    3  d
    4  a
    5  b

In [4]: df[df.duplicated(keep=False)]
Out[4]: 
       0
    0  a
    1  b
    4  a
    5  b

How to use source: function()... and AJAX in JQuery UI autocomplete

$("#id").autocomplete(
{
    search: function () {},
    source: function (request, response)
    {
        $.ajax(
        {
            url: ,
            dataType: "json",
            data:
            {
                term: request.term,
            },
            success: function (data)
            {
                response(data);
            }
        });
    },
    minLength: 2,
    select: function (event, ui)
    {
        var test = ui.item ? ui.item.id : 0;
        if (test > 0)
        {
           alert(test);
        }
    }
});

What are "res" and "req" parameters in Express functions?

req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

Those parameters can be named anything. You could change that code to this if it's more clear:

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

Edit:

Say you have this method:

app.get('/people.json', function(request, response) { });

The request will be an object with properties like these (just to name a few):

  • request.url, which will be "/people.json" when this particular action is triggered
  • request.method, which will be "GET" in this case, hence the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
  • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

To respond to that request, you use the response object to build your response. To expand on the people.json example:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

How to secure the ASP.NET_SessionId cookie?

Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.

    protected void Session_Start(Object sender, EventArgs e)
    {
        SessionStateSection sessionState = 
 (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
        string sidCookieName = sessionState.CookieName;

        if (Request.Cookies[sidCookieName] != null)
        {
            HttpCookie sidCookie = Response.Cookies[sidCookieName];
            sidCookie.Value = Session.SessionID;
            sidCookie.HttpOnly = true;
            sidCookie.Secure = true;
            sidCookie.Path = "/";
        }
    }

AngularJS Folder Structure

enter image description here

Sort By Type

On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.

Sort By Feature (preferred)

On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.

A well written blog post: http://www.johnpapa.net/angular-growth-structure/

Example App: https://github.com/angular-app/angular-app

Lightweight XML Viewer that can handle large files

firstobject's 605k download lightweight native Windows free XML editor opens a 50MB file in 1.3 seconds and provides text editing, search, syntax-colored printing, plus tree view and additional XML features including formatting and full-blown CMarkup scripting built in. You can reformat an entire 50MB XML document to a different indentation (takes 3 seconds on a nothing special 2.3GHz/2GB machine).

How can I correctly format currency using jquery?

Another option (If you are using ASP.Net razor view) is, On your view you can do

<div>@String.Format("{0:C}", Model.total)</div>

This would format it correctly. note (item.total is double/decimal)

if in jQuery you can also use Regex

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

Converting map to struct

There are two steps:

  1. Convert interface to JSON Byte
  2. Convert JSON Byte to struct

Below is an example:

dbByte, _ := json.Marshal(dbContent)
_ = json.Unmarshal(dbByte, &MyStruct)

How do you save/store objects in SharedPreferences on Android?

An other way to save and restore an object from android sharedpreferences without using the Json format

private static ExampleObject getObject(Context c,String db_name){
            SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            ExampleObject o = new ExampleObject();
            Field[] fields = o.getClass().getFields();
            try {
                for (Field field : fields) {
                    Class<?> type = field.getType();
                    try {
                        final String name = field.getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            field.set(o,sharedPreferences.getString(name, ""));
                        } else if (type.equals(int.class) || type.equals(Short.class))
                            field.setInt(o,sharedPreferences.getInt(name, 0));
                        else if (type.equals(double.class))
                            field.setDouble(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(float.class))
                            field.setFloat(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(long.class))
                            field.setLong(o,sharedPreferences.getLong(name, 0));
                        else if (type.equals(Boolean.class))
                            field.setBoolean(o,sharedPreferences.getBoolean(name, false));
                        else if (type.equals(UUID.class))
                            field.set(
                                    o,
                                    UUID.fromString(
                                            sharedPreferences.getString(
                                                    name,
                                                    UUID.nameUUIDFromBytes("".getBytes()).toString()
                                            )
                                    )
                            );

                    } catch (IllegalAccessException e) {
                        Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                    } catch (IllegalArgumentException e) {
                        Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
            return o;
        }
        private static void setObject(Context context, Object o, String db_name) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (Field field : fields) {
                Class<?> type = field.getType();
                try {
                    final String name = field.getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = field.get(o);
                        if (value != null)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class) || type.equals(Short.class))
                        editor.putInt(name, field.getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) field.getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, field.getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, field.getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, field.getBoolean(o));
                    else if (type.equals(UUID.class))
                        editor.putString(name, field.get(o).toString());

                } catch (IllegalAccessException e) {
                    Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                } catch (IllegalArgumentException e) {
                    Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                }
            }

            editor.apply();
        }

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

You can use the following function to convert the text "HTML" to the element

_x000D_
_x000D_
function htmlToElement(html)_x000D_
{_x000D_
  var element = document.createElement('div');_x000D_
  element.innerHTML = html;_x000D_
  return(element);_x000D_
}_x000D_
var html="<li>text and html</li>";_x000D_
var e=htmlToElement(html);
_x000D_
_x000D_
_x000D_

Adding a newline into a string in C#

Then just modify the previous answers to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don't want the newlines in the text file, then don't preserve it.

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

How do I read a resource file from a Java jar file?

Outside of your technique, why not use the standard Java JarFile class to get the references you want? From there most of your problems should go away.

How to remove line breaks (no characters!) from the string?

Something a bit more functional (easy to use anywhere):

function strip_carriage_returns($string)
{
    return str_replace(array("\n\r", "\n", "\r"), '', $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

Convert seconds to Hour:Minute:Second

Here is a one liner that handles negative seconds and more than 1 day worth of seconds.

sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

For Example:

$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

outputs: -26:03:04

HTTP GET request in JavaScript?

Modern, clean and shortest

fetch('https://www.randomtext.me/api/lorem')

_x000D_
_x000D_
let url = 'https://www.randomtext.me/api/lorem';

// to only send GET request without waiting for response just call 
fetch(url);

// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));

// or async/await
(async()=> 
  console.log('\nREQUEST 3', await(await fetch(url)).json()) 
)();
_x000D_
Open Chrome console network tab to see request
_x000D_
_x000D_
_x000D_

Basic HTTP authentication with Node and Express 4

Express has removed this functionality and now recommends you use the basic-auth library.

Here's an example of how to use:

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

To send a request to this route you need to include an Authorization header formatted for basic auth.

Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

Your curl request will then look like:

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

Tooltips with Twitter Bootstrap

Simply mark all the data-toggles...

jQuery(function () {
    jQuery('[data-toggle=tooltip]').tooltip();
});

http://jsfiddle.net/Amged/xUQ6D/19/

Maximum value for long integer

Python long can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf'), since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf').

post checkbox value

In your form tag, rather than

name="booking.php"

use

action="booking.php"

And then, in booking.php use

$checkValue = $_POST['booking-check'];

Also, you'll need a submit button in there

<input type='submit'>

How to verify if $_GET exists?

Use and empty() whit negation (for test if not empty)

if(!empty($_GET['id'])) {
    // if get id is not empty
}

how to set radio button checked in edit mode in MVC razor view

You have written like

@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })

Here you have taken gender as a Enum type and you have written the value for the radio button as a string type- change "Male" to 0 and "Female" to 1.

Set angular scope variable in markup

I like the answer but I think it would be better that you create a global scope function that will allow you to set the scope variable needed.

So in the globalController create

$scope.setScopeVariable = function(variable, value){
    $scope[variable] = value;
}

and then in your html file call it

{{setScopeVariable('myVar', 'whatever')}}

This will then allow you to use $scope.myVar in your respective controller

long long in C/C++

The letters 100000000000 make up a literal integer constant, but the value is too large for the type int. You need to use a suffix to change the type of the literal, i.e.

long long num3 = 100000000000LL;

The suffix LL makes the literal into type long long. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.

What is the correct JSON content type?

Extending the accepted responses, when you are using JSON in a REST context...

There is a strong argument about using application/x-resource+json and application/x-collection+json when you are representing REST resources and collections.

And if you decide to follow the jsonapi specification, you should use of application/vnd.api+json, as it is documented.

Altough there is not an universal standard, it is clear that the added semantic to the resources being transfered justify a more explicit Content-Type than just application/json.

Following this reasoning, other contexts could justify a more specific Content-Type.

DevTools failed to load SourceMap: Could not load content for chrome-extension

include.prepload.js file will have a line something like below. probably as the last line.

//# sourceMappingURL=include.prepload.js.map

Delete it and the error will go away.

How do I change a single value in a data.frame?

In RStudio you can write directly in a cell. Suppose your data.frame is called myDataFrame and the row and column are called columnName and rowName. Then the code would look like:

myDataFrame["rowName", "columnName"] <- value

Hope that helps!

How does one get started with procedural generation?

There is an excellent book about the topic:

http://www.amazon.com/Texturing-Modeling-Third-Procedural-Approach/dp/1558608486

It is biased toward non-real-time visual effects and animation generation, but the theory and ideas are usable outside of these fields, I suppose.

It may also worth to mention that there is a professional software package that implements a complete procedural workflow called SideFX's Houdini. You can use it to invent and prototype procedural solutions to problems, that you can later translate to code.

While it's a rather expensive package, it has a free evaluation licence, which can be used as a very nice educational and/or engineering tool.

Is there any WinSCP equivalent for linux?

One thing I find WinSCP does well that I cannot do easily with Ubuntu tools is tunneling to a secondary machine. This is done with one with one connection setting in WinSCP. While I can use the native file browsers in Ubuntu (11.11) to reach any machine, I cannot easily tunnel thru an intermediate machine to reach a third one. I suspect it is because I do not well understand how to set up tunneling. I am toying with gSTM, but there is little documentation, and I suspect it is for setting up local tunnels, not remote ones. In any case it is not as dead simple as WinSCP made it. This is no anwser, but perhaps it highlights a critical feature of WinSCP that suggestions for alternatives should address.

Now off to learn more about tunneling...

How to check if a network port is open on linux?

If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socket
from contextlib import closing

def check_socket(host, port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        if sock.connect_ex((host, port)) == 0:
            print "Port is open"
        else:
            print "Port is not open"

Server did not recognize the value of HTTP Header SOAPAction

I had to sort out capitalisation of my service reference, delete the references and re add them to fix this. I am not sure if any of these steps are superstitious, but the problem went away.

Cannot open include file 'afxres.h' in VC2010 Express

You can also try replace afxres.h with WinResrc.h

How to make the checkbox unchecked by default always

One quick solution that came to mind :-

<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;">&nbsp</label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
  document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->

Proper Linq where clauses

EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...


They're different in terms of what will be called - the first is equivalent to:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido")
          .Where(x => x.Fat == true)

wheras the latter is equivalent to:

Collection.Where(x => x.Age == 10 && 
                      x.Name == "Fido" &&
                      x.Fat == true)

Now what difference that actually makes depends on the implementation of Where being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.

Typically I would use several where clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.

How To Execute SSH Commands Via PHP

Do you have the SSH2 extension available?

Docs: http://www.php.net/manual/en/function.ssh2-exec.php

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');

minimum double value in C/C++

A truly portable C++ solution

As from C++11 you can use numeric_limits<double>::lowest(). According to the standard, it returns exactly what you're looking for:

A finite value x such that there is no other finite value y where y < x.
Meaningful for all specializations in which is_bounded != false.

Online demo


Lots of non portable C++ answers here !

There are many answers going for -std::numeric_limits<double>::max().

Fortunately, they will work well in most of the cases. Floating point encoding schemes decompose a number in a mantissa and an exponent and most of them (e.g. the popular IEEE-754) use a distinct sign bit, which doesn't belong to the mantissa. This allows to transform the largest positive in the smallest negative just by flipping the sign:

enter image description here

Why aren't these portable ?

The standard doesn't impose any floating point standard.

I agree that my argument is a little bit theoretic, but suppose that some excentric compiler maker would use a revolutionary encoding scheme with a mantissa encoded in some variations of a two's complement. Two's complement encoding are not symmetric. for example for a signed 8 bit char the maximum positive is 127, but the minimum negative is -128. So we could imagine some floating point encoding show similar asymmetric behavior.

I'm not aware of any encoding scheme like that, but the point is that the standard doesn't guarantee that the sign flipping yields the intended result. So this popular answer (sorry guys !) can't be considered as fully portable standard solution ! /* at least not if you didn't assert that numeric_limits<double>::is_iec559 is true */

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Django download a file

Simple using html like this downloads the file mentioned using static keyword

<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

php timeout - set_time_limit(0); - don't work

ini_set('max_execution_time', 300);

use this

javascript - Create Simple Dynamic Array

Some of us are referring to use from which is not good at the performance:

_x000D_
_x000D_
function getArrayViaFrom(input) {_x000D_
  console.time('Execution Time');_x000D_
  let output = Array.from(Array(input), (value, i) => (i + 1).toString())_x000D_
  console.timeEnd('Execution Time');_x000D_
_x000D_
  return output;_x000D_
}_x000D_
_x000D_
function getArrayViaFor(input) {_x000D_
  console.time('Execution Time 1');_x000D_
  var output = [];_x000D_
  for (var i = 1; i <= input; i++) {_x000D_
    output.push(i.toString());_x000D_
  }_x000D_
  console.timeEnd('Execution Time 1');_x000D_
_x000D_
  return output;_x000D_
}_x000D_
_x000D_
console.log(getArrayViaFrom(10)) // Takes 10x more than for that is 0.220ms_x000D_
console.log(getArrayViaFor(10))  // Takes 10x less than From that is 0.020ms
_x000D_
_x000D_
_x000D_

How to search for occurrences of more than one space between words in a line

Search for [ ]{2,}. This will find two or more adjacent spaces anywhere within the line. It will also match leading and trailing spaces as well as lines that consist entirely of spaces. If you don't want that, check out Alexander's answer.

Actually, you can leave out the brackets, they are just for clarity (otherwise the space character that is being repeated isn't that well visible :)).

The problem with \s{2,} is that it will also match newlines on Windows files (where newlines are denoted by CRLF or \r\n which is matched by \s{2}.

If you also want to find multiple tabs and spaces, use [ \t]{2,}.

How do I configure PyCharm to run py.test tests?

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the 'unittests' test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

How do I add a new class to an element dynamically?

This is how you do it:

var e = document.getElementById('myIdName');
var value = window.getComputedStyle(e, null).getPropertyValue("zIndex");
alert('z-index: ' + value);

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

in SQL 2017 You can do it more easily in the toolbar to the right just hit
enter image description here

the SQL button then its gonna apear the query with the top 200 you edit until the quantity that You want and Execute the query and Done! just Edit

Can I set variables to undefined or pass undefined as an argument?

The basic difference is that undefined and null represent different concepts.

If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

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

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

http://en.wikipedia.org/wiki/Undefined_value

iOS 7: UITableView shows under status bar

I don't know how Kosher it is, but I found that this scheme moves the ViewController's view down and provides the status bar with a solid background:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Shove everything down if iOS 7 or later
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 7.0f) {

        // Move the view down 20 pixels
        CGRect bounds = self.view.bounds;
        bounds.origin.y -= 20.0;
        [self.view setBounds:bounds];

        // Create a solid color background for the status bar
        CGRect statusFrame = CGRectMake(0.0, -20.0, bounds.size.width, 20);
        UIView* statusBar = [[UIView alloc] initWithFrame:statusFrame];
        statusBar.backgroundColor = [UIColor redColor];
        [self.view addSubview:statusBar];
    }

Of course, replace redColor with whatever color you want for the background.

You must separately do one of the swizzles to set the color of the characters/symbols in the status bar. I use View controller-based status bar appearance = NO and Status bar style = Opaque black style in the plist, to do this globally.

Seems to work, and I'd be interested to hear of any bugs or issues with it.

How do I combine two dataframes?

Thought to add this here in case someone finds it useful. @ostrokach already mentioned how you can merge the data frames across rows which is

df_row_merged = pd.concat([df_a, df_b], ignore_index=True)

To merge across columns, you can use the following syntax:

df_col_merged = pd.concat([df_a, df_b], axis=1)

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

Make xargs execute the command once for each line of input

In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.

Connect to sqlplus in a shell script and run SQL scripts

This should handle issue:

  1. WHENEVER SQLERROR EXIT SQL.SQLCODE
  2. SPOOL ${SPOOL_FILE}
  3. $RC returns oracle's exit code
  4. cat from $SPOOL_FILE explains error
SPOOL_FILE=${LOG_DIR}/${LOG_FILE_NAME}.spool 

SQLPLUS_OUTPUT=`sqlplus -s  "$SFDC_WE_CORE" <<EOF 
        SET HEAD OFF
        SET AUTOPRINT OFF
        SET TERMOUT OFF
        SET SERVEROUTPUT ON

        SPOOL  ${SPOOL_FILE} 

        WHENEVER SQLERROR EXIT SQL.SQLCODE
        DECLARE 

        BEGIN
           foooo 
        --rollback; 
        END;
    /
    EOF` 

RC=$?

if [[ $RC != 0 ]] ; then

    echo " RDBMS exit code : $RC  "     | tee -a ${LOG_FILE}
    cat ${SPOOL_FILE}                   | tee -a ${LOG_FILE}

    cat ${LOG_FILE} | mail -s "Script ${INIT_EXE} failed on $SFDC_ENV" $SUPPORT_LIST

    exit 3

fi

percentage of two int?

Well to make the decimal into a percent you can do this,

float percentage = (correct * 100.0f) / questionNum;

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

  1. Download apache-maven-3.3.9-bin.zip file and extract it.

  2. Then set system variable M2_HOME = B:\sql software\apache-maven-3.3.9 or as appropriate

  3. Also set variable M2 = %M2_HOME%\bin

  4. Open CMD and write mvn

I solved thank you

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

How to initialize a JavaScript Date to a particular time zone

As Matt Johnson said

If you can limit your usage to modern web browsers, you can now do the following without any special libraries:

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

This isn't a comprehensive solution, but it works for many scenarios that require only output conversion (from UTC or local time to a specific time zone, but not the other direction).

So although the browser can not read IANA timezones when creating a date, or has any methods to change the timezones on an existing Date object, there seems to be a hack around it:

_x000D_
_x000D_
function changeTimezone(date, ianatz) {

  // suppose the date is 12:00 UTC
  var invdate = new Date(date.toLocaleString('en-US', {
    timeZone: ianatz
  }));

  // then invdate will be 07:00 in Toronto
  // and the diff is 5 hours
  var diff = date.getTime() - invdate.getTime();

  // so 12:00 in Toronto is 17:00 UTC
  return new Date(date.getTime() - diff); // needs to substract

}

// E.g.
var here = new Date();
var there = changeTimezone(here, "America/Toronto");

console.log(`Here: ${here.toString()}\nToronto: ${there.toString()}`);
_x000D_
_x000D_
_x000D_

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

Grep characters before and after match?

You could use

awk '/test_pattern/ {
    match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file

How to find all occurrences of a substring?

src = input() # we will find substring in this string
sub = input() # substring

res = []
pos = src.find(sub)
while pos != -1:
    res.append(pos)
    pos = src.find(sub, pos + 1)

Scikit-learn train_test_split with indices

Here's the simplest solution (Jibwa made it seem complicated in another answer), without having to generate indices yourself - just using the ShuffleSplit object to generate 1 split.

import numpy as np 
from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit
sss = ShuffleSplit(n_splits=1, test_size=0.1)

data_size = 100
X = np.reshape(np.random.rand(data_size*2),(data_size,2))
y = np.random.randint(2, size=data_size)

sss.get_n_splits(X, y)
train_index, test_index = next(sss.split(X, y)) 

X_train, X_test = X[train_index], X[test_index] 
y_train, y_test = y[train_index], y[test_index]

How to align text below an image in CSS?

Instead of images i choose background option:

HTML:

  <div class="class1">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>    
  <div class="class2">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>
  <div class="class3">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>        

CSS:

  .class1 {

    background: url("Some.png") no-repeat top center;
    text-align: center;

   }

  .class2 {

    background: url("Some2.png") no-repeat top center;
    text-align: center;

   }

  .class3 {

    background: url("Some3.png") no-repeat top center;
    text-align: center;

   }

Remove padding from columns in Bootstrap 3

Specifically for SASS mixin:

@mixin no-padding($side) {
    @if $side == 'all' {
        .no-padding {
            padding: 0 !important;
        }
    } @else {
        .no-padding-#{$side} {
            padding-#{$side}: 0 !important;
        }
    }
}

@include no-padding("left");
@include no-padding("right");
@include no-padding("top");
@include no-padding("bottom");
@include no-padding("all");

Then in HTML, you can use

.no-padding-left
.no-padding-right
.no-padding-bottom
.no-padding-top
.no-padding - to remove padding from all sides

Sure, you can @include only those declarations, which you need.

Difference between core and processor

Let's clarify first what is a CPU and what is a core, a central processing unit CPU, can have multiple core units, those cores are a processor by itself, capable of execute a program but it is self contained on the same chip.

In the past one CPU was distributed among quite a few chips, but as Moore's Law progressed they made to have a complete CPU inside one chip (die), since the 90's the manufacturer's started to fit more cores in the same die, so that's the concept of Multi-core.

In these days is possible to have hundreds of cores on the same CPU (chip or die) GPUs, Intel Xeon. Other technique developed in the 90's was simultaneous multi-threading, basically they found that was possible to have another thread in the same single core CPU, since most of the resources were duplicated already like ALU, multiple registers.

So basically a CPU can have multiple cores each of them capable to run one thread or more at the same time, we may expect to have more cores in the future, but with more difficulty to be able to program efficiently.

How can I toggle word wrap in Visual Studio?

In latest version.

1.click the left bottom of the icon setting

2.select setting setting

3.select "text editor"> "word wrap" on word wrap

How can I replace every occurrence of a String in a file with PowerShell?

I prefer using the File-class of .NET and its static methods as seen in the following example.

$content = [System.IO.File]::ReadAllText("c:\bla.txt").Replace("[MYID]","MyValue")
[System.IO.File]::WriteAllText("c:\bla.txt", $content)

This has the advantage of working with a single String instead of a String-array as with Get-Content. The methods also take care of the encoding of the file (UTF-8 BOM, etc.) without you having to take care most of the time.

Also the methods don't mess up the line endings (Unix line endings that might be used) in contrast to an algorithm using Get-Content and piping through to Set-Content.

So for me: Fewer things that could break over the years.

A little-known thing when using .NET classes is that when you have typed in "[System.IO.File]::" in the PowerShell window you can press the Tab key to step through the methods there.

How to put an image next to each other

You don't need the div's.

HTML:

<div class="nav3" style="height:705px;">
    <a href="http://www.facebook.com/" class="icons"><img src="images/facebook.png"></a>
    <a href="https://twitter.com" class="icons"><img src="images/twitter.png"></a>
</div>

CSS:

.nav3 {
    background-color: #E9E8C7;
    height: auto;
    width: 150px;
    float: left;
    padding-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #333333;
    padding-top: 20px;
    padding-right: 20px;
}

.icons{
    display:inline-block;
    width: 64px; 
    height: 64px; 
   }

 a.icons:hover {
     background: #C93;
 }

See this fiddle

How can I control Chromedriver open window size?

try this

using System.Drawing;
driver.Manage().Window.Size = new Size(width, height);

Format JavaScript date as yyyy-mm-dd

If you use momentjs, now they include a constant for that format YYYY-MM-DD:

date.format(moment.HTML5_FMT.DATE)

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

This worked perfectly for me without css. I think css would put some icing on the cake though.

    <form>
        <label for="First Name" >First Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
        <label for="Last Name" >Last Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
    </form>

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

It's actually a quirk in Chrome, not the JavaScript library. Here's the fix:

To prevent the message appearing and also allow chrome to render the response nicely as JSON in the console, append a query string to your request URL.

e.g

var xhr_object = new XMLHttpRequest();

var url = 'mysite.com/'; // Using this one, Chrome throws error

var url = 'mysite.com/?'; // Using this one, Chrome works

xhr_object.open('POST', url, false);

textarea's rows, and cols attribute in CSS

As far as I know, you can't.

Besides, that isnt what CSS is for anyway. CSS is for styling and HTML is for markup.

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

It's October 2017, and Google makes Android Support Library with the new things call Lifecycle component. It provides some new idea for this 'Can not perform this action after onSaveInstanceState' problem.

In short:

  • Use lifecycle component to determine if it's correct time for popping up your fragment.

Longer version with explain:

  • why this problem come out?

    It's because you are trying to use FragmentManager from your activity(which is going to hold your fragment I suppose?) to commit a transaction for you fragment. Usually this would look like you are trying to do some transaction for an up coming fragment, meanwhile the host activity already call savedInstanceState method(user may happen to touch the home button so the activity calls onStop(), in my case it's the reason)

    Usually this problem shouldn't happen -- we always try to load fragment into activity at the very beginning, like the onCreate() method is a perfect place for this. But sometimes this do happen, especially when you can't decide what fragment you will load to that activity, or you are trying to load fragment from an AsyncTask block(or anything will take a little time). The time, before the fragment transaction really happens, but after the activity's onCreate() method, user can do anything. If user press the home button, which triggers the activity's onSavedInstanceState() method, there would be a can not perform this action crash.

    If anyone want to see deeper in this issue, I suggest them to take a look at this blog post. It looks deep inside the source code layer and explain a lot about it. Also, it gives the reason that you shouldn't use the commitAllowingStateLoss() method to workaround this crash(trust me it offers nothing good for your code)

  • How to fix this?

    • Should I use commitAllowingStateLoss() method to load fragment? Nope you shouldn't;

    • Should I override onSaveInstanceState method, ignore super method inside it? Nope you shouldn't;

    • Should I use the magical isFinishing inside activity, to check if the host activity is at the right moment for fragment transaction? Yeah this looks like the right way to do.

  • Take a look at what Lifecycle component can do.

    Basically, Google makes some implementation inside the AppCompatActivity class(and several other base class you should use in your project), which makes it a easier to determine current lifecycle state. Take a look back to our problem: why would this problem happen? It's because we do something at the wrong timing. So we try not to do it, and this problem will be gone.

    I code a little for my own project, here is what I do using LifeCycle. I code in Kotlin.

val hostActivity: AppCompatActivity? = null // the activity to host fragments. It's value should be properly initialized.

fun dispatchFragment(frag: Fragment) {
    hostActivity?.let {
       if(it.lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED)){
           showFragment(frag)
       }
    }
}

private fun showFragment(frag: Fragment) {
    hostActivity?.let {
        Transaction.begin(it, R.id.frag_container)
                .show(frag)
                .commit()
    }

As I show above. I will check the lifecycle state of the host activity. With Lifecycle component within support library, this could be more specific. The code lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED) means, if current state is at least onResume, not later than it? Which makes sure my method won't be execute during some other life state(like onStop).

  • Is it all done?

    Of course not. The code I have shown tells some new way to prevent application from crashing. But if it do go to the state of onStop, that line of code wont do things and thus show nothing on your screen. When users come back to the application, they will see an empty screen, that's the empty host activity showing no fragments at all. It's bad experience(yeah a little bit better than a crash).

    So here I wish there could be something nicer: app won't crash if it comes to life state later than onResume, the transaction method is life state aware; besides, the activity will try continue to finished that fragment transaction action, after the user come back to our app.

    I add something more to this method:

class FragmentDispatcher(_host: FragmentActivity) : LifecycleObserver {
    private val hostActivity: FragmentActivity? = _host
    private val lifeCycle: Lifecycle? = _host.lifecycle
    private val profilePendingList = mutableListOf<BaseFragment>()

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
        if (profilePendingList.isNotEmpty()) {
            showFragment(profilePendingList.last())
        }
    }

    fun dispatcherFragment(frag: BaseFragment) {
        if (lifeCycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true) {
            showFragment(frag)
        } else {
            profilePendingList.clear()
            profilePendingList.add(frag)
        }
    }

    private fun showFragment(frag: BaseFragment) {
        hostActivity?.let {
            Transaction.begin(it, R.id.frag_container)
                    .show(frag)
                    .commit()
        }
    }
}

I maintain a list inside this dispatcher class, to store those fragment don't have chance to finish the transaction action. And when user come back from home screen and found there is still fragment waiting to be launched, it will go to the resume() method under the @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) annotation. Now I think it should be working like I expected.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.

Assuming the existing rule is 'Use a formula to dtermine which cells to format':

Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.

This will work assuming the relative offsets are appropriate throughout your desired apply-to range.

You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.

Where to install Android SDK on Mac OS X?

I have been toying with this as well. I initially had it in my documents folder, but decided that didn't make 'philosophical' sense. I decided to create an Android directory in my home folder and place Eclipse and the Android SKK in there.

Formatting floats without trailing zeros

OP would like to remove superflouous zeros and make the resulting string as short as possible.

I find the %g exponential formatting shortens the resulting string for very large and very small values. The problem comes for values that don't need exponential notation, like 128.0, which is neither very large or very small.

Here is one way to format numbers as short strings that uses %g exponential notation only when Decimal.normalize creates strings that are too long. This might not be the fastest solution (since it does use Decimal.normalize)

def floatToString (inputValue, precision = 3):
    rc = str(Decimal(inputValue).normalize())
    if 'E' in rc or len(rc) > 5:
        rc = '{0:.{1}g}'.format(inputValue, precision)        
    return rc

inputs = [128.0, 32768.0, 65536, 65536 * 2, 31.5, 1.000, 10.0]

outputs = [floatToString(i) for i in inputs]

print(outputs)

# ['128', '32768', '65536', '1.31e+05', '31.5', '1', '10']

Split (explode) pandas dataframe string entry to separate rows

Here is a fairly straightforward message that uses the split method from pandas str accessor and then uses NumPy to flatten each row into a single array.

The corresponding values are retrieved by repeating the non-split column the correct number of times with np.repeat.

var1 = df.var1.str.split(',', expand=True).values.ravel()
var2 = np.repeat(df.var2.values, len(var1) / len(df))

pd.DataFrame({'var1': var1,
              'var2': var2})

  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Your receiver:

public class MyReceiver extends BroadcastReceiver {   

    @Override
    public void onReceive(Context context, Intent intent) {

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);

    }
}

Your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.broadcast.receiver.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <activity android:name=".BR_Example"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

    <!-- Adding the permission -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

</manifest>

Angular2: Cannot read property 'name' of undefined

You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

Specifically, under the heading Display hero names in a template, it states:

To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

followed by this code block:

<h2>My Heroes</h2>
<ul class="heroes">
  <li>
    <!-- each hero goes here -->
  </li>
</ul>

It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

<h2>{{hero.name}} details!</h2>

outside of our *ngFor.

However, if you scroll further down the page, you will encounter the following:

The template for displaying heroes should look like this:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Note the absence of the detail elements from previous efforts.

An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

IOError: [Errno 32] Broken pipe: Python

I know this is not the "proper" way to do it, but if you are simply interested in getting rid of the error message, you could try this workaround:

python your_python_code.py 2> /dev/null | other_command

How to tell which row number is clicked in a table?

This would get you the index of the clicked row, starting with one:

_x000D_
_x000D_
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
   <tr>_x000D_
      <td>1</td><td>1</td><td>1</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>2</td><td>2</td><td>2</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>3</td><td>3</td><td>3</td>_x000D_
   </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If you want to return the number stored in that first cell of each row:

$('#thetable').find('tr').click( function(){
  var row = $(this).find('td:first').text();
  alert('You clicked ' + row);
});

Round double in two decimal places in C#?

You should use

inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

Math.Round

Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.

MidpointRounding

Specifies how mathematical rounding methods should process a number that is midway between two numbers.

Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.

Proper way to handle multiple forms on one page in Django

Django's class based views provide a generic FormView but for all intents and purposes it is designed to only handle one form.

One way to handle multiple forms with same target action url using Django's generic views is to extend the 'TemplateView' as shown below; I use this approach often enough that I have made it into an Eclipse IDE template.

class NegotiationGroupMultifacetedView(TemplateView):
    ### TemplateResponseMixin
    template_name = 'offers/offer_detail.html'

    ### ContextMixin 
    def get_context_data(self, **kwargs):
        """ Adds extra content to our template """
        context = super(NegotiationGroupDetailView, self).get_context_data(**kwargs)

        ...

        context['negotiation_bid_form'] = NegotiationBidForm(
            prefix='NegotiationBidForm', 
            ...
            # Multiple 'submit' button paths should be handled in form's .save()/clean()
            data = self.request.POST if bool(set(['NegotiationBidForm-submit-counter-bid',
                                              'NegotiationBidForm-submit-approve-bid',
                                              'NegotiationBidForm-submit-decline-further-bids']).intersection(
                                                    self.request.POST)) else None,
            )
        context['offer_attachment_form'] = NegotiationAttachmentForm(
            prefix='NegotiationAttachment', 
            ...
            data = self.request.POST if 'NegotiationAttachment-submit' in self.request.POST else None,
            files = self.request.FILES if 'NegotiationAttachment-submit' in self.request.POST else None
            )
        context['offer_contact_form'] = NegotiationContactForm()
        return context

    ### NegotiationGroupDetailView 
    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        if context['negotiation_bid_form'].is_valid():
            instance = context['negotiation_bid_form'].save()
            messages.success(request, 'Your offer bid #{0} has been submitted.'.format(instance.pk))
        elif context['offer_attachment_form'].is_valid():
            instance = context['offer_attachment_form'].save()
            messages.success(request, 'Your offer attachment #{0} has been submitted.'.format(instance.pk))
                # advise of any errors

        else 
            messages.error('Error(s) encountered during form processing, please review below and re-submit')

        return self.render_to_response(context)

The html template is to the following effect:

...

<form id='offer_negotiation_form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
    {% csrf_token %}
    {{ negotiation_bid_form.as_p }}
    ...
    <input type="submit" name="{{ negotiation_bid_form.prefix }}-submit-counter-bid" 
    title="Submit a counter bid"
    value="Counter Bid" />
</form>

...

<form id='offer-attachment-form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
    {% csrf_token %}
    {{ offer_attachment_form.as_p }}

    <input name="{{ offer_attachment_form.prefix }}-submit" type="submit" value="Submit" />
</form>

...

System.loadLibrary(...) couldn't find native library in my case

Try to call your library after include PREBUILT_SHARED_LIBRARY section:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := <PATH>/libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)

#...

LOCAL_SHARED_LIBRARIES += libcalculate

Update:

If you will use this library in Java you need compile it as shared library

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := <PATH>/libcalculate.so
include $(BUILD_SHARED_LIBRARY)

And you need deploy the library in the /vendor/lib directory.

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

How to concatenate two numbers in javascript?

// enter code here
var a = 9821099923;
var b = 91;
alert ("" + b + a); 
// after concating , result is 919821099923 but its is now converted into string  

console.log(Number.isInteger("" + b + a))  // false

// you have to do something like this

var c= parseInt("" + b + a)
console.log(c); // 919821099923
console.log(Number.isInteger(c)) // true

CSS: Hover one element, effect for multiple elements?

I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:

<html>
<head>
<style>
  div.both:hover .image { border: 1px solid blue }
  div.both:hover .layer { border: 1px solid blue }
</style>
</head>

<body>
<div class="section">

<div class="both">
  <div class="image"><img src="myImage.jpg" /></div>
  <div class="layer">Lorem Ipsum</div>
</div>

</div>
</body>
</html>

How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

Custom header to HttpClient request

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

How to do a recursive find/replace of a string with awk or sed?

For replace all occurrences in a git repository you can use:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

See List files in local git repo? for other options to list all files in a repository. The -z options tells git to separate the file names with a zero byte, which assures that xargs (with the option -0) can separate filenames, even if they contain spaces or whatnot.

Shell script - remove first and last quote (") from a variable

There is another way to do it. Like:

echo ${opt:1:-1}

How do you create a Marker with a custom icon for google maps API v3?

Symbol You Want on Color You Want!

I was looking for this answer for days and here it is the right and easy way to create a custom marker:

'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=xxx%7c5680FC%7c000000&.png' where xxx is the text and 5680fc is the hexadecimal color code of the background and 000000 is the hexadecimal color code of the text.

Theses markers are totally dynamic and you can create whatever balloon icon you want. Just change the URL.

How to resolve ambiguous column names when retrieving results?

When using PDO for a database interacttion, one can use the PDO::FETCH_NAMED fetch mode that could help to resolve the issue:

$sql = "SELECT * FROM news JOIN users ON news.user = user.id";
$data = $pdo->query($sql)->fetchAll(PDO::FETCH_NAMED);
foreach ($data as $row) {
    echo $row['column-name'][0]; // from the news table
    echo $row['column-name'][1]; // from the users table
    echo $row['other-column']; // any unique column name
}

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

For me it was a case sensitivity issue. My local branch was Version_feature2 instead of Version_Feature2. I re-checked out my branch using the correct casing and then git pull worked.

String Concatenation in EL

With EL 2 you can do the following:

#{'this'.concat(' is').concat(' a').concat(' test!')}

Python - Extracting and Saving Video Frames

Following script will extract frames every half a second of all videos in folder. (Works on python 3.7)

import cv2
import os
listing = os.listdir(r'D:/Images/AllVideos')
count=1
for vid in listing:
    vid = r"D:/Images/AllVideos/"+vid
    vidcap = cv2.VideoCapture(vid)
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("D:/Images/Frames/image"+str(count)+".jpg", image) # Save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 # Change this number to 1 for each 1 second
    
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)

Returning IEnumerable<T> vs. IQueryable<T>

In general you want to preserve the original static type of the query until it matters.

For this reason, you can define your variable as 'var' instead of either IQueryable<> or IEnumerable<> and you will know that you are not changing the type.

If you start out with an IQueryable<>, you typically want to keep it as an IQueryable<> until there is some compelling reason to change it. The reason for this is that you want to give the query processor as much information as possible. For example, if you're only going to use 10 results (you've called Take(10)) then you want SQL Server to know about that so that it can optimize its query plans and send you only the data you'll use.

A compelling reason to change the type from IQueryable<> to IEnumerable<> might be that you are calling some extension function that the implementation of IQueryable<> in your particular object either cannot handle or handles inefficiently. In that case, you might wish to convert the type to IEnumerable<> (by assigning to a variable of type IEnumerable<> or by using the AsEnumerable extension method for example) so that the extension functions you call end up being the ones in the Enumerable class instead of the Queryable class.

C++ convert string to hexadecimal and vice versa

Using lookup tables and the like works, but is just overkill, here are some very simple ways of taking a string to hex and hex back to a string:

#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdint>

std::string string_to_hex(const std::string& in) {
    std::stringstream ss;

    ss << std::hex << std::setfill('0');
    for (size_t i = 0; in.length() > i; ++i) {
        ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i]));
    }

    return ss.str(); 
}

std::string hex_to_string(const std::string& in) {
    std::string output;

    if ((in.length() % 2) != 0) {
        throw std::runtime_error("String is not valid length ...");
    }

    size_t cnt = in.length() / 2;

    for (size_t i = 0; cnt > i; ++i) {
        uint32_t s = 0;
        std::stringstream ss;
        ss << std::hex << in.substr(i * 2, 2);
        ss >> s;

        output.push_back(static_cast<unsigned char>(s));
    }

    return output;
}

Android Studio AVD - Emulator: Process finished with exit code 1

This works to me:

click in Sdk manager in SDK Tools and: enter image description here

Unistal and install the Android Emulator: enter image description here

Hope to help!

What are best practices that you use when writing Objective-C and Cocoa?

Some of these have already been mentioned, but here's what I can think of off the top of my head:

  • Follow KVO naming rules. Even if you don't use KVO now, in my experience often times it's still beneficial in the future. And if you are using KVO or bindings, you need to know things are going work the way they are supposed to. This covers not just accessor methods and instance variables, but to-many relationships, validation, auto-notifying dependent keys, and so on.
  • Put private methods in a category. Not just the interface, but the implementation as well. It's good to have some distance conceptually between private and non-private methods. I include everything in my .m file.
  • Put background thread methods in a category. Same as above. I've found it's good to keep a clear conceptual barrier when you're thinking about what's on the main thread and what's not.
  • Use #pragma mark [section]. Usually I group by my own methods, each subclass's overrides, and any information or formal protocols. This makes it a lot easier to jump to exactly what I'm looking for. On the same topic, group similar methods (like a table view's delegate methods) together, don't just stick them anywhere.
  • Prefix private methods & ivars with _. I like the way it looks, and I'm less likely to use an ivar when I mean a property by accident.
  • Don't use mutator methods / properties in init & dealloc. I've never had anything bad happen because of it, but I can see the logic if you change the method to do something that depends on the state of your object.
  • Put IBOutlets in properties. I actually just read this one here, but I'm going to start doing it. Regardless of any memory benefits, it seems better stylistically (at least to me).
  • Avoid writing code you don't absolutely need. This really covers a lot of things, like making ivars when a #define will do, or caching an array instead of sorting it each time the data is needed. There's a lot I could say about this, but the bottom line is don't write code until you need it, or the profiler tells you to. It makes things a lot easier to maintain in the long run.
  • Finish what you start. Having a lot of half-finished, buggy code is the fastest way to kill a project dead. If you need a stub method that's fine, just indicate it by putting NSLog( @"stub" ) inside, or however you want to keep track of things.