Programs & Examples On #Itoa

Alternative to itoa() for converting integer to string C++?

Behind the scenes, lexical_cast does this:

std::stringstream str;
str << myint;
std::string result;
str >> result;

If you don't want to "drag in" boost for this, then using the above is a good solution.

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

How to add a downloaded .box file to Vagrant?

Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:

{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:

vagrant box add laravel/homestead /path/to/metadata.json

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Time part of a DateTime Field in SQL

you can use CONVERT(TIME,GETDATE()) in this case:

INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))

or if you want print it or return that time use like this:

DECLARE @dt TIME
SET @dt = CONVERT(TIME,GETDATE())
PRINT @dt

Simple example of threading in C++

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

Duplicate and rename Xcode project & associated folders

One more thing to try!

When I copied all of my files, opened the project, and renamed it, everything changed to my new project name except for the test target! I got a linker error that said I was missing a file called "myOldProjectname.app". Here's what fixed it:

  1. Click on your project settings and select your test target enter image description here

  2. Click on build settings and search for "test host" enter image description here

  3. Check those 2 file paths. Chances are that those 2 paths are still pointing at your old project name. enter image description here

Hope that helps!

How does the "view" method work in PyTorch?

Let's do some examples, from simpler to more difficult.

  1. The view method returns a tensor with the same data as the self tensor (which means that the returned tensor has the same number of elements), but with a different shape. For example:

    a = torch.arange(1, 17)  # a's shape is (16,)
    
    a.view(4, 4) # output below
      1   2   3   4
      5   6   7   8
      9  10  11  12
     13  14  15  16
    [torch.FloatTensor of size 4x4]
    
    a.view(2, 2, 4) # output below
    (0 ,.,.) = 
    1   2   3   4
    5   6   7   8
    
    (1 ,.,.) = 
     9  10  11  12
    13  14  15  16
    [torch.FloatTensor of size 2x2x4]
    
  2. Assuming that -1 is not one of the parameters, when you multiply them together, the result must be equal to the number of elements in the tensor. If you do: a.view(3, 3), it will raise a RuntimeError because shape (3 x 3) is invalid for input with 16 elements. In other words: 3 x 3 does not equal 16 but 9.

  3. You can use -1 as one of the parameters that you pass to the function, but only once. All that happens is that the method will do the math for you on how to fill that dimension. For example a.view(2, -1, 4) is equivalent to a.view(2, 2, 4). [16 / (2 x 4) = 2]

  4. Notice that the returned tensor shares the same data. If you make a change in the "view" you are changing the original tensor's data:

    b = a.view(4, 4)
    b[0, 2] = 2
    a[2] == 3.0
    False
    
  5. Now, for a more complex use case. The documentation says that each new view dimension must either be a subspace of an original dimension, or only span d, d + 1, ..., d + k that satisfy the following contiguity-like condition that for all i = 0, ..., k - 1, stride[i] = stride[i + 1] x size[i + 1]. Otherwise, contiguous() needs to be called before the tensor can be viewed. For example:

    a = torch.rand(5, 4, 3, 2) # size (5, 4, 3, 2)
    a_t = a.permute(0, 2, 3, 1) # size (5, 3, 2, 4)
    
    # The commented line below will raise a RuntimeError, because one dimension
    # spans across two contiguous subspaces
    # a_t.view(-1, 4)
    
    # instead do:
    a_t.contiguous().view(-1, 4)
    
    # To see why the first one does not work and the second does,
    # compare a.stride() and a_t.stride()
    a.stride() # (24, 6, 2, 1)
    a_t.stride() # (24, 2, 1, 6)
    

    Notice that for a_t, stride[0] != stride[1] x size[1] since 24 != 2 x 3

Python `if x is not None` or `if not x is None`?

Python if x is not None or if not x is None?

TLDR: The bytecode compiler parses them both to x is not None - so for readability's sake, use if x is not None.

Readability

We use Python because we value things like human readability, useability, and correctness of various paradigms of programming over performance.

Python optimizes for readability, especially in this context.

Parsing and Compiling the Bytecode

The not binds more weakly than is, so there is no logical difference here. See the documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

The is not is specifically provided for in the Python grammar as a readability improvement for the language:

comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'

And so it is a unitary element of the grammar as well.

Of course, it is not parsed the same:

>>> import ast
>>> ast.dump(ast.parse('x is not None').body[0].value)
"Compare(left=Name(id='x', ctx=Load()), ops=[IsNot()], comparators=[Name(id='None', ctx=Load())])"
>>> ast.dump(ast.parse('not x is None').body[0].value)
"UnaryOp(op=Not(), operand=Compare(left=Name(id='x', ctx=Load()), ops=[Is()], comparators=[Name(id='None', ctx=Load())]))"

But then the byte compiler will actually translate the not ... is to is not:

>>> import dis
>>> dis.dis(lambda x, y: x is not y)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE
>>> dis.dis(lambda x, y: not x is y)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

So for the sake of readability and using the language as it was intended, please use is not.

To not use it is not wise.

link with target="_blank" does not open in new tab in Chrome

Your syntax for the target attribute is correct, but browsers need not honor it. They may interpret it as opening the destination in a new tab rather than new window, or they may completely ignore the attribute. Browsers have settings for such issues. Moreover, opening of new windows may be prevented by browser plugins (typically designed to prevent annoying advertisements).

There’s little you can do about this as an author. You might consider opening a new window with JavaScript instead, cf. to the accepted answer to target="_blank" is not working in firefox?, but browsers may be even more reluctant to let pages open new windows that way than via target.

target="_blank" is not working in firefox?

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

How to create a backup of a single table in a postgres database?

I was trying to run pg_dump from within psql command prompt and I was not able to trace output file anywhere on my ubuntu 20.04 box. I tried finding by find / -name "myfilename.sql".

Instead When I tried pg_dump from /home/ubuntu, I found my output file in /home/ubuntu

Stripping non printable characters from a string in python

Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.

import unicodedata, re, itertools, sys

all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For Python2

import unicodedata, re, sys

all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:

  • Cc (control): 65
  • Cf (format): 161
  • Cs (surrogate): 2048
  • Co (private-use): 137468
  • Cn (unassigned): 836601

Edit Adding suggestions from the comments.

How does collections.defaultdict work?

Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.

It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations. A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key.

A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')

ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'

print(ice_cream['Sarah'])
>>>Chunky Monkey

print(ice_cream['Joe'])
>>>Vanilla

Here is another example on How using defaultdict, we can reduce complexity

from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
    ans = []
    for num in array:
        if ans.count(num) < n:
            ans.append(num)
    return ans

# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
    result = []
    counts = defaultdict(int)

    for i in array:
        if counts[i] < n:
            result.append(i)
            counts[i] += 1
    return result


x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))

In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.

Inheritance and Overriding __init__ in python

In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...

class Female_Grandparent:
    def __init__(self):
        self.grandma_name = 'Grandma'

class Male_Grandparent:
    def __init__(self):
        self.grandpa_name = 'Grandpa'

class Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):
        Female_Grandparent.__init__(self)
        Male_Grandparent.__init__(self)

        self.parent_name = 'Parent Class'

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
#---------------------------------------------------------------------------------------#
        for cls in Parent.__bases__: # This block grabs the classes of the child
             cls.__init__(self)      # class (which is named 'Parent' in this case), 
                                     # and iterates through them, initiating each one.
                                     # The result is that each parent, of each child,
                                     # is automatically handled upon initiation of the 
                                     # dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#



g = Female_Grandparent()
print g.grandma_name

p = Parent()
print p.grandma_name

child = Child()

print child.grandma_name

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Limiting the output of PHP's echo to 200 characters

Well, you could make a custom function:

function custom_echo($x, $length)
{
  if(strlen($x)<=$length)
  {
    echo $x;
  }
  else
  {
    $y=substr($x,0,$length) . '...';
    echo $y;
  }
}

You use it like this:

<?php custom_echo($row['style-info'], 200); ?>

Command line to remove an environment variable from the OS level configuration

I agree with CupawnTae.

SET is not useful for changes to the master environment.

FYI: System variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (a good deal longer than user vars).

The full command for a system var named FOOBAR therefore is:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

(Note the quotes required to handle the space.)

It is too bad the setx command doesn't support a delete syntax. :(

PS: Use responsibly - If you kill your path variable, don't blame me!

Is mongodb running?

check with either:

   ps -edaf | grep mongo | grep -v grep  # "ps" flags may differ on your OS

or

   /etc/init.d/mongodb status     # for MongoDB version < 2.6

   /etc/init.d/mongod status      # for MongoDB version >= 2.6

or

   service mongod status

to see if mongod is running (you need to be root to do this, or prefix everything with sudo). Please note that the 'grep' command will always also show up as a separate process.

