Programs & Examples On #Qpid

Apache Qpid™ is a cross-platform enterprise messaging system which implements the Advanced Message Queuing Protocol (AMQP), providing message brokers written in C++ and Java, along with clients for C++, Java JMS, .NET, Python, and Ruby.

Remove tracking branches no longer on remote

This is gonna delete all the remote branches that are not present locally (in ruby):

bs = `git branch`.split; bs2 = `git branch -r | grep origin`.split.reject { |b| bs.include?(b.split('/')[1..-1].join('/')) }; bs2.each { |b| puts `git  push origin --delete #{b.split('/')[1..-1].join('/')}` }

Explained:

# local branches
bs = `git branch`.split
# remote branches
bs2 = `git branch -r | grep origin`.split
# reject the branches that are present locally (removes origin/ in front)
bs2.reject! { |b| bs.include?(b.split('/')[1..-1].join('/')) }
# deletes the branches (removes origin/ in front)
bs2.each { |b| puts `git  push origin --delete #{b.split('/')[1..-1].join('/')}` }

MySQL Insert into multiple tables? (Database normalization?)

fairly simple if you use stored procedures:

call insert_user_and_profile('f00','http://www.f00.com');

full script:

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null
)
engine=innodb;

drop table if exists user_profile;
create table user_profile
(
profile_id int unsigned not null auto_increment primary key,
user_id int unsigned not null,
homepage varchar(255) not null,
key (user_id)
)
engine=innodb;

drop procedure if exists insert_user_and_profile;

delimiter #

create procedure insert_user_and_profile
(
in p_username varchar(32),
in p_homepage varchar(255)
)
begin
declare v_user_id int unsigned default 0;

insert into users (username) values (p_username);
set v_user_id = last_insert_id(); -- save the newly created user_id

insert into user_profile (user_id, homepage) values (v_user_id, p_homepage);

end#

delimiter ;

call insert_user_and_profile('f00','http://www.f00.com');

select * from users;
select * from user_profile;

How can I convert string date to NSDate?

This work for me..

    import Foundation
    import UIKit

    //dateString = "01/07/2017"
    private func parseDate(_ dateStr: String) -> String {
            let simpleDateFormat = DateFormatter()
            simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
            let dateFormat = DateFormatter()
            dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return

            let date = simpleDateFormat.date(from: dateStr)
            return dateFormat.string(from: date!)
    }

ConcurrentModificationException for ArrayList

there should has a concurrent implemention of List interface supporting such operation.

try java.util.concurrent.CopyOnWriteArrayList.class

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

HTML: How to make a submit button with text + image in it?

I have found a very easy solution! If you have a form and you want to have a custom submit button you can use some code like this:

<button type="submit">
    <img src="login.png" onmouseover="this.src='login2.png';" onmouseout="this.src='login.png';" />
</button>

Or just direct it to a link of a page.

Best Practice for Forcing Garbage Collection in C#

However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...

IMHO, this is similar to saying "If you can prove that your program will never have any bugs in the future, then go ahead..."

In all seriousness, forcing the GC is useful for debugging/testing purposes. If you feel like you need to do it at any other times, then either you are mistaken, or your program has been built wrong. Either way, the solution is not forcing the GC...

Strip out HTML and Special Characters

All the other solutions are creepy because they are from someone that arrogantly simply thinks that English is the only language in the world :)

All those solutions strip also diacritics like ç or à.

The perfect solution, as stated in PHP documentation, is simply:

$clear = strip_tags($des);

TypeScript Objects as Dictionary types as in C#

In addition to using an map-like object, there has been an actual Map object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:

let people = new Map<string, Person>();

It supports the same functionality as Object, and more, with a slightly different syntax:

// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });

// Checking for the presence of a key:
people.has("John"); // true

// Retrieving a value by a key:
people.get("John").lastName; // "Doe"

// Deleting an item by a key:
people.delete("John");

This alone has several advantages over using a map-like object, such as:

  • Support for non-string based keys, e.g. numbers or objects, neither of which are supported by Object (no, Object does not support numbers, it converts them to strings)
  • Less room for errors when not using --noImplicitAny, as a Map always has a key type and a value type, whereas an object might not have an index-signature
  • The functionality of adding/removing items (key-value pairs) is optimized for the task, unlike creating properties on an Object

Additionally, a Map object provides a more powerful and elegant API for common tasks, most of which are not available through simple Objects without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):

// Iterate over Map entries:
people.forEach((person, key) => ...);

// Clear the Map:
people.clear();

// Get Map size:
people.size;

// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());

// Extract values into array (in insertion order):
let values = Array.from(people.values());

Using %s in C correctly - very basic level

%s will get all the values until it gets NULL i.e. '\0'.

char str1[] = "This is the end\0";
printf("%s",str1);

will give

This is the end

char str2[] = "this is\0 the end\0";
printf("%s",str2);

will give

this is

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

How to get thread id of a pthread in linux c program?

pthread_getthreadid_np wasn't on my Mac os x. pthread_t is an opaque type. Don't beat your head over it. Just assign it to void* and call it good. If you need to printf use %p.

How to center a window on the screen in Tkinter?

Use:

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Centered!')

    w = 800
    h = 650

    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)

    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

    root.mainloop()

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

Concatenate two JSON objects

Just try this, using underscore

var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
  resultArray.push(_.extend(obj,  json2[index]));
});

console.log("Result Array", resultArray);

Result

fs.writeFile in a promise, asynchronous-synchronous stuff

Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

return new Promise(function(resolve, reject) {
    fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
        if (err) reject(err);
        else resolve(data);
    });
});

So in your code you would use it like so right after your call to .then():

 .then(function(results) {
    return new Promise(function(resolve, reject) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
               if (err) reject(err);
               else resolve(data);
            });
    });
  }).then(function(results) {
       console.log("results here: " + results)
  }).catch(function(err) {
       console.log("error here: " + err);
  });

How to get the indexpath.row when an element is activated?

In Swift 4 , just use this:

func buttonTapped(_ sender: UIButton) {
        let buttonPostion = sender.convert(sender.bounds.origin, to: tableView)

        if let indexPath = tableView.indexPathForRow(at: buttonPostion) {
            let rowIndex =  indexPath.row
        }
}

Rails migration for change column

I think this should work.

change_column :table_name, :column_name, :date

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

Compiling/Executing a C# Source File in Command Prompt

You can build your class files within the VS Command prompt (so that all required environment variables are loaded), not the default Windows command window.

To know more about command line building with csc.exe (the compiler), see this article.

Determine function name from within that function (without using traceback)

import sys

def func_name():
    """
    :return: name of caller
    """
    return sys._getframe(1).f_code.co_name

class A(object):
    def __init__(self):
        pass
    def test_class_func_name(self):
        print(func_name())

def test_func_name():
    print(func_name())

Test:

a = A()
a.test_class_func_name()
test_func_name()

Output:

test_class_func_name
test_func_name

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

GDB: Listing all mapped memory regions for a crashed process

The problem with maintenance info sections is that command tries to extract information from the section header of the binary. It does not work if the binary is tripped (e.g by sstrip) or it gives wrong information when the loader may change the memory permission after loading (e.g. the case of RELRO).

Reading a plain text file in Java

I had to benchmark the different ways. I shall comment on my findings but, in short, the fastest way is to use a plain old BufferedInputStream over a FileInputStream. If many files must be read then three threads will reduce the total execution time to roughly half, but adding more threads will progressively degrade performance until making it take three times longer to complete with twenty threads than with just one thread.

The assumption is that you must read a file and do something meaningful with its contents. In the examples here is reading lines from a log and count the ones which contain values that exceed a certain threshold. So I am assuming that the one-liner Java 8 Files.lines(Paths.get("/path/to/file.txt")).map(line -> line.split(";")) is not an option.

I tested on Java 1.8, Windows 7 and both SSD and HDD drives.

I wrote six different implementations:

rawParse: Use BufferedInputStream over a FileInputStream and then cut lines reading byte by byte. This outperformed any other single-thread approach, but it may be very inconvenient for non-ASCII files.

lineReaderParse: Use a BufferedReader over a FileReader, read line by line, split lines by calling String.split(). This is approximatedly 20% slower that rawParse.

lineReaderParseParallel: This is the same as lineReaderParse, but it uses several threads. This is the fastest option overall in all cases.

nioFilesParse: Use java.nio.files.Files.lines()

nioAsyncParse: Use an AsynchronousFileChannel with a completion handler and a thread pool.

nioMemoryMappedParse: Use a memory-mapped file. This is really a bad idea yielding execution times at least three times longer than any other implementation.

These are the average times for reading 204 files of 4 MB each on an quad-core i7 and SSD drive. The files are generated on the fly to avoid disk caching.

rawParse                11.10 sec
lineReaderParse         13.86 sec
lineReaderParseParallel  6.00 sec
nioFilesParse           13.52 sec
nioAsyncParse           16.06 sec
nioMemoryMappedParse    37.68 sec

I found a difference smaller than I expected between running on an SSD or an HDD drive being the SSD approximately 15% faster. This may be because the files are generated on an unfragmented HDD and they are read sequentially, therefore the spinning drive can perform nearly as an SSD.

