Programs & Examples On #Stack

A stack is a last in, first out (LIFO) abstract data type and data structure. One common use of stacks is to store subroutine arguments and return addresses.

Stack smashing detected

Another source of stack smashing is (incorrect) use of vfork() instead of fork().

I just debugged a case of this, where the child process was unable to execve() the target executable and returned an error code rather than calling _exit().

Because vfork() had spawned that child, it returned while actually still executing within the parent's process space, not only corrupting the parent's stack, but causing two disparate sets of diagnostics to be printed by "downstream" code.

Changing vfork() to fork() fixed both problems, as did changing the child's return statement to _exit() instead.

But since the child code precedes the execve() call with calls to other routines (to set the uid/gid, in this particular case), it technically does not meet the requirements for vfork(), so changing it to use fork() is correct here.

(Note that the problematic return statement was not actually coded as such -- instead, a macro was invoked, and that macro decided whether to _exit() or return based on a global variable. So it wasn't immediately obvious that the child code was nonconforming for vfork() usage.)

For more information, see:

The difference between fork(), vfork(), exec() and clone()

What is a stack pointer used for in microprocessors?

The stack pointer stores the address of the most recent entry that was pushed onto the stack.

To push a value onto the stack, the stack pointer is incremented to point to the next physical memory address, and the new value is copied to that address in memory.

To pop a value from the stack, the value is copied from the address of the stack pointer, and the stack pointer is decremented, pointing it to the next available item in the stack.

The most typical use of a hardware stack is to store the return address of a subroutine call. When the subroutine is finished executing, the return address is popped off the top of the stack and placed in the Program Counter register, causing the processor to resume execution at the next instruction following the call to the subroutine.

http://en.wikipedia.org/wiki/Stack_%28data_structure%29#Hardware_stacks

Parenthesis/Brackets Matching using Stack algorithm

Algorithm to use for checking well balanced parenthesis -

  1. Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
  2. Declare a set openingParenSet and initialize it with the values of matchingParenMap.
  3. Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
  4. Now traverse the string expression input.

    1. If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.

    2. If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.

  5. After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.

I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

How do you implement a Stack and a Queue in JavaScript?

My implementation of Stack and Queue using Linked List

_x000D_
_x000D_
// Linked List_x000D_
function Node(data) {_x000D_
  this.data = data;_x000D_
  this.next = null;_x000D_
}_x000D_
_x000D_
// Stack implemented using LinkedList_x000D_
function Stack() {_x000D_
  this.top = null;_x000D_
}_x000D_
_x000D_
Stack.prototype.push = function(data) {_x000D_
  var newNode = new Node(data);_x000D_
_x000D_
  newNode.next = this.top; //Special attention_x000D_
  this.top = newNode;_x000D_
}_x000D_
_x000D_
Stack.prototype.pop = function() {_x000D_
  if (this.top !== null) {_x000D_
    var topItem = this.top.data;_x000D_
    this.top = this.top.next;_x000D_
    return topItem;_x000D_
  }_x000D_
  return null;_x000D_
}_x000D_
_x000D_
Stack.prototype.print = function() {_x000D_
  var curr = this.top;_x000D_
  while (curr) {_x000D_
    console.log(curr.data);_x000D_
    curr = curr.next;_x000D_
  }_x000D_
}_x000D_
_x000D_
// var stack = new Stack();_x000D_
// stack.push(3);_x000D_
// stack.push(5);_x000D_
// stack.push(7);_x000D_
// stack.print();_x000D_
_x000D_
// Queue implemented using LinkedList_x000D_
function Queue() {_x000D_
  this.head = null;_x000D_
  this.tail = null;_x000D_
}_x000D_
_x000D_
Queue.prototype.enqueue = function(data) {_x000D_
  var newNode = new Node(data);_x000D_
_x000D_
  if (this.head === null) {_x000D_
    this.head = newNode;_x000D_
    this.tail = newNode;_x000D_
  } else {_x000D_
    this.tail.next = newNode;_x000D_
    this.tail = newNode;_x000D_
  }_x000D_
}_x000D_
_x000D_
Queue.prototype.dequeue = function() {_x000D_
  var newNode;_x000D_
  if (this.head !== null) {_x000D_
    newNode = this.head.data;_x000D_
    this.head = this.head.next;_x000D_
  }_x000D_
  return newNode;_x000D_
}_x000D_
_x000D_
Queue.prototype.print = function() {_x000D_
  var curr = this.head;_x000D_
  while (curr) {_x000D_
    console.log(curr.data);_x000D_
    curr = curr.next;_x000D_
  }_x000D_
}_x000D_
_x000D_
var queue = new Queue();_x000D_
queue.enqueue(3);_x000D_
queue.enqueue(5);_x000D_
queue.enqueue(7);_x000D_
queue.print();_x000D_
queue.dequeue();_x000D_
queue.dequeue();_x000D_
queue.print();
_x000D_
_x000D_
_x000D_

What do Push and Pop mean for Stacks?

after all these good examples adam shankman still can't make sense of it. I think you should open up some code and try it. The second you try a myStack.Push(1) and myStack.Pop(1) you really should get the picture. But by the looks of it, even that will be a challenge for you!

How to implement a queue using two stacks?

for c# developer here is the complete program :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QueueImplimentationUsingStack
{
    class Program
    {
        public class Stack<T>
        {
            public int size;
            public Node<T> head;
            public void Push(T data)
            {
                Node<T> node = new Node<T>();
                node.data = data;
                if (head == null)
                    head = node;
                else
                {
                    node.link = head;
                    head = node;
                }
                size++;
                Display();
            }
            public Node<T> Pop()
            {
                if (head == null)
                    return null;
                else
                {
                    Node<T> temp = head;
                    //temp.link = null;
                    head = head.link;
                    size--;
                    Display();
                    return temp;
                }
            }
            public void Display()
            {
                if (size == 0)
                    Console.WriteLine("Empty");
                else
                {
                    Console.Clear();
                    Node<T> temp = head;
                    while (temp!= null)
                    {
                        Console.WriteLine(temp.data);
                        temp = temp.link;
                    }
                }
            }
        }

        public class Queue<T>
        {
            public int size;
            public Stack<T> inbox;
            public Stack<T> outbox;
            public Queue()
            {
                inbox = new Stack<T>();
                outbox = new Stack<T>();
            }
            public void EnQueue(T data)
            {
                inbox.Push(data);
                size++;
            }
            public Node<T> DeQueue()
            {
                if (outbox.size == 0)
                {
                    while (inbox.size != 0)
                    {
                        outbox.Push(inbox.Pop().data);
                    }
                }
                Node<T> temp = new Node<T>();
                if (outbox.size != 0)
                {
                    temp = outbox.Pop();
                    size--;
                }
                return temp;
            }

        }
        public class Node<T>
        {
            public T data;
            public Node<T> link;
        }

        static void Main(string[] args)
        {
            Queue<int> q = new Queue<int>();
            for (int i = 1; i <= 3; i++)
                q.EnQueue(i);
           // q.Display();
            for (int i = 1; i < 3; i++)
                q.DeQueue();
            //q.Display();
            Console.ReadKey();
        }
    }
}

How to increase the Java stack size?

Hmm... it works for me and with far less than 999MB of stack:

> java -Xss4m Test
0

(Windows JDK 7, build 17.0-b05 client VM, and Linux JDK 6 - same version information as you posted)

design a stack such that getMinimum( ) should be O(1)

public class MinStack<E>{

    private final LinkedList<E> mainStack = new LinkedList<E>();
    private final LinkedList<E> minStack = new LinkedList<E>();
    private final Comparator<E> comparator;

    public MinStack(Comparator<E> comparator) 
    {
        this.comparator = comparator;
    }

    /**
     * Pushes an element onto the stack.
     *
     *
     * @param e the element to push
     */
    public void push(E e) {
        mainStack.push(e);
        if(minStack.isEmpty())
        {
            minStack.push(e);
        }
        else if(comparator.compare(e, minStack.peek())<=0)
        {
            minStack.push(e);
        }
        else
        {
            minStack.push(minStack.peek());
        }
    }

    /**
     * Pops an element from the stack.
     *
     *
     * @throws NoSuchElementException if this stack is empty
     */
    public E pop() {
       minStack.pop();
       return  mainStack.pop();
    }

    /**
     * Returns but not remove smallest element from the stack. Return null if stack is empty.
     *
     */
    public E getMinimum()
    {
        return minStack.peek();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Main stack{");
        for (E e : mainStack) {         
            sb.append(e.toString()).append(",");
        }
        sb.append("}");

        sb.append(" Min stack{");
        for (E e : minStack) {          
            sb.append(e.toString()).append(",");
        }
        sb.append("}");

        sb.append(" Minimum = ").append(getMinimum());
        return sb.toString();
    }

    public static void main(String[] args) {
        MinStack<Integer> st = new MinStack<Integer>(Comparators.INTEGERS);

        st.push(2);
        Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
        System.out.println(st);

        st.push(6);
        Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
        System.out.println(st);

        st.push(4);
        Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
        System.out.println(st);

        st.push(1);
        Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
        System.out.println(st);

        st.push(5);
        Assert.assertTrue("1 is min in stack {2,6,4,1,5}", st.getMinimum().equals(1));
        System.out.println(st);

        st.pop();
        Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
        System.out.println(st);

        st.pop();
        Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
        System.out.println(st);

        st.pop();
        Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
        System.out.println(st);

        st.pop();
        Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
        System.out.println(st);

        st.pop();
        Assert.assertTrue("null is min in stack {}", st.getMinimum()==null);
        System.out.println(st);
    }
}

What does "ulimit -s unlimited" do?

ulimit -s unlimited lets the stack grow unlimited.

This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.

Stacking DIVs on top of each other?

I positioned the divs slightly offset, so that you can see it at work.
HTML

<div class="outer">
  <div class="bot">BOT</div>
  <div class="top">TOP</div>
</div>

CSS

.outer {
  position: relative;
  margin-top: 20px;
}

.top {
  position: absolute;
  margin-top: -10px;
  background-color: green;
}

.bot {
  position: absolute;
  background-color: yellow;
}

https://codepen.io/anon/pen/EXxKzP

Android: Clear the back stack

Use finishAffinity() to clear all backstack with existing one.

Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, 

    - Activity B will be finished / removing from stack.
    - Activity A will be finished / removing from stack.
    - Activity C will finished / removing from stack.

What and where are the stack and heap?

A lot of answers are correct as concepts, but we must note that a stack is needed by the hardware (i.e. microprocessor) to allow calling subroutines (CALL in assembly language..). (OOP guys will call it methods)

On the stack you save return addresses and call ? push / ret ? pop is managed directly in hardware.

You can use the stack to pass parameters.. even if it is slower than using registers (would a microprocessor guru say or a good 1980s BIOS book...)

  • Without stack no microprocessor can work. (we can't imagine a program, even in assembly language, without subroutines/functions)
  • Without the heap it can. (An assembly language program can work without, as the heap is a OS concept, as malloc, that is a OS/Lib call.

Stack usage is faster as:

  • Is hardware, and even push/pop are very efficient.
  • malloc requires entering kernel mode, use lock/semaphore (or other synchronization primitives) executing some code and manage some structures needed to keep track of allocation.

Android: Clear Activity Stack

I noted that you asked for a solution that does not rely on finish(), but I wonder if this may help nonetheless.

I tracked whether an exit flag is raised with a static class variable, which survives the entire app lifespan. In each relevant activity's onResume(), use

@Override
public void onResume() {
    super.onResume();
    if (ExitHelper.isExitFlagRaised) {
        this.finish();
    }
}

The ExitHelper class

public class ExitHelper {
    public static boolean isExitFlagRaised = false;
}

Let's say in mainActivity, a user presses a button to exit - you can set ExitHelper.isExitFlagRaised = true; and then finish(). Thereafter, other relevant activities that are resumed automatically will be finished as well.

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

How to clone object in C++ ? Or Is there another solution?

The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};

// ...

Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

Sometimes it is beneficial to provide an explicit clone() method, especially for polymorphic classes.

class Interface
{
public:
  virtual Interface* clone() const = 0;
};

class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};

class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};


Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

EDIT: Since Stack has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack's members from the so-called "right hand side" (rhs). However, you still need to ensure that any base classes are given the opportunity to initialize their members.

You do this by calling the base class:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

How does the stack work in assembly language?

Regarding whether the stack is implemented in the hardware, this Wikipedia article might help.

Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's Application Binary Interface (ABI).

That article and the others it links to might be useful to get a feel for stack usage in processors.

what is the basic difference between stack and queue?

STACK is a LIFO (last in, first out) list. means suppose 3 elements are inserted in stack i.e 10,20,30. 10 is inserted first & 30 is inserted last so 30 is first deleted from stack & 10 is last deleted from stack.this is an LIFO list(Last In First Out).

QUEUE is FIFO list(First In First Out).means one element is inserted first which is to be deleted first.e.g queue of peoples.

Stack array using pop() and push()

Here is an example of implementing stack in java (Array Based implementation):

public class MyStack extends Throwable{

/**
 * 
 */
private static final long serialVersionUID = -4433344892390700337L;

protected static int top = -1;
protected static int capacity;
protected static int size;

public int stackDatas[] = null;

public MyStack(){
    stackDatas = new int[10];
    capacity = stackDatas.length;
}

public static int size(){

    if(top < 0){
        size = top + 1;
        return size;
    }
    size = top+1;
    return size; 
}

public void push(int data){
    if(capacity == size()){
        System.out.println("no memory");
    }else{
        stackDatas[++top] = data;
    }
}

public boolean topData(){
    if(top < 0){
        return true;
    }else{
        System.out.println(stackDatas[top]);
        return false;
    }
}

public void pop(){
    if(top < 0){
        System.out.println("stack is empty");
    }else{
        int temp = stackDatas[top];
        stackDatas = ArrayUtils.remove(stackDatas, top--);
        System.out.println("poped data---> "+temp);
    }
}

public String toString(){
    String result = "[";

    if(top<0){
        return "[]";
    }else{


    for(int i = 0; i< size(); i++){
        result = result + stackDatas[i] +",";
    }
    }

    return result.substring(0, result.lastIndexOf(",")) +"]";
 }
}

calling MyStack:

    public class CallingMyStack {

public static MyStack ms;

public static void main(String[] args) {

    ms = new MyStack();
    ms.push(1);
    ms.push(2);
    ms.push(3);
    ms.push(4);
    ms.push(5);
    ms.push(6);
    ms.push(7);
    ms.push(8);
    ms.push(9);
    ms.push(10);
    System.out.println("size: "+MyStack.size());
    System.out.println("List---> "+ms);
    System.out.println("----------");
    ms.pop();
    ms.pop();
    ms.pop();
    ms.pop();
    System.out.println("List---> "+ms);
    System.out.println("size: "+MyStack.size());

 }
}

output:

size: 10
List---> [1,2,3,4,5,6,7,8,9,10]
----------
poped data---> 10
poped data---> 9
poped data---> 8
poped data---> 7
List---> [1,2,3,4,5,6]
size: 6

Java ArrayList how to add elements at the beginning

You may want to look at Deque. it gives you direct access to both the first and last items in the list.

Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();

    // Push element x onto stack.
    public void push(int x) {
        if(isEmpty()){
            queue1.offer(x);
        }else{
            if(queue1.size()>0){
                queue2.offer(x);
                int size = queue1.size();
                while(size>0){
                    queue2.offer(queue1.poll());
                    size--;
                }
            }else if(queue2.size()>0){
                queue1.offer(x);
                int size = queue2.size();
                while(size>0){
                    queue1.offer(queue2.poll());
                    size--;
                }
            }
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(queue1.size()>0){
            queue1.poll();
        }else if(queue2.size()>0){
            queue2.poll();
        }
    }

    // Get the top element. You can make it more perfect just example
    public int top() {
       if(queue1.size()>0){
            return queue1.peek();
        }else if(queue2.size()>0){
            return queue2.peek();
        }
        return 0;
    }

    // Return whether the stack is empty.
    public boolean isEmpty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}

Object creation on the stack/heap?

In both your examples, local variables of Object* type are allocated on the stack. The compiler is free to produce the same code from both snippets if there is no way for your program to detect a difference.

The memory area for global variables is the same as the memory area for static variables - it's neither on the stack nor on the heap. You can place variables in that area by declaring them static inside the function. The consequence of doing so is that the instance becomes shared among concurrent invocations of your function, so you need to carefully consider synchronization when you use statics.

Here is a link to a discussion of the memory layout of a running C program.

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Why is the use of alloca() not considered good practice?

As noted in this newsgroup posting, there are a few reasons why using alloca can be considered difficult and dangerous:

  • Not all compilers support alloca.
  • Some compilers interpret the intended behaviour of alloca differently, so portability is not guaranteed even between compilers that support it.
  • Some implementations are buggy.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Which is faster: Stack allocation or Heap allocation

I'd like to say actually code generate by GCC (I remember VS also) doesn't have overhead to do stack allocation.

Say for following function:

  int f(int i)
  {
      if (i > 0)
      {   
          int array[1000];
      }   
  }

Following is the code generate:

  __Z1fi:
  Leh_func_begin1:
      pushq   %rbp
  Ltmp0:
      movq    %rsp, %rbp
  Ltmp1:
      subq    $**3880**, %rsp <--- here we have the array allocated, even the if doesn't excited.
  Ltmp2:
      movl    %edi, -4(%rbp)
      movl    -8(%rbp), %eax
      addq    $3880, %rsp
      popq    %rbp
      ret 
  Leh_func_end1:

So whatevery how much local variable you have (even inside if or switch), just the 3880 will change to another value. Unless you didn't have local variable, this instruction just need to execute. So allocate local variable doesn't have overhead.

Java balanced expressions check {[()]}

public void validateExpression(){

    if(!str.isEmpty() && str != null){
        if( !str.trim().equals("(") && !str.trim().equals(")")){

            char[] chars = str.toCharArray();

            for(char c: chars){
                if(!Character.isLetterOrDigit(c) && c == '('  || c == ')') {
                    charList.add(c);
                }
            }

            for(Character ele: charList){                   
                if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){                      
                    operatorMap.put(ele,operatorMap.get(ele)+1);
                }else{
                    operatorMap.put(ele,1);
                }
            }

            for(Map.Entry<Character, Integer> ele: operatorMap.entrySet()){
                System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));                   
            }

            if(operatorMap.get('(') == operatorMap.get(')')){
                System.out.println("**** Valid Expression ****");
            }else{
                System.out.println("**** Invalid Expression ****");
            }

        }else{
            System.out.println("**** Incomplete expression to validate ****");
        }

    }else{
        System.out.println("**** Expression is  empty or null ****");
    }       
}