check the log file /var/log/mongo/mongo.log to see if there are any problems reported

How do you convert a byte array to a hexadecimal string in C?

I just wanted to add the following, even if it is slightly off-topic (not standard C), but I find myself looking for it often, and stumbling upon this question among the first search hits. The Linux kernel print function, printk, also has format specifiers for outputting array/memory contents "directly" through a singular format specifier:

https://www.kernel.org/doc/Documentation/printk-formats.txt

Raw buffer as a hex string:
    %*ph    00 01 02  ...  3f
    %*phC   00:01:02: ... :3f
    %*phD   00-01-02- ... -3f
    %*phN   000102 ... 3f

    For printing a small buffers (up to 64 bytes long) as a hex string with
    certain separator. For the larger buffers consider to use
    print_hex_dump(). 

... however, these format specifiers do not seem to exist for the standard, user-space (s)printf.

putting a php variable in a HTML form value

value="<?php echo htmlspecialchars($name); ?>"

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

How to clear memory to prevent "out of memory error" in excel vba?

I had a similar problem that I resolved myself.... I think it was partially my code hogging too much memory while too many "big things"

in my application - the workbook goes out and grabs another departments "daily report".. and I extract out all the information our team needs (to minimize mistakes and data entry).

I pull in their sheets directly... but I hate the fact that they use Merged cells... which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)

I made my problem go away by

a)unmerging only the "used cells" - rather than merely attempting to do entire column... ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)

b) Knowing that the undo only looks after the last ~16 events... between each "unmerge" - i put 15 events which clear out what is stored in the "undo" to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value... I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing

Yes it doesn't allow for any chance of an Undo... but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn't an issue

Sound corny - but my problem went away

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

Python: convert string from UTF-8 to Latin-1

data="UTF-8 data"
udata=data.decode("utf-8")
data=udata.encode("latin-1","ignore")

Should do it.

Dynamically display a CSV file as an HTML table on a web page

The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:

<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";

SQL set values of one column equal to values of another column in the same table

I would do it this way:

UPDATE YourTable SET B = COALESCE(B, A);

COALESCE is a function that returns its first non-null argument.

In this example, if B on a given row is not null, the update is a no-op.

If B is null, the COALESCE skips it and uses A instead.

placeholder for select tag

<select>

    <option selected="selected" class="Country">Country Name</option>

    <option value="1">India</option>

    <option value="2">us</option>

</select>

.country
{


    display:none;
}

</style>

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

Changing background color of ListView items on Android

By changing a code of Francisco Cabezas, I got the following:

private int selectedRow = -1;

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    parent.getChildAt(position).setBackgroundResource(R.color.orange);
    if (selectedRow != -1 && selectedRow != position) {
        parent.getChildAt(selectedRow).setBackgroundResource(R.color.black);
    }
    selectedRow = position;

Windows task scheduler error 101 launch failure code 2147943785

I have the same today on Win7.x64, this solve it.

Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

Why am I getting this redefinition of class error?

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
{
    x = inx;
    y = iny;
}

int gameObject::add()
{
    return x+y;
}

etc

HTML5 Email input pattern attribute

One more solution that is built on top of w3org specification.
Original regex is taken from w3org.
The last "* Lazy quantifier" in this regex was replaced with "+ One or more quantifier".
Such a pattern fully complies with the specification, with one exception: it does not allow top level domain addresses such as "foo@com"

<input
    type="email" 
    pattern="[a-zA-Z0-9.!#$%&amp;’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"
    title="[email protected]"
    placeholder="[email protected]"
    required>

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Anything that is not stored on an EBS volume that is mounted to the instance will be lost.

For example, if you mount your EBS volume at /mystuff, then anything not in /mystuff will be lost. If you don't mount an ebs volume and save stuff on it, then I believe everything will be lost.

You can create an AMI from your current machine state, which will contain everything in your ephemeral storage. Then, when you launch a new instance based on that AMI it will contain everything as it is now.

Update: to clarify based on comments by mattgmg1990 and glenn bech:

Note that there is a difference between "stop" and "terminate". If you "stop" an instance that is backed by EBS then the information on the root volume will still be in the same state when you "start" the machine again. According to the documentation, "By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates" but you can modify that via configuration.

Spring Boot - How to log all requests and responses with exceptions in single place?

Spring already provides a filter that does this job. Add following bean to your config

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(64000);
    return loggingFilter;
}

Don't forget to change log level of org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG.

Converting from a string to boolean in Python?

Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:

s == 'True'

Or to checks against a whole bunch of values:

s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']

Be cautious when using the following:

>>> bool("foo")
True
>>> bool("")
False

Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

How to change row color in datagridview?

Works on Visual Studio 2010. (I tried it and it works!) It will paint your entire row.

  1. Create a button for the datagridview.
  2. Create a CellClick event and put the next line of code inside of it.

if (dataGridView3.Columns[e.ColumnIndex].Index.Equals(0)    
{
    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
}

Multiple models in a view

Use a view model that contains multiple view models:

   namespace MyProject.Web.ViewModels
   {
      public class UserViewModel
      {
          public UserDto User { get; set; }
          public ProductDto Product { get; set; }
          public AddressDto Address { get; set; }
      }
   }

In your view:

  @model MyProject.Web.ViewModels.UserViewModel

  @Html.LabelFor(model => model.User.UserName)
  @Html.LabelFor(model => model.Product.ProductName)
  @Html.LabelFor(model => model.Address.StreetName)

Java 8 lambdas, Function.identity() or t->t

In your example there is no big difference between str -> str and Function.identity() since internally it is simply t->t.

But sometimes we can't use Function.identity because we can't use a Function. Take a look here:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

this will compile fine

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

but if you try to compile

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

you will get compilation error since mapToInt expects ToIntFunction, which is not related to Function. Also ToIntFunction doesn't have identity() method.

How to convert from int to string in objective c: example code

You can use literals, it's more compact.

NSString* myString = [@(17) stringValue];

(Boxes as a NSNumber and uses its stringValue method)

Get child Node of another Node, given node name

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Works for me, has nothing to do with PHP 5.3. Just like many such options it cannot be overriden via ini_set() when safe_mode is enabled. Check your updated php.ini (and better yet: change the memory_limit there too).

I can not find my.cnf on my windows computer

You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)

SHOW VARIABLES

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

I just posted a fix here that would also apply in this case - basically, you do a hex find-and-replace in your external library to make it think that it's ARMv7s code. You should be able to use lipo to break it into 3 static libraries, duplicate / modify the ARMv7 one, then use lipo again to assemble a new library for all 4 architectures.

How do I extract data from JSON with PHP?

https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w

Check below code for converting json to array in PHP, If JSON is correct then json_decode() works well, and will return an array, But if malformed JSON, then It will return NULL,

<?php
function jsonDecode1($json){
    $arr = json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );

If malformed JSON, and you are expecting only array, then you can use this function,

<?php
function jsonDecode2($json){
    $arr = (array) json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );

If malformed JSON, and you want to stop code execution, then you can use this function,

<?php
function jsonDecode3($json){
    $arr = (array) json_decode($json, true);

    if(empty(json_last_error())){
        return $arr;
    }
    else{
        throw new ErrorException( json_last_error_msg() );
    }
}

// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );

You can use any function depends on your requirement,

python: sys is not defined

I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.

try:

import sys
# .. other safe imports
try:
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Position a div container on the right side

This works for me.

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>

jQuery: how to get which button was clicked upon form submission?

You can create input type="hidden" as holder for a button id information.

<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

How to add local .jar file dependency to build.gradle file?

A simple way to do this is

compile fileTree(include: ['*.jar'], dir: 'libs')

it will compile all the .jar files in your libs directory in App.

How can I count the occurrences of a list item?

If you want to count all values at once you can do it very fast using numpy arrays and bincount as follows

import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)

which gives

>>> array([0, 3, 1, 1, 2])

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

i have the same problem. this is how i fixed the problem. first when the error is occurred, my array data is coming form DB like this --,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"} 

make sure that your data is an ARRAY, not an OBJECT that carries an array. only array look like this --,

(5) [{…}, {…}, {…}, {…}, {…}]

it solved my problem.

String to HashMap JAVA

Use StringTokenizer to parse the string.

String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    Map<String, Integer> lMap=new HashMap<String, Integer>();


    StringTokenizer st=new StringTokenizer(s, ",");
    while(st.hasMoreTokens())
    {
        String [] array=st.nextToken().split(":");
        lMap.put(array[0], Integer.valueOf(array[1]));
    }

What is the best way to get the count/length/size of an iterator?

You will always have to iterate. Yet you can use Java 8, 9 to do the counting without looping explicitely:

Iterable<Integer> newIterable = () -> iter;
long count = StreamSupport.stream(newIterable.spliterator(), false).count();

Here is a test:

public static void main(String[] args) throws IOException {
    Iterator<Integer> iter = Arrays.asList(1, 2, 3, 4, 5).iterator();
    Iterable<Integer> newIterable = () -> iter;
    long count = StreamSupport.stream(newIterable.spliterator(), false).count();
    System.out.println(count);
}

This prints:

5

Interesting enough you can parallelize the count operation here by changing the parallel flag on this call:

long count = StreamSupport.stream(newIterable.spliterator(), *true*).count();

What are POD types in C++?

A POD (plain old data) object has one of these data types--a fundamental type, pointer, union, struct, array, or class--with no constructor. Conversely, a non-POD object is one for which a constructor exists. A POD object begins its lifetime when it obtains storage with the proper size for its type and its lifetime ends when the storage for the object is either reused or deallocated.

PlainOldData types also must not have any of:

  • Virtual functions (either their own, or inherited)
  • Virtual base classes (direct or indirect).

A looser definition of PlainOldData includes objects with constructors; but excludes those with virtual anything. The important issue with PlainOldData types is that they are non-polymorphic. Inheritance can be done with POD types, however it should only be done for ImplementationInheritance (code reuse) and not polymorphism/subtyping.

A common (though not strictly correct) definition is that a PlainOldData type is anything that doesn't have a VeeTable.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

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

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

Regex for allowing alphanumeric,-,_ and space

Try this regex

*Updated regex

/^[a-z0-9]+([-_\s]{1}[a-z0-9]+)*$/i

This will allow only single space or - or _ between the text

Ex: this-some abc123_regex

To learn : https://regexr.com

*Note: I have updated the regex based on Toto question

git push says "everything up-to-date" even though I have local changes

I was working with Jupyter-Notebook when I encountered this deceptive error.

I wasn't able to resolve through the solutions provided above as I neither had a detached head nor did I have different names for my local and remote repo.

But what I did have was my file sizes were slightly greater than 1MB and the largest was almost ~2MB.

I reduced the file size of each of the file using https://stackoverflow.com/questions/37807308/[][1] technique.

It helped reduce my file size by clearing the outputs. I was able to push the code, henceforth as it brought my file size in KBs.

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

Number of rows affected by an UPDATE in PL/SQL

Please try this one..


create table client (
  val_cli integer
 ,status varchar2(10)
);

---------------------
begin
insert into client
select 1, 'void' from dual
union all
select 4, 'void' from dual
union all
select 1, 'void' from dual
union all
select 6, 'void' from dual
union all
select 10, 'void' from dual;
end;

---------------------
select * from client;

---------------------
declare
  counter integer := 0;
begin
  for val in 1..10
    loop
      update client set status = 'updated' where val_cli = val;
      if sql%rowcount = 0 then
        dbms_output.put_line('no client with '||val||' val_cli.');
      else
        dbms_output.put_line(sql%rowcount||' client updated for '||val);
        counter := counter + sql%rowcount;
      end if;
  end loop;
   dbms_output.put_line('Number of total lines affected update operation: '||counter);
end;

---------------------
select * from client;

--------------------------------------------------------

Result will be like below:


2 client updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10
Number of total lines affected update operation: 5


How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

Submit form and stay on same page?

99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

<style>
  .hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>

<iframe name="hiddenFrame" class="hide"></iframe>

<form action="receiver.pl" method="post" target="hiddenFrame">
  <input name="signed" type="checkbox">
  <input value="Save" type="submit">
</form>

There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...

  • gracefully handle errors (e.g. retry)
  • provide UI indicators (e.g. loading, processing, success, failure)
  • run logic before the request is sent, or run logic after the response is received.

user authentication libraries for node.js?

There is a project called Drywall that implements a user login system with Passport and also has a user management admin panel. If you're looking for a fully-featured user authentication and management system similar to something like what Django has but for Node.js, this is it. I found it to be a really good starting point for building a node app that required a user authentication and management system. See Jared Hanson's answer for information on how Passport works.

jQuery .val change doesn't change input value

My similar issue was caused by having special characters (e.g. periods) in the selector.

The fix was to escape the special characters:

$("#dots\\.er\\.bad").val("mmmk");

How to get first and last day of the current week in JavaScript

I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.

Simply to get current date time in specific format

        case 'Today':
        moment().format("DD/MM/YYYY h:mm A");

        case 'This Week':
          moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");

Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.

        case 'This Month':
          moment().endOf('month').format("DD/MM/YYYY h:mm A");

        case 'This Quarter':
          moment().endOf('quarter').format("DD/MM/YYYY h:mm A");

I chose this format as per my need. You can change the format according to your requirement.

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

  • Android studio-> Build -> Make Project Or Make Module 'xxx' fix the problem.
  • Yes, run app can not fix the problem...
  • Yes, clean can not fix the problem...
  • Yes, File -> Invalidate cache can not fix the problem...
  • by the way, should I use yes? or may be no is right in English?

Where is the syntax for TypeScript comments documented?

Future

The TypeScript team, and other TypeScript involved teams, plan to create a standard formal TSDoc specification. The 1.0.0 draft hasn't been finalised yet: https://github.com/Microsoft/tsdoc#where-are-we-on-the-roadmap

enter image description here

Current

TypeScript uses JSDoc. e.g.

/** This is a description of the foo function. */
function foo() {
}

To learn jsdoc : https://jsdoc.app/

Demo

But you don't need to use the type annotation extensions in JSDoc.

You can (and should) still use other jsdoc block tags like @returns etc.

Example

Just an example. Focus on the types (not the content).

JSDoc version (notice types in docs):

/**
 * Returns the sum of a and b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function sum(a, b) {
    return a + b;
}

TypeScript version (notice the re-location of types):

/**
 * Takes two numbers and returns their sum
 * @param a first input to sum
 * @param b second input to sum
 * @returns sum of a and b
 */
function sum(a: number, b: number): number {
    return a + b;
}

Google Apps Script to open a URL

Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.

It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers

Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.

The example in the HTML Service linked page is pretty simple,

Code.gs

// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

A customized version of index.html to show two hyperlinks

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>

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

Step 1: Copy paste these two functions in your java file.

 public void setDefaults(String key, String value, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }


    public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }

Step 2: to save use:

 setDefaults("key","value",this);

to retrieve use:

String retrieve= getDefaults("key",this);

You can set different shared preferences by using different key names like:

setDefaults("key1","xyz",this);

setDefaults("key2","abc",this);

setDefaults("key3","pqr",this);

Find duplicate records in a table using SQL Server

To get the list of multiple records use following command

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

FIX CSS <!--[if lt IE 8]> in IE

If you want this to work in IE 8 and below, use

<!--[if lte IE 8]>

lte meaning "Less than or equal".

For more on conditional comments, see e.g. the quirksmode.org page.

How to backup MySQL database in PHP?

@T.Todua's answer. It's cool. However, it failed to backup my database correctly. Hence, I've modified it. Please use like so: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" ); Thank you.

 <?php            
/**========================================================+
 *                                                         +
 * Static class with functions for backing up database.    +
 *                                                         +
 * PHP Version 5.6.31                                      +
 *=========================================================+*/ 