I was surprised by the low performance of the nioAsyncParse implementation. Either I have implemented something in the wrong way or the multi-thread implementation using NIO and a completion handler performs the same (or even worse) than a single-thread implementation with the java.io API. Moreover the asynchronous parse with a CompletionHandler is much longer in lines of code and tricky to implement correctly than a straight implementation on old streams.

Now the six implementations followed by a class containing them all plus a parametrizable main() method that allows to play with the number of files, file size and concurrency degree. Note that the size of the files varies plus minus 20%. This is to avoid any effect due to all the files being of exactly the same size.

rawParse

public void rawParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    overrunCount = 0;
    final int dl = (int) ';';
    StringBuffer lineBuffer = new StringBuffer(1024);
    for (int f=0; f<numberOfFiles; f++) {
        File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        FileInputStream fin = new FileInputStream(fl);
        BufferedInputStream bin = new BufferedInputStream(fin);
        int character;
        while((character=bin.read())!=-1) {
            if (character==dl) {

                // Here is where something is done with each line
                doSomethingWithRawLine(lineBuffer.toString());
                lineBuffer.setLength(0);
            }
            else {
                lineBuffer.append((char) character);
            }
        }
        bin.close();
        fin.close();
    }
}

public final void doSomethingWithRawLine(String line) throws ParseException {
    // What to do for each line
    int fieldNumber = 0;
    final int len = line.length();
    StringBuffer fieldBuffer = new StringBuffer(256);
    for (int charPos=0; charPos<len; charPos++) {
        char c = line.charAt(charPos);
        if (c==DL0) {
            String fieldValue = fieldBuffer.toString();
            if (fieldValue.length()>0) {
                switch (fieldNumber) {
                    case 0:
                        Date dt = fmt.parse(fieldValue);
                        fieldNumber++;
                        break;
                    case 1:
                        double d = Double.parseDouble(fieldValue);
                        fieldNumber++;
                        break;
                    case 2:
                        int t = Integer.parseInt(fieldValue);
                        fieldNumber++;
                        break;
                    case 3:
                        if (fieldValue.equals("overrun"))
                            overrunCount++;
                        break;
                }
            }
            fieldBuffer.setLength(0);
        }
        else {
            fieldBuffer.append(c);
        }
    }
}

lineReaderParse

public void lineReaderParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    String line;
    for (int f=0; f<numberOfFiles; f++) {
        File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        FileReader frd = new FileReader(fl);
        BufferedReader brd = new BufferedReader(frd);

        while ((line=brd.readLine())!=null)
            doSomethingWithLine(line);
        brd.close();
        frd.close();
    }
}

public final void doSomethingWithLine(String line) throws ParseException {
    // Example of what to do for each line
    String[] fields = line.split(";");
    Date dt = fmt.parse(fields[0]);
    double d = Double.parseDouble(fields[1]);
    int t = Integer.parseInt(fields[2]);
    if (fields[3].equals("overrun"))
        overrunCount++;
}

lineReaderParseParallel

public void lineReaderParseParallel(final String targetDir, final int numberOfFiles, final int degreeOfParalelism) throws IOException, ParseException, InterruptedException {
    Thread[] pool = new Thread[degreeOfParalelism];
    int batchSize = numberOfFiles / degreeOfParalelism;
    for (int b=0; b<degreeOfParalelism; b++) {
        pool[b] = new LineReaderParseThread(targetDir, b*batchSize, b*batchSize+b*batchSize);
        pool[b].start();
    }
    for (int b=0; b<degreeOfParalelism; b++)
        pool[b].join();
}

class LineReaderParseThread extends Thread {

    private String targetDir;
    private int fileFrom;
    private int fileTo;
    private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int overrunCounter = 0;

    public LineReaderParseThread(String targetDir, int fileFrom, int fileTo) {
        this.targetDir = targetDir;
        this.fileFrom = fileFrom;
        this.fileTo = fileTo;
    }

    private void doSomethingWithTheLine(String line) throws ParseException {
        String[] fields = line.split(DL);
        Date dt = fmt.parse(fields[0]);
        double d = Double.parseDouble(fields[1]);
        int t = Integer.parseInt(fields[2]);
        if (fields[3].equals("overrun"))
            overrunCounter++;
    }

    @Override
    public void run() {
        String line;
        for (int f=fileFrom; f<fileTo; f++) {
            File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
            try {
            FileReader frd = new FileReader(fl);
            BufferedReader brd = new BufferedReader(frd);
            while ((line=brd.readLine())!=null) {
                doSomethingWithTheLine(line);
            }
            brd.close();
            frd.close();
            } catch (IOException | ParseException ioe) { }
        }
    }
}

nioFilesParse

public void nioFilesParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
    for (int f=0; f<numberOfFiles; f++) {
        Path ph = Paths.get(targetDir+filenamePreffix+String.valueOf(f)+".txt");
        Consumer<String> action = new LineConsumer();
        Stream<String> lines = Files.lines(ph);
        lines.forEach(action);
        lines.close();
    }
}


class LineConsumer implements Consumer<String> {

    @Override
    public void accept(String line) {

        // What to do for each line
        String[] fields = line.split(DL);
        if (fields.length>1) {
            try {
                Date dt = fmt.parse(fields[0]);
            }
            catch (ParseException e) {
            }
            double d = Double.parseDouble(fields[1]);
            int t = Integer.parseInt(fields[2]);
            if (fields[3].equals("overrun"))
                overrunCount++;
        }
    }
}

nioAsyncParse

public void nioAsyncParse(final String targetDir, final int numberOfFiles, final int numberOfThreads, final int bufferSize) throws IOException, ParseException, InterruptedException {
    ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(numberOfThreads);
    ConcurrentLinkedQueue<ByteBuffer> byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();

    for (int b=0; b<numberOfThreads; b++)
        byteBuffers.add(ByteBuffer.allocate(bufferSize));

    for (int f=0; f<numberOfFiles; f++) {
        consumerThreads.acquire();
        String fileName = targetDir+filenamePreffix+String.valueOf(f)+".txt";
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(fileName), EnumSet.of(StandardOpenOption.READ), pool);
        BufferConsumer consumer = new BufferConsumer(byteBuffers, fileName, bufferSize);
        channel.read(consumer.buffer(), 0l, channel, consumer);
    }
    consumerThreads.acquire(numberOfThreads);
}


class BufferConsumer implements CompletionHandler<Integer, AsynchronousFileChannel> {

        private ConcurrentLinkedQueue<ByteBuffer> buffers;
        private ByteBuffer bytes;
        private String file;
        private StringBuffer chars;
        private int limit;
        private long position;
        private DateFormat frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public BufferConsumer(ConcurrentLinkedQueue<ByteBuffer> byteBuffers, String fileName, int bufferSize) {
            buffers = byteBuffers;
            bytes = buffers.poll();
            if (bytes==null)
                bytes = ByteBuffer.allocate(bufferSize);

            file = fileName;
            chars = new StringBuffer(bufferSize);
            frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            limit = bufferSize;
            position = 0l;
        }

        public ByteBuffer buffer() {
            return bytes;
        }

        @Override
        public synchronized void completed(Integer result, AsynchronousFileChannel channel) {

            if (result!=-1) {
                bytes.flip();
                final int len = bytes.limit();
                int i = 0;
                try {
                    for (i = 0; i < len; i++) {
                        byte by = bytes.get();
                        if (by=='\n') {
                            // ***
                            // The code used to process the line goes here
                            chars.setLength(0);
                        }
                        else {
                                chars.append((char) by);
                        }
                    }
                }
                catch (Exception x) {
                    System.out.println(
                        "Caught exception " + x.getClass().getName() + " " + x.getMessage() +
                        " i=" + String.valueOf(i) + ", limit=" + String.valueOf(len) +
                        ", position="+String.valueOf(position));
                }

                if (len==limit) {
                    bytes.clear();
                    position += len;
                    channel.read(bytes, position, channel, this);
                }
                else {
                    try {
                        channel.close();
                    }
                    catch (IOException e) {
                    }
                    consumerThreads.release();
                    bytes.clear();
                    buffers.add(bytes);
                }
            }
            else {
                try {
                    channel.close();
                }
                catch (IOException e) {
                }
                consumerThreads.release();
                bytes.clear();
                buffers.add(bytes);
            }
        }

        @Override
        public void failed(Throwable e, AsynchronousFileChannel channel) {
        }
};

FULL RUNNABLE IMPLEMENTATION OF ALL CASES

https://github.com/sergiomt/javaiobenchmark/blob/master/FileReadBenchmark.java

IntelliJ shortcut to show a popup of methods in a class that can be searched

Do Cmd+F12+Fn Key on mac in IntelliJ if clicking Cmd+F12 starts.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

What is the default initialization of an array in Java?

Java says that the default length of a JAVA array at the time of initialization will be 10.

private static final int DEFAULT_CAPACITY = 10;

But the size() method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.

private int size;

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}

XCOPY switch to create specified directory if it doesn't exist?

Simple short answer is this:

xcopy /Y /I "$(SolutionDir)<my-src-path>" "$(SolutionDir)<my-dst-path>\"

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

background: fixed no repeat not working on mobile

This is what i do and it works everythere :)

.container {
  background: url(${myImage})
  background-attachment: fixed;
  background-size: cover;
 transform: scale(1.1, 1.1);

}

then...

@media only screen and (max-width: 768px){
   background-size: 100% 100vh;
}