Stack, Static, and Heap in C++

An advantage of GC in some situations is an annoyance in others; reliance on GC encourages not thinking much about it. In theory, waits until 'idle' period or until it absolutely must, when it will steal bandwidth and cause response latency in your app.

But you don't have to 'not think about it.' Just as with everything else in multithreaded apps, when you can yield, you can yield. So for example, in .Net, it is possible to request a GC; by doing this, instead of less frequent longer running GC, you can have more frequent shorter running GC, and spread out the latency associated with this overhead.

But this defeats the primary attraction of GC which appears to be "encouraged to not have to think much about it because it is auto-mat-ic."

If you were first exposed to programming before GC became prevalent and were comfortable with malloc/free and new/delete, then it might even be the case that you find GC a little annoying and/or are distrustful(as one might be distrustful of 'optimization,' which has had a checkered history.) Many apps tolerate random latency. But for apps that don't, where random latency is less acceptable, a common reaction is to eschew GC environments and move in the direction of purely unmanaged code (or god forbid, a long dying art, assembly language.)

I had a summer student here a while back, an intern, smart kid, who was weaned on GC; he was so adament about the superiorty of GC that even when programming in unmanaged C/C++ he refused to follow the malloc/free new/delete model because, quote, "you shouldn't have to do this in a modern programming language." And you know? For tiny, short running apps, you can indeed get away with that, but not for long running performant apps.

C/C++ maximum stack size of program

Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.

Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.

You should specify which OS and development environment you're using for more targeted assistance.

For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack option of ld to do that.

What is the function of the push / pop instructions used on registers in x86 assembly?

pushing a value (not necessarily stored in a register) means writing it to the stack.

popping means restoring whatever is on top of the stack into a register. Those are basic instructions:

push 0xdeadbeef      ; push a value to the stack
pop eax              ; eax is now 0xdeadbeef

; swap contents of registers
push eax
mov eax, ebx
pop ebx

PHP function ssh2_connect is not working

I am running CentOS 5.6 as my development environment and the following worked for me.

su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart

What is the difference between an Instance and an Object?

Class : A class is a blue print. Object : It is the copy of the class. Instance : Its a variable which is used to hold memory address of the object.

A very basic analytical example

Class House --> Blueprint of the house. But you can't live in the blue print. You need a physical House which is the instance of the class to live in. i.e., actual address of the object is instance. Instances represent objects.

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

Java - Check if input is a positive integer, negative integer, natural number and so on.

What about using the following:

int number = input.nextInt();
if (number < 0) {
    // negative
} else {
   // it's a positive
}

Python return statement error " 'return' outside function"

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

Angular 2 Dropdown Options Default Value

Fully fleshing out other posts, here is what works in Angular2 quickstart,

To set the DOM default: along with *ngFor, use a conditional statement in the <option>'s selected attribute.

To set the Control's default: use its constructor argument. Otherwise before an onchange when the user re-selects an option, which sets the control's value with the selected option's value attribute, the control value will be null.

script:

import {ControlGroup,Control} from '@angular/common';
...
export class MyComponent{
  myForm: ControlGroup;
  myArray: Array<Object> = [obj1,obj2,obj3];
  myDefault: Object = myArray[1]; //or obj2

  ngOnInit(){ //override
    this.myForm = new ControlGroup({'myDropdown': new Control(this.myDefault)});
  }
  myOnSubmit(){
    console.log(this.myForm.value.myDropdown); //returns the control's value 
  }
}

markup:

<form [ngFormModel]="myForm" (ngSubmit)="myOnSubmit()">
  <select ngControl="myDropdown">
    <option *ngFor="let eachObj of myArray" selected="eachObj==={{myDefault}}"
            value="{{eachObj}}">{{eachObj.myText}}</option>
  </select>
  <br>
  <button type="submit">Save</button>
</form>

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Download file from an ASP.NET Web API method using AngularJS

Send your file as a base64 string.

 var element = angular.element('<a/>');
                         element.attr({
                             href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
                             target: '_blank',
                             download: fname
                         })[0].click();

If attr method not working in Firefox You can also use javaScript setAttribute method

How to make JavaScript execute after page load?

Use this code with jQuery library, this would work perfectly fine.

$(window).bind("load", function() { 

  // your javascript event

});

Bring a window to the front in WPF

If you are trying to hide the window, for example you minimize the window, I have found that using

    this.Hide();

will hide it correctly, then simply using

    this.Show();

will then show the window as the top most item once again.

How to install pywin32 module in windows 7

are you just trying to install it, or are you looking to build from source?

If you just need to install, the easiest way is to use the MSI installers provided here:

http://sourceforge.net/projects/pywin32/files/pywin32/ (for updated versions)

make sure you get the correct version (matches Python version, 32bit/64bit, etc)

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Why use 'virtual' for class properties in Entity Framework model definitions?

In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

Post multipart request with Android SDK

I highly recommend Loopj.

I have successfully used it to upload multiple files at once, including different mime types. Simply do this:

File myVideo = new File("/path/to/myvideo.mp4");
File myPic = new File("/path/to/mypic.jpg");
RequestParams params = new RequestParams();
try {
  params.put("profile_picture", myPic);
  params.put("my_video", myVideo);
} catch(FileNotFoundException e) {}

For large or many files you might have to increase the timeout amount else the default timeout is used which might be too short:

client.setTimeout(500000) //make this the appropriate timeout in milliseconds

Please see this links for a full description of loopj and how to use it, by far the easiest async http library I have come across:

http://loopj.com/android-async-http/ http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

How to enable local network users to access my WAMP sites?

if you use Windows and if you do all comments in above ,

You can check your network and sharing center.

Network and Sharing Center -> Advanced sharing settings ->Home or Work Profile Change

Thanks good work!

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

As the previous answers exhaustively covered the theory behind the value categories, there is just another thing I'd like to add: you can actually play with it and test it.

For some hands-on experimentation with the value categories, you can make use of the decltype specifier. Its behavior explicitly distinguishes between the three primary value categories (xvalue, lvalue, and prvalue).

Using the preprocessor saves us some typing ...

Primary categories:

#define IS_XVALUE(X) std::is_rvalue_reference<decltype((X))>::value
#define IS_LVALUE(X) std::is_lvalue_reference<decltype((X))>::value
#define IS_PRVALUE(X) !std::is_reference<decltype((X))>::value

Mixed categories:

#define IS_GLVALUE(X) (IS_LVALUE(X) || IS_XVALUE(X))
#define IS_RVALUE(X) (IS_PRVALUE(X) || IS_XVALUE(X))

Now we can reproduce (almost) all the examples from cppreference on value category.

Here are some examples with C++17 (for terse static_assert):

void doesNothing(){}
struct S
{
    int x{0};
};
int x = 1;
int y = 2;
S s;

static_assert(IS_LVALUE(x));
static_assert(IS_LVALUE(x+=y));
static_assert(IS_LVALUE("Hello world!"));
static_assert(IS_LVALUE(++x));

static_assert(IS_PRVALUE(1));
static_assert(IS_PRVALUE(x++));
static_assert(IS_PRVALUE(static_cast<double>(x)));
static_assert(IS_PRVALUE(std::string{}));
static_assert(IS_PRVALUE(throw std::exception()));
static_assert(IS_PRVALUE(doesNothing()));

static_assert(IS_XVALUE(std::move(s)));
// The next one doesn't work in gcc 8.2 but in gcc 9.1. Clang 7.0.0 and msvc 19.16 are doing fine.
static_assert(IS_XVALUE(S().x)); 

The mixed categories are kind of boring once you figured out the primary category.

For some more examples (and experimentation), check out the following link on compiler explorer. Don't bother reading the assembly, though. I added a lot of compilers just to make sure it works across all the common compilers.

Generate your own Error code in swift 3

 let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
            self.showLoginError(error)

create an NSError object and typecast it to Error ,show it anywhere

private func showLoginError(_ error: Error?) {
    if let errorObj = error {
        UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
    }
}

How to zip a file using cmd line?

The zip Package should be installed in system.

To Zip a File

zip <filename.zip> <file>

Example:

zip doc.zip doc.txt 

To Unzip a File

unzip <filename.zip>

Example:

unzip mydata.zip

How can I protect my .NET assemblies from decompilation?

One thing to keep in mind is that you want to do this in a way that makes business sense. To do that, you need to define your goals. So, exactly what are your goals?

Preventing piracy? That goal is not achievable. Even native code can be decompiled or cracked; the multitude of warez available online (even for products like Windows and Photoshop) is proof a determined hacker can always gain access.

If you can't prevent piracy, then how about merely reducing it? This, too, is misguided. It only takes one person cracking your code for it to be available to everyone. You have to be lucky every time. The pirates only have to be lucky once.

I put it to you the goal should be to maximize profits. You appear to believe that stopping piracy is necessary to this endeavor. It is not. Profit is simply revenue minus costs. Stopping piracy increases costs. It takes effort, which means adding cost somewhere in the process, and so reduces that side of the equation. Protecting your product also fails to increase your revenue. I know you look at all those pirates and see all the money you could make if only they would pay your license fees instead, but the reality is this will never happen. There is some hyperbole here, but it generally holds that pirates who are unable to crack your security will either find a similar product they can crack or do without. They will never buy it instead, and therefore they do not represent lost sales.

Additionally, securing your product actually reduces revenue. There are two reasons for this. One is the small percentage of customers who have trouble with your activation or security, and therefore decide not to buy again or ask for their money back. The other is the small percentage of people who actually try a pirated version of software to make sure it works before buying. Limiting the pirated distribution of your product (if you are somehow able to succeed at this) prevents these people from ever trying your product, and so they will never buy it. Moreover, piracy can also help your product spread to a wider audience, thus reaching more people who will be willing to pay for it.

A better strategy is to assume that your product will be pirated, and think about ways to take advantage of the situation. A couple more links on the topic:
How do i prevent my code from being stolen?
Securing a .NET Application

Troubleshooting misplaced .git directory (nothing to commit)

I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.

When I execute cd .. to the correct directory, I was able to commit, as expected.

Share cookie between subdomain and domain

Please everyone note that you can set a cookie from a subdomain on a domain.

(sent in the response for requesting subdomain.mydomain.com)

Set-Cookie: name=value; Domain=mydomain.com // GOOD

But you CAN'T set a cookie from a domain on a subdomain.

(sent in the response for requesting mydomain.com)

Set-Cookie: name=value; Domain=subdomain.mydomain.com // Browser rejects cookie

WHY ?

According to the specifications RFC 6265 section 5.3.6 Storage Model

If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.

and RFC 6265 section 5.1.3 Domain Matching

Domain Matching

A string domain-matches a given domain string if at least one of the following conditions hold:

  1. The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

  2. All of the following conditions hold:

    • The domain string is a suffix of the string.

    • The last character of the string that is not included in the domain string is a %x2E (".") character.

    • The string is a host name (i.e., not an IP address).

So "subdomain.mydomain.com" domain-matches "mydomain.com", but "mydomain.com" does NOT domain-match "subdomain.mydomain.com"

Check this answer also.

Call to undefined function mysql_query() with Login

I would recommend that start using mysqli_() and stop using mysql_()

Check the following page: LINK

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_affected_rows() PDOStatement::rowCount()

Try and use mysqli_() Or PDO

How to adjust text font size to fit textview

Use app:autoSizeTextType="uniform" for backward compatibility because android:autoSizeTextType="uniform" only work in API Level 26 and higher.

How can I render inline JavaScript with Jade / Pug?

For multi-line content jade normally uses a "|", however:

Tags that accept only text such as script, style, and textarea do not need the leading | character

This said, i cannot reproduce the problem you are having. When i paste that code in a jade template, it produces the right output and prompts me with an alert on page-load.

How do I enable the column selection mode in Eclipse?

To activate the cursor and select the columns you want to select use:

Windows: Alt+Shift+A

Mac: command + option + A

Linux-based OS: Alt+Shift+A

To deactivate, press the keys again.

This information was taken from DJ's Java Blog.

process.env.NODE_ENV is undefined

For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:

NODE_ENV=development node server.js

Easier, no? :)

Wait one second in running program

The Best way to wait without freezing your main thread is using the Task.Delay function.

So your code will look like this

var t = Task.Run(async delegate
{              
    dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
    dataGridView1.Refresh();
    await Task.Delay(1000);             
});

Adding an item to an associative array

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

echo $data[$category]["test"];

which should print $question

Is Python faster and lighter than C++?

I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.

My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones being: a) Python is interpreted, while C++ is compiled; b) Python has no primitives, everything including the builtin types (int, float, etc.) are objects; c) a Python list can hold objects of different type, so each entry has to store additional data about its type. These all severely hinder both runtime and memory consumption.

This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor. Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.

How to count string occurrence in string?

Simple version without regex:

_x000D_
_x000D_
var temp = "This is a string.";_x000D_
_x000D_
var count = (temp.split('is').length - 1);_x000D_
_x000D_
alert(count);
_x000D_
_x000D_
_x000D_

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

How can I measure the actual memory usage of an application or process?

Valgrind can show detailed information, but it slows down the target application significantly, and most of the time it changes the behavior of the application.

Exmap was something I didn't know yet, but it seems that you need a kernel module to get the information, which can be an obstacle.

I assume what everyone wants to know with respect to "memory usage" is the following... In Linux, the amount of physical memory a single process might use can be roughly divided into following categories.

  • M.a anonymous mapped memory

  • .p private

    • .d dirty == malloc/mmapped heap and stack allocated and written memory
    • .c clean == malloc/mmapped heap and stack memory once allocated, written, then freed, but not reclaimed yet
  • .s shared

    • .d dirty == malloc/mmaped heap could get copy-on-write and shared among processes (edited)
    • .c clean == malloc/mmaped heap could get copy-on-write and shared among processes (edited)
  • M.n named mapped memory

  • .p private

    • .d dirty == file mmapped written memory private
    • .c clean == mapped program/library text private mapped
  • .s shared

    • .d dirty == file mmapped written memory shared
    • .c clean == mapped library text shared mapped

Utility included in Android called showmap is quite useful

virtual                    shared   shared   private  private
size     RSS      PSS      clean    dirty    clean    dirty    object
-------- -------- -------- -------- -------- -------- -------- ------------------------------
       4        0        0        0        0        0        0 0:00 0                  [vsyscall]
       4        4        0        4        0        0        0                         [vdso]
      88       28       28        0        0        4       24                         [stack]
      12       12       12        0        0        0       12 7909                    /lib/ld-2.11.1.so
      12        4        4        0        0        0        4 89529                   /usr/lib/locale/en_US.utf8/LC_IDENTIFICATION
      28        0        0        0        0        0        0 86661                   /usr/lib/gconv/gconv-modules.cache
       4        0        0        0        0        0        0 87660                   /usr/lib/locale/en_US.utf8/LC_MEASUREMENT
       4        0        0        0        0        0        0 89528                   /usr/lib/locale/en_US.utf8/LC_TELEPHONE
       4        0        0        0        0        0        0 89527                   /usr/lib/locale/en_US.utf8/LC_ADDRESS
       4        0        0        0        0        0        0 87717                   /usr/lib/locale/en_US.utf8/LC_NAME
       4        0        0        0        0        0        0 87873                   /usr/lib/locale/en_US.utf8/LC_PAPER
       4        0        0        0        0        0        0 13879                   /usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES
       4        0        0        0        0        0        0 89526                   /usr/lib/locale/en_US.utf8/LC_MONETARY
       4        0        0        0        0        0        0 89525                   /usr/lib/locale/en_US.utf8/LC_TIME
       4        0        0        0        0        0        0 11378                   /usr/lib/locale/en_US.utf8/LC_NUMERIC
    1156        8        8        0        0        4        4 11372                   /usr/lib/locale/en_US.utf8/LC_COLLATE
     252        0        0        0        0        0        0 11321                   /usr/lib/locale/en_US.utf8/LC_CTYPE
     128       52        1       52        0        0        0 7909                    /lib/ld-2.11.1.so
    2316       32       11       24        0        0        8 7986                    /lib/libncurses.so.5.7
    2064        8        4        4        0        0        4 7947                    /lib/libdl-2.11.1.so
    3596      472       46      440        0        4       28 7933                    /lib/libc-2.11.1.so
    2084        4        0        4        0        0        0 7995                    /lib/libnss_compat-2.11.1.so
    2152        4        0        4        0        0        0 7993                    /lib/libnsl-2.11.1.so
    2092        0        0        0        0        0        0 8009                    /lib/libnss_nis-2.11.1.so
    2100        0        0        0        0        0        0 7999                    /lib/libnss_files-2.11.1.so
    3752     2736     2736        0        0      864     1872                         [heap]
      24       24       24        0        0        0       24 [anon]
     916      616      131      584        0        0       32                         /bin/bash