class Backup_Mysql_Db
{ 
private function __construct() {}  
/**Initializes the database backup
 * @param String $host mysql hostname
 * @param String $user mysql user
 * @param String $pass mysql password
 * @param String $name name of database
 * @param String $outputDir the path to the output directory for storing the backup file
 * @param Array $tables (optional) to backup specific tables only,like: array("mytable1","mytable2",...)  
 * @param String $backup_name (optional) backup filename (otherwise, it creates random name) 
 * EXAMPLE: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );  
*/  
public static function init($host,$user,$pass,$name, $outputDir, $tables=false, $backup_name=false)
{
    set_time_limit(3000); 
    $mysqli = new mysqli($host,$user,$pass,$name); 
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    //change database to $name
    $mysqli->select_db($name);  
    /* change character set to utf8 */
    if (!$mysqli->set_charset("utf8")) 
    {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
    }  
    //list all tables in the database
    $queryTables = $mysqli->query('SHOW TABLES'); 
    while($row = $queryTables->fetch_row()) 
    { 
        $target_tables[] = $row[0];  
    }
    //if user opted to backup specific tables only
    if($tables !== false) 
    { 
        $target_tables = array_intersect( $target_tables, $tables); 
    }  
    date_default_timezone_set('Africa/Accra');//set your timezone
    //$content is the text data to be written to the file for backup
    $content = "-- phpMyAdmin SQL Dump\r\n-- version 4.7.4". //insert your phpMyAdmin version 
           "\r\n-- https://www.phpmyadmin.net/\r\n--\r\n-- Host: ".$host.
           "\r\n-- Generation Time: ".date('M d, Y \a\t h:i A',strtotime(date('Y-m-d H:i:s', time()))).
           "\r\n-- Server version: ".$mysqli->server_info.
           "\r\n-- PHP Version: ". phpversion();
    $content .= "\r\n\r\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET AUTOCOMMIT = 0;\r\nSTART TRANSACTION;\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n\r\n--\r\n-- Database: `".
                $name."`\r\n--\r\nCREATE DATABASE IF NOT EXISTS `".
                $name."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\r\nUSE `".
                $name."`;"; 
    //traverse through every table in the database
    foreach($target_tables as $table)
    {
        if (empty($table)){ continue; } 
        $result = $mysqli->query('SELECT * FROM `'.$table.'`');     
        //get the number of columns
        $fields_amount=$result->field_count;
        //get the number of affected rows in the MySQL operation
        $rows_num=$mysqli->affected_rows;   
        //Retrieve the Table Definition of the existing table 
        $res = $mysqli->query('SHOW CREATE TABLE '.$table); 
        $TableMLine=$res->fetch_row(); 
        $content .= "\r\n\r\n-- --------------------------------------------------------\r\n\r\n"."--\r\n-- Table structure for table `".$table."`\r\n--\r\n\r\n";
        //if the table is not empty
        if(!self::table_is_empty($table,$mysqli))  
        {   $content .= $TableMLine[1].";\n\n";//append the Table Definition 
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this  
            $content .= "--\r\n-- Dumping data for table `".$table."`\r\n--\r\n"; 
            $content .= "\nINSERT INTO `".$table."` (".self::get_columns_from_table($table, $mysqli)." ) VALUES\r\n".self::get_values_from_table($table,$mysqli); 
        } 
        else//otherwise if the table is empty
        {
            $content .= $TableMLine[1].";";  
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this  
        } 
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    date_default_timezone_set('Africa/Accra');
    //format the time at this very moment and get rid of the colon ( windows doesn't allow colons in filenames)
    $date = str_replace(":", "-", date('jS M, y. h:i:s A.',strtotime(date('Y-m-d H:i:s', time())))); 
    //if there's a backup name, use it , otherwise device one
    $backup_name = $backup_name ? $backup_name : $name.'___('.$date.').sql'; 
    //Get current buffer contents and delete current output buffer
    ob_get_clean();     
    self::saveFile($content, $backup_name, $outputDir); 
    exit; 
}

/** Save data to file. 
 * @param String $data The text data to be stored in the file 
 * @param String $backup_name The name of the backup file 
 * @param String $outputDir (optional) The directory to save the file to. 
 * If unspecified, will save in the current directory. 
 * */ 
private static function saveFile(&$data,$backup_name, $outputDir = '.') 
{
    if (!$data)
    {
        return false; 
    } 
    try 
    { 
        $handle = fopen($outputDir . '/'. $backup_name , 'w+');
        fwrite($handle, $data);
        fclose($handle);
    } catch (Exception $e) 
    {
      var_dump($e->getMessage());
      return false;
    }
    return true;
}
/**Checks if table is empty
 * @param String $table table in mysql database
 * @return Boolean true if table is empty, false otherwise   
*/ 
private static function table_is_empty($table,$mysqli)
{
    $sql = "SELECT * FROM $table";
    $result = mysqli_query($mysqli, $sql);  
    if($result) 
    {    
        if(mysqli_num_rows($result) > 0)
        {  
            return false; 
        }
        else 
        {    
            return true; 
        }
    }
    return false;  
}
/**Retrieves the columns in the table 
 * @param String $table table in mysql database
 * @return String a list of all the columns in the right format    
*/ 
private static function get_columns_from_table($table, $mysqli)
{ 
    $column_header = "";
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");  
    while($row = $result->fetch_row()) 
    { 
        $column_header .= "`".$row[0]."`, "; 
    }
    //remove leading and trailing whitespace, and remove the last comma in the string
    return rtrim(trim($column_header),','); 
} 

/**Retrieves the values in the table row by row in the table 
 * @param String $table table in mysql database
 * @return String a list of all the values in the table in the right format    
*/
private static function get_values_from_table($table, $mysqli)
{
    $values = ""; 
    $columns = [];
    //get all the columns in the table
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");  
    while($row = $result->fetch_row()) 
    { 
        array_push($columns,$row[0] ); 
    } 

    $result1 = mysqli_query($mysqli, "SELECT * FROM $table");  
    //while traversing every row in the table(row by row)
    while($row = mysqli_fetch_array($result1))
    {   $values .= "("; 
        //get the values in each column
        foreach($columns as $col)
        {               //if the value is an Integer
            $values .=  (self::column_is_of_int_type($table, $col,$mysqli)? 
                    $row["$col"].", "://do not surround it with single quotes
                    "'".$row["$col"]."', "); //otherwise, surround it with single quotes 
        }   
        $values = rtrim(trim($values),','). "),\r\n";  
    }  
    return rtrim(trim($values),',').";"; 
}

/**Checks if the data type in the column is an integer
 * @param String $table table in mysql database
 * @return Boolean true if it is an integer, false otherwise. 
*/
private static function column_is_of_int_type($table, $column,$mysqli)
{
    $q = mysqli_query($mysqli,"DESCRIBE $table");  
    while($row = mysqli_fetch_array($q)) 
    {
        if ($column === "{$row['Field']}")
        {
            if (strpos("{$row['Type']}", 'int') !== false) 
            {
                return true;
            }
        } 
    }
    return false; 
} 

}

How to download image using requests

This is the first response that comes up for google searches on how to download a binary file with requests. In case you need to download an arbitrary file with requests, you can use:

import requests
url = 'https://s3.amazonaws.com/lab-data-collections/GoogleNews-vectors-negative300.bin.gz'
open('GoogleNews-vectors-negative300.bin.gz', 'wb').write(requests.get(url, allow_redirects=True).content)

How to programmatically tell if a Bluetooth device is connected?

Add bluetooth permission to your AndroidManifest,

<uses-permission android:name="android.permission.BLUETOOTH" />

Then use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:

public void onCreate() {
    ...
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};

A few notes:

  • There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to QUERY, instead it allows you to listen to CHANGES.
  • A hoaky work around to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
  • Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.

How to change the URL from "localhost" to something else, on a local system using wampserver?

This method will work for xamp/wamp/lamp

  1. 1st go to your server directory, for example, C:\xamp
  2. 2nd go to apache/conf/extra and open httpd-vhosts.conf
  3. 3rd add following code to this file
 <VirtualHost myWebsite.local>
        DocumentRoot "C:/wamp/www/php-bugs/"
        ServerName php-bugs.local
        ServerAlias php-bugs.local
        <Directory "C:/wamp/www/php-bugs/">
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>

For DocumentRoot and Directory add your local directory For ServerName and ServerAlias give your server a name

  1. Finally go to C:/Windows/System32/drivers/etc and open hosts file
    add 127.0.0.1 php-bugs.local and nothing else

  2. For the finishing touch restart your server

    For Multile local domain add another section of code into httpd-vhosts.conf

 <VirtualHost myWebsite.local>
        DocumentRoot "C:/wamp/www/php-bugs2/"
        ServerName php-bugs.local2
        ServerAlias php-bugs.local2
        <Directory "C:/wamp/www/php-bugs2/">
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>

and add your host into host file 127.0.0.1 php-bugs.local2

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Filter element based on .data() key/value

Sounds like more work than its worth.

1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.

2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.

Do you have the key backed up somewhere?

Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.

How to check if a string in Python is in ASCII?

You could use the regular expression library which accepts the Posix standard [[:ASCII:]] definition.

Epoch vs Iteration when training neural networks

To my understanding, when you need to train a NN, you need a large dataset involves many data items. when NN is being trained, data items go in to NN one by one, that is called an iteration; When the whole dataset goes through, it is called an epoch.

Find index of last occurrence of a substring in a string

Use the str.rindex method.

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

IntelliJ does not show project folders

So after asking another question, someone helped me figure out that under File > Project Structure > Modules, there's supposed to be stuff there. If it's empty (says "Nothing to show"), do the following:

  1. In File > Project Structure > Modules, click the "+" button,
  2. Press Enter (because weirdly it won't let me click on "New Module") step 2
  3. In the window that pops up, click on the "..." next button which takes you to the Content root. Find your root folder and select it step 3 part 1 step 3
  4. Click the "ok" button
  5. Ignore any warning that says the name is already in use

How To limit the number of characters in JTextField?

Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.

This solution will work an any Document, not just a PlainDocument.

This is a more current solution than the one accepted.

How do I float a div to the center?

Give the DIV a specific with in percentage or pixels and center it using CSS margin property.

HTML

<div id="my-main-div"></div>

CSS

#my-main-div { margin: 0 auto; }

enjoy :)

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Most updated solution

If you are using Javascript, the best solution that I came up with is using match instead of exec method. Then, iterate matches and remove the delimiters with the result of the first group using $1

const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]