How to ignore the first line of data when processing CSV data?

The documentation for the Python 3 CSV module provides this example:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

The Sniffer will try to auto-detect many things about the CSV file. You need to explicitly call its has_header() method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:

if sniffer.has_header():
    for header_row in reader:
        break
for data_row in reader:
    # do something with the row

How can I make a horizontal ListView in Android?

Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.

I don't understand -Wl,-rpath -Wl,

The -Wl,xxx option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So

gcc -Wl,aaa,bbb,ccc

eventually becomes a linker call

ld aaa bbb ccc

In your case, you want to say "ld -rpath .", so you pass this to gcc as -Wl,-rpath,. Alternatively, you can specify repeat instances of -Wl:

gcc -Wl,aaa -Wl,bbb -Wl,ccc

Note that there is no comma between aaa and the second -Wl.

Or, in your case, -Wl,-rpath -Wl,..

Grep only the first match and stop

You can pipe grep result to head in conjunction with stdbuf.

Note, that in order to ensure stopping after Nth match, you need to using stdbuf to make sure grep don't buffer its output:

stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1

As soon as head consumes 1 line, it terminated and grep will receive SIGPIPE because it still output something to pipe while head was gone.

This assumed that no file names contain newline.

How to print a percentage value in python?

Then you'd want to do this instead:

print str(int(1.0/3.0*100))+'%'

The .0 denotes them as floats and int() rounds them to integers afterwards again.

Best way to define error codes/strings in Java?

I (and the rest of our team in my company) prefer to raise exceptions instead of returning error codes. Error codes have to be checked everywhere, passed around, and tend to make the code unreadable when the amount of code becomes bigger.

The error class would then define the message.

PS: and actually also care for internationalization !
PPS: you could also redefine the raise-method and add logging, filtering etc. if required (at leastin environments, where the Exception classes and friends are extendable/changeable)

Convert a CERT/PEM certificate to a PFX certificate

Here is how to do this on Windows without third-party tools:

  1. Import certificate to the certificate store. In Windows Explorer select "Install Certificate" in context menu. enter image description here Follow the wizard and accept default options "Local User" and "Automatically".

  2. Find your certificate in certificate store. On Windows 10 run the "Manage User Certificates" MMC. On Windows 2013 the MMC is called "Certificates". On Windows 10 by default your certificate should be under "Personal"->"Certificates" node.

  3. Export Certificate. In context menu select "Export..." menu: enter image description here

    Select "Yes, export the private key": enter image description here

    You will see that .PFX option is enabled in this case: enter image description here

    Specify password for private key.

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

How to add more than one machine to the trusted hosts list using winrm

The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:

PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current

geom_smooth() what are the methods available?

The method argument specifies the parameter of the smooth statistic. You can see stat_smooth for the list of all possible arguments to the method argument.

CSS Circular Cropping of Rectangle Image

Try this:

img {
    height: auto;
    width: 100%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
}

DEMO here.

OR:

.rounded {
    height: 100px;
    width: 100px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
    background:url("http://www.electricvelocity.com.au/Upload/Blogs/smart-e-bike-side_2.jpg") center no-repeat;
    background-size:cover;
}

DEMO here.

Node.js getaddrinfo ENOTFOUND

I got rid of http and extra slash(/). I just used this 'node-test.herokuapp.com' and it worked.

Round to at most 2 decimal places (only if necessary)

You can use

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57

Oracle Age calculation from Date of birth and Today

Age (full years) of the Person:

SELECT
  TRUNC(months_between(sysdate, per.DATE_OF_BIRTH) / 12) AS "Age"
FROM PD_PERSONS per

PYTHONPATH vs. sys.path

Neither hacking PYTHONPATH nor sys.path is a good idea due to the before mentioned reasons. And for linking the current project into the site-packages folder there is actually a better way than python setup.py develop, as explained here:

pip install --editable path/to/project

If you don't already have a setup.py in your project's root folder, this one is good enough to start with:

from setuptools import setup
setup('project')

How to query SOLR for empty fields?

Try this:

?q=-id:["" TO *]

Java: Find .txt files in specified folder

Here is my platform specific code(unix)

public static List<File> findFiles(String dir, String... names)
    {
        LinkedList<String> command = new LinkedList<String>();
        command.add("/usr/bin/find");
        command.add(dir);
        List<File> result = new LinkedList<File>();
        if (names.length > 1)
            {
                List<String> newNames = new LinkedList<String>(Arrays.asList(names));
                String first = newNames.remove(0);
                command.add("-name");
                command.add(first);
                for (String newName : newNames)
                    {
                        command.add("-or");
                        command.add("-name");
                        command.add(newName);
                    }
            }
        else if (names.length > 0)
            {
                command.add("-name");
                command.add(names[0]);
            }
        try
            {
                ProcessBuilder pb = new ProcessBuilder(command);
                Process p = pb.start();
                p.waitFor();
                InputStream is = p.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null)
                    {
                        // System.err.println(line);
                        result.add(new File(line));
                    }
                p.destroy();
            }
        catch (Exception e)
            {
                e.printStackTrace();
            }
        return result;
    }

What is the correct syntax of ng-include?

    <ng-include src="'views/sidepanel.html'"></ng-include>

OR

    <div ng-include="'views/sidepanel.html'"></div>

OR

    <div ng-include src="'views/sidepanel.html'"></div>

Points To Remember:

--> No spaces in src

--> Remember to use single quotation in double quotation for src

Printing HashMap In Java

Worth mentioning Java 8 approach, using BiConsumer and lambda functions:

BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) -> 
           System.out.println(o1 + ", " + o2);

example.forEach(consumer);

Assuming that you've overridden toString method of the two types if needed.

check / uncheck checkbox using jquery?

You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {
   prop=true; 
}
$('#checkbox').prop('checked',prop);

or simply,

$('#checkbox').prop('checked',(value == 1));

Snippet

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
_x000D_
_x000D_

How to get current user, and how to use User class in MVC5?

if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution

 ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);

you will also need the following:

using Microsoft.AspNet.Identity;

and

using Microsoft.AspNet.Identity.Owin;

Split array into two parts without for loop in java

Splits an array in multiple arrays with a fixed maximum size.

public static <T extends Object> List<T[]> splitArray(T[] array, int max){

  int x = array.length / max;
  int r = (array.length % max); // remainder

  int lower = 0;
  int upper = 0;

  List<T[]> list = new ArrayList<T[]>();

  int i=0;

  for(i=0; i<x; i++){

    upper += max;

    list.add(Arrays.copyOfRange(array, lower, upper));

    lower = upper;
  }

  if(r > 0){

    list.add(Arrays.copyOfRange(array, lower, (lower + r)));

  }

  return list;
}

Example - an Array of 11 shall be splitted into multiple Arrays not exceeding a size of 5:

// create and populate an array
Integer[] arr = new Integer[11];

for(int i=0; i<arr.length; i++){
  arr[i] = i;
}

// split into pieces with a max. size of 5
List<Integer[]> list = ArrayUtil.splitArray(arr, 5);

// check
for(int i=0; i<list.size(); i++){

  System.out.println("Array " + i);

  for(int j=0; j<list.get(i).length; j++){
    System.out.println("  " + list.get(i)[j]);
  }
}

Output:

Array 0
  0
  1
  2
  3
  4
Array 1
  5
  6
  7
  8
  9
Array 2
  10

are there dictionaries in javascript like python?

Have created a simple dictionary in JS here:

function JSdict() {
    this.Keys = [];
    this.Values = [];
}

// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
    JSdict.prototype.getVal = function (key) {
        if (key == null) {
            return "Key cannot be null";
        }
        for (var i = 0; i < this.Keys.length; i++) {
            if (this.Keys[i] == key) {
                return this.Values[i];
            }
        }
        return "Key not found!";
    }
}


// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
    JSdict.prototype.update = function (key, val) {
        if (key == null || val == null) {
            return "Key or Value cannot be null";
        }
        // Verify dict integrity before each operation
        if (keysLength != valsLength) {
            return "Dictionary inconsistent. Keys length don't match values!";
        }
        var keysLength = this.Keys.length;
        var valsLength = this.Values.length;
        var flag = false;
        for (var i = 0; i < keysLength; i++) {
            if (this.Keys[i] == key) {
                this.Values[i] = val;
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "Key does not exist";
        }
    }
}



// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
    JSdict.prototype.add = function (key, val) {
        // Allow only strings or numbers as keys
        if (typeof (key) == "number" || typeof (key) == "string") {
            if (key == null || val == null) {
                return "Key or Value cannot be null";
            }
            if (keysLength != valsLength) {
                return "Dictionary inconsistent. Keys length don't match values!";
            }
            var keysLength = this.Keys.length;
            var valsLength = this.Values.length;
            for (var i = 0; i < keysLength; i++) {
                if (this.Keys[i] == key) {
                    return "Duplicate keys not allowed!";
                }
            }
            this.Keys.push(key);
            this.Values.push(val);
        }
        else {
            return "Only number or string can be key!";
        }
    }
}

// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
    JSdict.prototype.remove = function (key) {
        if (key == null) {
            return "Key cannot be null";
        }
        if (keysLength != valsLength) {
            return "Dictionary inconsistent. Keys length don't match values!";
        }
        var keysLength = this.Keys.length;
        var valsLength = this.Values.length;
        var flag = false;
        for (var i = 0; i < keysLength; i++) {
            if (this.Keys[i] == key) {
                this.Keys.shift(key);
                this.Values.shift(this.Values[i]);
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "Key does not exist";
        }
    }
}

The above implementation can now be used to simulate a dictionary as:

var dict = new JSdict();

dict.add(1, "one")

dict.add(1, "one more")
"Duplicate keys not allowed!"

dict.getVal(1)
"one"

dict.update(1, "onne")

dict.getVal(1)
"onne"

dict.remove(1)

dict.getVal(1)
"Key not found!"

This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.

Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.

Hope this helps!

EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.

However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.

Viz: dict.hasOwnProperty(key) and delete dict[key]

Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array

THanks!

T-SQL to list all the user mappings with database roles/permissions for a Login

Did you sort this? I just found this code here:

http://www.pythian.com/news/29665/httpconsultingblogs-emc-comjamiethomsonarchive20070209sql-server-2005_3a00_-view-all-permissions-_2800_2_2900_-aspx/

I think I'll need to do a bit of tweaking, but essentially this has sorted it for me!

I hope it does for you too!

J

Rails 4 Authenticity Token

Came across the same problem. Fixed it by adding to my controller:

      skip_before_filter :verify_authenticity_token, if: :json_request?

Tomcat Server not starting with in 45 seconds

I know it's a bit late, but I've tried everything above and nothing worked. The real problem was that I'm using hibernate, so it was trying to connect to mysql but was not able, thats why it showed time out.

Just to let u guys know, I'm using RDS(Amazon), so just to make a test I changed to my local mysql and it worked perfectly.

Hope that this answer helps somebody.

Thanks.

"Could not find a part of the path" error message

There's something wrong. You have written:

string source_dir = @"E:\\Debug\\VipBat\\{0}";

and the error was

Could not find a part of the path E\Debug\VCCSBat

This is not the same directory.

In your code there's a problem, you have to use:

string source_dir = @"E:\Debug\VipBat"; // remove {0} and the \\ if using @

or

string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the @ if using \\

Git log out user from command line

Try this on Windows:

cmdkey /delete:LegacyGeneric:target=git:https://github.com

Jersey stopped working with InjectionManagerFactory not found

Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager and InjectionManagerFactory. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2 others are talking about.

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.26</version>
</dependency>

The CDI dependency is

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-cdi2-se</artifactId>
    <version>2.26</version>
</dependency>

This (jersey-cdi2-se) should only be used for SE environments and not EE environments.

Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManagers, though others have made attempts at implementing one for Guice.

Shorter syntax for casting from a List<X> to a List<Y>?

The direct cast var ListOfY = (List<Y>)ListOfX is not possible because it would require co/contravariance of the List<T> type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.

While it seems normal to be able to write code like this:

List<Animal> animals = (List<Animal>) mammalList;

because we can guarantee that every mammal will be an animal, this is obviously a mistake:

List<Mammal> mammals = (List<Mammal>) animalList;

since not every animal is a mammal.

However, using C# 3 and above, you can use

IEnumerable<Animal> animals = mammalList.Cast<Animal>();

that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal in the list to an Animal, and will fail if the cast is not successfull.

If you like more control over the casting / conversion process, you could use the ConvertAll method of the List<T> class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List, instead of IEnumerable, so no .ToList() is necessary.

List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);

IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

What is the purpose of "pip install --user ..."?

Why not just put an executable somewhere in my $PATH

~/.local/bin directory is theoretically expected to be in your $PATH.

According to these people it's a bug not adding it in the $PATH when using systemd.

This answer explains it more extensively.

But even if your distro includes the ~/.local/bin directory to the $PATH, it might be in the following form (inside ~/.profile):

if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi

which would require you to logout and login again, if the directory was not there before.

How to enable file upload on React's Material UI simple input?

You need to wrap your input with component, and add containerElement property with value 'label' ...

<RaisedButton
   containerElement='label' // <-- Just add me!
   label='My Label'>
   <input type="file" />
</RaisedButton>

You can read more about it in this GitHub issue.

EDIT: Update 2019.

Check at the bottom answer from @galki

TLDR;

<input
  accept="image/*"
  className={classes.input}
  style={{ display: 'none' }}
  id="raised-button-file"
  multiple
  type="file"
/>
<label htmlFor="raised-button-file">
  <Button variant="raised" component="span" className={classes.button}>
    Upload
  </Button>
</label> 

How to use FormData in react-native?

I was looking for a long time an answer that solve the problem and this is the way I did it

I take the file with expo-document-picker

const pickDocument = async (tDocument) => {
    let result = await DocumentPicker.getDocumentAsync();
    result.type = mimetype(result.name);
    if (result.type === undefined){
      alert("not allowed extention");
      return null;
    }
    let formDat = new FormData();
    formDat.append("file", result);
    uploadDoc(formDat);
  };

  const mimetype = (name) => {
    let allow =  {"png":"image/png","pdf":"application/json","jpeg":"image/jpeg", "jpg":"image/jpg"};
    let extention = name.split(".")[1];
    if (allow[extention] !== undefined){
      return allow[extention]
    }
    else {
      return undefined
    }
  }

const uploadDoc = (data) =>  {
    fetch("MyApi", {
      method: "POST",
      body: data
    }).then(res => res.json())
    .then(response =>{
      if (response.result === 1) {
        //somecode
      } else {
        //somecode
      }
    });
  }

this is because android doesn't manage the mime-type of your file so if you put away the header "Content-type" and instead you put the mime-type on the file it gonna send the correct header

works on IOS an Android

How can I find the length of a number?

I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.

function Longueur(numberlen)
{
    var length = 0, i; //define `i` with `var` as not to clutter the global scope
    numberlen = parseInt(numberlen);
    for(i = numberlen; i >= 1; i)
    {
        ++length;
        i = Math.floor(i/10);
    }
    return length;
}

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Facebook Android Generate Key Hash

The only thing working for me is using the password android. Why is that not mentioned in any guides out there?

How can I export the schema of a database in PostgreSQL?

set up a new postgresql server and replace its data folder with the files from your external disk.

You will then be able to start that postgresql server up and retrieve the data using pg_dump (pg_dump -s for the schema-only as mentioned)

An implementation of the fast Fourier transform (FFT) in C#

An old question but it still shows up in Google results...

A very un-restrictive MIT Licensed C# / .NET library can be found at,

https://www.codeproject.com/articles/1107480/dsplib-fft-dft-fourier-transform-library-for-net

This library is fast as it parallel threads on multiple cores and is very complete and ready to use.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

How to hash a string into 8 digits?

Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

This means the hash()-based solution suggested, which can be shortened to just:

hash(s) % 10**8

will only return the same value within a given script run:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.

Send private messages to friends

You can use Facebook Chat API to send private messages, here is an example in Ruby using xmpp4r_facebook gem:

sender_chat_id = "-#{sender_uid}@chat.facebook.com"
receiver_chat_id = "-#{receiver_uid}@chat.facebook.com"
message_body = "message body"
message_subject = "message subject"

jabber_message = Jabber::Message.new(receiver_chat_id, message_body)
jabber_message.subject = message_subject

client = Jabber::Client.new(Jabber::JID.new(sender_chat_id))
client.connect
client.auth_sasl(Jabber::SASL::XFacebookPlatform.new(client,
   ENV.fetch('FACEBOOK_APP_ID'), facebook_auth.token,
   ENV.fetch('FACEBOOK_APP_SECRET')), nil)
client.send(jabber_message)
client.close

How do I create a comma-separated list using a SQL query?

MySQL

  SELECT r.name,
         GROUP_CONCAT(a.name SEPARATOR ',')
    FROM RESOURCES r
    JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
    JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name

SQL Server (2005+)