-------- -------- -------- -------- -------- -------- -------- ------------------------------
   22816     4004     3005     1116        0      876     2012 TOTAL

How to set header and options in axios?

You can initialize a default header axios.defaults.headers

 axios.defaults.headers = {
        'Content-Type': 'application/json',
        Authorization: 'myspecialpassword'
    }

   axios.post('https://myapi.com', { data: "hello world" })
        .then(response => {
            console.log('Response', response.data)
        })
        .catch(e => {
            console.log('Error: ', e.response.data)
        })

ERROR: Google Maps API error: MissingKeyMapError

Update django-geoposition at least to version 0.2.3 and add this to settings.py:

GEOPOSITION_GOOGLE_MAPS_API_KEY = 'YOUR_API_KEY'

How can you remove all documents from a collection with Mongoose?

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

Regular Expressions: Is there an AND operator?

Is it not possible in your case to do the AND on several matching results? in pseudocode

regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

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.

How can I merge two commits into one if I already started rebase?

If there are multiple commits, you can use git rebase -i to squash two commits into one.

If there are only two commits you want to merge, and they are the "most recent two", the following commands can be used to combine the two commits into one:

git reset --soft "HEAD^"
git commit --amend

difference between primary key and unique key

Primary Key:

  • There can only be one primary key in a table
  • In some DBMS it cannot be NULL - e.g. MySQL adds NOT NULL
  • Primary Key is a unique key identifier of the record

Unique Key:

  • Can be more than one unique key in one table
  • Unique key can have NULL values
  • It can be a candidate key
  • Unique key can be NULL ; multiple rows can have NULL values and therefore may not be considered "unique"

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

C/C++ maximum stack size of program

In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.

Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s and set it to a new value with for example ulimit -s 16384.

Here's a link with default stack sizes for gcc.

DFS without recursion:

std::stack<Node> dfs;
dfs.push(start);
do {
    Node top = dfs.top();
    if (top is what we are looking for) {
       break;
    }
    dfs.pop();
    for (outgoing nodes from top) {
        dfs.push(outgoing node);
    }
} while (!dfs.empty())

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

TypeError: $(...).autocomplete is not a function

In my exprience I added two Jquery libraries in my file.The versions were jquery 1.11.1 and 2.1.Suddenly I took out 2.1 Jquery from my code. Then ran it and was working for me well. After trying out the first answer. please check out your file like I said above.

How to style icon color, size, and shadow of Font Awesome Icons

Dynamically change the css properties of .fa-xxx icons:

<li class="nws">
<a href="#NewsModal" class="urgent" title="' + title + '" onclick=""><span class="label label-icon label-danger"><i class="fa fa-bolt"></i></span>' 
</a>
</li>
<script>
  $(document).ready(function(){
   $('li.nws').on("focusin", function(){
    $('.fa-bolt').addClass('lightning');
   });
 });
</script>

<style>
.lightning{ /*do something cool like shutter*/}
</style>

How to get AM/PM from a datetime in PHP

for flexibility with different formats, use:

$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')

Check the php manual for additional format options.

Check if string contains a value in array

    $message = "This is test message that contain filter world test3";

    $filterWords = array('test1', 'test2', 'test3');

    $messageAfterFilter =  str_replace($filterWords, '',$message);

    if( strlen($messageAfterFilter) != strlen($message) )
        echo 'message is filtered';
    else
        echo 'not filtered';

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Difference between partition key, composite key and clustering key in Cassandra?

There is a lot of confusion around this, I will try to make it as simple as possible.

The primary key is a general concept to indicate one or more columns used to retrieve data from a Table.

The primary key may be SIMPLE and even declared inline:

 create table stackoverflow_simple (
      key text PRIMARY KEY,
      data text      
  );

That means that it is made by a single column.

But the primary key can also be COMPOSITE (aka COMPOUND), generated from more columns.

 create table stackoverflow_composite (
      key_part_one text,
      key_part_two int,
      data text,
      PRIMARY KEY(key_part_one, key_part_two)      
  );

In a situation of COMPOSITE primary key, the "first part" of the key is called PARTITION KEY (in this example key_part_one is the partition key) and the second part of the key is the CLUSTERING KEY (in this example key_part_two)

Please note that the both partition and clustering key can be made by more columns, here's how:

 create table stackoverflow_multiple (
      k_part_one text,
      k_part_two int,
      k_clust_one text,
      k_clust_two int,
      k_clust_three uuid,
      data text,
      PRIMARY KEY((k_part_one, k_part_two), k_clust_one, k_clust_two, k_clust_three)      
  );

Behind these names ...

  • The Partition Key is responsible for data distribution across your nodes.
  • The Clustering Key is responsible for data sorting within the partition.
  • The Primary Key is equivalent to the Partition Key in a single-field-key table (i.e. Simple).
  • The Composite/Compound Key is just any multiple-column key

Further usage information: DATASTAX DOCUMENTATION


Small usage and content examples
SIMPLE KEY:

insert into stackoverflow_simple (key, data) VALUES ('han', 'solo');
select * from stackoverflow_simple where key='han';

table content

key | data
----+------
han | solo

COMPOSITE/COMPOUND KEY can retrieve "wide rows" (i.e. you can query by just the partition key, even if you have clustering keys defined)

insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 9, 'football player');
insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 10, 'ex-football player');
select * from stackoverflow_composite where key_part_one = 'ronaldo';

table content

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |            9 |    football player
      ronaldo |           10 | ex-football player

But you can query with all key (both partition and clustering) ...

select * from stackoverflow_composite 
   where key_part_one = 'ronaldo' and key_part_two  = 10;

query output

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |           10 | ex-football player

Important note: the partition key is the minimum-specifier needed to perform a query using a where clause. If you have a composite partition key, like the following

eg: PRIMARY KEY((col1, col2), col10, col4))

You can perform query only by passing at least both col1 and col2, these are the 2 columns that define the partition key. The "general" rule to make query is you have to pass at least all partition key columns, then you can add optionally each clustering key in the order they're set.

so the valid queries are (excluding secondary indexes)

  • col1 and col2
  • col1 and col2 and col10
  • col1 and col2 and col10 and col 4

Invalid:

  • col1 and col2 and col4
  • anything that does not contain both col1 and col2

Hope this helps.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

Generating a random hex color code with PHP

This is how i do it.

<?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>

Print line numbers starting at zero using awk

If Perl is an option, you can try this:

perl -ne 'printf "%s,$_" , $.-1' file

$_ is the line
$. is the line number

Difference between CR LF, LF and CR line break types?

The sad state of "record separators" or "line terminators" is a legacy of the dark ages of computing.

Now, we take it for granted that anything we want to represent is in some way structured data and conforms to various abstractions that define lines, files, protocols, messages, markup, whatever.

But once upon a time this wasn't exactly true. Applications built-in control characters and device-specific processing. The brain-dead systems that required both CR and LF simply had no abstraction for record separators or line terminators. The CR was necessary in order to get the teletype or video display to return to column one and the LF (today, NL, same code) was necessary to get it to advance to the next line. I guess the idea of doing something other than dumping the raw data to the device was too complex.

Unix and Mac actually specified an abstraction for the line end, imagine that. Sadly, they specified different ones. (Unix, ahem, came first.) And naturally, they used a control code that was already "close" to S.O.P.

Since almost all of our operating software today is a descendent of Unix, Mac, or MS operating SW, we are stuck with the line ending confusion.

How to make in CSS an overlay over an image?

A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.

You could simply use a background-blend-mode

.foo {
    background-image: url(images/image1.png), url(images/image2.png);
    background-color: violet;
    background-blend-mode: screen multiply;
}

What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.

multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How does HTTP file upload work?

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

http://www.tutorialspoint.com/http/http_messages.htm

How to Select Min and Max date values in Linq Query

If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:

var min = myData.OrderBy( cv => cv.Date1 ).First();

The above will return the entire object. If you just want the date returned:

var min = myData.Min( cv => cv.Date1 );

Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.

From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:

What about the future of LINQ to SQL?

It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.

Commit history on remote repository

I don't believe this is possible. I believe you have to clone that remote repo locally and perform git fetch on it before you can issue a git log against it.

Leave only two decimal places after the dot

double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

Why is there no Constant feature in Java?

There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.

How to implement authenticated routes in React Router 4?

install react-router-dom

then create two components one for valid users and other for invalid users.

try this on app.js

import React from 'react';

import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';

import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;

class App extends React.Component {
 render() {
    return ( 
      <Router>
      <div>
        <Route exact path="/" render={() =>(
          loggedin ? ( <Route  component={ValidUser} />)
          : (<Route component={InValidUser} />)
        )} />

        </div>
      </Router>
    )
  }
}
export default App;

How to apply filters to *ngFor?

After some googling, I came across ng2-search-filter. In will take your object and apply the search term against all object properties looking for a match.

Sorting an Array of int using BubbleSort

You're only making one pass through your array! Bubble sort requires you to keep looping until you find that you are no longer doing any swapping; hence the running time of O(n^2).

Try this:

public void sortArray(int[] x) {
    boolean swapped = true;
    while (swapped) {
       swapped = false;
       for(int i=1; i<x.length; i++) {
           int temp=0;
           if(x[i-1] > x[i]) {
               temp = x[i-1];
                x[i-1] = x[i];
                x[i] = temp;
                swapped = true;
            }
        }
    }
}

Once swapped == false at the end of a loop, you have made a whole pass without finding any instances where x[i-1] > x[i] and, hence, you know the array is sorted. Only then can you terminate the algorithm.

You can also replace the outer while loop with a for loop of n+1 iterations, which will guarantee that the array is in order; however, the while loop has the advantage of early termination in a better-than-worst-case scenario.

Javascript for "Add to Home Screen" on iPhone?

In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/iPhoneOTAConfiguration/ConfigurationProfileExamples/ConfigurationProfileExamples.html

http://appdistro.cttapp.com/webclip/

after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..

Reset select value to default

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});

This is a simple way for your question. only one line answer.

How to open SharePoint files in Chrome/Firefox

Installing the Chrome extension IE Tab did the job for me.

It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.

You can install IETab for FireFox too.

How to center body on a page?

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.

How do I use the lines of a file as arguments of a command?

As already mentioned, you can use the backticks or $(cat filename).

What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:

a "b c" d

the arguments you will get are:

a
"b
c"
d

If you want to pull each line as an argument, use the while/read/do construct:

while read i ; do command_name $i ; done < filename

Angular CLI SASS options

Quoted from Officials github repo here -

To use one just install for example

npm install node-sass

and rename .css files in your project to .scss or .sass. They will be compiled automatically. The Angular2App's options argument has sassCompiler, lessCompiler, stylusCompiler and compassCompiler options that are passed directly to their respective CSS preprocessors.

See here

cartesian product in pandas

Use pd.MultiIndex.from_product as an index in an otherwise empty dataframe, then reset its index, and you're done.

a = [1, 2, 3]
b = ["a", "b", "c"]

index = pd.MultiIndex.from_product([a, b], names = ["a", "b"])

pd.DataFrame(index = index).reset_index()

out:

   a  b
0  1  a
1  1  b
2  1  c
3  2  a
4  2  b
5  2  c
6  3  a
7  3  b
8  3  c

How to use Visual Studio Code as Default Editor for Git

In addition of export EDITOR="code --wait", note that, with VSCode v1.47 (June 2020), those diff editors will survice a VSCode reload/restart.
See issue 99290:

with commit 1428d44, diff editors now have a chance to survive reloads and this works OK unless the diff editor on a git resource is opened as the active one:

enter image description here

(and commit 24f1b69 fixes that)

Remove Elements from a HashSet while Iterating

you can also refactor your solution removing the first loop:

Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>(set);

for(Integer element : set)
   if(element % 2 == 0)
       removeCandidates.add(element);

set.removeAll(removeCandidates);

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