As you can see, this is useful for multiple delimiters in the text as well

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Auto height div with overflow and scroll when needed

Well, after long research, i found a workaround that does what i need: http://jsfiddle.net/CqB3d/25/

CSS:

body{
    margin: 0;
    padding: 0;
    border: 0;
    overflow: hidden;
    height: 100%; 
    max-height: 100%; 
}

#caixa{
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}
#framecontentTop, #framecontentBottom{
    position: absolute; 
    top: 0;   
    width: 800px; 
    height: 100px; /*Height of top frame div*/
    overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
    background-color: navy;
    color: white; 
}

#framecontentBottom{
    top: auto;
    bottom: 0; 
    height: 110px; /*Height of bottom frame div*/
    overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
    background-color: navy;
    color: white;
}

#maincontent{
    position: fixed; 
    top: 100px; /*Set top value to HeightOfTopFrameDiv*/
    margin-left:auto;
    margin-right: auto;
    bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/
    overflow: auto; 
    background: #fff;
    width: 800px;
}

.innertube{
    margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/
}

* html body{ /*IE6 hack*/
    padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/
}

* html #maincontent{ /*IE6 hack*/
    height: 100%; 
    width: 800px; 
}

HTML:

<div id="framecontentBottom">
    <div class="innertube">
        <h3>Sample text here</h3>
    </div>
</div>
<div id="maincontent">
    <div class="innertube">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text...
    </div>
</div>

might not work with the horizontal thingy yet, but, it's a work in progress!

I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.

Hope this might help whoever finds the question later!

EDIT: This is the final answer.

Can an Option in a Select tag carry multiple values?

In HTML

<SELECT NAME="Testing" id="Testing">  
  <OPTION VALUE="1,2010"> One  
  <OPTION VALUE="2,2122"> Two  
  <OPTION VALUE="3,0"> Three
</SELECT>

For JS

  var valueOne= $('#Testing').val().split(',')[0];
  var valueTwo =$('#Testing').val().split(',')[1];
  console.log(valueOne); //output 1
  console.log(valueTwo); //output 2010

OR FOR PHP

  $selectedValue= explode(',', $value);
  $valueOne= $exploded_value[0]; //output 1
  $valueTwo= $exploded_value[1]; //output 2010

How to convert a std::string to const char* or char*?

Just see this:

string str1("stackoverflow");
const char * str2 = str1.c_str();

However, note that this will return a const char *.

For a char *, use strcpy to copy it into another char array.

What are MVP and MVC and what is the difference?

MVP

MVP stands for Model - View- Presenter. This came to a picture in early 2007 where Microsoft introduced Smart Client windows applications.

A presenter is acting as a supervisory role in MVP which binding View events and business logic from models.

View event binding will be implemented in the Presenter from a view interface.

The view is the initiator for user inputs and then delegates the events to the Presenter and the presenter handles event bindings and gets data from models.

Pros: The view is having only UI not any logics High level of testability

Cons: Bit complex and more work when implementing event bindings

MVC

MVC stands for Model-View-Controller. Controller is responsible for creating models and rendering views with binding models.

Controller is the initiator and it decides which view to render.

Pros: Emphasis on Single Responsibility Principle High level of testability

Cons: Sometimes too much workload for Controllers, if try to render multiple views in same controller.

How to Display blob (.pdf) in an AngularJS app

I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.

Most of the questions have the same components, but it took a while to figure out the right order to make it work.

Thank you @Nikolay Melnikov, your comment/reply to this question was what made it work.

In a nutshell, here is my AngularJS Service backend call:

  getDownloadUrl(fileID){
    //
    //Get the download url of the file
    let fullPath = this.paths.downloadServerURL + fileId;
    //
    // return the file as arraybuffer 
    return this.$http.get(fullPath, {
      headers: {
        'Authorization': 'Bearer ' + this.sessionService.getToken()
      },
      responseType: 'arraybuffer'
    });
  }

From my controller:

downloadFile(){
   myService.getDownloadUrl(idOfTheFile).then( (response) => {
      //Create a new blob object
      let myBlobObject=new Blob([response.data],{ type:'application/pdf'});

      //Ideally the mime type can change based on the file extension
      //let myBlobObject=new Blob([response.data],{ type: mimeType});

      var url = window.URL || window.webkitURL
      var fileURL = url.createObjectURL(myBlobObject);
      var downloadLink = angular.element('<a></a>');
      downloadLink.attr('href',fileURL);
      downloadLink.attr('download',this.myFilesObj[documentId].name);
      downloadLink.attr('target','_self');
      downloadLink[0].click();//call click function
      url.revokeObjectURL(fileURL);//revoke the object from URL
    });
}

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

Ho i simply solved this issue by going to source control explorer and selected the issue project, right clicked and selected the option Get Specific Version under Advanced menu. And then selected Type as Latest Version and ticked following two check boxes and clicked Get button. Then i refreshed the solution and my project came back to live and problem gone. Please note that This may overwrite your local projects so your current changes may lose. So if you dont have any issues with your local copy then you can try this. Hope it helps

C# DataRow Empty-check

To delete null and also empty entries Try this

  foreach (var column in drEntitity.Columns.Cast<DataColumn>().ToArray())
            {
                if (drEntitity.AsEnumerable().All(dr => dr.IsNull(column) | string.IsNullOrEmpty( dr[column].ToString())))
                    drEntitity.Columns.Remove(column);
            }

Select rows where column is null

for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :

**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **

Datatables - Search Box outside datatable

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

merge one local branch into another local branch

First, checkout to your Branch3:

git checkout Branch3

Then merge the Branch1:

git merge Branch1

And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase

git checkout Branch2
git rebase Branch1

This will update your Branch2 with the latest updates of Branch1.

node.js - how to write an array to file

Remember you can access good old ECMAScript APIs, in this case, JSON.stringify().

For simple arrays like the one in your example:

require('fs').writeFile(

    './my.json',

    JSON.stringify(myArray),

    function (err) {
        if (err) {
            console.error('Crap happens');
        }
    }
);

docker unauthorized: authentication required - upon push with successful login

Though the standard process is to login and then push to docker registry, trick to get over this particular problem is to login by providing username and password in same line.

So :

docker login -u xxx -p yyy sampledockerregistry.com/myapp 
docker push sampledockerregistry.com/myapp

Works

whereas

docker login sampledockerregistry.com 
username : xxx
password : yyy
Login Succeeded

docker push sampledockerregistry.com/myapp

Fails

Finding a branch point with Git?

Not quite a solution to the question but I thought it was worth noting the the approach I use when I have a long-living branch:

At the same time I create the branch, I also create a tag with the same name but with an -init suffix, for example feature-branch and feature-branch-init.

(It is kind of bizarre that this is such a hard question to answer!)

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I was experiencing the same problem on OS X. I've solved it now. I post my solution here for anyone who has the similar issue.

Firstly, I set the password for root in mysql client:

shell> mysql -u root
mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MY_PASSWORD');

Then, I checked the version info:

shell> /usr/local/mysql/bin/mysqladmin -u root -p version
...
Server version    5.6.26
Protocol version  10
Connection        Localhost via UNIX socket
UNIX socket       /tmp/mysql.sock
Uptime:           11 min 0 sec
...

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'socket';
$cfg['Servers'][$i]['socket'] = '/tmp/mysql.sock';

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Just letting you all know I had this problem too. Rather than the code, the issue lay with what macro a button was calling. (It had been calling the 'createroutes.createroutes' macro, but I had renamed the 'createroutes' module to 'routes'.) Therefore the problem was fixed by pointing the button to the correct location.

How to import and export components using React + ES6 + webpack?

MDN has really nice documentation for all the new ways to import and export modules is ES 6 Import-MDN . A brief description of it in regards to your question you could've either:

  1. Declared the component you were exporting as the 'default' component that this module was exporting: export default class MyNavbar extends React.Component { , and so when Importing your 'MyNavbar' you DON'T have to put curly braces around it : import MyNavbar from './comp/my-navbar.jsx';. Not putting curly braces around an import though is telling the document that this component was declared as an 'export default'. If it wasn't you'll get an error (as you did).

  2. If you didn't want to declare your 'MyNavbar' as a default export when exporting it : export class MyNavbar extends React.Component { , then you would have to wrap your import of 'MyNavbar in curly braces: import {MyNavbar} from './comp/my-navbar.jsx';

I think that since you only had one component in your './comp/my-navbar.jsx' file it's cool to make it the default export. If you'd had more components like MyNavbar1, MyNavbar2, MyNavbar3 then I wouldn't make either or them a default and to import selected components of a module when the module hasn't declared any one thing a default you can use: import {foo, bar} from "my-module"; where foo and bar are multiple members of your module.

Definitely read the MDN doc it has good examples for the syntax. Hopefully this helps with a little more of an explanation for anyone that's looking to toy with ES 6 and component import/exports in React.

Java: How To Call Non Static Method From Main Method?

You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

Android: textview hyperlink

What about data binding?

@JvmStatic
@BindingAdapter("textHtml")
fun setHtml(textView: TextView, resource: String) {
    val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
    } else {
        Html.fromHtml(resource)
    }

    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.text = html
}