SELECT r.name,
       STUFF((SELECT ','+ a.name
               FROM APPLICATIONS a
               JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
              WHERE ar.resource_id = r.id
           GROUP BY a.name
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
 FROM RESOURCES r

SQL Server (2017+)

  SELECT r.name,
         STRING_AGG(a.name, ',')
    FROM RESOURCES r
    JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
    JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name

Oracle

I recommend reading about string aggregation/concatentation in Oracle.

Hosting a Maven repository on github

Don't use GitHub as a Maven Repository.

Edit: This option gets a lot of down votes, but no comments as to why. This is the correct option regardless of the technical capabilities to actually host on GitHub. Hosting on GitHub is wrong for all the reasons outlined below and without comments I can't improve the answer to clarify your issues.

Best Option - Collaborate with the Original Project

The best option is to convince the original project to include your changes and stick with the original.

Alternative - Maintain your own Fork

Since you have forked an open source library, and your fork is also open source, you can upload your fork to Maven Central (read Guide to uploading artifacts to the Central Repository) by giving it a new groupId and maybe a new artifactId.

Only consider this option if you are willing to maintain this fork until the changes are incorporated into the original project and then you should abandon this one.

Really consider hard whether a fork is the right option. Read the myriad Google results for 'why not to fork'

Reasoning

Bloating your repository with jars increases download size for no benefit

A jar is an output of your project, it can be regenerated at any time from its inputs, and your GitHub repo should contain only inputs.

Don't believe me? Then check Google results for 'dont store binaries in git'.

GitHub's help Working with large files will tell you the same thing. Admittedly jar's aren't large but they are larger than the source code and once a jar has been created by a release they have no reason to be versioned - that is what a new release is for.

Defining multiple repos in your pom.xml slows your build down by Number of Repositories times Number of Artifacts

Stephen Connolly says:

If anyone adds your repo they impact their build performance as they now have another repo to check artifacts against... It's not a big problem if you only have to add one repo... But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog.

That's right! Maven needs to check every artifact (and its dependencies) defined in your pom.xml against every Repository you have defined, as a newer version might be available in any of those repositories.

Try it out for yourself and you will feel the pain of a slow build.

The best place for artifacts is in Maven Central, as its the central place for jars, and this means your build will only ever check one place.

You can read some more about repositories at Maven's documentation on Introduction to Repositories

Updating to latest version of CocoaPods?

Refer this link https://guides.cocoapods.org/using/getting-started.html

brew install cocoapods

brew upgrade cocoapods

brew link cocoapods

enter image description here

enter image description here

How do I replace all the spaces with %20 in C#?

To properly escape spaces as well as the rest of the special characters, use System.Uri.EscapeDataString(string stringToEscape).

Failed to resolve version for org.apache.maven.archetypes

Read carefully about the reason.

"Failed to resolve version for org.apache.maven.archetypes:maven-archetype- webapp:pom:RELEASE: Could not find metadata org.apache.maven.archetypes:maven-archetype- webapp/maven-metadata.xml in local"

So all you need to do is download the maven-metadata.xml to your {HOME}.m2\repository

That's it.

Writing data into CSV file in C#

UPDATE

Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.

CSV is way more complicated than what the question/answer suggests.

Original Answer

As you already have a loop, consider doing it like this:

//before your loop
    var csv = new StringBuilder();

//in your loop
    var first = reader[0].ToString();
    var second = image.ToString();
    //Suggestion made by KyleMit
    var newLine = string.Format("{0},{1}", first, second);
    csv.AppendLine(newLine);  

//after your loop
    File.WriteAllText(filePath, csv.ToString());

Or something to this effect. My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.

You can replace

File.WriteAllText(filePath, csv.ToString());

with

File.AppendAllText(filePath, csv.ToString());

if you want to keep previous versions of csv in the same file

C# 6

If you are using c# 6.0 then you can do the following

var newLine = $"{first},{second}"

EDIT

Here is a link to a question that explains what Environment.NewLine does.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

How to read and write to a text file in C++?

To read you should create an instance of ifsteam and not ofstream.

ifstream iusrfile;

You should open the file in read mode.

iusrfile.open("usrfile.txt", ifstream::in);

Also this statement is not correct.

cout<<iusrfile;

If you are trying to print the data you read from the file you should do:

cout<<usr;

You can read more about ifstream and its API here

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

To get it to work with FullScreen:

Use the ionic keyboard plugin. This allows you to listen for when the keyboard appears and disappears.

OnDeviceReady add these event listeners:

// Allow Screen to Move Up when Keyboard is Present
window.addEventListener('native.keyboardshow', onKeyboardShow);
// Reset Screen after Keyboard hides
window.addEventListener('native.keyboardhide', onKeyboardHide);

The Logic:

function onKeyboardShow(e) {
    // Get Focused Element
    var thisElement = $(':focus');
    // Get input size
    var i = thisElement.height();
    // Get Window Height
    var h = $(window).height()
    // Get Keyboard Height
    var kH = e.keyboardHeight
    // Get Focused Element Top Offset
    var eH = thisElement.offset().top;
    // Top of Input should still be visible (30 = Fixed Header)
    var vS = h - kH;
    i = i > vS ? (vS - 30) : i;
    // Get Difference
    var diff = (vS - eH - i);
    if (diff < 0) {
        var parent = $('.myOuter-xs.myOuter-md');
        // Add Padding
        var marginTop = parseInt(parent.css('marginTop')) + diff - 25;
        parent.css('marginTop', marginTop + 'px');
    }
}

function onKeyboardHide(e) {
  // Remove All Style Attributes from Parent Div
  $('.myOuter-xs.myOuter-md').removeAttr('style');
}

Basically if they difference is minus then that is the amount of pixels that the keyboard is covering of your input. So if you adjust your parent div by this that should counteract it.

Adding timeouts to the logic say 300ms should also optimise performance (as this will allow keyboard time to appear.

Link to the issue number on GitHub within a commit message

Just include #xxx in your commit message to reference an issue without closing it.

With new GitHub issues 2.0 you can use these synonyms to reference an issue and close it (in your commit message):

  • fix #xxx
  • fixes #xxx
  • fixed #xxx
  • close #xxx
  • closes #xxx
  • closed #xxx
  • resolve #xxx
  • resolves #xxx
  • resolved #xxx

You can also substitute #xxx with gh-xxx.

Referencing and closing issues across repos also works:

fixes user/repo#xxx

Check out the documentation available in their Help section.

How to remove border from specific PrimeFaces p:panelGrid?

Try

<p:panelGrid styleClass="ui-noborder">

How to show a GUI message box from a bash script in linux?

If you are using Ubuntu many distros the notify-send command will throw one of those nice perishable notifications in the top right corner. Like so:

notify-send "My name is bash and I rock da house"

B.e.a.utiful!

Vertically align an image inside a div with responsive height

Try

Html

<div class="responsive-container">
     <div class="img-container">
         <IMG HERE>
     </div>
</div>

CSS

.img-container {
    position: absolute;
    top: 0;
    left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}

How to get just the responsive grid from Bootstrap 3?

In Bootstrap 4, there are already separated files in their GitHub. You can find them here

https://github.com/twbs/bootstrap/tree/main/dist/css

How to re import an updated package while in Python Interpreter?

Basically reload as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:

#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
>>> x = mymodule.x
>>> x()
version 1
>>> x is mymodule.x
True


# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
>>> x()
version 1
>>> x is mymodule.x
False

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.

//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events

ComboBox combobox2 = ManagerControl.myComboBox2;
...some events

.

//method in constructor
public static void InitializeDynamicControls()
{
     ComboBox cb = new ComboBox();
     cb.Background = new SolidColorBrush(Colors.Blue);
     ...
     cb.Width = 100;
     cb.Text = "Select window";
        
     ManagerControls.myCombobox1 = cb;
     ManagerControls.myComboBox2 = cb; // <-- error here
}

Solution: create another ComboBox cb2 and assign it to ManagerControls.myComboBox2.

I hope I helped someone.

Conda activate not working?

Just use this command in your cmd:

activate <envname>

Works like charm! (worked for windows, don't know about mac)

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

This might help someone:

I am installing the latest Java on my system for development, and currently it's Java SE 7. Now, let's dive into this "madness", as you put it...

All of these are the same (when developers are talking about Java for development):

  • Java SE 7
  • Java SE v1.7.0
  • Java SE Development Kit 7

Starting with Java v1.5:

  • v5 = v1.5.
  • v6 = v1.6.
  • v7 = v1.7.

And we can assume this will remain for future versions.

Next, for developers, download JDK, not JRE.

JDK will contain JRE. If you need JDK and JRE, get JDK. Both will be installed from the single JDK install, as you will see below.

As someone above mentioned:

  • JDK = Java Development Kit (developers need this, this is you if you code in Java)
  • JRE = Java Runtime Environment (users need this, this is every computer user today)
  • Java SE = Java Standard Edition

Here's the step by step links I followed (one step leads to the next, this is all for a single download) to download Java for development (JDK):

  1. Visit "Java SE Downloads": http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Click "JDK Download" and visit "Java SE Development Kit 7 Downloads": http://www.oracle.com/technetwork/java/javase/downloads/java-se-jdk-7-download-432154.html (note that following the link from step #1 will take you to a different link as JDK 1.7 updates, later versions, are now out)
  3. Accept agreement :)
  4. Click "Java SE Development Kit 7 (Windows x64)": http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-windows-x64.exe (for my 64-bit Windows 7 system)
  5. You are now downloading (hopefully the latest) JDK for your system! :)

Keep in mind the above links are for reference purposes only, to show you the step by step method of what it takes to download the JDK.

And install with default settings to:

  • “C:\Program Files\Java\jdk1.7.0\” (JDK)
  • “C:\Program Files\Java\jre7\” (JRE) <--- why did it ask a new install folder? it's JRE!

Remember from above that JDK contains JRE, which makes sense if you know what they both are. Again, see above.

After your install, double check “C:\Program Files\Java” to see both these folders. Now you know what they are and why they are there.

I know I wrote this for newbies, but I enjoy knowing things in full detail, so I hope this helps.

'int' object has no attribute '__getitem__'

The error:

'int' object has no attribute '__getitem__'

means that you're attempting to apply the index operator [] on an int, not a list. So is col not a list, even when it should be? Let's start from that.

Look here:

col = [[0 for col in range(5)] for row in range(6)]

Use a different variable name inside, looks like the list comprehension overwrites the col variable during iteration. (Not during the iteration when you set col, but during the following ones.)

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

Convert normal Java Array or ArrayList to Json Array in android

ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);

This is only an example using a string arraylist

Swift: print() vs println() vs NSLog()

If you're using Swift 2, now you can only use print() to write something to the output.

Apple has combined both println() and print() functions into one.

Updated to iOS 9

By default, the function terminates the line it prints by adding a line break.

print("Hello Swift")

Terminator

To print a value without a line break after it, pass an empty string as the terminator

print("Hello Swift", terminator: "")

Separator

You now can use separator to concatenate multiple items

print("Hello", "Swift", 2, separator:" ")

Both

Or you could combine using in this way

print("Hello", "Swift", 2, separator:" ", terminator:".")

How to validate a file upload field using Javascript/jquery

Check it's value property:

In jQuery (since your tag mentions it):

$('#fileInput').val()

Or in vanilla JavaScript:

document.getElementById('myFileInput').value

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

How to add a named sheet at the end of all Excel sheets?

Try to use:

Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"

If you want to check whether a sheet with the same name already exists, you can create a function:

Function funcCreateList(argCreateList)
    For Each Worksheet In ThisWorkbook.Worksheets
        If argCreateList = Worksheet.Name Then
            Exit Function ' if found - exit function
        End If
    Next Worksheet
    Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function

When the function is created, you can call it from your main Sub, e.g.:

Sub main

    funcCreateList "MySheet"

Exit Sub

How can change width of dropdown list?

This worked for me:

ul.dropdown-menu > li {
    max-width: 144px;
}

in Chromium and Firefox.

"The page you are requesting cannot be served because of the extension configuration." error message

I fixed that on my Windows 10:

  1. Go to Control Panel - Programs and Features - Turn Windows features on or off.

  2. Select .NET Framework 4.6 Advanced Services - WCF Services

  3. Check HTTP Activation.

  4. OK done.

Extracting date from a string in Python

If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:

import re
from datetime import datetime

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

Otherwise, if the date is given in an arbitrary form, you can't extract it easily.

drag drop files into standard html file input

Few years later, I've built this library to do drop files into any HTML element.

You can use it like

const Droppable = require('droppable');

const droppable = new Droppable({
    element: document.querySelector('#my-droppable-element')
})

droppable.onFilesDropped((files) => {
    console.log('Files were dropped:', files);
});

// Clean up when you're done!
droppable.destroy();

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

SQL Server JOIN missing NULL values

Use Left Outer Join instead of Inner Join to include rows with NULLS.

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 LEFT OUTER JOIN 
    Table2 ON Table1.Col1 = Table2.Col1 
    AND Table1.Col2 = Table2.Col2

For more information, see here: http://technet.microsoft.com/en-us/library/ms190409(v=sql.105).aspx

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I had the same problem error that is shown, i solve it by adding

defaultConfig {        
    // Enabling multidex support.
    multiDexEnabled true
}

I had this problem cause i exceeded the 65K methods dex limit imposed by Android i used so many libraries

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

Copy row but with new id

This works in MySQL all versions and Amazon RDS Aurora:

INSERT INTO my_table SELECT 0,tmp.* FROM tmp;

or

Setting the index column to NULL and then doing the INSERT.

But not in MariaDB, I tested version 10.

Change "on" color of a Switch

In Android Lollipop and above, define it in your theme style:

<style name="BaseAppTheme" parent="Material.Theme">
    ...
    <item name="android:colorControlActivated">@color/color_switch</item>
</style>

Why is vertical-align:text-top; not working in CSS

The problem I had can't be made out from the info I have provided:

  • I had the text enclosed in old school <p> tags.

I changed the <p> to <span> and it works fine.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)