What's the difference between “mod” and “remainder”?

Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:

7 % 3 = 1  // dividend % divisor = remainder

What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.

Can I use Objective-C blocks as properties?

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

As others have suggested, the best way to do this is to use a join instead of variable assignment. Re-writing your query to use a join (and using the explicit join syntax instead of the implicit join, which was also suggested--and is the best practice), you would get something like this:

select  
  OrderDetails.Sku,
  OrderDetails.mf_item_number,
  OrderDetails.Qty,
  OrderDetails.Price,
  Supplier.SupplierId, 
  Supplier.SupplierName,
  Supplier.DropShipFees, 
  Supplier_Item.Price as cost
from 
  OrderDetails
join Supplier on OrderDetails.Mfr_ID = Supplier.SupplierId
join Group_Master on Group_Master.Sku = OrderDetails.Sku 
join Supplier_Item on 
  Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID 
where 
  invoiceid='339740' 

How do you check current view controller class in Swift?

To go off of Thapa's answer, you need to cast to the viewcontroller class before using...

   if let wd = self.view.window {
        var vc = wd.rootViewController!
        if(vc is UINavigationController){
            vc = (vc as! UINavigationController).visibleViewController
        }
        if(vc is customViewController){
            var viewController : customViewController = vc as! customViewController

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

moment.js - UTC gives wrong date

By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.

In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.

If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.

Here are some examples to illustrate it (my local time offset is UTC+3 during DST):

>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"

If you want the date-time string interpreted as UTC, you should be explicit about it:

>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"

or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc() and include the format string as a second argument to prevent ambiguity.

>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"

To go the other way around and convert a UTC date to a local date, you can use the local() method, as follows:

>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"

Check if XML Element exists

How about trying this:

using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { 
            //do your code here
        }
    }
}

VBScript How can I Format Date?

This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").

option explicit

Wscript.Echo "Today is " & myDate(now)

' date formatted as your request
Function myDate(dt)
    dim d,m,y, sep
    sep = "-"
    ' right(..) here works as rpad(x,2,"0")
    d = right("0" & datePart("d",dt),2)
    m = right("0" & datePart("m",dt),2)
    y = datePart("yyyy",dt)
    myDate= m & sep & d & sep & y
End Function

How do I order my SQLITE database in descending order, for an android app?

This a terrible thing! It costs my a few hours! this is my table rows :

private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";

Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);

Every time when I update the table , I will update the CURRENT_TIME for sort. But I found that it is not work.The result is not sorted what I want. Finally, I found that, the column "current_time" is the default row of sqlite.

The solution is, rename the column "cur_time" instead of "current_time".

What does Include() do in LINQ?

I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application


Excerpt from the linked page:

Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:

Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.

Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the Include method.

Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace Collection(x => x.Courses) with Reference(x => x.Administrator).) Typically you'd use explicit loading only when you've turned lazy loading off.

Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.

Android: keep Service running when app is killed

The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs

The IntentService does the following:

Stops the service after all start requests have been handled, so you never have to call stopSelf().

Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground() method.
2)Restart the service if it gets killed. Here is a part of the example from the docs where they talk about restarting the service after it is killed

 public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the 
      // start ID so we know which request we're stopping when we finish the job 
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart 
      return START_STICKY;
  }  

Can't access Eclipse marketplace

Im my case, I changed the default browser to internet explorer from google chrome and the issue was resolved.

Error 1022 - Can't write; duplicate key in table

From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.

Error 1022: Can't write; duplicate key in table

jQuery find() method not working in AngularJS directive

You can do it like this:

 var myApp = angular.module('myApp', [])
  .controller('Ctrl', ['$scope', function($scope) {
     $scope.aaa = 3432
 }])
 .directive('test', function () {
    return {
       link: function (scope, elm, attr) {
           var look = elm.children('#findme').addClass("addedclass");
           console.log(look);
        }
   };
});

<div ng-app="myApp" ng-controller="Ctrl">
   <div test>TEST Div
      <div id="findme">{{aaa}}</div>
   </div>
</div>

http://jsfiddle.net/FZGKA/133/

To add server using sp_addlinkedserver

-- check if server exists in table sys.server

select * from sys.servers

-- set database security

    EXEC sp_configure 'show advanced options', 1
    RECONFIGURE
    GO

    EXEC sp_configure 'ad hoc distributed queries', 1
    RECONFIGURE
    GO

-- add the external dbserver

EXEC sp_addlinkedserver @server='#servername#'

-- add login on external server

EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'

-- control query on remote table

select top (1000) * from [#server#].[#database#].[#schema#].[#table#]

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

Firebase Storage How to store and Retrieve images

Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.

How to force IE to reload javascript?

If you are running ASP.Net, check out the Bundling and Minification module available in ASP.Net 4.5.

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

You can declare a "bundle" that points to your javascript file. Every time your file changes, it will generate a new querystring suffix... but will only do so when the file changes. This makes it super simple to deploy updates, because you don't even have to think about updating your tags with new version numbers.

It can also bundle multiple .js files together into one file, and minify them, all in one step. Ditto for css.

Restore a deleted file in the Visual Studio Code Recycle Bin

  1. First go to Recycle Bin of your local machine.
  2. Your VS code deleted files is there in Recycle Bin.
  3. So, Right click on deleted files and select-> Restore option then your deleted files will be automatically restored in your VS code.

What are the differences between a program and an application?

When I studied IT in college my prof. made it simple for me:

"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."

Got it right on the exam.

So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.

Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(

Closing database connections in Java

It is always better to close the database/resource objects after usage. Better close the connection, resultset and statement objects in the finally block.

Until Java 7, all these resources need to be closed using a finally block. If you are using Java 7, then for closing the resources, you can do as follows.

try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {

    // Statements
}
catch(....){}

Now, the con, stmt and rs objects become part of try block and Java automatically closes these resources after use.

Reactjs - Form input validation

You should avoid using refs, you can do it with onChange function.

On every change, update the state for the changed field.

Then you can easily check if that field is empty or whatever else you want.

You could do something as follows :

    class Test extends React.Component {
        constructor(props){
           super(props);
      
           this.state = {
               fields: {},
               errors: {}
           }
        }
    
        handleValidation(){
            let fields = this.state.fields;
            let errors = {};
            let formIsValid = true;

            //Name
            if(!fields["name"]){
               formIsValid = false;
               errors["name"] = "Cannot be empty";
            }
      
            if(typeof fields["name"] !== "undefined"){
               if(!fields["name"].match(/^[a-zA-Z]+$/)){
                  formIsValid = false;
                  errors["name"] = "Only letters";
               }        
            }
       
            //Email
            if(!fields["email"]){
               formIsValid = false;
               errors["email"] = "Cannot be empty";
            }
      
            if(typeof fields["email"] !== "undefined"){
               let lastAtPos = fields["email"].lastIndexOf('@');
               let lastDotPos = fields["email"].lastIndexOf('.');

               if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
                  formIsValid = false;
                  errors["email"] = "Email is not valid";
                }
           }  

           this.setState({errors: errors});
           return formIsValid;
       }
        
       contactSubmit(e){
            e.preventDefault();

            if(this.handleValidation()){
               alert("Form submitted");
            }else{
               alert("Form has errors.")
            }
      
        }
    
        handleChange(field, e){         
            let fields = this.state.fields;
            fields[field] = e.target.value;        
            this.setState({fields});
        }
    
        render(){
            return (
                <div>           
                   <form name="contactform" className="contactform" onSubmit= {this.contactSubmit.bind(this)}>
                        <div className="col-md-6">
                          <fieldset>
                               <input ref="name" type="text" size="30" placeholder="Name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                               <span style={{color: "red"}}>{this.state.errors["name"]}</span>
                              <br/>
                             <input refs="email" type="text" size="30" placeholder="Email" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                             <span style={{color: "red"}}>{this.state.errors["email"]}</span>
                             <br/>
                             <input refs="phone" type="text" size="30" placeholder="Phone" onChange={this.handleChange.bind(this, "phone")} value={this.state.fields["phone"]}/>
                             <br/>
                             <input refs="address" type="text" size="30" placeholder="Address" onChange={this.handleChange.bind(this, "address")} value={this.state.fields["address"]}/>
                             <br/>
                         </fieldset>
                      </div>
          
                  </form>
                </div>
          )
        }
    }

    React.render(<Test />, document.getElementById('container'));

In this example I did the validation only for email and name, but you have an idea how to do it. For the rest you can do it self.

There is maybe a better way, but you will get the idea.

Here is fiddle.

Hope this helps.

ImportError: No module named 'bottle' - PyCharm

pycharm 2019.3 ,my solution is below: enter image description here

downloading all the files in a directory with cURL

You can use script like this for mac:

for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/) 
 do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f 
done

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

What is the difference between DSA and RSA?

With reference to man ssh-keygen, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.

In conclusion, a 2048 bit RSA key is currently the best choice.

MORE PRECAUTIONS TO TAKE

Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.

To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

How do you Change a Package's Log Level using Log4j?

This work for my:

log4j.logger.org.hibernate.type=trace

Also can try:

log4j.category.org.hibernate.type=trace

indexOf Case Sensitive?

 static string Search(string factMessage, string b)
        {

            int index = factMessage.IndexOf(b, StringComparison.CurrentCultureIgnoreCase);
            string line = null;
            int i = index;
            if (i == -1)
            { return "not matched"; }
            else
            {
                while (factMessage[i] != ' ')
                {
                    line = line + factMessage[i];
                    i++;
                }

                return line;
            }

        }

List of strings to one string

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

Remove category & tag base from WordPress url - without a plugin

The dot trick will likely ruin your rss feeds and/or pagination. These work, though:

add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
    $category_rewrite=array();
    $categories=get_categories(array('hide_empty'=>false));
    foreach($categories as $category) {
        $category_nicename = $category->slug;
        if ( $category->parent == $category->cat_ID )
            $category->parent = 0;
        elseif ($category->parent != 0 )
            $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename;
        $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_category_permastruct();
    $old_base = str_replace( '%category%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]';
    return $category_rewrite;
}

// remove tag base
add_filter('tag_rewrite_rules', 'no_tag_base_rewrite_rules');
function no_tag_base_rewrite_rules($tag_rewrite) {
    $tag_rewrite=array();
    $tags=get_tags(array('hide_empty'=>false));
    foreach($tags as $tag) {
        $tag_nicename = $tag->slug;
        if ( $tag->parent == $tag->tag_ID )
            $tag->parent = 0;
        elseif ($tag->parent != 0 )
            $tag_nicename = get_tag_parents( $tag->parent, false, '/', true ) . $tag_nicename;
        $tag_rewrite['('.$tag_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?tag=$matches[1]&feed=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?tag=$matches[1]&paged=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/?$'] = 'index.php?tag=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_tag_permastruct();
    $old_base = str_replace( '%tag%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $tag_rewrite[$old_base.'$'] = 'index.php?tag_redirect=$matches[1]';
    return $tag_rewrite;
}

// remove author base
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) { 
    global $wpdb;    
    $author_rewrite = array();    
    $authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");    
    foreach($authors as $author) {
        $author_rewrite["({$author->nicename})/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?author_name=$matches[1]&feed=$matches[2]';
        $author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
    }      
    return $author_rewrite;}
add_filter('author_link', 'no_author_base', 1000, 2);
function no_author_base($link, $author_id) {
    $link_base = trailingslashit(get_option('home'));
    $link = preg_replace("|^{$link_base}author/|", '', $link);
    return $link_base . $link;
}

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

How to create a GUID in Excel?

=LOWER(
    CONCATENATE(
        DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8), "-", 
        DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4),"-","4", 
        DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",
        DEC2HEX(RANDBETWEEN(8,11)),
        DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",
        DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),
        DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4)
    )
)

Taken from git @mobilitymaster.

generate random string for div id

Based on HTML 4, the id should start from letter:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So, one of the solutions could be (alphanumeric):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