strings.xml

<string name="text_with_link">&lt;a href=%2$s>%1$s&lt;/a> </string>

in your layout.xml

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:textHtml="@{@string/text_with_link(model.title, model.url)}"
            tools:text="Some text" />

Where title and link in xml is a simple String

Also you can pass multiple arguments to data binding adapter

@JvmStatic
@BindingAdapter(value = ["textLink", "link"], requireAll = true)
fun setHtml(textView: TextView, textLink: String?, link: String?) {
    val resource = String.format(textView.context.getString(R.string.text_with_link, textLink, link))

    val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
    } else {
        Html.fromHtml(resource)
    }

    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.text = html
}

and in .xml pass arguments separately

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:link="@{model.url}"
            app:textLink="@{model.title}"
            tools:text="Some text" />

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Remove/ truncate leading zeros by javascript/jquery

Simply try to multiply by one as following:

"00123" * 1;              // Get as number
"00123" * 1 + "";       // Get as string

How to overwrite existing files in batch?

If destination file is read only use /y/r

xcopy /y/r source.txt dest.txt

HTTP test server accepting GET/POST requests

You might don't need any web site for that, only open up the browser, press F12 to get access to developer tools > console, then in console write some JavaScript Code to do that.

Here I share some ways to accomplish that:

For GET request: *.Using jQuery:

$.get("http://someurl/status/?messageid=597574445", function(data, status){
    console.log(data, status);
  });

For POST request: 1. Using jQuery $.ajax:

var url= "http://someurl/",
        api_key = "6136-bc16-49fb-bacb-802358",
        token1 = "Just for test",
        result;
    $.ajax({
          url: url,
          type: "POST",
          data: {
            api_key: api_key,
            token1: token1
          },
        }).done(function(result) {
                console.log("done successfuly", result);
        }).fail(function(error) {

          console.log(error.responseText, error);

        });
  1. Using jQuery, append and submit

     var merchantId = "AA86E",
            token = "4107120133142729",
            url = "https://payment.com/Index";
    
        var form = `<form id="send-by-post" method="post" action="${url}">
                                    <input id="token" type="hidden" name="token" value="${merchantId}"/>
                                    <input id="merchantId" name="merchantId" type="hidden" value="${token}"/>
                                    <button type="submit" >Pay</button>
                        </div>
                    </form> `; 
        $('body').append(form);
        $("#send-by-post").submit();//Or $(form).appendTo("body").submit();
    
    1. Using Pure JavaScript:

    var api_key = "73736-bc16-49fb-bacb-643e58", recipient = "095552565", token1 = "4458", url = 'http://smspanel.com/send/';

var form = `<form id="send-by-post" method="post" action="${url}"> <input id="api_key" type="hidden" name="api_key" value="${api_key}"/> <input id="recipient" type="hidden" name="recipient" value="${recipient}"/> <input id="token1" name="token1" type="hidden" value="${token1}"/> <button type="submit" >Send</button> </div> </form>`;

document.querySelector("body").insertAdjacentHTML('beforeend',form);
document.querySelector("#send-by-post").submit();
  1. Or even using ASP.Net:

    var url = "https://Payment.com/index"; Response.Clear(); var sb = new System.Text.StringBuilder();

    sb.Append(""); sb.AppendFormat(""); sb.AppendFormat("", url); sb.AppendFormat("", "C668"); sb.AppendFormat("", "22720281459"); sb.Append(""); sb.Append(""); sb.Append(""); Response.Write(sb.ToString()); Response.End();

(Note: Since I have backtick character (`) in my code the code format ruined, I have no idea how to correct it)

Powershell script to locate specific file/file name?

Assuming you have a Z: drive mapped:

Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }

Extracting .jar file with command line

Given a file named Me.Jar:

  1. Go to cmd
  2. Hit Enter
  3. Use the Java jar command -- I am using jdk1.8.0_31 so I would type

    C:\Program Files (x86)\Java\jdk1.8.0_31\bin\jar xf me.jar

That should extract the file to the folder bin. Look for the file .class in my case my Me.jar contains a Valentine.class

Type java Valentine and press Enter and your message file will be opened.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

Benefits of inline functions in C++?

Generally speaking, these days with any modern compiler worrying about inlining anything is pretty much a waste of time. The compiler should actually optimize all of these considerations for you through its own analysis of the code and your specification of the optimization flags passed to the compiler. If you care about speed, tell the compiler to optimize for speed. If you care about space, tell the compiler to optimize for space. As another answer alluded to, a decent compiler will even inline automatically if it really makes sense.

Also, as others have stated, using inline does not guarantee inline of anything. If you want to guarantee it, you will have to define a macro instead of an inline function to do it.

When to inline and/or define a macro to force inclusion? - Only when you have a demonstrated and necessary proven increase in speed for a critical section of code that is known to have an affect on the overall performance of the application.

Web Reference vs. Service Reference

If I understand your question right:

To add a .net 2.0 Web Service Reference instead of a WCF Service Reference, right-click on your project and click 'Add Service Reference.'

Then click "Advanced.." at the bottom left of the dialog.

Then click "Add Web Reference.." on the bottom left of the next dialog.

Now you can add a regular SOAP web reference like you are looking for.

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

How to destroy an object?

This is a simple prove that you cannot destroy an object, you can only destroy a link to it.

$var = (object)['a'=>1];
$var2 = $var;
$var2->a = 2;
unset($var2);
echo $var->a;

returns

2

See it in action here: https://eval.in/1054130

How can I add new array elements at the beginning of an array in Javascript?

you can reverse your array and push the data , at the end again reverse it:

var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

IntelliJ IDEA JDK configuration on Mac OS

Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/ appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...

I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk in my case)

And voila, IntelliJ can find everything from that point on.

Dynamically converting java object of Object class to a given class when class name is known

@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
    return (T) obj;
}

CURL alternative in Python

import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

Install msi with msiexec in a Specific Directory

Actually, both INSTALLPATH/TARGETDIR are correct. It depends on how MSI processes this.

I create a MSG using wixToolSet. In WXS file, there is "Directory" Node, which root dir maybe like the following:

<Directory Id="**TARGETDIR**" Name="SourceDir">;

As you can see: Id is which you should use.

How to get element's width/height within directives and component?

For a bit more flexibility than with micronyks answer, you can do it like that:

1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

<p #myIdentifier>
  my-component works!
</p>

2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}

Security

About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

MySQL: Get column name or alias from query

I think this should do what you need (builds on the answer above) . I am sure theres a more pythony way to write it, but you should get the general idea.

cursor.execute(query)
columns = cursor.description
result = []
for value in cursor.fetchall():
    tmp = {}
    for (index,column) in enumerate(value):
        tmp[columns[index][0]] = column
    result.append(tmp)
pprint.pprint(result)

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

i simply change my import from import from { AngularFirestore} from '@angular/fire/firestore'; to import { AngularFirestoreModule } from '@angular/fire/firestore';

and it's working fine

How can I add spaces between two <input> lines using CSS?

CSS:

form div {
  padding: x; /*default div padding in the form e.g. 5px 0 5px 0*/
  margin: y; /*default div padding in the form e.g. 5px 0 5px 0*/
}
.divForText { /*For Text line only*/
  padding: a;
  margin: b;
}
.divForLabelInput{ /*For Text and Input line */
  padding: c;
  margin: d;
}
.divForInput{ /*For Input line only*/
  padding: e;
  margin: f;
}

HTML:

<div class="divForText">some text</div>
<input ..... />
<div class="divForLabelInput">some label <input ... /></div>
<div class="divForInput"><input ... /></div>

Eclipse Error: "Failed to connect to remote VM"

I get this error for Weblogic after i installed Quicktime and removing QTJava.zip from classpath solves the problem.

https://blogs.oracle.com/adfjdev/entry/java_jre7_lib_ext_qtjava

Specifying colClasses in the read.csv

If you want to refer to names from the header rather than column numbers, you can use something like this:

fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)

Apply style ONLY on IE

For /* Internet Explorer 9+ (one-liner) */

_::selection, .selector { property:value\0; }

Only this solution perfectly work for me.

Regular expression for extracting tag attributes

You cannot use the same name for multiple captures. Thus you cannot use a quantifier on expressions with named captures.

So either don’t use named captures:

(?:(\b\w+\b)\s*=\s*("[^"]*"|'[^']*'|[^"'<>\s]+)\s+)+

Or don’t use the quantifier on this expression:

(?<name>\b\w+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'|[^"'<>\s]+)

This does also allow attribute values like bar=' baz='quux:

foo="bar=' baz='quux"

Well the drawback will be that you have to strip the leading and trailing quotes afterwards.

convert date string to mysql datetime field

$time = strtotime($oldtime);

Then use date() to put it into the correct format.

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

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);

DataTables: Cannot read property style of undefined

Make sure that in your input data, response[i] and response[i][j], are not undefined/null.

If so, replace them with "".

SQL alias for SELECT statement

You could store this into a temporary table.

So instead of doing the CTE/sub query you would use a temp table.

Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

When do I need to do "git pull", before or after "git add, git commit"?

You want your change to sit on top of the current state of the remote branch. So probably you want to pull right before you commit yourself. After that, push your changes again.

"Dirty" local files are not an issue as long as there aren't any conflicts with the remote branch. If there are conflicts though, the merge will fail, so there is no risk or danger in pulling before committing local changes.

Get record counts for all tables in MySQL database

Based on @Nathan's answer above, but without needing to "remove the final union" and with the option to sort the output, I use the following SQL. It generates another SQL statement which then just run:

select CONCAT( 'select * from (\n', group_concat( single_select SEPARATOR ' UNION\n'), '\n ) Q order by Q.exact_row_count desc') as sql_query
from (
    SELECT CONCAT(
        'SELECT "', 
        table_name, 
        '" AS table_name, COUNT(1) AS exact_row_count
        FROM `', 
        table_schema,
        '`.`',
        table_name, 
        '`'
    ) as single_select
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE table_schema = 'YOUR_SCHEMA_NAME'
      and table_type = 'BASE TABLE'
) Q 