How to return a specific status code and no contents from Controller?

If anyone wants to do this with a IHttpActionResult may be in a Web API project, Below might be helpful.

// GET: api/Default/
public IHttpActionResult Get()
{
    //return Ok();//200
    //return StatusCode(HttpStatusCode.Accepted);//202
    //return BadRequest();//400
    //return InternalServerError();//500
    //return Unauthorized();//401
    return Ok();
}

Git says local branch is behind remote branch, but it's not

This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:

git co master
git pull

Which fetched those changes. Then,

git co develop
git pull

Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.

Multiple models in a view

This is a simplified example with IEnumerable.

I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:

@using DelegatePortal.ViewModels;

@model SearchViewModel

@using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
{

                Employee First Name
                @Html.EditorFor(model => model.SearchParams.FirstName,
new { htmlAttributes = new { @class = "form-control form-control-sm " } })

                <input type="submit" id="getResults" value="SEARCH" class="btn btn-primary btn-lg btn-block" />

}
<br />
    @(Html
        .Grid(Model.Delegates)
        .Build(columns =>
        {
            columns.Add(model => model.Id).Titled("Id").Css("collapse");
            columns.Add(model => model.LastName).Titled("Last Name");
            columns.Add(model => model.FirstName).Titled("First Name");
        })

... )

SearchViewModel.cs:

namespace DelegatePortal.ViewModels
{
    public class SearchViewModel
    {
        public IEnumerable<DelegatePortal.Models.DelegateView> Delegates { get; set; }

        public SearchParamsViewModel SearchParams { get; set; }
....

DelegateController.cs:

// GET: /Delegate/Search
    public ActionResult Search(String firstName)
    {
        SearchViewModel model = new SearchViewModel();
        model.Delegates = db.Set<DelegateView>();
        return View(model);
    }

    // POST: /Delegate/Search
    [HttpPost]
    public ActionResult Search(SearchParamsViewModel searchParams)
    {
        String firstName = searchParams.FirstName;
        SearchViewModel model = new SearchViewModel();

        if (firstName != null)
            model.Delegates = db.Set<DelegateView>().Where(x => x.FirstName == firstName);

        return View(model);
    }

SearchParamsViewModel.cs:

namespace DelegatePortal.ViewModels
{
    public class SearchParamsViewModel
    {
        public string FirstName { get; set; }
    }
}

Android: How to change CheckBox size?

Starting with API Level 11 there is another approach exists:

<CheckBox
    ...
    android:scaleX="0.70"
    android:scaleY="0.70"
/>

How to convert hex string to Java string?

Just another way to convert hex string to java string:

public static String unHex(String arg) {        

    String str = "";
    for(int i=0;i<arg.length();i+=2)
    {
        String s = arg.substring(i, (i + 2));
        int decimal = Integer.parseInt(s, 16);
        str = str + (char) decimal;
    }       
    return str;
}

How to read a single character from the user?

If you want to register only one single key press even if the user pressed it for more than once or kept pressing the key longer. To avoid getting multiple pressed inputs use the while loop and pass it.

import keyboard

while(True):
  if(keyboard.is_pressed('w')):
      s+=1
      while(keyboard.is_pressed('w')):
        pass
  if(keyboard.is_pressed('s')):
      s-=1
      while(keyboard.is_pressed('s')):
        pass
  print(s)

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

How to use activity indicator view on iPhone?

Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.

http://iphone.trac.wordpress.org/browser/trunk

The files you want are:

  • WPActivityIndicator.xib
  • RoundedRectBlack.png
  • WPActivityIndicator.h
  • WPActivityIndicator.m

Then to show it use something like:

[[WPActivityIndicator sharedActivityIndicator] show];

And hide with:

[[WPActivityIndicator sharedActivityIndicator] hide];

How should I do integer division in Perl?

Integer division $x divided by $y ...

$z = -1 & $x / $y

How does it work?

$x / $y

return the floating point division

&

perform a bit-wise AND

-1

stands for

&HFFFFFFFF

for the largest integer ... whence

$z = -1 & $x / $y

gives the integer division ...

Is there a way to 'uniq' by column?

awk -F"," '!_[$1]++' file
  • -F sets the field separator.
  • $1 is the first field.
  • _[val] looks up val in the hash _(a regular variable).
  • ++ increment, and return old value.
  • ! returns logical not.
  • there is an implicit print at the end.

Wait for Angular 2 to load/resolve model before rendering view/template

The package @angular/router has the Resolve property for routes. So you can easily resolve data before rendering a route view.

See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html

Example from docs as of today, August 28, 2017:

class Backend {
  fetchTeam(id: string) {
    return 'someTeam';
  }
}

@Injectable()
class TeamResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    return this.backend.fetchTeam(route.params.id);
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

Now your route will not be activated until the data has been resolved and returned.

Accessing Resolved Data In Your Component

To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:

  1. route.snapshot.paramMap which returns a string, or the
  2. route.paramMap which returns an Observable you can .subscribe() to.

Example:

  // the no-observable method
  this.dataYouResolved= this.route.snapshot.paramMap.get('id');
  // console.debug(this.licenseNumber);