jQuery: get data attribute

This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');
    console.log($varName);
});

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

It doesn't matter - they are exactly the same thing. However, the main thing is that you must be consistent

p.s. I struggle with this sort of "whats the right thing" all the time.

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

Effects of the extern keyword on C functions

The extern keyword takes on different forms depending on the environment. If a declaration is available, the extern keyword takes the linkage as that specified earlier in the translation unit. In the absence of any such declaration, extern specifies external linkage.

static int g();
extern int g(); /* g has internal linkage */

extern int j(); /* j has tentative external linkage */

extern int h();
static int h(); /* error */

Here are the relevant paragraphs from the C99 draft (n1256):

6.2.2 Linkages of identifiers

[...]

4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

How to rename JSON key

If you want to rename all occurrences of some key you can use a regex with the g option. For example:

var json = [{"_id":"1","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"[email protected]","image":"some_image_url","name":"Name 2"}];

str = JSON.stringify(json);

now we have the json in string format in str.

Replace all occurrences of "_id" to "id" using regex with the g option:

str = str.replace(/\"_id\":/g, "\"id\":");

and return to json format:

json = JSON.parse(str);

now we have our json with the wanted key name.

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

Is there a shortcut to make a block comment in Xcode?

Cmd + Shift + 7 will comment the selected lines.

SQL Left Join first match only

After careful consideration this dillema has a few different solutions:

Aggregate Everything Use an aggregate on each column to get the biggest or smallest field value. This is what I am doing since it takes 2 partially filled out records and "merges" the data.

http://sqlfiddle.com/#!3/59cde/1

SELECT
  UPPER(IDNo) AS user_id
, MAX(FirstName) AS name_first
, MAX(LastName) AS name_last
, MAX(entry) AS row_num
FROM people P
GROUP BY 
  IDNo

Get First (or Last record)

http://sqlfiddle.com/#!3/59cde/23

-- ------------------------------------------------------
-- Notes
-- entry: Auto-Number primary key some sort of unique PK is required for this method
-- IDNo:  Should be primary key in feed, but is not, we are making an upper case version
-- This gets the first entry to get last entry, change MIN() to MAX()
-- ------------------------------------------------------

SELECT 
   PC.user_id
  ,PData.FirstName
  ,PData.LastName
  ,PData.entry
FROM (
  SELECT 
      P2.user_id
     ,MIN(P2.entry) AS rownum
  FROM (
    SELECT
        UPPER(P.IDNo) AS user_id 
      , P.entry 
    FROM people P
  ) AS P2
  GROUP BY 
    P2.user_id
) AS PC
LEFT JOIN people PData
ON PData.entry = PC.rownum
ORDER BY 
   PData.entry

WCF ServiceHost access rights

If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

.NET Core vs Mono

This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:

  • APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
    different; type shape differs in key cases). These differences
    currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
    include more of the .NET Framework BCL APIs over time.
  • Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
    programming model. For example, Code Access Security (CAS) is not
    supported, while reflection is supported.

If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

Linq and Entity framework are included in .NET Core, so you are safe to take a shot.

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

How to draw a path on a map using kml file?

In above code, you don't pass the kml data to your mapView anywhere in your code, as far as I can see. To display the route, you should parse the kml data i.e. via SAX parser, then display the route markers on the map.

See the code below for an example, but it's not complete though - just for you as a reference and get some idea.

This is a simple bean I use to hold the route information I will be parsing.

package com.myapp.android.model.navigation;

import java.util.ArrayList;
import java.util.Iterator;


public class NavigationDataSet { 

private ArrayList<Placemark> placemarks = new ArrayList<Placemark>();
private Placemark currentPlacemark;
private Placemark routePlacemark;

public String toString() {
    String s= "";
    for (Iterator<Placemark> iter=placemarks.iterator();iter.hasNext();) {
        Placemark p = (Placemark)iter.next();
        s += p.getTitle() + "\n" + p.getDescription() + "\n\n";
    }
    return s;
}

public void addCurrentPlacemark() {
    placemarks.add(currentPlacemark);
}

public ArrayList<Placemark> getPlacemarks() {
    return placemarks;
}

public void setPlacemarks(ArrayList<Placemark> placemarks) {
    this.placemarks = placemarks;
}

public Placemark getCurrentPlacemark() {
    return currentPlacemark;
}

public void setCurrentPlacemark(Placemark currentPlacemark) {
    this.currentPlacemark = currentPlacemark;
}

public Placemark getRoutePlacemark() {
    return routePlacemark;
}

public void setRoutePlacemark(Placemark routePlacemark) {
    this.routePlacemark = routePlacemark;
}

}

And the SAX Handler to parse the kml:

package com.myapp.android.model.navigation;

import android.util.Log;
import com.myapp.android.myapp;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.myapp.android.model.navigation.NavigationDataSet;
import com.myapp.android.model.navigation.Placemark;


public class NavigationSaxHandler extends DefaultHandler{ 

 // =========================================================== 
 // Fields 
 // =========================================================== 

 private boolean in_kmltag = false; 
 private boolean in_placemarktag = false; 
 private boolean in_nametag = false;
 private boolean in_descriptiontag = false;
 private boolean in_geometrycollectiontag = false;
 private boolean in_linestringtag = false;
 private boolean in_pointtag = false;
 private boolean in_coordinatestag = false;

 private StringBuffer buffer;

 private NavigationDataSet navigationDataSet = new NavigationDataSet(); 

 // =========================================================== 
 // Getter & Setter 
 // =========================================================== 

 public NavigationDataSet getParsedData() {
      navigationDataSet.getCurrentPlacemark().setCoordinates(buffer.toString().trim());
      return this.navigationDataSet; 
 } 

 // =========================================================== 
 // Methods 
 // =========================================================== 
 @Override 
 public void startDocument() throws SAXException { 
      this.navigationDataSet = new NavigationDataSet(); 
 } 

 @Override 
 public void endDocument() throws SAXException { 
      // Nothing to do
 } 

 /** Gets be called on opening tags like: 
  * <tag> 
  * Can provide attribute(s), when xml was like: 
  * <tag attribute="attributeValue">*/ 
 @Override 
 public void startElement(String namespaceURI, String localName, 
           String qName, Attributes atts) throws SAXException { 
      if (localName.equals("kml")) { 
           this.in_kmltag = true;
      } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = true; 
           navigationDataSet.setCurrentPlacemark(new Placemark());
      } else if (localName.equals("name")) { 
           this.in_nametag = true;
      } else if (localName.equals("description")) { 
          this.in_descriptiontag = true;
      } else if (localName.equals("GeometryCollection")) { 
          this.in_geometrycollectiontag = true;
      } else if (localName.equals("LineString")) { 
          this.in_linestringtag = true;              
      } else if (localName.equals("point")) { 
          this.in_pointtag = true;          
      } else if (localName.equals("coordinates")) {
          buffer = new StringBuffer();
          this.in_coordinatestag = true;                        
      }
 } 

 /** Gets be called on closing tags like: 
  * </tag> */ 
 @Override 
 public void endElement(String namespaceURI, String localName, String qName) 
           throws SAXException { 
       if (localName.equals("kml")) {
           this.in_kmltag = false; 
       } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = false;

       if ("Route".equals(navigationDataSet.getCurrentPlacemark().getTitle())) 
               navigationDataSet.setRoutePlacemark(navigationDataSet.getCurrentPlacemark());
        else navigationDataSet.addCurrentPlacemark();

       } else if (localName.equals("name")) { 
           this.in_nametag = false;           
       } else if (localName.equals("description")) { 
           this.in_descriptiontag = false;
       } else if (localName.equals("GeometryCollection")) { 
           this.in_geometrycollectiontag = false;
       } else if (localName.equals("LineString")) { 
           this.in_linestringtag = false;              
       } else if (localName.equals("point")) { 
           this.in_pointtag = false;          
       } else if (localName.equals("coordinates")) { 
           this.in_coordinatestag = false;
       }
 } 

 /** Gets be called on the following structure: 
  * <tag>characters</tag> */ 
 @Override 
public void characters(char ch[], int start, int length) { 
    if(this.in_nametag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setTitle(new String(ch, start, length));            
    } else 
    if(this.in_descriptiontag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setDescription(new String(ch, start, length));          
    } else
    if(this.in_coordinatestag){        
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        //navigationDataSet.getCurrentPlacemark().setCoordinates(new String(ch, start, length));
        buffer.append(ch, start, length);
    }
} 
}

and a simple placeMark bean:

package com.myapp.android.model.navigation;

public class Placemark {

String title;
String description;
String coordinates;
String address;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getCoordinates() {
    return coordinates;
}
public void setCoordinates(String coordinates) {
    this.coordinates = coordinates;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}

Finally the service class in my model that calls the calculation:

package com.myapp.android.model.navigation;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.myapp.android.myapp;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class MapService {

public static final int MODE_ANY = 0;
public static final int MODE_CAR = 1;
public static final int MODE_WALKING = 2;


public static String inputStreamToString (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}


public static NavigationDataSet calculateRoute(Double startLat, Double startLng, Double targetLat, Double targetLng, int mode) {
    return calculateRoute(startLat + "," + startLng, targetLat + "," + targetLng, mode);
}

public static NavigationDataSet calculateRoute(String startCoords, String targetCoords, int mode) {
    String urlPedestrianMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&dirflg=w&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlPedestrianMode: "+urlPedestrianMode);

    String urlCarMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlCarMode: "+urlCarMode);

    NavigationDataSet navSet = null;
    // for mode_any: try pedestrian route calculation first, if it fails, fall back to car route
    if (mode==MODE_ANY||mode==MODE_WALKING) navSet = MapService.getNavigationDataSet(urlPedestrianMode);
    if (mode==MODE_ANY&&navSet==null||mode==MODE_CAR) navSet = MapService.getNavigationDataSet(urlCarMode);
    return navSet;
}

/**
 * Retrieve navigation data set from either remote URL or String
 * @param url
 * @return navigation set
 */
public static NavigationDataSet getNavigationDataSet(String url) {

    // urlString = "http://192.168.1.100:80/test.kml";
    Log.d(myapp.APP,"urlString -->> " + url);
    NavigationDataSet navigationDataSet = null;
    try
        {           
        final URL aUrl = new URL(url);
        final URLConnection conn = aUrl.openConnection();
        conn.setReadTimeout(15 * 1000);  // timeout for reading the google maps data: 15 secs
        conn.connect();

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        SAXParser sp = spf.newSAXParser(); 

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /* Create a new ContentHandler and apply it to the XML-Reader*/ 
        NavigationSaxHandler navSax2Handler = new NavigationSaxHandler(); 
        xr.setContentHandler(navSax2Handler); 

        /* Parse the xml-data from our URL. */ 
        xr.parse(new InputSource(aUrl.openStream()));

        /* Our NavigationSaxHandler now provides the parsed data to us. */ 
        navigationDataSet = navSax2Handler.getParsedData(); 

        /* Set the result to be displayed in our GUI. */ 
        Log.d(myapp.APP,"navigationDataSet: "+navigationDataSet.toString());

    } catch (Exception e) {
        // Log.e(myapp.APP, "error with kml xml", e);
        navigationDataSet = null;
    }   

    return navigationDataSet;
}

}

Drawing:

/**
 * Does the actual drawing of the route, based on the geo points provided in the nav set
 *
 * @param navSet     Navigation set bean that holds the route information, incl. geo pos
 * @param color      Color in which to draw the lines
 * @param mMapView01 Map view to draw onto
 */
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {

    Log.d(myapp.APP, "map color before: " + color);        

    // color correction for dining, make it darker
    if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
    Log.d(myapp.APP, "map color after: " + color);

    Collection overlaysToAddAgain = new ArrayList();
    for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
        Object o = iter.next();
        Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
        if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
            // mMapView01.getOverlays().remove(o);
            overlaysToAddAgain.add(o);
        }
    }
    mMapView01.getOverlays().clear();
    mMapView01.getOverlays().addAll(overlaysToAddAgain);

    String path = navSet.getRoutePlacemark().getCoordinates();
    Log.d(myapp.APP, "path=" + path);
    if (path != null && path.trim().length() > 0) {
        String[] pairs = path.trim().split(" ");

        Log.d(myapp.APP, "pairs.length=" + pairs.length);

        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height

        Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);

        if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO 

        try {
            GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
            mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
            GeoPoint gp1;
            GeoPoint gp2 = startGP;

            for (int i = 1; i < pairs.length; i++) // the last one would be crash
            {
                lngLat = pairs[i].split(",");

                gp1 = gp2;

                if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                        && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

                    // for GeoPoint, first:latitude, second:longitude
                    gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

                    if (gp2.getLatitudeE6() != 22200000) { 
                        mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
                        Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
                    }
                }
                // Log.d(myapp.APP,"pair:" + pairs[i]);
            }
            //routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
            mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
        } catch (NumberFormatException e) {
            Log.e(myapp.APP, "Cannot draw route.", e);
        }
    }
    // mMapView01.getOverlays().addAll(routeOverlays); // use the default color
    mMapView01.setEnabled(true);
}