You do need a sufficiently large value of group_concat_max_len server variable but from MariaDb 10.2.4 it should default to 1M.

Mysql database sync between two databases

Replication is not very hard to create.

Here's some good tutorials:

http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/

http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html

http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication

Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):

  1. Setup 1 server (master) for writing data.
  2. Setup 1 or more servers (slaves) for reading data.

This way, you will avoid errors.

For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.

You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.

NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).

I would recommend to monitor your servers to make sure everything is fine.

Let me know if you need additional help

How to access local files of the filesystem in the Android emulator?

Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.

Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

CSS opacity only to background color, not the text on it?

My trick is to create a transparent .png with the color and use background:url().

Passing data between view controllers

I have seen a lot of people over complicating this using the didSelectRowAtPath method. I am using Core Data in my example.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // This solution is for using Core Data
    YourCDEntityName * value = (YourCDEntityName *)[[self fetchedResultsController] objectAtIndexPath: indexPath];

    YourSecondViewController * details = [self.storyboard instantiateViewControllerWithIdentifier:@"nameOfYourSecondVC"]; // Make sure in storyboards you give your second VC an identifier

    // Make sure you declare your value in the second view controller
    details.selectedValue = value;

    // Now that you have said to pass value all you need to do is change views
    [self.navigationController pushViewController: details animated:YES];

}

Four lines of code inside the method and you are done.

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

#include <sys/types.h>
#include <sys/stat.h>

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

A good Sorted List for Java

GlazedLists has a very, very good sorted list implementation

There was no endpoint listening at (url) that could accept the message

If you are using custom binding, please make sure that you are putting the same name for both custom binding (Server and Client)in config files

<bindings>
<customBinding>
 <binding name="BufferedHttpServerNoAuth" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <gzipMessageEncoding innerMessageEncoding="textMessageEncoding" MaxArrayLength="10485760" MaxBytesPerRead="31457280" MaxStringContentLength="102400000" />
          <httpsTransport hostNameComparisonMode="StrongWildcard" manualAddressing="False" maxReceivedMessageSize="31457280" authenticationScheme="Anonymous" bypassProxyOnLocal="True" realm="" useDefaultWebProxy="False" />
</binding>
</customBinding>
</bindings>

the binding name "BufferedHttpServerNoAuth" should be same in both.

Hope this would help someone

Maintaining Session through Angular.js

You can also try to make service based on window.sessionStorage or window.localStorage to keep state information between page reloads. I use it in the web app which is partially made in AngularJS and page URL is changed in "the old way" for some parts of workflow. Web storage is supported even by IE8. Here is angular-webstorage for convenience.

How do you extract IP addresses from files using a regex in a linux shell?

You could use awk, as well. Something like ...

awk '{i=1; if (NF > 0) do {if ($i ~ /regexp/) print $i; i++;} while (i <= NF);}' file

May require cleaning. just a quick and dirty response to shows basically how to do it with awk.

Convert date from String to Date format in Dataframes

I solved the same problem without the temp table/view and with dataframe functions.

Of course I found that only one format works with this solution and that's yyyy-MM-DD.

For example:

val df = sc.parallelize(Seq("2016-08-26")).toDF("Id")
val df2 = df.withColumn("Timestamp", (col("Id").cast("timestamp")))
val df3 = df2.withColumn("Date", (col("Id").cast("date")))

df3.printSchema

root
 |-- Id: string (nullable = true)
 |-- Timestamp: timestamp (nullable = true)
 |-- Date: date (nullable = true)

df3.show

+----------+--------------------+----------+
|        Id|           Timestamp|      Date|
+----------+--------------------+----------+
|2016-08-26|2016-08-26 00:00:...|2016-08-26|
+----------+--------------------+----------+

The timestamp of course has 00:00:00.0 as a time value.

What tools do you use to test your public REST API?

http://www.quadrillian.com/ this enables you to create an entire test suite for your API and run it from your browser and share it with others.

How to play videos in android from assets folder or raw folder?

In the fileName you must put the relative path to the file (without /asset) for example:

player.setDataSource(
    getAssets().openFd(**"media/video.mp4"**).getFileDescriptor()
);

MySQL Sum() multiple columns

//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns

SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'

What is the best way to remove the first element from an array?

Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.

int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);

Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.

An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

Checking for empty queryset in Django

If you have a huge number of objects, this can (at times) be much faster:

try:
    orgs[0]
    # If you get here, it exists...
except IndexError:
    # Doesn't exist!

On a project I'm working on with a huge database, not orgs is 400+ ms and orgs.count() is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)

Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.

EDIT: This will often be slower than orgs.count() if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)

How to get a variable type in Typescript?

Type guards in typescript

To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:

An expression which allows you to narrow down the type of something within a conditional block.

In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.

Example

declare let abc: number | string;

// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
    // abc: string
    console.log('abc is a string here')
} else {
    // abc: number, only option because the previous type guard removed the option of string
    console.log('abc is a number here')
}

Besides the typeof operator there are built in type guards like instanceof, in and even your own type guards.

Print to standard printer from Python?

This has only been tested on Windows:

You can do the following:

import os

os.startfile("C:/Users/TestFile.txt", "print")

This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os module which comes with the standard library

static files with express.js

npm install serve-index

var express    = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))

// Listen
app.listen(port,  function () {
  console.log('listening on port:',+ port );
})

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

Background blur with CSS