  // or the observable method
  this.route.paramMap
     .subscribe((params: ParamMap) => {
        // console.log(params);
        this.dataYouResolved= params.get('id');
        return params.get('dataYouResolved');
        // return null
     });
  console.debug(this.dataYouResolved);

I hope that helps.

I want to delete all bin and obj folders to force all projects to rebuild everything

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

How do I kill a process using Vb.NET or C#?

Something like this will work:

foreach ( Process process in Process.GetProcessesByName( "winword" ) )
{
    process.Kill();
    process.WaitForExit();
}

int to string in MySQL

You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.

select t2.* 
from t1 join t2 
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000

How do I concatenate const/literal strings in C?

Also malloc and realloc are useful if you don't know ahead of time how many strings are being concatenated.

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

void example(const char *header, const char **words, size_t num_words)
{
    size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
    char *message = (char*) malloc(message_len);
    strncat(message, header, message_len);

    for(int i = 0; i < num_words; ++i)
    {
       message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
       message = (char*) realloc(message, message_len);
       strncat(strncat(message, ";", message_len), words[i], message_len);
    }

    puts(message);

    free(message);
}

Get DateTime.Now with milliseconds precision

Use DateTime Structure with milliseconds and format like this:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", 
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");

Animate the transition between fragments

You need to use the new android.animation framework (object animators) with FragmentTransaction.setCustomAnimations as well as FragmentTransaction.setTransition.

Here's an example on using setCustomAnimations from ApiDemos' FragmentHideShow.java:

ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);

and here's the relevant animator XML from res/animator/fade_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/accelerate_quad"
    android:valueFrom="0"
    android:valueTo="1"
    android:propertyName="alpha"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that you can combine multiple animators using <set>, just as you could with the older animation framework.


EDIT: Since folks are asking about slide-in/slide-out, I'll comment on that here.

Slide-in and slide-out

You can of course animate the translationX, translationY, x, and y properties, but generally slides involve animating content to and from off-screen. As far as I know there aren't any transition properties that use relative values. However, this doesn't prevent you from writing them yourself. Remember that property animations simply require getter and setter methods on the objects you're animating (in this case views), so you can just create your own getXFraction and setXFraction methods on your view subclass, like this:

public class MyFrameLayout extends FrameLayout {
    ...
    public float getXFraction() {
        return getX() / getWidth(); // TODO: guard divide-by-zero
    }

    public void setXFraction(float xFraction) {
        // TODO: cache width
        final int width = getWidth();
        setX((width > 0) ? (xFraction * width) : -9999);
    }
    ...
}

Now you can animate the 'xFraction' property, like this:

res/animator/slide_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:valueFrom="-1.0"
    android:valueTo="0"
    android:propertyName="xFraction"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that if the object you're animating in isn't the same width as its parent, things won't look quite right, so you may need to tweak your property implementation to suit your use case.

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

Tar error: Unexpected EOF in archive

I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.

From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

How to get all subsets of a set? (powerset)

def get_power_set(s):
  power_set=[[]]
  for elem in s:
    # iterate over the sub sets so far
    for sub_set in power_set:
      # add a new subset consisting of the subset at hand added elem
      power_set=power_set+[list(sub_set)+[elem]]
  return power_set

For example:

get_power_set([1,2,3])

yield

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Are HTTPS headers encrypted?

The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.

Add or change a value of JSON key with jquery or javascript

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

try on jsfiddle

Paging with Oracle

Try the following:

SELECT *
FROM
  (SELECT FIELDA,
    FIELDB,
    FIELDC,
    ROW_NUMBER() OVER (ORDER BY FIELDC) R
  FROM TABLE_NAME
  WHERE FIELDA = 10
  )
WHERE R >= 10
AND R   <= 15;

via [tecnicume]

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

Using the RUN instruction in a Dockerfile with 'source' does not work

I also had issues in running source in a Dockerfile

This runs perfectly fine for building CentOS 6.6 Docker container, but gave issues in Debian containers

RUN cd ansible && source ./hacking/env-setup

This is how I tackled it, may not be an elegant way but this is what worked for me

RUN echo "source /ansible/hacking/env-setup" >> /tmp/setup
RUN /bin/bash -C "/tmp/setup"
RUN rm -f /tmp/setup

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

Verify if file exists or not in C#

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.

Is arr.__len__() the preferred way to get the length of an array in Python?

The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call len on it.

l = [1,2,3,4]
s = 'abcde'
len(l) #returns 4
len(s) #returns 5

The reason for the "strange" syntax is that internally python translates len(object) into object.__len__(). This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a __len__() method on it and then one can call len on those instances.

How to get the size of a JavaScript object?

i want to know if my memory reduction efforts actually help in reducing memory

Following up on this comment, here's what you should do: Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.

Now there are two options: option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.

option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.

How do I load an url in iframe with Jquery

Try $(this).load("/file_name.html");. This method targets a local file.

You can also target remote files (on another domain) take a look at: http://en.wikipedia.org/wiki/Same_origin_policy

Label word wrapping

If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

git switch branch without discarding local changes

You can either :

  • Use git stash to shelve your changes or,

  • Create another branch and commit your changes there, and then merge that branch into your working directory

What's the simplest way to print a Java array?

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

  • Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));
    

    Output:

    [John, Mary, Bob]
    
  • Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    System.out.println(Arrays.toString(deepArray));
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    System.out.println(Arrays.deepToString(deepArray));
    

    Output:

    [[John, Mary], [Alice, Bob]]
    
  • double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));
    

    Output:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    
  • int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));
    

    Output:

    [7, 9, 5, 1, 3 ]
    

How to merge rows in a column into one cell in excel?

In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:

  1. In any cell write next code

    =Transpose(A1:A9) 
    

Where A1:A9 are cells you would like to merge.

  1. Without leaving the cell press F9

After that, the cell will contain the string:

={A1,A2,A3,A4,A5,A6,A7,A8,A9}

Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/

Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

Disable pasting text into HTML form

I use this vanilla JS solution:

const element = document.getElementById('textfield')
element.addEventListener('paste', e =>  e.preventDefault())

Method to find string inside of the text file. Then getting the following lines up to a certain limit

You can do something like this:

File file = new File("Student.txt");

try {
    Scanner scanner = new Scanner(file);

    //now read the file line by line...
    int lineNum = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        lineNum++;
        if(<some condition is met for the line>) { 
            System.out.println("ho hum, i found it on line " +lineNum);
        }
    }
} catch(FileNotFoundException e) { 
    //handle this
}

Testing javascript with Mocha - how can I use console.log to debug a test?

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

Get the first element of each tuple in a list in Python

If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>

How copy data from Excel to a table using Oracle SQL Developer

Click on "Tables" in "Connections" window, choose "Import data ...", follow the wizard and you will be asked for name for new table.

urllib2.HTTPError: HTTP Error 403: Forbidden

import urllib.request

bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]


def get_pdf(url):
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    
    #url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
    headers={'User-Agent':user_agent,} 
    
    request=urllib.request.Request(url,None,headers) #The assembled request
    response = urllib.request.urlopen(request)
    #print(response.text)
    data = response.read()
#    print(type(data))
    
    name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
    f = open(name, 'wb')
    f.write(data)
    f.close()
    

for bank_url in bank_pdf_list:
    try: 
        get_pdf(bank_url)
    except:
        pass

How do I add python3 kernel to jupyter (IPython)

Adding kernel means you want to use Jupyter Notebook with versions of python which are not showing up in the list.

Simple approach- Start notebook with required python version, suppose I have python3.7 installed then use below command from terminal (cmd) to run notebook:

python3.7 -m notebook

Sometimes instead of python3.7 it's install with alias of py, py3.7, python.

Python: list of lists

I came here because I'm new with python and lazy so I was searching an example to create a list of 2 lists, after a while a realized the topic here could be wrong... this is a code to create a list of lists:

listoflists = []
for i in range(0,2):
    sublist = []
    for j in range(0,10)
        sublist.append((i,j))
    listoflists.append(sublist)
print listoflists

this the output [ [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)], [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9)] ]

The problem with your code seems to be you are creating a tuple with your list and you get the reference to the list instead of a copy. That I guess should fall under a tuple topic...

How to lowercase a pandas dataframe string column if it has missing values?

Another possible solution, in case the column has not only strings but numbers too, is to use astype(str).str.lower() or to_string(na_rep='') because otherwise, given that a number is not a string, when lowered it will return NaN, therefore:

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan,2],columns=['x']) 
xSecureLower = df['x'].to_string(na_rep='').lower()
xLower = df['x'].str.lower()

then we have:

>>> xSecureLower
0    one
1    two
2   
3      2
Name: x, dtype: object

and not

>>> xLower
0    one
1    two
2    NaN
3    NaN
Name: x, dtype: object

edit:

if you don't want to lose the NaNs, then using map will be better, (from @wojciech-walczak, and @cs95 comment) it will look something like this

xSecureLower = df['x'].map(lambda x: x.lower() if isinstance(x,str) else x)

How to check if a string contains text from an array of substrings in JavaScript?

convert_to_array = function (sentence) {
     return sentence.trim().split(" ");
};

let ages = convert_to_array ("I'm a programmer in javascript writing script");

function confirmEnding(string) {
let target = "ipt";
    return  (string.substr(-target.length) === target) ? true : false;
}

function mySearchResult() {
return ages.filter(confirmEnding);
}

mySearchResult();

you could check like this and return an array of the matched words using filter

Waiting for background processes to finish before exiting script

You can use kill -0 for checking whether a particular pid is running or not.

Assuming, you have list of pid numbers in a file called pid in pwd

while true;
do 
    if [ -s pid ] ; then
        for pid in `cat pid`
        do  
            echo "Checking the $pid"
            kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
        done
    else
        echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
        break
    fi
done

Ruby Array find_first object?

Guess you just missed the find method in the docs:

my_array.find {|e| e.satisfies_condition? }

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

How to print a groupby object

Simply do:

grouped_df = df.groupby('A')

for key, item in grouped_df:
    print(grouped_df.get_group(key), "\n\n")

This also works,

grouped_df = df.groupby('A')    
gb = grouped_df.groups

for key, values in gb.iteritems():
    print(df.ix[values], "\n\n")