This is the RouteOverlay class:

package com.myapp.android.activity.map.nav;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class RouteOverlay extends Overlay { 

private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) { // GeoPoint is a int. (6E)
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    defaultColor = 999; // no defaultColor
}

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) {
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    this.defaultColor = defaultColor;
}

public void setText(String t) {
    this.text = t;
}

public void setBitmap(Bitmap bitmap) { 
    this.img = bitmap;
}

public int getMode() {
    return mode;
}

@Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) {
    Projection projection = mapView.getProjection();
    if (shadow == false) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Point point = new Point();
        projection.toPixels(gp1, point);
        // mode=1&#65306;start
        if(mode==1) {
            if(defaultColor==999)
            paint.setColor(Color.BLACK); // Color.BLUE
            else
            paint.setColor(defaultColor);
            RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
            point.x + mRadius, point.y + mRadius);
            // start point
            canvas.drawOval(oval, paint);
        }
        // mode=2&#65306;path
        else if(mode==2) {
            if(defaultColor==999)
            paint.setColor(Color.RED);
            else
            paint.setColor(defaultColor);
            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
        }
        /* mode=3&#65306;end */
        else if(mode==3) {
            /* the last path */

            if(defaultColor==999)
                paint.setColor(Color.BLACK);  // Color.GREEN
            else
                paint.setColor(defaultColor);

            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
            RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
            point2.x + mRadius,point2.y + mRadius);
            /* end point */
            paint.setAlpha(255);
            canvas.drawOval(oval, paint);
        }
    }
    return super.draw(canvas, mapView, shadow, when);
}

}

What's the best way to send a signal to all members of a process group?

Inspired by ysth’s comment

kill -- -PGID

instead of giving it a process number, give it the negation of the group number. As usual with almost any command, if you want a normal argument that starts with a - to not be interpreted as a switch, precede it with --

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

How do I mock a static method that returns void with PowerMock?

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();

What is the $$hashKey added to my JSON.stringify result

Here is how you can easily remove the $$hashKey from the object:

$scope.myNewObject = JSON.parse(angular.toJson($scope.myObject))

$scope.myObject - Refers to the Object that you want to perform the operation upon i.e. remove the $$hashKey from

$scope.myNewObject - Assign the modified original object to the new object so it can be used as necessary

Non-invocable member cannot be used like a method?

Where you've written "OffenceBox.Text()", you need to replace this with "OffenceBox.Text". It's a property, not a method - the clue's in the error!

Counting number of characters in a file through shell script

To get exact character count of string, use printf, as opposed to echo, cat, or running wc -c directly on a file, because using echo, cat, etc will count a newline character, which will give you the amount of characters including the newline character. So a file with the text 'hello' will print 6 if you use echo etc, but if you use printf it will return the exact 5, because theres no newline element to count.

How to use printf for counting characters within strings:

$printf '6chars' | wc -m
6

To turn this into a script you can run on a text file to count characters, save the following in a file called print-character-amount.sh:

#!/bin/bash
characters=$(cat "$1")
printf "$characters" | wc -m

chmod +x on file print-character-amount.sh containing above text, place the file in your PATH (i.e. /usr/bin/ or any directory exported as PATH in your .bashrc file) then to run script on text file type:

print-character-amount.sh file-to-count-characters-of.txt

Android: how do I check if activity is running?

Found an easy workaround with the following code

@Override 
protected void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
                // Activity is being brought to front and not being  created again, 
                // Thus finishing this activity will bring the last viewed activity to foreground
                finish(); 
            } 
    }

android TextView: setting the background color dynamically doesn't work

tv.setTextColor(getResources().getColor(R.color.solid_red));

Serializing PHP object to JSON

Following code is doing the job using reflection. It assumes you have getters for the properties you want to serialize

    <?php

    /**
     * Serialize a simple PHP object into json
     * Should be used for POPO that has getter methods for the relevant properties to serialize
     * A property can be simple or by itself another POPO object
     *
     * Class CleanJsonSerializer
     */
    class CleanJsonSerializer {

    /**
     * Local cache of a property getters per class - optimize reflection code if the same object appears several times
     * @var array
     */
    private $classPropertyGetters = array();

    /**
     * @param mixed $object
     * @return string|false
     */
    public function serialize($object)
    {
        return json_encode($this->serializeInternal($object));
    }

    /**
     * @param $object
     * @return array
     */
    private function serializeInternal($object)
    {
        if (is_array($object)) {
            $result = $this->serializeArray($object);
        } elseif (is_object($object)) {
            $result = $this->serializeObject($object);
        } else {
            $result = $object;
        }
        return $result;
    }

    /**
     * @param $object
     * @return \ReflectionClass
     */
    private function getClassPropertyGetters($object)
    {
        $className = get_class($object);
        if (!isset($this->classPropertyGetters[$className])) {
            $reflector = new \ReflectionClass($className);
            $properties = $reflector->getProperties();
            $getters = array();
            foreach ($properties as $property)
            {
                $name = $property->getName();
                $getter = "get" . ucfirst($name);
                try {
                    $reflector->getMethod($getter);
                    $getters[$name] = $getter;
                } catch (\Exception $e) {
                    // if no getter for a specific property - ignore it
                }
            }
            $this->classPropertyGetters[$className] = $getters;
        }
        return $this->classPropertyGetters[$className];
    }

    /**
     * @param $object
     * @return array
     */
    private function serializeObject($object) {
        $properties = $this->getClassPropertyGetters($object);
        $data = array();
        foreach ($properties as $name => $property)
        {
            $data[$name] = $this->serializeInternal($object->$property());
        }
        return $data;
    }

    /**
     * @param $array
     * @return array
     */
    private function serializeArray($array)
    {
        $result = array();
        foreach ($array as $key => $value) {
            $result[$key] = $this->serializeInternal($value);
        }
        return $result;
    }  
} 

How do I get the classes of all columns in a data frame?

Hello was looking for the same, and it could be also

unlist(lapply(mtcars,class))

Best C# API to create PDF

I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

jQuery: selecting each td in a tr

$('#tblNewAttendees tbody tr).each((index, tr)=> {
        //console.log(tr);
        $(tr).children('td').each ((index, td) => {
            console.log(td);

        }); 

    });

You can use this tr and td parameter also.

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Multiple returns from a function

I have implement like this for multiple return value PHP function. be nice with your code. thank you.

 <?php
    function multi_retun($aa)
    {
        return array(1,3,$aa);
    }
    list($one,$two,$three)=multi_retun(55);
    echo $one;
    echo $two;
    echo $three;
    ?>

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

POSIX 7

First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

That contains a link to a time.h, which as a header should be where structs are defined:

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

Can I set an opacity only to the background image of a div?

css

div { 
    width: 200px;
    height: 200px;
    display: block;
    position: relative;
}

div::after {
    content: "";
    background: url(image.jpg); 
    opacity: 0.5;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

html

<div> put your div content</div>

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

How do I exit the Vim editor?

This is for the worst-case scenario of exiting Vim if you just want out, have no idea what you've done and you don't care what will happen to the files you opened.

Ctrl-cEnterEnterviEnterCtrl-\Ctrl-n:qa!Enter

This should get you out most of the time.

Some interesting cases where you need something like this:

  • iCtrl-ovg (you enter insert mode, then visual mode and then operator pending mode)

  • QappendEnter

  • iCtrl-ogQCtrl-r=Ctrl-k (thanks to porges for this case)

  • :set insertmode (this is a case when Ctrl-\Ctrl-n returns you to normal mode)


Edit: This answer was corrected due to cases above. It used to be:

EscEscEsc:qa!Enter

However, that doesn't work if you have entered Ex mode. In that case you would need to do:

viEnter:qa!Enter

So a complete command for "I don't want to know what I've done and I don't want to save anything, I just want out now!" would be

viEnterEscEscEsc:qa!Enter

Javascript to sort contents of select element

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.

function sortSelect(selElem) {
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
}

How do I base64 encode (decode) in C?

I needed C++ implementation working on std::string. None of answers satisfied my needs, I needed simple two-function solution for encoding and decoding, but I was too lazy to write my own code, so I found this:

http://www.adp-gmbh.ch/cpp/common/base64.html

Credits for code go to René Nyffenegger.

Putting the code below in case the site goes down:

base64.cpp

/* 
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger [email protected]

*/

#include "base64.h"
#include <iostream>

static const std::string base64_chars = 
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}

base64.h

#include <string>

std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);

Usage

const std::string s = "test";
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
  std::string decoded = base64_decode(encoded);

Bootstrap datepicker disabling past dates without current date

Disable all past date

<script type="text/javascript">
        $(function () {
            /*--FOR DATE----*/
            var date = new Date();
            var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());

            //Date1
            $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({
              format: 'dd-mm-yyyy',
              todayHighlight:'TRUE',
              startDate: today,
              endDate:0,
              autoclose: true
            });

        });
</script>

Disable all future date

 var date = new Date();
 var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());

   //Date1
   $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({
       format: 'dd-mm-yyyy',
       todayHighlight:'TRUE',
       minDate: today,
       autoclose: true
   });

Linux command-line call not returning what it should from os.system?

Yes it's counter-intuitive and does not seem very pythonic, but it actually just mimics the unix API design, where these calld are C POSIX functions. Check man 3 popen && man 3 system

Somewhat more convenient snippet to replace os.system that I use:

from subprocess import (PIPE, Popen)


def invoke(command):
    '''
    Invoke command as a new system process and return its output.
    '''
    return Popen(command, stdout=PIPE, shell=True).stdout.read()


result = invoke('echo Hi, bash!')
# Result contains standard output (as you expected it in the first place).

Execute jar file with multiple classpath libraries from command prompt

Regardless of the OS the below command should work:

java -cp "MyJar.jar;lib/*" com.mainClass