In which way do you want it dynamic? If you want the popup to successfully map to the background, you need to create two backgrounds. It requires both the use of element() or -moz-element() and a filter (for Firefox, use a SVG filter like filter: url(#svgBlur) since Firefox does not support -moz-filter: blur() as yet?). It only works in Firefox at the time of writing.

See demo here.

I still need to create a simple demo to show how it is done. You're welcome to view the source.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Convert generic list to dataset in C#

Brute force code to answer your question:

DataTable dt = new DataTable();

//for each of your properties
dt.Columns.Add("PropertyOne", typeof(string));

foreach(Entity entity in entities)
{
  DataRow row = dt.NewRow();

  //foreach of your properties
  row["PropertyOne"] = entity.PropertyOne;

  dt.Rows.Add(row);
}

DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;

Now for the actual question. Why would you want to do this? As mentioned earlier, you can bind directly to an object list. Maybe a reporting tool that only takes datasets?

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

How do I automatically play a Youtube video (IFrame API) muted?

The player_api will be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API

It looks like the following code:

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

What does 'low in coupling and high in cohesion' mean

I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Copying files into the application folder at compile time

Personally I prefer this way.

Modify the .csproj to add

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\MyFirstConfigFile.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

or generalizing, if you want to copy all subfolders and files, you could do:

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\**">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(RecursiveDir)\%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

How to scroll to an element?

The nicest way is to use element.scrollIntoView({ behavior: 'smooth' }). This scrolls the element into view with a nice animation.

When you combine it with React's useRef(), it can be done the following way.

import React, { useRef } from 'react'

const Article = () => {
  const titleRef = useRef()

  function handleBackClick() {
      titleRef.current.scrollIntoView({ behavior: 'smooth' })
  }

  return (
      <article>
            <h1 ref={titleRef}>
                A React article for Latin readers
            </h1>

            // Rest of the article's content...

            <button onClick={handleBackClick}>
                Back to the top
            </button>
        </article>
    )
}

When you would like to scroll to a React component, you need to forward the ref to the rendered element. This article will dive deeper into the problem.

jQuery autoComplete view all on click?

I found this to work best

var data = [
    { label: "Choice 1", value: "choice_1" },
    { label: "Choice 2", value: "choice_2" },
    { label: "Choice 3", value: "choice_3" }
];

$("#example")
.autocomplete({
    source: data,
    minLength: 0
})
.focus(function() {
    $(this).autocomplete('search', $(this).val())
});

It searches the labels and places the value into the element $(#example)

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

Try choosing project -> clean. A simple clean may fix it up.

How can I insert values into a table, using a subquery with more than one result?

Try this:

INSERT INTO prices (
    group, 
    id,
    price
) 
SELECT
    7,
    articleId,
    1.50
FROM
    article 
WHERE 
    name LIKE 'ABC%';

Error: package or namespace load failed for ggplot2 and for data.table

These steps work for me:

  1. Download the Rcpp manually from WebSite (https://cran.r-project.org/web/packages/Rcpp/index.html)
  2. unzip the folder/files to "Rcpp" folder
  3. Locate the "library" folder under R install directory Ex: C:\R\R-3.3.1\library
  4. Copy the "Rcpp" folder to Library folder.

Good to go!!!

library(Rcpp)
library(ggplot2) 

Is there shorthand for returning a default value if None in Python?

x or "default"

works best — i can even use a function call inline, without executing it twice or using extra variable:

self.lineEdit_path.setText( self.getDir(basepath) or basepath )

I use it when opening Qt's dialog.getExistingDirectory() and canceling, which returns empty string.

Convert char to int in C#

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

What is move semantics?

Here's an answer from the book "The C++ Programming Language" by Bjarne Stroustrup. If you don't want to see the video, you can see the text below:

Consider this snippet. Returning from an operator+ involves copying the result out of the local variable res and into someplace where the caller can access it.

Vector operator+(const Vector& a, const Vector& b)
{
    if (a.size()!=b.size())
        throw Vector_siz e_mismatch{};
    Vector res(a.size());
        for (int i=0; i!=a.size(); ++i)
            res[i]=a[i]+b[i];
    return res;
}

We didn’t really want a copy; we just wanted to get the result out of a function. So we need to move a Vector rather than to copy it. We can define move constructor as follows:

class Vector {
    // ...
    Vector(const Vector& a); // copy constructor
    Vector& operator=(const Vector& a); // copy assignment
    Vector(Vector&& a); // move constructor
    Vector& operator=(Vector&& a); // move assignment
};

Vector::Vector(Vector&& a)
    :elem{a.elem}, // "grab the elements" from a
    sz{a.sz}
{
    a.elem = nullptr; // now a has no elements
    a.sz = 0;
}

The && means "rvalue reference" and is a reference to which we can bind an rvalue. "rvalue"’ is intended to complement "lvalue" which roughly means "something that can appear on the left-hand side of an assignment." So an rvalue means roughly "a value that you can’t assign to", such as an integer returned by a function call, and the res local variable in operator+() for Vectors.

Now, the statement return res; will not copy!

Get timezone from users browser using moment(timezone).js

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

A Simple, 2d cross-platform graphics library for c or c++?

Heavy-weight:

  • GTK
  • QT
  • WxWidgets

Lightweight:

  • FLTK
  • Fox
  • Tk
  • Lua IUP
  • Ultimate++
  • dlib

Drawing frameworks without GUI widgets:

  • SDL
  • Cairo

Programmatically go back to the previous fragment in the backstack

To make that fragment come again, just add that fragment to backstack which you want to come on back pressed, Eg:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new LoginFragment();
        //replacing the fragment
        if (fragment != null) {
            FragmentTransaction ft = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.addToBackStack("SignupFragment");
            ft.commit();
        }
    }
});

In the above case, I am opening LoginFragment when Button button is pressed, right now the user is in SignupFragment. So if addToBackStack(TAG) is called, where TAG = "SignupFragment", then when back button is pressed in LoginFragment, we come back to SignUpFragment.

Happy Coding!

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Java: how can I split an ArrayList in multiple small ArrayLists?

You need to know the chunk size by which you're dividing your list. Say you have a list of 108 entries and you need a chunk size of 25. Thus you will end up with 5 lists:

  • 4 having 25 entries each;
  • 1 (the fifth) having 8 elements.

Code:

public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<108; i++){
            list.add(i);
        }
        int size= list.size();
        int j=0;
                List< List<Integer> > splittedList = new ArrayList<List<Integer>>()  ;
                List<Integer> tempList = new ArrayList<Integer>();
        for(j=0;j<size;j++){
            tempList.add(list.get(j));
        if((j+1)%25==0){
            // chunk of 25 created and clearing tempList
            splittedList.add(tempList);
            tempList = null;
            //intializing it again for new chunk 
            tempList = new ArrayList<Integer>();
        }
        }
        if(size%25!=0){
            //adding the remaining enteries 
            splittedList.add(tempList);
        }
        for (int k=0;k<splittedList.size(); k++){
            //(k+1) because we started from k=0
            System.out.println("Chunk number: "+(k+1)+" has elements = "+splittedList.get(k).size());
        }
    }

How to remove leading whitespace from each line in a file

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

List all tables in postgresql information_schema

You should be able to just run select * from information_schema.tables to get a listing of every table being managed by Postgres for a particular database.

You can also add a where table_schema = 'information_schema' to see just the tables in the information schema.

Best way to store time (hh:mm) in a database

Are you sure you will only ever need the hours and minutes? If you want to do anything meaningful with it (like for example compute time spans between two such data points) not having information about time zones and DST may give incorrect results. Time zones do maybe not apply in your case, but DST most certainly will.

Creating a daemon in Linux

Daemon Template

I wrote a daemon template following the new-style daemon: link

You can find the entire template code on GitHub: here

Main.cpp

// This function will be called when the daemon receive a SIGHUP signal.
void reload() {
    LOG_INFO("Reload function called.");
}

int main(int argc, char **argv) {
    // The Daemon class is a singleton to avoid be instantiate more than once
    Daemon& daemon = Daemon::instance();
    // Set the reload function to be called in case of receiving a SIGHUP signal
    daemon.setReloadFunction(reload);
    // Daemon main loop
    int count = 0;
    while(daemon.IsRunning()) {
        LOG_DEBUG("Count: ", count++);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    LOG_INFO("The daemon process ended gracefully.");
}

Daemon.hpp

class Daemon {
    public:

    static Daemon& instance() {
        static Daemon instance;
        return instance;
    }

    void setReloadFunction(std::function<void()> func);

    bool IsRunning();

    private:

    std::function<void()> m_reloadFunc;
    bool m_isRunning;
    bool m_reload;

    Daemon();
    Daemon(Daemon const&) = delete;
    void operator=(Daemon const&) = delete;

    void Reload();

    static void signalHandler(int signal);
};

Daemon.cpp

Daemon::Daemon() {
    m_isRunning = true;
    m_reload = false;
    signal(SIGINT, Daemon::signalHandler);
    signal(SIGTERM, Daemon::signalHandler);
    signal(SIGHUP, Daemon::signalHandler);
}

void Daemon::setReloadFunction(std::function<void()> func) {
    m_reloadFunc = func;
}

bool Daemon::IsRunning() {
    if (m_reload) {
        m_reload = false;
        m_reloadFunc();
    }
    return m_isRunning;
}

void Daemon::signalHandler(int signal) {
    LOG_INFO("Interrup signal number [", signal,"] recived.");
    switch(signal) {
        case SIGINT:
        case SIGTERM: {
            Daemon::instance().m_isRunning = false;
            break;
        }
        case SIGHUP: {
            Daemon::instance().m_reload = true;
            break;
        }
    }
}

daemon-template.service

[Unit]
Description=Simple daemon template
After=network.taget

[Service]
Type=simple
ExecStart=/usr/bin/daemon-template --conf_file /etc/daemon-template/daemon-tenplate.conf
ExecReload=/bin/kill -HUP $MAINPID
User=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=daemon-template

[Install]
WantedBy=multi-user.target

How to set RelativeLayout layout params in code not in xml?

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);


   // If you want to add some controls in this Relative Layout
    labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);


    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.popupnew_bg);        
    layout.addView(mImage,labelLayoutParams);

    setContentView(layout);

What is a postback?

Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.

An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.

See: http://en.wikipedia.org/wiki/Postback

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

HTML form with two submit buttons and two "target" attributes

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>

With this javascript:

var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.