For selective key grouping: Insert the keys you want inside the key_list_from_gb, in following, using gb.keys(): For Example,

gb = grouped_df.groups
gb.keys()

key_list_from_gb = [key1, key2, key3]

for key, values in gb.items():
    if key in key_list_from_gb:
        print(df.ix[values], "\n")

Is there an eval() function in Java?

There are some perfectly capable answers here. However for non-trivial script it may be desirable to retain the code in a cache, or for debugging purposes, or even to have dynamically self-updating code.

To that end, sometimes it's simpler or more robust to interact with Java via command line. Create a temporary directory, output your script and any assets, create the jar. Finally import your new code.

It's a bit beyond the scope of normal eval() use in most languages, though you could certainly implement eval by returning the result from some function in your jar.

Still, thought I'd mention this method as it does fully encapsulate everything Java can do without 3rd party tools, in case of desperation. This method allows me to turn HTML templates into objects and save them, avoiding the need to parse a template at runtime.

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

How to return a value from try, catch, and finally?

The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

What's the difference between setWebViewClient vs. setWebChromeClient?

From the source code:

// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;

// SOME OTHER SUTFFF.......

/**
 * Set the WebViewClient.
 * @param client An implementation of WebViewClient.
 */
public void setWebViewClient(WebViewClient client) {
    mWebViewClient = client;
}

/**
 * Set the WebChromeClient.
 * @param client An implementation of WebChromeClient.
 */
public void setWebChromeClient(WebChromeClient client) {
    mWebChromeClient = client;
}

Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView

At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient object and override the onReceivedIcon(WebView view, Bitmap icon).

Most of the times, if you don't want to worry about those things... you can just do this:

webView= (WebView) findViewById(R.id.webview); 
webView.setWebChromeClient(new WebChromeClient()); 
webView.setWebViewClient(new WebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url); 

And your WebView will (in theory) have all features implemented (as the android native browser).

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If you dont find Hyper-V option in control panel as said in other responses here, try entering BIOS setup (restarting and pressing F-12 or ESC or other depending on your PC) and enabling Virtualization, located probably in CPU options.

How to handle change of checkbox using jQuery?

You can use Id of the field as well

$('#checkbox1').change(function() {
   if($(this).is(":checked")) {
      //'checked' event code
      return;
   }
   //'unchecked' event code
});

how to call an ASP.NET c# method using javascript

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

in markup:

 var $Username = $("#txtUsername").val();
            var $Password = $("#txtPassword").val();

            //Call the approve method on the code behind
            $.ajax({
                type: "POST",
                url: "Pages/Mobile/Login.aspx/LoginUser",
                data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
                success: function (msg) {
                    if (msg.d == true) {
                        window.location.href = "Pages/Mobile/Basic/Index.aspx";
                    }
                    else {
                        //show error
                        alert('login failed');
                    }
                }
            });

In Code Behind:

/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
    try
    {
        StaticStore.CurrentUser = new User( Username, Password );

        //check the login details were correct
        if ( StaticStore.CurrentUser.IsAuthentiacted )
        {
            //change the status to logged in
            StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;

            //Store the user ID in the list of active users
            ( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;

            return true;
        }
        else
        {
            return false;
        }
    }
    catch ( Exception ex )
    {
        return false;
    }
}

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

How to extract code of .apk file which is not working?

Click here this is a good tutorial for both window/ubuntu.

  1. apktool1.5.1.jar download from here.

  2. apktool-install-linux-r05-ibot download from here.

  3. dex2jar-0.0.9.15.zip download from here.

  4. jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.

  5. framework-res.apk ( Located at your android device /system/framework/)

Procedure:

  1. Rename the .apk file and change the extension to .zip ,

it will become .zip.

  1. Then extract .zip.

  2. Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.

  3. Open terminal and change directory to unzip “dex2jar-0.0.9.15 “

– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).

  1. Now, create new folder and copy “classes.dex.dex2jar.jar” into it.

  2. Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.

  3. Click on open file and select “classes.dex.dex2jar.jar” into the window.

  4. “Java Decompiler” and go to file > save and save the source in a .zip file.

  5. Create “source_code” folder.

  6. Extract the saved .zip and copy the contents to “source_code” folder.

  7. This will be where we keep your source code.

  8. Extract apktool1.5.1.tar.bz2 , you get apktool.jar

  9. Now, unzip “apktool-install-linux-r05-ibot.zip”

  10. Copy “framework-res.apk” , “.apk” and apktool.jar

  11. Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).

  12. Then open terminal and type:

    – cd

    – chown -R : ‘apktool.jar’

    – chown -R : ‘apktool’

    – chown -R : ‘aapt’

    – sudo chmod +x ‘apktool.jar’

    – sudo chmod +x ‘apktool’

    – sudo chmod +x ‘aapt’

    – sudo mv apktool.jar /usr/local/bin

    – sudo mv apktool /usr/local/bin

    – sudo mv aapt /usr/local/bin

    – apktool if framework-res.apk – apktool d .apk

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Installing a plain plugin jar in Eclipse 3.5

For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):

  1. Add plugins folder to C:\eclipseMarsEE\dropins so that it looks like: C:\eclipseMarsEE\dropins\plugins
  2. Then add plugin you want to install into that folder: C:\eclipseMarsEE\dropins\plugins\someplugin.jar
  3. Start Eclipse with clean option.
  4. If you are using shortcut on desktop then just right click on Eclipse icon > Properties and in Target field add: -clean like this: C:\eclipseMarsEE\eclipse.exe -clean

enter image description here

  1. Start Eclipse and verify that your plugin works.
  2. Remove -clean option from Target field.

How to scale a UIImageView proportionally?

Here is how you can scale it easily.

This works in 2.x with the Simulator and the iPhone.

UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];

Change button background color using swift language

After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:

 yourUIButton.backgroundColor = UIColor.blue

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.

For the second case (event handler never fires even though request made), you may want to try the following suggestions:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.
  2. As long as view state is on, only bind the list data when it is not a post back.
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad.

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.

In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.

Thanks for your time reading this, and welcome everyone to correct if I am wrong.

How to make a <div> appear in front of regular text/tables

make these changes in your div's style

  1. z-index:100; some higher value makes sure that this element is above all
  2. position:fixed; this makes sure that even if scrolling is done,

div lies on top and always visible

subsetting a Python DataFrame

Regarding some points mentioned in previous answers, and to improve readability:

No need for data.loc or query, but I do think it is a bit long.

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.

I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.

q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time

df.loc[q_product & q_start & q_end, c('Time,Product')]

# c is just a convenience
c = lambda v: v.split(',') 

Removing the textarea border in HTML

textarea {
border: 0;
overflow: auto; }

less CSS ^ you can't align the text to the bottom unfortunately.

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

How do I add a resources folder to my Java project in Eclipse

If aim is to create a resources folder parallel to src/main/java, then do the following:

Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish

Best way to check if a character array is empty

The second method would almost certainly be the fastest way to test whether a null-terminated string is empty, since it involves one read and one comparison. There's certainly nothing wrong with this approach in this case, so you may as well use it.

The third method doesn't check whether a character array is empty; it ensures that a character array is empty.

Google Chrome forcing download of "f.txt" file

This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.

  • Some time around the summer of 2014, IT Security Engineer Michele Spagnuolo (apparently employed at Google Zurich) developed a proof-of-concept exploit and supporting tool called Rosetta Flash that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
    • Known affected browsers: Chrome, IE
    • Possibly unaffected browsers: Firefox
  • Adobe has released at least 5 different fixes over the past year while trying to comprehensively fix this vulnerability, but various major websites also introduced their own fixes earlier on in order to prevent mass vulnerability to their userbases. Among the sites to do so: Google, Youtube, Facebook, Github, and others. One component of the ad-hoc mitigation implemented by these website owners was to force the HTTP Header Content-Disposition: attachment; filename=f.txt on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.
  • In conclusion, the websites you were visiting when this file spontaneously downloaded are not bad or malicious, but some domain serving content on their pages (usually ads) had content with this exploit inside it. Note that this issue will be random and intermittent in nature because even visiting the same pages consecutively will often produce different ad content. For example, the advertisement domain ad.doubleclick.net probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.
  • The only way I'm aware that you could stop this f.txt file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htm
  • Short list of domains you could block (by no means a comprehensive list). Most of these are highly associated with adware and malware:
    • ad.doubleclick.net
    • adclick.g.doubleclick.net
    • secure-us.imrworldwide.com
    • d.turn.com
    • ad.turn.com
    • secure.insightexpressai.com
    • core.insightexpressai.com

Examples of good gotos in C or C++

One good place to use a goto is in a procedure that can abort at several points, each of which requires various levels of cleanup. Gotophobes can always replace the gotos with structured code and a series of tests, but I think this is more straightforward because it eliminates excessive indentation:

if (!openDataFile())
  goto quit;

if (!getDataFromFile())
  goto closeFileAndQuit;

if (!allocateSomeResources)
  goto freeResourcesAndQuit;

// Do more work here....

freeResourcesAndQuit:
   // free resources
closeFileAndQuit:
   // close file
quit:
   // quit!

Jackson serialization: ignore empty values (or null)

Code bellow may help if you want to exclude boolean type from serialization either:

@JsonInclude(JsonInclude.Include.NON_ABSENT)