Always use quotes and please take attention that lib/*.jar will not work.

What is cardinality in Databases?

It depends a bit on context. Cardinality means the number of something but it gets used in a variety of contexts.

  • When you're building a data model, cardinality often refers to the number of rows in table A that relate to table B. That is, are there 1 row in B for every row in A (1:1), are there N rows in B for every row in A (1:N), are there M rows in B for every N rows in A (N:M), etc.
  • When you are looking at things like whether it would be more efficient to use a b*-tree index or a bitmap index or how selective a predicate is, cardinality refers to the number of distinct values in a particular column. If you have a PERSON table, for example, GENDER is likely to be a very low cardinality column (there are probably only two values in GENDER) while PERSON_ID is likely to be a very high cardinality column (every row will have a different value).
  • When you are looking at query plans, cardinality refers to the number of rows that are expected to be returned from a particular operation.

There are probably other situations where people talk about cardinality using a different context and mean something else.

How to parse JSON using Node.js?

NodeJs is a JavaScript based server, so you can do the way you do that in pure JavaScript...

Imagine you have this Json in NodeJs...

var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);

And you can do above to get a parsed version of your json...

Read Variable from Web.Config

Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File

How can I get last characters of a string

Here 2 examples that will show you always the last character

_x000D_
_x000D_
var id="ctl03_Tabs1";

console.log(id.charAt(id.length - 1)); 

console.log(id[id.length - 1]); 
_x000D_
_x000D_
_x000D_

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

Run a Command Prompt command from Desktop Shortcut

Using the Drag and Drop method

  1. From the windows search bar type in cmd to pull up the windows bar operation.
  2. When the command line option is shown, right click it and select Open File Location.
  3. The file explorer opens and the shortcut link is highlighted in the folder. If it is not highlighted, then select it.
  4. Hold down the Control key and using the mouse drag the shortcut to the desktop. If you don't see Copy to Desktop while dragging and before dropping, then push down and hold the Control key until you see the message.
  5. Drop the link on the desktop.
  6. Change properties as needed.

How do I overload the square-bracket operator in C#?

That would be the item property: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

Maybe something like this would work:

public T Item[int index, int y]
{ 
    //Then do whatever you need to return/set here.
    get; set; 
}

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

ImportError: Cannot import name X

While you should definitely avoid circular dependencies, you can defer imports in python.

for example:

import SomeModule

def someFunction(arg):
    from some.dependency import DependentClass

this ( at least in some instances ) will circumvent the error.

Backbone.js fetch with parameters

changing:

collection.fetch({ data: { page: 1} });

to:

collection.fetch({ data: $.param({ page: 1}) });

So with out over doing it, this is called with your {data: {page:1}} object as options

Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default JSON-request options.
    var params = _.extend({
      type:         type,
      dataType:     'json',
      processData:  false
    }, options);

    // Ensure that we have a URL.
    if (!params.url) {
      params.url = getUrl(model) || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!params.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(model.toJSON());
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (Backbone.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.processData = true;
      params.data        = params.data ? {model : params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (Backbone.emulateHTTP) {
      if (type === 'PUT' || type === 'DELETE') {
        if (Backbone.emulateJSON) params.data._method = type;
        params.type = 'POST';
        params.beforeSend = function(xhr) {
          xhr.setRequestHeader('X-HTTP-Method-Override', type);
        };
      }
    }

    // Make the request.
    return $.ajax(params);
};

So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data is to the URL.

How do I prevent Conda from activating the base environment by default?

I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:

conda config --set auto_activate_base false

The first time you run it, it'll create a ./condarc in your home directory with that setting to override the default.

This wouldn't de-clutter your .bash_profile but it's a cleaner solution without manual editing that section that conda manages.

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

How to get screen width and height

Try via context.getResources().getDisplayMetrics() if you have a context available.

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}

Examples

Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

Labels

Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

Sql query to insert datetime in SQL Server

you need to add it like

insert into table1(date1) values('12-mar-2013');

How to establish ssh key pair when "Host key verification failed"

When you try to connect your remote server with ssh:

$ ssh username@ip_address

then the error raise, to solve it:

$ ssh-keygen -f "/home/local_username/.ssh/known_hosts" -R "ip_address"

Gitignore not working

I solved my problem doing the following:

First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.

There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.

Here is a quick fix for that

Edit > EOL Conversion > Windows Format > Save

You can blame your text editor settings for that.

For example:

As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.

So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore


# See https://help.github.com/ignore-files/ for more about ignoring files.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

If i open the same file using the default Notepad, this is what i get

## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from  https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache 

So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.

The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following

Edit > EOL Conversion > Windows Format > Save

The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.

How to remove the URL from the printing page?

<style type="text/css" media="print">
  @page {
    size: auto;  
    margin: 0;  
  }
</style>
//now set manual padding to body
<style>
  body{
    padding-left: 1.3cm;
    padding-right: 1.3cm; 
    padding-top: 1.1cm;
  }
</style>

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml

And, make sure following dependencies are present:

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>

pandas groupby sort within groups

If you don't need to sum a column, then use @tvashtar's answer. If you do need to sum, then you can use @joris' answer or this one which is very similar to it.

df.groupby(['job']).apply(lambda x: (x.groupby('source')
                                      .sum()
                                      .sort_values('count', ascending=False))
                                     .head(3))

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

For everyone struggling with this issue, you simply need to upgrade your openssl installation. I'm running windows 10, installed the latest anaconda 64-bit and am getting this error when I try to install/upgrade anything with 'conda' or 'pip'. If I uninstall the 64-bit anaconda and install the 32-bit, it works fine. I had a 64-bit version of openssl for windows installed, version 1.1.0 something. I uninstalled that and installed the latest I could find from here: https://slproweb.com/products/Win32OpenSSL.html -- there is a 64-bit version of 1.1.1 on there that worked. Now I can install packages via pip and conda successfully. Hope this helps.

Spring not autowiring in unit tests with JUnit

Add something like this to your root unit test class:

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration

This will use the XML in your default path. If you need to specify a non-default path then you can supply a locations property to the ContextConfiguration annotation.

http://static.springsource.org/spring/docs/2.5.6/reference/testing.html

Docker error cannot delete docker container, conflict: unable to remove repository reference

Noticed this is a 2-years old question, but still want to share my workaround for this particular question:

Firstly, run docker container ls -a to list all the containers you have and pinpoint the want you want to delete.

Secondly, delete the one with command docker container rm <CONTAINER ID> (If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID> to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container).

Thirdly, remove the container by running docker container rm <CONTAINER ID>.

Lastly you can run docker image ls -a to view all the images and delete the one you want to by running docker image rm <hash>.

Escape @ character in razor view engine

@Html.Raw("@") seems to me to be even more reliable than @@, since not in all cases @@ will escape.

Therefore:

<meta name="twitter:site" content="@twitterSite">

would be:

<meta name="twitter:site" content="@Html.Raw("@")twitterSite">

How to upload a project to Github

What you need it an SSH connection and GitHub init into your project. I will explain under Linux machine.

Let's start with some easy stuff: navigate into your project in the terminal, and use:

git init
git add .
git commit 

now let's add SSH into your machine: use ssh-keygen -t rsa -C "[email protected]" and copy the public key, then add it to your GitHub repo Deploy keys -> add one back to your machine project now launch: git push origin master if there is an error config your .github/config by nano .github/config and change the URL to ssh one by url = [email protected]:username/repo.... and that's it

How to call getClass() from a static method in Java?

Try something like this. It works for me. Logg (Class name)

    String level= "";

    Properties prop = new Properties();

    InputStream in =
            Logg.class.getResourceAsStream("resources\\config");

    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    level = prop.getProperty("Level");

How do I create a comma-separated list from an array in PHP?

You want to use implode for this.

ie: $commaList = implode(', ', $fruit);


There is a way to append commas without having a trailing one. You'd want to do this if you have to do some other manipulation at the same time. For example, maybe you want to quote each fruit and then separate them all by commas:

$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
    $fruitList .= $prefix . '"' . $fruit . '"';
    $prefix = ', ';
}

Also, if you just do it the "normal" way of appending a comma after each item (like it sounds you were doing before), and you need to trim the last one off, just do $list = rtrim($list, ', '). I see a lot of people unnecessarily mucking around with substr in this situation.

How to get back to the latest commit after checking out a previous commit?

show all branches and commit
git log --branches --oneline

show last commit
git log --branches -1 --oneline

show before last commit
git log --branches -2 --oneline

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
}
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...
}

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems

How can I make a Python script standalone executable to run without ANY dependency?

You can find the list of distribution utilities listed at Distribution Utilities.

I use bbfreeze and it has been working very well (yet to have Python 3 support though).

R memory management / cannot allocate vector of size n Mb

If you are running your script at linux environment you can use this command:

bsub -q server_name -R "rusage[mem=requested_memory]" "Rscript script_name.R"

and the server will allocate the requested memory for you (according to the server limits, but with good server - hugefiles can be used)

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

API token is the same as password from API point of view, see source code uses token in place of passwords for the API.

See related answer from @coffeebreaks in my question python-jenkins or jenkinsapi for jenkins remote access API in python

Others is described in doc to use http basic authentication model

Multiple Where clauses in Lambda expressions

Maybe

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty)
    .Where(l => l.InternalName != string.Empty)

?

You can probably also put it in the same where clause:

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

Properties file in python (similar to Java Properties)

i have used this, this library is very useful

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'

How to split CSV files as per number of rows specified?

Use the Linux split command:

split -l 20 file.txt new    

Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.

Type man split at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail command, for example) and then add it back on to each of the split files.

Moment js date time comparison

You should be able to compare them directly.

var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  _x000D_
  $('.compare').click(function(e) {_x000D_
  _x000D_
    var date = $('#date').val();_x000D_
  _x000D_
    var now = moment();_x000D_
    var then = moment(date);_x000D_
  _x000D_
    if (now > then) {_x000D_
      $('.result').text('Date is past');_x000D_
    } else {_x000D_
      $('.result').text('Date is future');_x000D_
    }_x000D_
_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<input type="text" name="date" id="date" value="2014-12-18"  placeholder="yyyy-mm-dd">_x000D_
<button class="compare">Compare date to current date</button>_x000D_
<br>_x000D_
<div class="result"></div>
_x000D_
_x000D_
_x000D_

Get program execution time in the shell

one possibly simple method ( that may not meet different users needs ) is the use of shell PROMPT.it is a simple solution that can be useful in some cases. You can use the bash prompting feature as in the example below:

export PS1='[\t \u@\h]\$' 

The above command will result in changing the shell prompt to :

[HH:MM:SS username@hostname]$ 

Each time you run a command (or hit enter) returning back to the shell prompt, the prompt will display current time.

notes:
1) beware that if you waited for sometime before you type your next command, then this time need to be considered, i.e the time displayed in the shell prompt is the timestamp when the shell prompt was displayed, not when you enter command. some users choose to hit Enter key to get a new prompt with a new timestamp before they are ready for the next command.
2) There are other available options and modifiers that can be used to change the bash prompt, refer to ( man bash ) for more details.

Can't connect to localhost on SQL Server Express 2012 / 2016

According to Aaron Bertand:

  1. You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services, and checking that the service SQL Server (SQLEXPRESS) is running. If not, start it.

  2. While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.

  3. You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools (or SQL Server Configuration Manager), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.

    SQL Server Configuration Manager

  4. Verify your SQL Server connection authentication mode matches your connection string:

    • If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":

      -- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
      USE [master]
      GO
      DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
      EXEC xp_instance_regwrite
        N'HKEY_LOCAL_MACHINE',
        N'Software\Microsoft\MSSQLServer\MSSQLServer',
        N'LoginMode',
        REG_DWORD,
        @SqlServerAndWindowsAuthenticationMode;
      GO
      
    • If you're connecting using "Integrated Security=true" (Windows Mode), and this error only comes up when debugging in web applications, then you need to add the ApplicationPoolIdentity as a SQL Server login:
  5. otherwise, run Start -> Run -> Services.msc If so, is it running?

If it's not running then

It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.

"SyntaxError: Unexpected token < in JSON at position 0"

Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path

'/:url(app|assets|stuff|etc)';

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had this issue when attempting to import data from an excel file (xlsx) into a SQL Server DB using SSMS 2014.

The 2007 Office System Driver: Data Connectivity Components install did the trick for me.

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

You should use async pipe. Doc: https://angular.io/api/common/AsyncPipe

For example:

<li *ngFor="let a of authorizationTypes | async"[value]="a.id">
     {{ a.name }}
</li>

Multiple GitHub Accounts & SSH Config

Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

git config user.name "account1"
git config user.email "[email protected]" 

Navigate to account2 project and run these:

git config user.name "account2"
git config user.email "[email protected]"