Programs & Examples On #X++

X++ is the development language used by Microsoft Dynamics AX. It belongs to the curly brackets and dot-operator class of programming languages (like C# or Java). It is an object-oriented, class-based, single dispatch language. X++ supports garbage collection, and SQL queries are integrated into the language.

Find the smallest positive integer that does not occur in a given sequence

I find another solution to do it with additional storage,

/*
* if A = [-1,2] the solution works fine
* */
public static int solution(int[] A) {

    int N = A.length;

    int[] C = new int[N];

    /*
     * Mark A[i] as visited by making A[A[i] - 1] negative
     * */
    for (int i = 0; i < N; i++) {

        /*
         * we need the absolute value for the duplicates
         * */
        int j = Math.abs(A[i]) - 1;

        if (j >= 0 && j < N && A[j] > 0) {
            C[j] = -A[j];
        }
    }

    for (int i = 0; i < N; i++) {

        if (C[i] == 0) {
            return i + 1;
        }
    }

    return N + 1;
}

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Initializing C dynamic arrays

Instead of using

int * p;
p = {1,2,3};

we can use

int * p;
p =(int[3]){1,2,3};

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Adding values to an array in java

  • First line : array created.
  • Third line loop started from j = 1 to j = 28123
  • Fourth line you give the variable x value (0) each time the loop is accessed.
  • Fifth line you put the value of j in the index 0.
  • Sixth line you do increment to the value x by 1.(but it will be reset to 0 at line 4)

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

Printing *s as triangles in Java?

Left alinged triangle- * **



from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)each  row contains star and no of stars i each row is incremented by 1.
So for Left alinged triangle we need to use 2 for loop.
1st "for loop" for printing n row.
2nd  "for loop for printing stars in each rows. 


 Code for  Left alinged triangle-

 public static void leftTriangle()
{
       /// here  no of rows is 4
 for (int a=1;a<=4;a++)// for loop for row
 {   
 for (int b=1;b<=a;b++)for loop for column
 {
 System.out.print("*");
 }

System.out.println();}
}

Right alinged triangle- *
**



from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
 2)In each  row we need to print spaces followed by a star & no of spaces            in each row is decremented by 1.
 So for Right alinged triangle we need to use 3 for loop.
 1st "for loop" for printing n row.
 2nd  "for loop for printing spaces.
 3rd "for loop" for printing stars.

Code for Right alinged triangle -

public void rightTriangle()
{
    // here 1st print space and then print star
  for (int a=1;a<=4;a++)// for loop for row
 { 
 for (int c =3;c>=a;c--)// for loop fr space
 {  
 System.out.print(" ");
 }
 for (int d=1;d<=a;d++)// for loop for column
 { 
 System.out.print("*");   
 }
 System.out.println(); 
 }
 }

Center Triangle- *
* *



from above pattern we come to know that- 1)we need to print pattern containing n rows (for above pattern n is 4). 2)Intially in each row we need to print spaces followed by a star & then again a space . NO of spaces in each row at start is decremented by 1. So for Right alinged triangle we need to use 3 for loop. 1st "for loop" for printing n row. 2nd "for loop for printing spaces. 3rd "for loop" for printing stars.

Code for center Triangle-

public  void centerTriangle()
{   
for (int a=1;a<=4;a++)// for lop for row
{   
for (int c =4;c>=a;c--)// for loop for space
{  
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}

CODE FOR PRINTING ALL 3 PATTERNS - public class space4 { public static void leftTriangle() { /// here no of rows is 4 for (int a=1;a<=4;a++)// for loop for row {
for (int b=1;b<=a;b++)for loop for column { System.out.print("*"); }

System.out.println();}
}

public static void rightTriangle()
{
    // here 1st print space and then print star
  for (int a=1;a<=4;a++)// for loop for row
 { 
 for (int c =3;c>=a;c--)// for loop for space
 {  
 System.out.print(" ");
 }
 for (int d=1;d<=a;d++)// for loop for column
 { 
 System.out.print("*");   
 }
 System.out.println(); 
 }
 }

public static void centerTriangle()
{   
for (int a=1;a<=4;a++)// for lop for row
{   
for (int c =4;c>=a;c--)// for loop for space
{  
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
public static void main (String args [])
{
space4 s=new space4();
s.leftTriangle();
s.rightTriangle();
s.centerTriangle();
}
}

Why am I getting InputMismatchException?

Instead of using a dot, like: 1.2, try to input like this: 1,2.

Change image in HTML page every few seconds

Change setTimeout("changeImage()", 30000); to setInterval("changeImage()", 30000); and remove var timerid = setInterval(changeImage, 30000);.

How to calculate the median of an array?

If you want to use any external library here is Apache commons math library using you can calculate the Median.
For more methods and use take look at the API documentation

import org.apache.commons.math3.*;
.....
......
........
//calculate median
public double getMedian(double[] values){
 Median median = new Median();
 double medianValue = median.evaluate(values);
 return medianValue;
}
.......

Update

Calculate in program

Generally, median is calculated using the following two formulas given here

If n is odd then Median (M) = value of ((n + 1)/2)th item term.
If n is even then Median (M) = value of [((n)/2)th item term + ((n)/2 + 1)th item term ]/2

In your program you have numArray, first you need to sort array using Arrays#sort

Arrays.sort(numArray);
int middle = numArray.length/2;
int medianValue = 0; //declare variable 
if (numArray.length%2 == 1) 
    medianValue = numArray[middle];
else
   medianValue = (numArray[middle-1] + numArray[middle]) / 2;

Why use a ReentrantLock if one can use synchronized(this)?

One thing to keep in mind is :

The name 'ReentrantLock' gives out a wrong message about other locking mechanism that they are not re-entrant. This is not true. Lock acquired via 'synchronized' is also re-entrant in Java.

Key difference is that 'synchronized' uses intrinsic lock ( one that every Object has ) while Lock API doesn't.

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

Hexadecimal value 0x00 is a invalid character

Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:

  • Unicode NUL (0x00) is illegal in all versions of XML and validating parsers must reject input that contains it.
  • Despite the above; real-world non-validated XML can contain any kind of garbage ill-formed bytes imaginable.
  • XML 1.1 allows zero-width and nonprinting control characters (except NUL), so you cannot look at an XML 1.1 file in a text editor and tell what characters it contains.

Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.

Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.

If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.

Check file encoding (for UTF-16)

Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.

How do I print out the contents of a vector?

This solution was inspired by Marcelo's solution, with a few changes:

#include <iostream>
#include <iterator>
#include <type_traits>
#include <vector>
#include <algorithm>

// This works similar to ostream_iterator, but doesn't print a delimiter after the final item
template<typename T, typename TChar = char, typename TCharTraits = std::char_traits<TChar> >
class pretty_ostream_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
    typedef TChar char_type;
    typedef TCharTraits traits_type;
    typedef std::basic_ostream<TChar, TCharTraits> ostream_type;

    pretty_ostream_iterator(ostream_type &stream, const char_type *delim = NULL)
        : _stream(&stream), _delim(delim), _insertDelim(false)
    {
    }

    pretty_ostream_iterator<T, TChar, TCharTraits>& operator=(const T &value)
    {
        if( _delim != NULL )
        {
            // Don't insert a delimiter if this is the first time the function is called
            if( _insertDelim )
                (*_stream) << _delim;
            else
                _insertDelim = true;
        }
        (*_stream) << value;
        return *this;
    }

    pretty_ostream_iterator<T, TChar, TCharTraits>& operator*()
    {
        return *this;
    }

    pretty_ostream_iterator<T, TChar, TCharTraits>& operator++()
    {
        return *this;
    }

    pretty_ostream_iterator<T, TChar, TCharTraits>& operator++(int)
    {
        return *this;
    }
private:
    ostream_type *_stream;
    const char_type *_delim;
    bool _insertDelim;
};

#if _MSC_VER >= 1400

// Declare pretty_ostream_iterator as checked
template<typename T, typename TChar, typename TCharTraits>
struct std::_Is_checked_helper<pretty_ostream_iterator<T, TChar, TCharTraits> > : public std::tr1::true_type
{
};

#endif // _MSC_VER >= 1400

namespace std
{
    // Pre-declarations of container types so we don't actually have to include the relevant headers if not needed, speeding up compilation time.
    // These aren't necessary if you do actually include the headers.
    template<typename T, typename TAllocator> class vector;
    template<typename T, typename TAllocator> class list;
    template<typename T, typename TTraits, typename TAllocator> class set;
    template<typename TKey, typename TValue, typename TTraits, typename TAllocator> class map;
}

// Basic is_container template; specialize to derive from std::true_type for all desired container types
template<typename T> struct is_container : public std::false_type { };

// Mark vector as a container
template<typename T, typename TAllocator> struct is_container<std::vector<T, TAllocator> > : public std::true_type { };

// Mark list as a container
template<typename T, typename TAllocator> struct is_container<std::list<T, TAllocator> > : public std::true_type { };

// Mark set as a container
template<typename T, typename TTraits, typename TAllocator> struct is_container<std::set<T, TTraits, TAllocator> > : public std::true_type { };

// Mark map as a container
template<typename TKey, typename TValue, typename TTraits, typename TAllocator> struct is_container<std::map<TKey, TValue, TTraits, TAllocator> > : public std::true_type { };

// Holds the delimiter values for a specific character type
template<typename TChar>
struct delimiters_values
{
    typedef TChar char_type;
    const TChar *prefix;
    const TChar *delimiter;
    const TChar *postfix;
};

// Defines the delimiter values for a specific container and character type
template<typename T, typename TChar>
struct delimiters
{
    static const delimiters_values<TChar> values; 
};

// Default delimiters
template<typename T> struct delimiters<T, char> { static const delimiters_values<char> values; };
template<typename T> const delimiters_values<char> delimiters<T, char>::values = { "{ ", ", ", " }" };
template<typename T> struct delimiters<T, wchar_t> { static const delimiters_values<wchar_t> values; };
template<typename T> const delimiters_values<wchar_t> delimiters<T, wchar_t>::values = { L"{ ", L", ", L" }" };

// Delimiters for set
template<typename T, typename TTraits, typename TAllocator> struct delimiters<std::set<T, TTraits, TAllocator>, char> { static const delimiters_values<char> values; };
template<typename T, typename TTraits, typename TAllocator> const delimiters_values<char> delimiters<std::set<T, TTraits, TAllocator>, char>::values = { "[ ", ", ", " ]" };
template<typename T, typename TTraits, typename TAllocator> struct delimiters<std::set<T, TTraits, TAllocator>, wchar_t> { static const delimiters_values<wchar_t> values; };
template<typename T, typename TTraits, typename TAllocator> const delimiters_values<wchar_t> delimiters<std::set<T, TTraits, TAllocator>, wchar_t>::values = { L"[ ", L", ", L" ]" };

// Delimiters for pair
template<typename T1, typename T2> struct delimiters<std::pair<T1, T2>, char> { static const delimiters_values<char> values; };
template<typename T1, typename T2> const delimiters_values<char> delimiters<std::pair<T1, T2>, char>::values = { "(", ", ", ")" };
template<typename T1, typename T2> struct delimiters<std::pair<T1, T2>, wchar_t> { static const delimiters_values<wchar_t> values; };
template<typename T1, typename T2> const delimiters_values<wchar_t> delimiters<std::pair<T1, T2>, wchar_t>::values = { L"(", L", ", L")" };

// Functor to print containers. You can use this directly if you want to specificy a non-default delimiters type.
template<typename T, typename TChar = char, typename TCharTraits = std::char_traits<TChar>, typename TDelimiters = delimiters<T, TChar> >
struct print_container_helper
{
    typedef TChar char_type;
    typedef TDelimiters delimiters_type;
    typedef std::basic_ostream<TChar, TCharTraits>& ostream_type;

    print_container_helper(const T &container)
        : _container(&container)
    {
    }

    void operator()(ostream_type &stream) const
    {
        if( delimiters_type::values.prefix != NULL )
            stream << delimiters_type::values.prefix;
        std::copy(_container->begin(), _container->end(), pretty_ostream_iterator<typename T::value_type, TChar, TCharTraits>(stream, delimiters_type::values.delimiter));
        if( delimiters_type::values.postfix != NULL )
            stream << delimiters_type::values.postfix;
    }
private:
    const T *_container;
};

// Prints a print_container_helper to the specified stream.
template<typename T, typename TChar, typename TCharTraits, typename TDelimiters>
std::basic_ostream<TChar, TCharTraits>& operator<<(std::basic_ostream<TChar, TCharTraits> &stream, const print_container_helper<T, TChar, TDelimiters> &helper)
{
    helper(stream);
    return stream;
}

// Prints a container to the stream using default delimiters
template<typename T, typename TChar, typename TCharTraits>
typename std::enable_if<is_container<T>::value, std::basic_ostream<TChar, TCharTraits>&>::type
    operator<<(std::basic_ostream<TChar, TCharTraits> &stream, const T &container)
{
    stream << print_container_helper<T, TChar, TCharTraits>(container);
    return stream;
}

// Prints a pair to the stream using delimiters from delimiters<std::pair<T1, T2>>.
template<typename T1, typename T2, typename TChar, typename TCharTraits>
std::basic_ostream<TChar, TCharTraits>& operator<<(std::basic_ostream<TChar, TCharTraits> &stream, const std::pair<T1, T2> &value)
{
    if( delimiters<std::pair<T1, T2>, TChar>::values.prefix != NULL )
        stream << delimiters<std::pair<T1, T2>, TChar>::values.prefix;

    stream << value.first;

    if( delimiters<std::pair<T1, T2>, TChar>::values.delimiter != NULL )
        stream << delimiters<std::pair<T1, T2>, TChar>::values.delimiter;

    stream << value.second;

    if( delimiters<std::pair<T1, T2>, TChar>::values.postfix != NULL )
        stream << delimiters<std::pair<T1, T2>, TChar>::values.postfix;
    return stream;    
}

// Used by the sample below to generate some values
struct fibonacci
{
    fibonacci() : f1(0), f2(1) { }
    int operator()()
    {
        int r = f1 + f2;
        f1 = f2;
        f2 = r;
        return f1;
    }
private:
    int f1;
    int f2;
};

int main()
{
    std::vector<int> v;
    std::generate_n(std::back_inserter(v), 10, fibonacci());

    std::cout << v << std::endl;

    // Example of using pretty_ostream_iterator directly
    std::generate_n(pretty_ostream_iterator<int>(std::cout, ";"), 20, fibonacci());
    std::cout << std::endl;
}

Like Marcelo's version, it uses an is_container type trait that must be specialized for all containers that are to be supported. It may be possible to use a trait to check for value_type, const_iterator, begin()/end(), but I'm not sure I'd recommend that since it might match things that match those criteria but aren't actually containers, like std::basic_string. Also like Marcelo's version, it uses templates that can be specialized to specify the delimiters to use.

The major difference is that I've built my version around a pretty_ostream_iterator, which works similar to the std::ostream_iterator but doesn't print a delimiter after the last item. Formatting the containers is done by the print_container_helper, which can be used directly to print containers without an is_container trait, or to specify a different delimiters type.

I've also defined is_container and delimiters so it will work for containers with non-standard predicates or allocators, and for both char and wchar_t. The operator<< function itself is also defined to work with both char and wchar_t streams.

Finally, I've used std::enable_if, which is available as part of C++0x, and works in Visual C++ 2010 and g++ 4.3 (needs the -std=c++0x flag) and later. This way there is no dependency on Boost.

Pointers in JavaScript?

Depending on what you would like to do, you could simply save the variable name, and then access it later on like so:

function toAccessMyVariable(variableName){
  alert(window[variableName]);
}

var myFavoriteNumber = 6; 

toAccessMyVariable("myFavoriteNumber");

To apply to your specific example, you could do something like this:

var x = 0;
var pointerToX = "x";

function a(variableName)
{
    window[variableName]++;
}
a(pointerToX);
alert(x); //Here I want to have 1 instead of 0

Calculating and printing the nth prime number

I can see that you have received many correct answers and very detailed one. I believe you are not testing it for very large prime numbers. And your only concern is to avoid printing intermediary prime number by your program.

A tiny change your program will do the trick.

Keep your logic same way and just pull out the print statement outside of loop. Break outer loop after n prime numbers.

import java.util.Scanner;
/**
 * Calculates the nth prime number
 * @author {Zyst}
 */
public class Prime {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int n, 
            i = 2, 
            x = 2;

        System.out.printf("This program calculates the nth Prime number\n");
        System.out.printf("Please enter the nth prime number you want to find:");
        n = input.nextInt();

        for(i = 2, x = 2; n > 0; i++) {
            for(x = 2; x < i; x++) {
                if(i % x == 0) {
                    break;
                }
            }
            if(x == i) {
                n--;
            }
        }
        System.out.printf("\n%d is prime", x);

    }
}

Pass variables by reference in JavaScript

Yet another approach to pass any (local, primitive) variables by reference is by wrapping variable with closure "on the fly" by eval. This also works with "use strict". (Note: be aware that eval is not friendly to JavaScript optimizers, and also missing quotes around variable name may cause unpredictive results)

"use strict"

// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
    return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}

// Demo

// Assign argument by reference
function modifyArgument(argRef, multiplier){
    argRef.value = argRef.value * multiplier;
}

(function(){
    var x = 10;

    alert("x before: " + x);
    modifyArgument(eval(byRef("x")), 42);
    alert("x after: " + x);
})()

Live sample: https://jsfiddle.net/t3k4403w/

Writing a large resultset to an Excel file using POI

For now I took @Gian's advice & limited the number of records per Workbook to 500k and rolled over the rest to the next Workbook. Seems to be working decent. For the above configuration, it took me about 10 mins per workbook.

How can I get javascript to read from a .json file?

NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

_x000D_
_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
    if (this.readyState == 4 && this.status == 200) {_x000D_
        var myObj = JSON.parse(this.responseText);_x000D_
        document.getElementById("demo").innerHTML = myObj.name;_x000D_
    }_x000D_
};_x000D_
xmlhttp.open("GET", "json_demo.txt", true);_x000D_
xmlhttp.send();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

_x000D_
_x000D_
var json = '{"result":true, "count":42}';_x000D_
obj = JSON.parse(json);_x000D_
_x000D_
console.log(obj.count);_x000D_
// expected output: 42_x000D_
_x000D_
console.log(obj.result);_x000D_
// expected output: true
_x000D_
_x000D_
_x000D_

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

You can get all keys in the Request.Form and then compare and get your desired values.

Your method body will look like this: -

List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("List"))
    {
        listValues.Add(Convert.ToInt32(Request.Form[key]));
    }
}

Initialize a byte array to a certain value, other than the default null?

You can use a collection initializer:

UserCode = new byte[]{0x20,0x20,0x20,0x20,0x20,0x20};

This will work better than Repeat if the values are not identical.

Generating UNIQUE Random Numbers within a range

The idea consists to use the keys, when a value is already present in the array keys, the array size stays the same:

function getDistinctRandomNumbers ($nb, $min, $max) {
    if ($max - $min + 1 < $nb)
        return false; // or throw an exception

    $res = array();
    do {
        $res[mt_rand($min, $max)] = 1;
    } while (count($res) !== $nb);
    return array_keys($res); 
}

Pro: This way avoids the use of in_array and doesn't generate a huge array. So, it is fast and preserves a lot of memory.

Cons: when the rate (range/quantity) decreases, the speed decreases too (but stays correct). For a same rate, relative speed increases with the range size.(*)

(*) I understand that fact since there are more free integers to select (in particular for the first steps), but if somebody has the mathematical formula that describes this behaviour, I am interested by, don't hesitate.

Conclusion: The best "general" function seems to be a mix between this function and @Anne function that is more efficient with a little rate. This function should switch between the two ways when a certain quantity is needed and a rate (range/quantity) is reached. So the complexity/time of the test to know that, must be taken in account.

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

Undefined Reference to

I was getting this error because my cpp files was not added in the CMakeLists.txt file

Parse JSON from JQuery.ajax success data

One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do

alert(data)

if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert

[object Object]

If this the response then you can be sure that you can use this as an object (json in this case).

Thus, you need to convert your string into json first, before using it by doing this:

JSON.parse(data)

Static variable inside of a function in C

A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

try using return 0;

if it keeps failing change your solution platform to 64x instead of 86x and go to configuration manager(that's were you change the 86x to 64x) and in platform set it to 64 bits

that works for me, hope it work to you

Floating point exception

It's caused by n % x, when x is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

General notes:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.

create array from mysql query php

while($row = mysql_fetch_assoc($result)) {
  echo $row['type'];
}

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

Creating a JSON response using Django and Python

Most of these answers are out of date. JsonResponse is not recommended because it escapes the characters, which is usually undesired. Here's what I use:

views.py (returns HTML)

from django.shortcuts import render
from django.core import serializers

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    context = {"data":data}
    return render(request, "your_view.html", context)

views.py (returns JSON)

from django.core import serializers
from django.http import HttpResponse

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    return HttpResponse(data, content_type='application/json')

Bonus for Vue Users

If you want to bring your Django Queryset into Vue, you can do the following.

template.html

<div id="dataJson" style="display:none">
{{ data }}
</div>

<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
  el: '#app',
  data: {
    yourVariable: dataParsed,
  },
})
</script>

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

Android: How to detect double-tap?

boolean nonDoubleClick = true, singleClick = false;
        private long firstClickTime = 0L;
        private final int DOUBLE_CLICK_TIMEOUT = 200;

        listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
                // TODO Auto-generated method stub
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (singleClick) {
                            Toast.makeText(getApplicationContext(), "Single Tap Detected", Toast.LENGTH_SHORT).show();
                        }
                        firstClickTime = 0L;
                        nonDoubleClick = true;
                        singleClick = false;
                    }
                }, 200);
                if (firstClickTime == 0) {
                    firstClickTime = SystemClock.elapsedRealtime();
                    nonDoubleClick = true;
                    singleClick = true;
                } else {
                    long deltaTime = SystemClock.elapsedRealtime() - firstClickTime;
                    firstClickTime = 0;
                    if (deltaTime < DOUBLE_CLICK_TIMEOUT) {
                        nonDoubleClick = false;
                        singleClick = false;
                        Toast.makeText(getApplicationContext(), "Double Tap Detected", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });

Append a Lists Contents to another List C#

Here is my example:

    private List<int> m_machinePorts = new List<int>();

    public List<int> machinePorts
    {
        get { return m_machinePorts; }
    }

    Init()
    {
        // Custom function to get available ethernet ports
        List<int> localEnetPorts = _Globals.GetAvailableEthernetPorts();

        // Custome function to get available serial ports
        List<int> localPorts = _Globals.GetAvailableSerialPorts();

        // Build Available port list 
        m_machinePorts.AddRange(localEnetPorts);
        m_machinePorts.AddRange(localPorts);
     }

Incrementing in C++ - When to use x++ or ++x?

You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.

An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.

Edit: fixed the mixup of prefix and suffix notation

Splitting words into letters in Java

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

How can I iterate through a string and also know the index (current position)?

Like this:


    std::string s("Test string");
    std::string::iterator it = s.begin();

    //Use the iterator...
    ++it;
    //...

    std::cout << "index is: " << std::distance(s.begin(), it) << std::endl;

How can I find the last element in a List<>?

Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!

You can also doing something like;


if (integerList.Count > 0) 
   var item = integerList[^1];

See the tutorial post on the MS C# docs here from a few months back.

I would personally still stick with LastOrDefault() / Last() but thought I'd share this.

EDIT; Just realised another answer has mentioned this with another doc link.

Pass Additional ViewData to a Strongly-Typed Partial View

I think this should work no?

ViewData["currentIndex"] = index;

Is there a difference between x++ and ++x in java?

Yes,

int x=5;
System.out.println(++x);

will print 6 and

int x=5;
System.out.println(x++);

will print 5.

Preloading images with jQuery

A quick, plugin-free way to preload images in jQuery and get a callback function is to create multiple img tags at once and count the responses, e.g.

function preload(files, cb) {
    var len = files.length;
    $(files.map(function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

preload(["one.jpg", "two.png", "three.png"], function() {
    /* Code here is called once all files are loaded. */
});
?    ?

Note that if you want to support IE7, you'll need to use this slightly less pretty version (Which also works in other browsers):

function preload(files, cb) {
    var len = files.length;
    $($.map(files, function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

How do you read CSS rule values with JavaScript?

Based on @dude answer this should return relevant styles in a object, for instance:

.recurly-input {                                                                                                                                                                             
  display: block;                                                                                                                                                                            
  border-radius: 2px;                                                                                                                                                                        
  -webkit-border-radius: 2px;                                                                                                                                                                
  outline: 0;                                                                                                                                                                                
  box-shadow: none;                                                                                                                                                                          
  border: 1px solid #beb7b3;                                                                                                                                                                 
  padding: 0.6em;                                                                                                                                                                            
  background-color: #f7f7f7;                                                                                                                                                                 
  width:100%;                                                                                                                                                                                
}

This will return:

backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"

Code:

function getStyle(className_) {

    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        if (!classes)
            continue;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
            }
        }
    }

}

What's the best way to break from nested loops in JavaScript?

If you use Coffeescript, there is a convenient "do" keyword that makes it easier to define and immediately execute an anonymous function:

do ->
  for a in first_loop
    for b in second_loop
      if condition(...)
        return

...so you can simply use "return" to get out of the loops.

How to check for valid email address?

"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$"

Generate a random point within a circle (uniformly)

Here is a fast and simple solution.

Pick two random numbers in the range (0, 1), namely a and b. If b < a, swap them. Your point is (b*R*cos(2*pi*a/b), b*R*sin(2*pi*a/b)).

You can think about this solution as follows. If you took the circle, cut it, then straightened it out, you'd get a right-angled triangle. Scale that triangle down, and you'd have a triangle from (0, 0) to (1, 0) to (1, 1) and back again to (0, 0). All of these transformations change the density uniformly. What you've done is uniformly picked a random point in the triangle and reversed the process to get a point in the circle.

Removing u in list

[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']

'u' denotes unicode characters. We can easily remove this with map function on the final list element

map(str, test)

Another way is when you are appending it to the list

test.append(str(a))

Rails how to run rake task

Rake::Task['reklamer:orville'].invoke

or

Rake::Task['reklamer:orville'].invoke(args)

How to pass a function as a parameter in Java?

Thanks to Java 8 you don't need to do the steps below to pass a function to a method, that's what lambdas are for, see Oracle's Lambda Expression tutorial. The rest of this post describes what we used to have to do in the bad old days in order to implement this functionality.

Typically you declare your method as taking some interface with a single method, then you pass in an object that implements that interface. An example is in commons-collections, where you have interfaces for Closure, Transformer, and Predicate, and methods that you pass implementations of those into. Guava is the new improved commons-collections, you can find equivalent interfaces there.

So for instance, commons-collections has org.apache.commons.collections.CollectionUtils, which has lots of static methods that take objects passed in, to pick one at random, there's one called exists with this signature:

static boolean exists(java.util.Collection collection, Predicate predicate) 

It takes an object that implements the interface Predicate, which means it has to have a method on it that takes some Object and returns a boolean.

So I can call it like this:

CollectionUtils.exists(someCollection, new Predicate() {
    public boolean evaluate(Object object) { 
        return ("a".equals(object.toString());
    }
});

and it returns true or false depending on whether someCollection contains an object that the predicate returns true for.

Anyway, this is just an example, and commons-collections is outdated. I just forget the equivalent in Guava.

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

Split by comma and strip whitespace in Python

import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.

Please try!

JQuery style display value

Just call css with one argument

  $('#idDetails').css('display');

If I understand your question. Otherwise, you want cletus' answer.

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

Adding Git-Bash to the new Windows Terminal

This is the complete answer (GitBash + color scheme + icon + context menu)

1) Set default profile:

"globals" : 
{
    "defaultProfile" : "{00000000-0000-0000-0000-000000000001}",
    ...

2) Add GitBash profile

"profiles" : 
[
    {
        "guid": "{00000000-0000-0000-0000-000000000001}",
        "acrylicOpacity" : 0.75,
        "closeOnExit" : true,
        "colorScheme" : "GitBash",
        "commandline" : "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i -l",
        "cursorColor" : "#FFFFFF",
        "cursorShape" : "bar",
        "fontFace" : "Consolas",
        "fontSize" : 10,
        "historySize" : 9001,
        "icon" : "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", 
        "name" : "GitBash",
        "padding" : "0, 0, 0, 0",
        "snapOnInput" : true,
        "startingDirectory" : "%USERPROFILE%",
        "useAcrylic" : false        
    },

3) Add GitBash color scheme

"schemes" : 
[
    {
        "background" : "#000000",
        "black" : "#0C0C0C",
        "blue" : "#6060ff",
        "brightBlack" : "#767676",
        "brightBlue" : "#3B78FF",
        "brightCyan" : "#61D6D6",
        "brightGreen" : "#16C60C",
        "brightPurple" : "#B4009E",
        "brightRed" : "#E74856",
        "brightWhite" : "#F2F2F2",
        "brightYellow" : "#F9F1A5",
        "cyan" : "#3A96DD",
        "foreground" : "#bfbfbf",
        "green" : "#00a400",
        "name" : "GitBash",
        "purple" : "#bf00bf",
        "red" : "#bf0000",
        "white" : "#ffffff",
        "yellow" : "#bfbf00",
        "grey" : "#bfbfbf"
    },  

4) To add a right-click context menu "Windows Terminal Here"

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt]
@="Windows terminal here"
"Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico"

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command]
@="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\""
  • replace {YOUR_WINDOWS_USERNAME}
  • create icon folder, put the icon there and replace {YOUR_ICONS_FOLDER}
  • save this in a whatever_filename.reg file and run it.

'names' attribute must be the same length as the vector

The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

How to get main window handle from process id?

There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())) as the MainWindow. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows() to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.

Replace forward slash "/ " character in JavaScript string?

Just use the split - join approach:

my_string.split('/').join('replace_with_this')

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

Where can I find error log files?

This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.


You can get the current log file assigned natively to php on any platform at runtime by using:

ini_get('error_log');

This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.

You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

(change) vs (ngModelChange) in angular

(change) event bound to classical input change event.

https://developer.mozilla.org/en-US/docs/Web/Events/change

You can use (change) event even if you don't have a model at your input as

<input (change)="somethingChanged()">

(ngModelChange) is the @Output of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.

https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124

As you discover more in the source code, (ngModelChange) emits the new value.

https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169

So it means you have ability of such usage:

<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
    // do something with new value
}

Basically, it seems like there is no big difference between two, but ngModel events gains the power when you use [ngValue].

  <select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
      <option *ngFor="let currentData of allData" [ngValue]="currentData">
          {{data.name}}
      </option>
  </select>
dataChanged(newObj) {
    // here comes the object as parameter
}

assume you try the same thing without "ngModel things"

<select (change)="changed($event)">
    <option *ngFor="let currentData of allData" [value]="currentData.id">
        {{data.name}}
    </option>
</select>
changed(e){
    // event comes as parameter, you'll have to find selectedData manually
    // by using e.target.data
}

How can I do an UPDATE statement with JOIN in SQL Server?

Another example why SQL isn't really portable.

For MySQL it would be:

update ud, sale
set ud.assid = sale.assid
where sale.udid = ud.id;

For more info read multiple table update: http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

How do I set the driver's python version in spark?

You can specify the version of Python for the driver by setting the appropriate environment variables in the ./conf/spark-env.sh file. If it doesn't already exist, you can use the spark-env.sh.template file provided which also includes lots of other variables.

Here is a simple example of a spark-env.sh file to set the relevant Python environment variables:

#!/usr/bin/env bash

# This file is sourced when running various Spark programs.
export PYSPARK_PYTHON=/usr/bin/python3       
export PYSPARK_DRIVER_PYTHON=/usr/bin/ipython

In this case it sets the version of Python used by the workers/executors to Python3 and the driver version of Python to iPython for a nicer shell to work in.

If you don't already have a spark-env.sh file, and don't need to set any other variables, this one should do what you want, assuming that paths to the relevant python binaries are correct (verify with which). I had a similar problem and this fixed it.

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

How to show a running progress bar while page is loading

Take a look here,

html file

<div class='progress' id="progress_div">
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
</div>

<div id="wrapper">
   <div id="content">
     <h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
   </div>
</div>

js file

document.onreadystatechange = function(e) {
  if (document.readyState == "interactive") {
    var all = document.getElementsByTagName("*");
    for (var i = 0, max = all.length; i < max; i++) {
      set_ele(all[i]);
    }
  }
}

function check_element(ele) {
  var all = document.getElementsByTagName("*");
  var totalele = all.length;
  var per_inc = 100 / all.length;

  if ($(ele).on()) {
    var prog_width = per_inc + Number(document.getElementById("progress_width").value);
    document.getElementById("progress_width").value = prog_width;
    $("#bar1").animate({
      width: prog_width + "%"
    }, 10, function() {
      if (document.getElementById("bar1").style.width == "100%") {
        $(".progress").fadeOut("slow");
      }
    });
  } else {
    set_ele(ele);
  }
}

function set_ele(set_element) {
  check_element(set_element);
}

it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will not "grayout" the textbox and will still submit the value on a postback.

Using sed, Insert a line above or below the pattern?

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

Library functions like "pow" are usually carefully crafted to yield the minimum possible error (in generic case). This is usually achieved approximating functions with splines (according to Pascal's comment the most common implementation seems to be using Remez algorithm)

fundamentally the following operation:

pow(x,y);

has a inherent error of approximately the same magnitude as the error in any single multiplication or division.

While the following operation:

float a=someValue;
float b=a*a*a*a*a*a;

has a inherent error that is greater more than 5 times the error of a single multiplication or division (because you are combining 5 multiplications).

The compiler should be really carefull to the kind of optimization it is doing:

  1. if optimizing pow(a,6) to a*a*a*a*a*a it may improve performance, but drastically reduce the accuracy for floating point numbers.
  2. if optimizing a*a*a*a*a*a to pow(a,6) it may actually reduce the accuracy because "a" was some special value that allows multiplication without error (a power of 2 or some small integer number)
  3. if optimizing pow(a,6) to (a*a*a)*(a*a*a) or (a*a)*(a*a)*(a*a) there still can be a loss of accuracy compared to pow function.

In general you know that for arbitrary floating point values "pow" has better accuracy than any function you could eventually write, but in some special cases multiple multiplications may have better accuracy and performance, it is up to the developer choosing what is more appropriate, eventually commenting the code so that noone else would "optimize" that code.

The only thing that make sense (personal opinion, and apparently a choice in GCC wichout any particular optimization or compiler flag) to optimize should be replacing "pow(a,2)" with "a*a". That would be the only sane thing a compiler vendor should do.

How do I check if the mouse is over an element in jQuery?

Thanks to both of you. At some point I had to give up on trying to detect if the mouse was still over the element. I know it's possible, but may require too much code to accomplish.

It took me a little while but I took both of your suggestions and came up with something that would work for me.

Here's a simplified (but functional) example:

$("[HoverHelp]").hover (
    function () {
        var HelpID = "#" + $(this).attr("HoverHelp");
        $(HelpID).css("top", $(this).position().top + 25);
        $(HelpID).css("left", $(this).position().left);
        $(HelpID).attr("fadeout", "false");
        $(HelpID).fadeIn();
    },
    function () {
        var HelpID = "#" + $(this).attr("HoverHelp");
        $(HelpID).attr("fadeout", "true");
        setTimeout(function() { if ($(HelpID).attr("fadeout") == "true") $(HelpID).fadeOut(); }, 100);
    }
);

And then to make this work on some text this is all I have to do:

<div id="tip_TextHelp" style="display: none;">This help text will show up on a mouseover, and fade away 100 milliseconds after a mouseout.</div>

This is a <span class="Help" HoverHelp="tip_TextHelp">mouse over</span> effect.

Along with a lot of fancy CSS, this allows some very nice mouseover help tooltips. By the way, I needed the delay in the mouseout because of tiny gaps between checkboxes and text that was causing the help to flash as you move the mouse across. But this works like a charm. I also did something similar for the focus/blur events.

Creating random colour in Java?

Sure. Just generate a color using random RGB values. Like:

public Color randomColor()
{
  Random random=new Random(); // Probably really put this somewhere where it gets executed only once
  int red=random.nextInt(256);
  int green=random.nextInt(256);
  int blue=random.nextInt(256);
  return new Color(red, green, blue);
}

You might want to vary up the generation of the random numbers if you don't like the colors it comes up with. I'd guess these will tend to be fairly dark.

How to make a phone call programmatically?

Solved..! September 5, 2020.

It is working very well. In this way, you do not need to have permission from user. You can open directly phone calling part.

Trick point, use ACTION_DIAL instead of ACTION_CALL.

private void callPhoneNumber() {
    String phone = "03131693169";
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.setData(Uri.parse("tel:" + phone));
    startActivity(callIntent);
}

For more question, ask me on Instagram: @canerkaseler

How can I stage and commit all files, including newly added files, using a single command?

One-liner to stage ALL files (modified, deleted, and new) and commit with comment:

git add --all && git commit -m "comment"

http://git-scm.com/docs/git-add
http://git-scm.com/docs/git-commit

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

Read XML Attribute using XmlDocument

XmlDocument.Attributes perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

Error while trying to run project: Unable to start program. Cannot find the file specified

I am only posting this because I had a specific issue with the command line arguments I was passing in. Being inexperienced with the command line I was using "<" and ">" in my arguments and it was redirecting the file on me. Hope this helps someone.

Unclosed Character Literal error

I'd like to give a small addition to the existing answers. You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form. Like when you write:

char HI = '\3072';

You have to use the correct form which is:

char HI = '\u3072';

Get the closest number out of an array

Here's the pseudo-code which should be convertible into any procedural language:

array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
number = 112
print closest (number, array)

def closest (num, arr):
    curr = arr[0]
    foreach val in arr:
        if abs (num - val) < abs (num - curr):
            curr = val
    return curr

It simply works out the absolute differences between the given number and each array element and gives you back one of the ones with the minimal difference.

For the example values:

number = 112  112  112  112  112  112  112  112  112  112
array  =   2   42   82  122  162  202  242  282  322  362
diff   = 110   70   30   10   50   90  130  170  210  250
                         |
                         +-- one with minimal absolute difference.

As a proof of concept, here's the Python code I used to show this in action:

def closest (num, arr):
    curr = arr[0]
    for index in range (len (arr)):
        if abs (num - arr[index]) < abs (num - curr):
            curr = arr[index]
    return curr

array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
number = 112
print closest (number, array)

And, if you really need it in Javascript, see below for a complete HTML file which demonstrates the function in action:

<html>
    <head></head>
    <body>
        <script language="javascript">
            function closest (num, arr) {
                var curr = arr[0];
                var diff = Math.abs (num - curr);
                for (var val = 0; val < arr.length; val++) {
                    var newdiff = Math.abs (num - arr[val]);
                    if (newdiff < diff) {
                        diff = newdiff;
                        curr = arr[val];
                    }
                }
                return curr;
            }
            array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
            number = 112;
            alert (closest (number, array));
        </script>
    </body>
</html>

Now keep in mind there may be scope for improved efficiency if, for example, your data items are sorted (that could be inferred from the sample data but you don't explicitly state it). You could, for example, use a binary search to find the closest item.

You should also keep in mind that, unless you need to do it many times per second, the efficiency improvements will be mostly unnoticable unless your data sets get much larger.

If you do want to try it that way (and can guarantee the array is sorted in ascending order), this is a good starting point:

<html>
    <head></head>
    <body>
        <script language="javascript">
            function closest (num, arr) {
                var mid;
                var lo = 0;
                var hi = arr.length - 1;
                while (hi - lo > 1) {
                    mid = Math.floor ((lo + hi) / 2);
                    if (arr[mid] < num) {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                if (num - arr[lo] <= arr[hi] - num) {
                    return arr[lo];
                }
                return arr[hi];
            }
            array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
            number = 112;
            alert (closest (number, array));
        </script>
    </body>
</html>

It basically uses bracketing and checking of the middle value to reduce the solution space by half for each iteration, a classic O(log N) algorithm whereas the sequential search above was O(N):

0  1  2   3   4   5   6   7   8   9  <- indexes
2 42 82 122 162 202 242 282 322 362  <- values
L             M                   H  L=0, H=9, M=4, 162 higher, H<-M
L     M       H                      L=0, H=4, M=2, 82 lower/equal, L<-M
      L   M   H                      L=2, H=4, M=3, 122 higher, H<-M
      L   H                          L=2, H=3, difference of 1 so exit
          ^
          |
          H (122-112=10) is closer than L (112-82=30) so choose H

As stated, that shouldn't make much of a difference for small datasets or for things that don't need to be blindingly fast, but it's an option you may want to consider.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

I had a similar issue. I resolved it by changing

<basicHttpBinding>

to

<basicHttpsBinding>

and also changed my URL to use https:// instead of http://.

Also in <endpoint> node, change

binding="basicHttpBinding" 

to

binding="basicHttpsBinding"

This worked.

What is console.log?

Places you can view the console! Just to have them all in one answer.

Firefox

http://getfirebug.com/

(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)

Safari and Chrome

Basically the same.

https://developers.google.com/chrome-developer-tools/docs/overview

https://developer.apple.com/technologies/safari/developer-tools.html

Internet Explorer

Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10

http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx

If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet

http://getfirebug.com/firebuglite/ look for stable bookmarklet

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

Opera

http://www.opera.com/dragonfly/

iOS

Works for all iPhones, iPod touch and iPads.

http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html

Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.

Windows Phone, Android

Both of these have no console built in and no bookmarklet ability. So we use http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.

iOS and Android

You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.


Older browser problems

Lastly older versions of IE will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily it's an easy fix. Use the below code snippet at the top of your code:

 if(!window.console){ window.console = {log: function(){} }; } 

This checks to see if the console is present, and if not it sets it to an object with a blank function called log. This way window.console and window.console.log is never truly undefined.

Given an RGB value, how do I create a tint (or shade)?

I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.

  1. Use this to calculate the grey-ness ( luma ? )
  2. but with both the existing value and the new 'tint' value
  3. calculate the difference ( I found I did not need to multiply )
  4. add to offset the 'tint' value

    var grey =  (r + g + b) / 3;    
    var grey2 = (new_r + new_g + new_b) / 3;
    
    var dr =  grey - grey2 * 1;    
    var dg =  grey - grey2 * 1    
    var db =  grey - grey2 * 1;  
    
    tint_r = new_r + dr;    
    tint_g = new_g + dg;   
    tint_b = new_b _ db;
    

or something like that...

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

How to determine CPU and memory consumption from inside a process?

Windows

Some of the above values are easily available from the appropriate WIN32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)

Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!


  • Total Virtual Memory:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.

  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

     DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • Virtual Memory currently used by current process:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • Physical Memory currently used by current process:

    Same code as in "Virtual Memory currently used by current process" and then

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    



  • CPU currently used:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • CPU currently used by current process:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    void init(){
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
    
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));
    
        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }
    
    double getCurrentValue(){
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));
    
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) +
            (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;
    
        return percent * 100;
    }
    

Linux

On Linux the choice that seemed obvious at first was to use the POSIX APIs like getrusage() etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?

In the end I got all values via a combination of reading the pseudo-filesystem /proc and kernel calls.

  • Total Virtual Memory:

    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • Virtual Memory currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '\0';
        i = atoi(p);
        return i;
    }
    
    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmSize:", 7) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    
  • Physical Memory currently used by current process:

    Change getValue() in "Virtual Memory currently used by current process" as follows:

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • CPU currently used:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • CPU currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    

TODO: Other Platforms

I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by getrusage() and similar functions? If someone with Unix know-how could edit this answer and fill in the details?!

How to resolve Unneccessary Stubbing exception

I had UnnecessaryStubbingException when I tried to use the when methods on a Spy object. Mockito.lenient() silenced the exception but the test results were not correct.

In case of Spy objects, one has to call the methods directly.

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
class ArithmTest {

    @Spy
    private Arithm arithm;

    @Test
    void testAddition() {

        int res = arithm.add(2, 5);

        // doReturn(7).when(arithm).add(2, 5);
        assertEquals(res, 7);
    }
}

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

How do I update the password for Git?

For Mac

If you have multiple remote repositories (Github, Bitbucket, Job, etc.)

1) run in the project directory

git config --unset user.password

2) run remote git command (ie. git push or git pull)

Git will prompt you to reenter your user.name and user.password for this repository

Or you can do it globally if you have only one remote repository

git config --global --unset user.password

How to set environment variables in Python?

What about os.environ["DEBUSSY"] = '1'? Environment variables are always strings.

Understanding __get__ and __set__ and Python descriptors

You'd see https://docs.python.org/3/howto/descriptor.html#properties

class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

How to implement and do OCR in a C# project?

Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

BehaviorSubject vs Observable?

Observable and subject both are observable's means an observer can track them. but both of them have some unique characteristics. Further there are total 3 type of subjects each of them again have unique characteristics. lets try to to understand each of them.

you can find the practical example here on stackblitz. (You need to check the console to see the actual output)

enter image description here

Observables

They are cold: Code gets executed when they have at least a single observer.

Creates copy of data: Observable creates copy of data for each observer.

Uni-directional: Observer can not assign value to observable(origin/master).

Subject

They are hot: code gets executed and value gets broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master).

If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject

ReplaySubject

They are hot: code gets executed and value get broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master). plus

Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

In subject and replay subject you can not set the initial value to observable. So here comes Behavioral Subject

BehaviorSubject

They are hot: code gets executed and value get broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master). plus

Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

You can set initial value: You can initialize the observable with default value.

Why can't I call a public method in another class?

For example 1 and 2 you need to create static methods:

public static string InstanceMethod() {return "Hello World";}

Then for example 3 you need an instance of your object to invoke the method:

object o = new object();
string s = o.InstanceMethod();

Simple Vim commands you wish you'd known earlier

Some of my latest additions to my Vim brainstore:

  • ^wi: Jump to the tag under the cursor by splitting the window.
  • cib/ciB: Change the text inside the current set of parenthesis () or braces {}, respectively.
  • :set listchars=tab:>-,trail:_ list: Show tabs/trailing spaces visually different from other spaces. It helps a lot with Python coding.

Angular - Use pipes in services and components

If you don't want do 'new myPipe()' because you're injecting dependencies to pipe, you can inject in component like provider and use without new.

Example:

    // In your component...

    import { Component, OnInit } from '@angular/core';
    import { myPipe} from './pipes';

    @Component({
      selector: 'my-component',
      template: '{{ data }}',
      providers: [ myPipe ]
    })
    export class MyComponent() implements OnInit {
      data = 'some data';
      constructor(private myPipe: myPipe) {}

      ngOnInit() {
        this.data = this.myPipe.transform(this.data);
      }
    }

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Meaning of @classmethod and @staticmethod for beginner?

Class method can modify the class state,it bound to the class and it contain cls as parameter.

Static method can not modify the class state,it bound to the class and it does't know class or instance

class empDetails:
    def __init__(self,name,sal):
        self.name=name
        self.sal=sal
    @classmethod
    def increment(cls,name,none):
        return cls('yarramsetti',6000 + 500)
    @staticmethod
    def salChecking(sal):
        return sal > 6000

emp1=empDetails('durga prasad',6000)
emp2=empDetails.increment('yarramsetti',100)
# output is 'durga prasad'
print emp1.name
# output put is 6000
print emp1.sal
# output is 6500,because it change the sal variable
print emp2.sal
# output is 'yarramsetti' it change the state of name variable
print emp2.name
# output is True, because ,it change the state of sal variable
print empDetails.salChecking(6500)

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

I believe that sorting by the column you want to get the MAX of and then grabbing the first should work. However, if there are multiple objects with the same MAX value, only one will be grabbed:

private void Test()
{
    test v1 = new test();
    v1.Id = 12;

    test v2 = new test();
    v2.Id = 12;

    test v3 = new test();
    v3.Id = 12;

    List<test> arr = new List<test>();
    arr.Add(v1);
    arr.Add(v2);
    arr.Add(v3);

    test max = arr.OrderByDescending(t => t.Id).First();
}

class test
{
    public int Id { get; set; }
}

Converting bool to text in C++

Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.

#define PRINTBOOL(x) x?"true":"false"

Execute CMD command from code

You can use this to work cmd in C#:

ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();

Don't forget to write /c before your argument !!

How do you create a daemon in Python?

The easiest way to create daemon with Python is to use the Twisted event-driven framework. It handles all of the stuff necessary for daemonization for you. It uses the Reactor Pattern to handle concurrent requests.

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

What are invalid characters in XML

For XSL (on really lazy days) I use:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

to translate all &-signs that aren't follwed på amp; to proper ones.

We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...

How to enter a series of numbers automatically in Excel

Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.

Replace whitespaces with tabs in linux

Use the unexpand(1) program


UNEXPAND(1)                      User Commands                     UNEXPAND(1)

NAME
       unexpand - convert spaces to tabs

SYNOPSIS
       unexpand [OPTION]... [FILE]...

DESCRIPTION
       Convert  blanks in each FILE to tabs, writing to standard output.  With
       no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are  mandatory  for  short  options
       too.

       -a, --all
              convert all blanks, instead of just initial blanks

       --first-only
              convert only leading sequences of blanks (overrides -a)

       -t, --tabs=N
              have tabs N characters apart instead of 8 (enables -a)

       -t, --tabs=LIST
              use comma separated LIST of tab positions (enables -a)

       --help display this help and exit

       --version
              output version information and exit
. . .
STANDARDS
       The expand and unexpand utilities conform to IEEE Std 1003.1-2001
       (``POSIX.1'').

Saving and loading objects and using pickle

You're forgetting to read it as binary too.

In your write part you have:

open(b"Fruits.obj","wb") # Note the wb part (Write Binary)

In the read part you have:

file = open("Fruits.obj",'r') # Note the r part, there should be a b too

So replace it with:

file = open("Fruits.obj",'rb')

And it will work :)


As for your second error, it is most likely cause by not closing/syncing the file properly.

Try this bit of code to write:

>>> import pickle
>>> filehandler = open(b"Fruits.obj","wb")
>>> pickle.dump(banana,filehandler)
>>> filehandler.close()

And this (unchanged) to read:

>>> import pickle
>>> file = open("Fruits.obj",'rb')
>>> object_file = pickle.load(file)

A neater version would be using the with statement.

For writing:

>>> import pickle
>>> with open('Fruits.obj', 'wb') as fp:
>>>     pickle.dump(banana, fp)

For reading:

>>> import pickle
>>> with open('Fruits.obj', 'rb') as fp:
>>>     banana = pickle.load(fp)

HTML list-style-type dash

I do not know if there is a better way, but you can create a custom bullet point graphic depicting a dash, and then let the browser know you want to use it in your list with the list-style-type property. An example on that page shows how to use a graphic as a bullet.

I have never tried to use :before in the way you have, although it may work. The downside is that it will not be supported by some older browsers. My gut reaction is that this is still important enough to take into consideration. In the future, this may not be as important.

EDIT: I have done a little testing with the OP's approach. In IE8, I couldn't get the technique to work, so it definitely is not yet cross-browser. Moreover, in Firefox and Chrome, setting list-style-type to none in conjunction appears to be ignored.

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

In Swift 4 You can use

->Go Info.plist

-> Click plus of Information properties list

->Add App Transport Security Settings as dictionary

-> Click Plus icon App Transport Security Settings

-> Add Allow Arbitrary Loads set YES

Bellow image look like

enter image description here

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

When and Why to use abstract classes/methods?

Typically one uses an abstract class to provide some incomplete functionality that will be fleshed out by concrete subclasses. It may provide methods that are used by its subclasses; it may also represent an intermediate node in the class hierarchy, to represent a common grouping of concrete subclasses, distinguishing them in some way from other subclasses of its superclass. Since an interface can't derive from a class, this is another situation where a class (abstract or otherwise) would be necessary, versus an interface.

A good rule of thumb is that only leaf nodes of a class hierarchy should ever be instantiated. Making non-leaf nodes abstract is an easy way of ensuring that.

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

How to add onload event to a div element

Try this! And never use trigger twice on div!

You can define function to call before the div tag.

$(function(){
    $('div[onload]').trigger('onload');
});

DEMO: jsfiddle

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

How to use onBlur event on Angular2?

This is the proposed answer on the Github repo:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

Github : feat(forms): add updateOn blur option to FormControls

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.

ALTER TABLE slide_image_sub DROP  KEY  FK_slide_image_sub;

here in DROP KEY instead of DROP FOREIGN KEY,

hope it will help.

Thanks

Javascript - Track mouse position

We recently had to find the current x,y position to enumerate elements over which the cursor is hovering independent of z-index. We ended up just attaching a mousemove event listener to document e.g.,

_x000D_
_x000D_
function findElements(e) {
  var els = document.elementsFromPoint(e.clientX, e.clientY);

  // do cool stuff with els
  console.log(els);

  return;
}

document.addEventListener("mousemove", findElements);
_x000D_
_x000D_
_x000D_

JQuery Event for user pressing enter in a textbox?

If your input is search, you also can use on 'search' event. Example

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

find all unchecked checkbox in jquery

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

Form inside a table

A form is not allowed to be a child element of a table, tbody or tr. Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind).

You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form.

Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates).

HTML 5 introduces the form attribute. This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id.

Copy folder recursively, excluding some folders

Similar to Jeff's idea (untested):

find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/

java: How can I do dynamic casting of a variable from one type to another?

Yes it is possible using Reflection

Object something = "something";
String theType = "java.lang.String";
Class<?> theClass = Class.forName(theType);
Object obj = theClass.cast(something);

but that doesn't make much sense since the resulting object must be saved in a variable of Object type. If you need the variable be of a given class, you can just cast to that class.

If you want to obtain a given class, Number for example:

Object something = new Integer(123);
String theType = "java.lang.Number";
Class<? extends Number> theClass = Class.forName(theType).asSubclass(Number.class);
Number obj = theClass.cast(something);

but there is still no point doing it so, you could just cast to Number.

Casting of an object does NOT change anything; it is just the way the compiler treats it.
The only reason to do something like that is to check if the object is an instance of the given class or of any subclass of it, but that would be better done using instanceof or Class.isInstance().

Update

according your last update the real problem is that you have an Integer in your HashMap that should be assigned to a Double. What you can do in this case, is check the type of the field and use the xxxValue() methods of Number

...
Field f =  this.getClass().getField(entry.getKey());
Object value = entry.getValue();
if (Integer.class.isAssignableFrom(f.getType())) {
    value = Integer.valueOf(((Number) entry.getValue()).intValue());
} else if (Double.class.isAssignableFrom(f.getType())) {
    value = Double.valueOf(((Number) entry.getValue()).doubleValue());
} // other cases as needed (Long, Float, ...)
f.set(this, value);
...

(not sure if I like the idea of having the wrong type in the Map)

How do I make a text go onto the next line if it overflows?

word-wrap: break-word; 

add this to your container that should do the trick

How do I change selected value of select2 dropdown with JqGrid?

This should be even easier.

$("#e1").select2("val", ["View" ,"Modify"]);

But make sure the values which you pass are already present in the HTMl

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

Can two applications listen to the same port?

When you create a TCP connection, you ask to connect to a specific TCP address, which is a combination of an IP address (v4 or v6, depending on the protocol you're using) and a port.

When a server listens for connections, it can inform the kernel that it would like to listen to a specific IP address and port, i.e., one TCP address, or on the same port on each of the host's IP addresses (usually specified with IP address 0.0.0.0), which is effectively listening on a lot of different "TCP addresses" (e.g., 192.168.1.10:8000, 127.0.0.1:8000, etc.)

No, you can't have two applications listening on the same "TCP address," because when a message comes in, how would the kernel know to which application to give the message?

However, you in most operating systems you can set up several IP addresses on a single interface (e.g., if you have 192.168.1.10 on an interface, you could also set up 192.168.1.11, if nobody else on the network is using it), and in those cases you could have separate applications listening on port 8000 on each of those two IP addresses.

How to manually set an authenticated user in Spring Security / SpringMVC

I couldn't find any other full solutions so I thought I would post mine. This may be a bit of a hack, but it resolved the issue to the above problem:

public void login(HttpServletRequest request, String userName, String password)
{

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);

    // Authenticate the user
    Authentication authentication = authenticationManager.authenticate(authRequest);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

    // Create a new session and add the security context.
    HttpSession session = request.getSession(true);
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

How to round a floating point number up to a certain decimal place?

This is normal (and has nothing to do with Python) because 8.83 cannot be represented exactly as a binary float, just as 1/3 cannot be represented exactly in decimal (0.333333... ad infinitum).

If you want to ensure absolute precision, you need the decimal module:

>>> import decimal
>>> a = decimal.Decimal("8.833333333339")
>>> print(round(a,2))
8.83

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

You can get this error if you define a project as an .exe but intent to create a .lib or a .dll

How can I call controller/view helper methods from the console in Ruby on Rails?

One possible approach for Helper method testing in the Ruby on Rails console is:

Struct.new(:t).extend(YourHelper).your_method(*arg)

And for reload do:

reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)

Check if EditText is empty.

with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

How to use JavaScript variables in jQuery selectors?

  1. ES6 String Template

    Here is a simple way if you don't need IE/EDGE support

    $(`input[id=${x}]`).hide();
    

    or

    $(`input[id=${$(this).attr("name")}]`).hide();
    

    This is a es6 feature called template string

    _x000D_
    _x000D_
        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                var x = $(this).attr("name");_x000D_
                $(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_


  1. String Concatenation

    If you need IE/EDGE support use

    $("#" + $(this).attr("name")).hide();
    

    _x000D_
    _x000D_
        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                $("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_


  1. Selector in DOM as data attribute

    This is my preferred way as it makes you code really DRY

    // HTML
    <input type="text"   id="bx" />
    <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
    
    //JS
    $($(this).data("input-sel")).hide();
    

    _x000D_
    _x000D_
        (function($) {_x000D_
            $(".js-hide-onclick").click(function() {_x000D_
                $($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_

Foreign key constraints: When to use ON UPDATE and ON DELETE

You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).

Consider how your application should respond to various cases.

The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.

Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

Jackson JSON: get node name from json-tree

JsonNode root = mapper.readTree(json);
root.at("/some-node").fields().forEachRemaining(e -> {
                              System.out.println(e.getKey()+"---"+ e.getValue());

        });

In one line Jackson 2+

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Easy way to use variables of enum types as string in C?

There is definitely a way to do this -- use X() macros. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.

Your example can be written as follows:

 // Source data -- Enum, String
 #define X_NUMBERS \
    X(ONE,   "one") \
    X(TWO,   "two") \
    X(THREE, "three")

 ...

 // Use preprocessor to create the Enum
 typedef enum {
  #define X(Enum, String)       Enum,
   X_NUMBERS
  #undef X
 } Numbers;

 ...

 // Use Preprocessor to expand data into switch statement cases
 switch(num)
 {
 #define X(Enum, String) \
     case Enum:  strcpy(num_str, String); break;
 X_NUMBERS
 #undef X

     default: return 0; break;
 }
 return 1;

There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.

Swift apply .uppercaseString to only the first letter of a string

If your string is all caps then below method will work

labelTitle.text = remarks?.lowercased().firstUppercased

This extension will helps you

extension StringProtocol {
    var firstUppercased: String {
        guard let first = first else { return "" }
        return String(first).uppercased() + dropFirst()
    }
}

How to hash some string with sha256 in Java?

You can use MessageDigest in the following way:

public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

I got this error while connecting to Amazon RDS. I checked the server status 50% of CPU usage while it was a development server and no one is using it.

It was working before, and nothing in the connection configuration has changed. Rebooting the server fixed the issue for me.

How to pass a type as a method parameter in Java

If you want to pass the type, than the equivalent in Java would be

java.lang.Class

If you want to use a weakly typed method, then you would simply use

java.lang.Object

and the corresponding operator

instanceof

e.g.

private void foo(Object o) {

  if(o instanceof String) {

  }

}//foo

However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.

The real question is what you actually want to achieve here, otherwise it is difficult to answer:

Or is there a better way?

Cannot invoke an expression whose type lacks a call signature

As mentioned in the github issue originally linked by @peter in the comments:

const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

Make body have 100% of the browser height

If you want to keep the margins on the body and don't want scroll bars, use the following css:

html { height:100%; }
body { position:absolute; top:0; bottom:0; right:0; left:0; }

Setting body {min-height:100%} will give you scroll bars.

See demo at http://jsbin.com/aCaDahEK/2/edit?html,output .

C#: Converting byte array to string and printing out to console

I've used this simple code in my codebase:

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

To use:

Console.WriteLine(ToReadableByteArray(bytes));

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

I have solved this problem in my pycharm in a bit different way.

Go to settings -> Project Interpreter and then click on the base package there.

You will see a page like this

problemGuide

After that when your package is installed then you should see the package is colored blue rather than white.

And the unresolved reference is also gone too.

enum Values to NSString (iOS)

You could use X macros - they are perfect for this.

Benefits 1. the relationship between the actual enum value and the string value is in one place. 2. you can use regular switch statements later in your code.

Detriment 1. The initial setup code is a bit obtuse, and uses fun macros.

The code

#define X(a, b, c) a b,
enum ZZObjectType {
    ZZOBJECTTYPE_TABLE
};
typedef NSUInteger TPObjectType;
#undef X

#define XXOBJECTTYPE_TABLE \
X(ZZObjectTypeZero, = 0, "ZZObjectTypeZero") \
X(ZZObjectTypeOne, = 1, "ZZObjectTypeOne") \
X(ZZObjectTypeTwo, = 2, "ZZObjectTypeTwo") \
X(ZZObjectTypeThree, = 3, "ZZObjectTypeThree") \

+ (NSString*)nameForObjectType:(ZZObjectType)objectType {
#define X(a, b, c) @c, [NSNumber numberWithInteger:a],
    NSDictionary *returnValue = [NSDictionary dictionaryWithObjectsAndKeys:ZZOBJECTTYPE_TABLE nil];
#undef X
    return [returnValue objectForKey:[NSNumber numberWithInteger:objectType]];
}

+ (ZZObjectType)objectTypeForName:(NSString *)objectTypeString {
#define X(a, b, c) [NSNumber numberWithInteger:a], @c,
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:ZZOBJECTSOURCE_TABLE nil];
#undef X
    NSUInteger value = [(NSNumber *)[dictionary objectForKey:objectTypeString] intValue];
    return (ZZObjectType)value;
}

Now you can do:

NSString *someString = @"ZZObjectTypeTwo"
ZZObjectType objectType = [[XXObject objectTypeForName:someString] intValue];
switch (objectType) {
    case ZZObjectTypeZero:
        //
        break;
    case ZZObjectTypeOne:
        //
        break;
    case ZZObjectTypeTwo:
        //
        break;
}

This pattern has been around since the 1960's (no kidding!): http://en.wikipedia.org/wiki/X_Macro

self referential struct definition?

A Structure which contain a reference to itself. A common occurrence of this in a structure which describes a node for a link list. Each node needs a reference to the next node in the chain.

struct node
{
       int data;
       struct node *next; // <-self reference
};

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Android widget: How to change the text of a button

//text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" text button" />

// color text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/color text"/>

// background button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/ background button"/>

// text size button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:textSize="text size"/>

Using getResources() in non-activity class

We can use context Like this try now Where the parent is the ViewGroup.

Context context = parent.getContext();

Ubuntu, how do you remove all Python 3 but not 2

EDIT: As pointed out in recent comments, this solution may BREAK your system.

You most likely don't want to remove python3.

Please refer to the other answers for possible solutions.

Outdated answer (not recommended)

sudo apt-get remove 'python3.*'

Iterate a certain number of times without storing the iteration number anywhere

Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _, a convention for "discarding" the value assigned. Though the _ reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:

for _ in range(2):
    print('Hello')

PHP Pass variable to next page

**page 1**
<form action="exapmple.php?variable_name=$value" method="POST"> 
    <button>
        <input  type="hidden" name="x">
    </button>
</form>`

page 2

if(isset($_POST['x'])) {
    $new_value=$_GET['variable_name'];
}

How to git commit a single file/directory

If you are in the folder which contains the file

git commit -m 'my notes' ./name_of_file.ext

How to prevent form from being submitted?

Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

html

<form onsubmit="return mySubmitFunction(event)">
  ...
</form>

script

function mySubmitFunction()
{
  someBug()
  return false;
}

returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

function mySubmitFunction(e) {
  e.preventDefault();
  someBug();
  return false;
}

In this case, even with the bug the form won't submit!

Alternatively, a try...catch block could be used.

function mySubmit(e) { 
  e.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

How to read from standard input in the console?

Always try to use the bufio.NewScanner for collecting input from the console. As others mentioned, there are multiple ways to do the job but Scanner is originally intended to do the job. Dave Cheney explains why you should use Scanner instead of bufio.Reader's ReadLine.

https://twitter.com/davecheney/status/604837853344989184?lang=en

Here is the code snippet answer for your question

package main

import (
    "bufio"
    "fmt"
    "os"
)

/*
 Three ways of taking input
   1. fmt.Scanln(&input)
   2. reader.ReadString()
   3. scanner.Scan()

   Here we recommend using bufio.NewScanner
*/

func main() {
    // To create dynamic array
    arr := make([]string, 0)
    scanner := bufio.NewScanner(os.Stdin)
    for {
        fmt.Print("Enter Text: ")
        // Scans a line from Stdin(Console)
        scanner.Scan()
        // Holds the string that scanned
        text := scanner.Text()
        if len(text) != 0 {
            fmt.Println(text)
            arr = append(arr, text)
        } else {
            break
        }

    }
    // Use collected inputs
    fmt.Println(arr)
}

If you don't want to programmatically collect the inputs, just add these lines

   scanner := bufio.NewScanner(os.Stdin)
   scanner.Scan()
   text := scanner.Text()
   fmt.Println(text)

The output of above program will be:

Enter Text: Bob
Bob
Enter Text: Alice
Alice
Enter Text:
[Bob Alice]

Above program collects the user input and saves them to an array. We can also break that flow with a special character. Scanner provides API for advanced usage like splitting using a custom function etc, scanning different types of I/O streams(Stdin, String) etc.

What is SuppressWarnings ("unchecked") in Java?

One trick is to create an interface that extends a generic base interface...

public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}

Then you can check it with instanceof before the cast...

Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
    String format = "Servlet context attribute \"%s\" is not of type "
            + "LoadFutures. Its type is %s.";
    String msg = String.format(format, FUTURES, obj.getClass());
    throw new RuntimeException(msg);
}
return (LoadFutures) obj;

Recommended date format for REST GET API

Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.

Pros:

  • Epoch format does not have a timezone.
  • Epoch has a single format (Unix time is a single signed number).
  • Epoch time is not effected by daylight saving.
  • Most of the Backend frameworks and all native ios/android APIs support epoch conversion.
  • Local time conversion part can be done entirely in application side depends on the timezone setting of user's device/browser.

Cons:

  • Extra processing for converting to UTC for storing in UTC format in the database.
  • Readability of input/output.
  • Readability of GET URLs.

Notes:

  • Timezones are a presentation-layer problem! Most of your code shouldn't be dealing with timezones or local time, it should be passing Unix time around.
  • If you want to store a humanly-readable time (e.g. logs), consider storing it along with Unix time, not instead of Unix time.

BeanFactory vs ApplicationContext

ApplicationContext is a big brother of BeanFactory and this would all thing that BeanFactory are provide plus many other things.

In addition to standard org.springframework.beans.factory.BeanFactory lifecycle capabilities, ApplicationContext implementations detect and invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

Database design for a survey

I think that your model #2 is fine, however you can take a look at the more complex model which stores questions and pre-made answers (offered answers) and allows them to be re-used in different surveys.

- One survey can have many questions; one question can be (re)used in many surveys.
- One (pre-made) answer can be offered for many questions. One question can have many answers offered. A question can have different answers offered in different surveys. An answer can be offered to different questions in different surveys. There is a default "Other" answer, if a person chooses other, her answer is recorded into Answer.OtherText.
- One person can participate in many surveys, one person can answer specific question in a survey only once.

survey_model_02

How to automatically add user account AND password with a Bash script?

For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:

#!/bin/sh
echo -n "Enter username: "
read uname

echo -n "Enter password: "
read -s passwd

adduser "$uname"
echo $uname:$passwd | sudo chpasswd

gpasswd wheel -a $uname

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

How can I time a code segment for testing performance with Pythons timeit?

I see the question has already been answered, but still want to add my 2 cents for the same.

I have also faced similar scenario in which I have to test the execution times for several approaches and hence written a small script, which calls timeit on all functions written in it.

The script is also available as github gist here.

Hope it will help you and others.

from random import random
import types

def list_without_comprehension():
    l = []
    for i in xrange(1000):
        l.append(int(random()*100 % 100))
    return l

def list_with_comprehension():
    # 1K random numbers between 0 to 100
    l = [int(random()*100 % 100) for _ in xrange(1000)]
    return l


# operations on list_without_comprehension
def sort_list_without_comprehension():
    list_without_comprehension().sort()

def reverse_sort_list_without_comprehension():
    list_without_comprehension().sort(reverse=True)

def sorted_list_without_comprehension():
    sorted(list_without_comprehension())


# operations on list_with_comprehension
def sort_list_with_comprehension():
    list_with_comprehension().sort()

def reverse_sort_list_with_comprehension():
    list_with_comprehension().sort(reverse=True)

def sorted_list_with_comprehension():
    sorted(list_with_comprehension())


def main():
    objs = globals()
    funcs = []
    f = open("timeit_demo.sh", "w+")

    for objname in objs:
        if objname != 'main' and type(objs[objname]) == types.FunctionType:
            funcs.append(objname)
    funcs.sort()
    for func in funcs:
        f.write('''echo "Timing: %(funcname)s"
python -m timeit "import timeit_demo; timeit_demo.%(funcname)s();"\n\n
echo "------------------------------------------------------------"
''' % dict(
                funcname = func,
                )
            )

    f.close()

if __name__ == "__main__":
    main()

    from os import system

    #Works only for *nix platforms
    system("/bin/bash timeit_demo.sh")

    #un-comment below for windows
    #system("cmd timeit_demo.sh")

Initializing IEnumerable<string> In C#

As string[] implements IEnumerable

IEnumerable<string> m_oEnum = new string[] {"1","2","3"}

How to get WordPress post featured image URL

Check the code below and let me know if it works for you.

<?php if (has_post_thumbnail( $post->ID ) ): ?>
  <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
  <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

  </div>
<?php endif; ?>

Turning error reporting off php

Does this work?

display_errors = Off

Also, what version of php are you using?

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

Getting output of system() calls in Ruby

As Simon Hürlimann already explained, Open3 is safer than backticks etc.

require 'open3'
output = Open3.popen3("ls") { |stdin, stdout, stderr, wait_thr| stdout.read }

Note that the block form will auto-close stdin, stdout and stderr- otherwise they'd have to be closed explicitly.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

In my apache error log, I saw:

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

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

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

I can't understand why this JAXB IllegalAnnotationException is thrown

All below options worked for me.

Option 1: Annotation for FIELD at class & field level with getter/setter methods

 @XmlRootElement(name = "fields")
 @XmlAccessorType(XmlAccessType.FIELD)
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter, setter
    }

Option 2: No Annotation for FIELD at class level(@XmlAccessorType(XmlAccessType.FIELD) and with only getter method. Adding Setter method will throw the error as we are not including the Annotation in this case. Remember, setter is not required when you explicitly set the values in your XML file.

@XmlRootElement(name = "fields")
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter
    }

Option 3: Annotation at getter method alone. Remember we can also use the setter method here as we are not doing any FIELD level annotation in this case.

@XmlRootElement(name = "fields")
    public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        //getter

        //setter
    }

Hope this helps you!

How to get current screen width in CSS?

this can be achieved with the css calc() operator

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
        zoom:calc(100% / 480);
    }
}

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Django ChoiceField

Better Way to Provide Choice inside a django Model :

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

PHP Function Comments

Functions:

/**
 * Does something interesting
 *
 * @param Place   $where  Where something interesting takes place
 * @param integer $repeat How many times something interesting should happen
 * 
 * @throws Some_Exception_Class If something interesting cannot happen
 * @author Monkey Coder <[email protected]>
 * @return Status
 */ 

Classes:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @copyright  2006 Zend Technologies
 * @license    http://www.zend.com/license/3_0.txt   PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://dev.zend.com/package/PackageName
 * @since      Class available since Release 1.2.0
 */ 

Sample File:

<?php

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * PHP version 5.6
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to [email protected] so we can mail you a copy immediately.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    SVN: $Id$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

/**
 * This is a "Docblock Comment," also known as a "docblock."  The class'
 * docblock, below, contains a complete description of how to write these.
 */
require_once 'PEAR.php';

// {{{ constants

/**
 * Methods return this if they succeed
 */
define('NET_SAMPLE_OK', 1);

// }}}
// {{{ GLOBALS

/**
 * The number of objects created
 * @global int $GLOBALS['_NET_SAMPLE_Count']
 */
$GLOBALS['_NET_SAMPLE_Count'] = 0;

// }}}
// {{{ Net_Sample

/**
 * An example of how to write code to PEAR's standards
 *
 * Docblock comments start with "/**" at the top.  Notice how the "/"
 * lines up with the normal indenting and the asterisks on subsequent rows
 * are in line with the first asterisk.  The last line of comment text
 * should be immediately followed on the next line by the closing asterisk
 * and slash and then the item you are commenting on should be on the next
 * line below that.  Don't add extra lines.  Please put a blank line
 * between paragraphs as well as between the end of the description and
 * the start of the @tags.  Wrap comments before 80 columns in order to
 * ease readability for a wide variety of users.
 *
 * Docblocks can only be used for programming constructs which allow them
 * (classes, properties, methods, defines, includes, globals).  See the
 * phpDocumentor documentation for more information.
 * http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html
 *
 * The Javadoc Style Guide is an excellent resource for figuring out
 * how to say what needs to be said in docblock comments.  Much of what is
 * written here is a summary of what is found there, though there are some
 * cases where what's said here overrides what is said there.
 * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide
 *
 * The first line of any docblock is the summary.  Make them one short
 * sentence, without a period at the end.  Summaries for classes, properties
 * and constants should omit the subject and simply state the object,
 * because they are describing things rather than actions or behaviors.
 *
 * Below are the tags commonly used for classes. @category through @version
 * are required.  The remainder should only be used when necessary.
 * Please use them in the order they appear here.  phpDocumentor has
 * several other tags available, feel free to use them.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
 */
class Net_Sample
{
    // {{{ properties

    /**
     * The status of foo's universe
     * Potential values are 'good', 'fair', 'poor' and 'unknown'.
     * @var string $foo
     */
    public $foo = 'unknown';

    /**
     * The status of life
     * Note that names of private properties or methods must be
     * preceeded by an underscore.
     * @var bool $_good
     */
    private $_good = true;

    // }}}
    // {{{ setFoo()

    /**
     * Registers the status of foo's universe
     *
     * Summaries for methods should use 3rd person declarative rather
     * than 2nd person imperative, beginning with a verb phrase.
     *
     * Summaries should add description beyond the method's name. The
     * best method names are "self-documenting", meaning they tell you
     * basically what the method does.  If the summary merely repeats
     * the method name in sentence form, it is not providing more
     * information.
     *
     * Summary Examples:
     *   + Sets the label              (preferred)
     *   + Set the label               (avoid)
     *   + This method sets the label  (avoid)
     *
     * Below are the tags commonly used for methods.  A @param tag is
     * required for each parameter the method has.  The @return
     * and @access tags are mandatory.  The @throws tag is required if
     * the method uses exceptions.  @static is required if the method can
     * be called statically.  The remainder should only be used when
     * necessary.  Please use them in the order they appear here.
     * phpDocumentor has several other tags available, feel free to use
     * them.
     *
     * The @param tag contains the data type, then the parameter's
     * name, followed by a description.  By convention, the first noun in
     * the description is the data type of the parameter.  Articles like
     * "a", "an", and  "the" can precede the noun.  The descriptions
     * should start with a phrase.  If further description is necessary,
     * follow with sentences.  Having two spaces between the name and the
     * description aids readability.
     *
     * When writing a phrase, do not capitalize and do not end with a
     * period:
     *   + the string to be tested
     *
     * When writing a phrase followed by a sentence, do not capitalize the
     * phrase, but end it with a period to distinguish it from the start
     * of the next sentence:
     *   + the string to be tested. Must use UTF-8 encoding.
     *
     * Return tags should contain the data type then a description of
     * the data returned.  The data type can be any of PHP's data types
     * (int, float, bool, string, array, object, resource, mixed)
     * and should contain the type primarily returned.  For example, if
     * a method returns an object when things work correctly but false
     * when an error happens, say 'object' rather than 'mixed.'  Use
     * 'void' if nothing is returned.
     *
     * Here's an example of how to format examples:
     * <code>
     * require_once 'Net/Sample.php';
     *
     * $s = new Net_Sample();
     * if (PEAR::isError($s)) {
     *     echo $s->getMessage() . "\n";
     * }
     * </code>
     *
     * Here is an example for non-php example or sample:
     * <samp>
     * pear install net_sample
     * </samp>
     *
     * @param string $arg1 the string to quote
     * @param int    $arg2 an integer of how many problems happened.
     *                     Indent to the description's starting point
     *                     for long ones.
     *
     * @return int the integer of the set mode used. FALSE if foo
     *             foo could not be set.
     * @throws exceptionclass [description]
     *
     * @access public
     * @static
     * @see Net_Sample::$foo, Net_Other::someMethod()
     * @since Method available since Release 1.2.0
     * @deprecated Method deprecated in Release 2.0.0
     */
    function setFoo($arg1, $arg2 = 0)
    {
        /*
         * This is a "Block Comment."  The format is the same as
         * Docblock Comments except there is only one asterisk at the
         * top.  phpDocumentor doesn't parse these.
         */
        if ($arg1 == 'good' || $arg1 == 'fair') {
            $this->foo = $arg1;
            return 1;
        } elseif ($arg1 == 'poor' && $arg2 > 1) {
            $this->foo = 'poor';
            return 2;
        } else {
            return false;
        }
    }

    // }}}
}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>

Source: PEAR Docblock Comment standards

Angular 2: import external js file into component

After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.

This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:

assets > testjs.js

function test(){
    alert('TestingFunction')
}

include testjs.js in your index.html

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Project1</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <script src="./assets/testjs.js"></script>

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:

app.component.ts

import { Component } from '@angular/core';

declare var test: any;


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app works!';


  f(){
    new test();
  }
}

Finally in your app.component.html test the function

app.component.html

<h1>
  <button (click)='f()'>Test</button>
</h1>

Want to upgrade project from Angular v5 to Angular v6

Angular 6 has just been released.

https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4

Here is what worked for one of my smaller projects

  1. npm install -g @angular/cli
  2. npm install @angular/cli
  3. ng update @angular/cli --migrate-only --from=1.7.0
  4. ng update @angular/core
  5. npm install rxjs-compat
  6. ng serve

You might need to update your run scripts in package.json For eg. if you use flags like "app" and "environment" These have been updated to "project" and "configuration" respectively.

Refer https://update.angular.io/ for more detailed guide.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

Regular expression that doesn't contain certain string

All you need is a reluctant quantifier:

regex: /aa.*?aa/

aabbabcaabda   => aabbabcaa

aaaaaabda      => aaaa

aabbabcaabda   => aabbabcaa

aababaaaabdaa  => aababaa, aabdaa

You could use negative lookahead, too, but in this case it's just a more verbose way accomplish the same thing. Also, it's a little trickier than gpojd made it out to be. The lookahead has to be applied at each position before the dot is allowed to consume the next character.

/aa(?:(?!aa).)*aa/

As for the approach suggested by Claudiu and finnw, it'll work okay when the sentinel string is only two characters long, but (as Claudiu acknowledged) it's too unwieldy for longer strings.

Python can't find module in the same folder

I had a similar problem, I solved it by explicitly adding the file's directory to the path list:

import os
import sys

file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

After that, I had no problem importing from the same directory.

git remote add with other SSH port

Rather than using the ssh:// protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:

git@host:path/to/repo.git

To specify an alternative port, put brackets around the user@host part, including the port:

[git@host:port]:path/to/repo.git

But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:

export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance

How to install iPhone application in iPhone Simulator

Enter the following in the terminal:

$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path/to/your/file/projectname.app/projectname

How to replicate vector in c?

A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:

typedef struct dynamic_array_struct
{
  int* data;
  size_t capacity; /* total capacity */
  size_t size; /* number of elements in vector */
} vector;

Then they would have various API function calls which operate on the vector:

int vector_init(vector* v, size_t init_capacity)
{
  v->data = malloc(init_capacity * sizeof(int));
  if (!v->data) return -1;

  v->size = 0;
  v->capacity = init_capacity;

  return 0; /* success */
}

Then of course, you need functions for push_back, insert, resize, etc, which would call realloc if size exceeds capacity.

vector_resize(vector* v, size_t new_size);

vector_push_back(vector* v, int element);

Usually, when a reallocation is needed, capacity is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by std::vector, except typically std::vector won't call realloc because of C++ object construction/destruction. Rather, std::vector might allocate a new buffer, and then copy construct/move construct the objects (using placement new) into the new buffer.

An actual vector implementation in C might use void* pointers as elements rather than int, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c for an example vector implementation in C.

Setting Short Value Java

Generally you can just cast the variable to become a short.

You can also get problems like this that can be confusing. This is because the + operator promotes them to an int

enter image description here

Casting the elements won't help:

enter image description here

You need to cast the expression:

enter image description here

What is a good regular expression to match a URL?

These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.

 function isURL(str) {
     var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
     var url = new RegExp(urlRegex, 'i');
     return str.length < 2083 && url.test(str);
}

How to fix/convert space indentation in Sublime Text?

The easiest thing i did was,

changed my Indentation to Tabs

and it resolved my problem.

You can do the same,

to Spaces

as well as per your need.

Mentioned the snapshot of the same.

enter image description here

Is JavaScript a pass-by-reference or pass-by-value language?

Mostly simplest way

// Copy JS object without reference
var first = {"a":"value1","b":"value2"};
var clone = JSON.parse( JSON.stringify( first ) ); 

var second = ["a","b","c"];
var clone = JSON.parse( JSON.stringify( second ) ); 

BAT file to map to network drive without running as admin

I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"

add -persist at the end, you will create a persisted mapped network drive

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist

for more details, refer New-PSDrive - Microsoft Docs

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Python: How to increase/reduce the fontsize of x and y tick labels?

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time.

ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

You can also set the ticklabel font size globally (i.e. for all figures/subplots in a script) using rcParams:

import matplotlib.pyplot as plt

plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)

Or, equivalently:

plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8

Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams in your matplotlibrc file:

xtick.labelsize      : 8 # fontsize of the x tick labels
ytick.labelsize      : 8 # fontsize of the y tick labels

How to validate phone number in laravel 5.2?

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:

 'phone' => 'required|numeric|phone' 

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


Python: Random numbers into a list

my_randoms = [randint(n1,n2) for x in range(listsize)]

Which JRE am I using?

I had a problem where my Java applications quit work with no discernible evidence that I could find. It turned out my system started using the 64-bit version rather than the 32-bit version was needed (Windows Server 2012). In Windows, the command:

Javaw -version

just brought me back to the command prompt without any information. It wasn't until I tried

Javaw -Version 2>x.txt
type x.txt

that it gave me what was being executed was the 64-bit version. It boiled down to my PATH environment variable finding the 64-bit version first.

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

How can I perform static code analysis in PHP?

There is RIPS - A static source code analyser for vulnerabilities in PHP scripts. The source code of RIPS is available at SourceForge.

From the RIPS site:

RIPS is a tool written in PHP to find vulnerabilities in PHP applications using static code analysis. By tokenizing and parsing all source code files RIPS is able to transform PHP source code into a program model and to detect sensitive sinks (potentially vulnerable functions) that can be tainted by userinput (influenced by a malicious user) during the program flow. Besides the structured output of found vulnerabilities RIPS also offers an integrated code audit framework for further manual analysis.

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

How can I see which Git branches are tracking which remote / upstream branch?

I use this alias

git config --global alias.track '!f() { ([ $# -eq 2 ] && ( echo "Setting tracking for branch " $1 " -> " $2;git branch --set-upstream $1 $2; ) || ( git for-each-ref --format="local: %(refname:short) <--sync--> remote: %(upstream:short)" refs/heads && echo --Remotes && git remote -v)); }; f'

then

git track

use localStorage across subdomains

I suggest making site.com redirect to www.site.com for both consistency and for avoiding issues like this.

Also, consider using a cross-browser solution like PersistJS that can use each browser native storage.

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.

You're trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That's exactly what getenv does:

Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don't want to get it, you want to check for it's existence.

Either way, getenv is just a wrapper around environ.get but you don't see people checking for membership in mappings with:

from os import environ
if environ.get('Foo') is not None:

To summarize, use:

if "FOO" in os.environ:
    pass

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

Reading/Writing a MS Word file in PHP

Most probably you won't be able to read Word documents without COM.

Writing was covered in this topic

Include files from parent or other directory

the root directory (in PHP) is the directory of the file that is pinged. For example, I go to http://localhost/directory/to/file/index.php, the root directory will be "/dictory/to/file", since it's the one that you've made a web request for.

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

For a start simply add the following to your application.properties file

spring.security.user.name=user
spring.security.user.password=pass

NB: with no double quote

Run your application and enter the credentials (user, pass)

How do I set the default locale in the JVM?

You can do this:

enter image description here

enter image description here

And to capture locale. You can do this:

private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
            + "-" + LocaleContextHolder.getLocale().getCountry();

How to write a UTF-8 file with Java?

Try using FileUtils.write from Apache Commons.

You should be able to do something like:

File f = new File("output.txt"); 
FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");

This will create the file if it does not exist.

Set content of iframe

$('#myiframe').contents().find('html').html(s); 

you can check from here http://jsfiddle.net/Y9beh/

Why does Math.Round(2.5) return 2 instead of 3?

I had this problem where my SQL server rounds up 0.5 to 1 while my C# application didn't. So you would see two different results.

Here's an implementation with int/long. This is how Java rounds.

int roundedNumber = (int)Math.Floor(d + 0.5);

It's probably the most efficient method you could think of as well.

If you want to keep it a double and use decimal precision , then it's really just a matter of using exponents of 10 based on how many decimal places.

public double getRounding(double number, int decimalPoints)
{
    double decimalPowerOfTen = Math.Pow(10, decimalPoints);
    return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
}

You can input a negative decimal for decimal points and it's word fine as well.

getRounding(239, -2) = 200

This IP, site or mobile application is not authorized to use this API key

Google Place API requires the referer HTTP header to be included when making the API call.

Include HTTP header "Referer:yourdomain.com" and this should fix the response issues.

How to get the current working directory in Java?

Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D and defining a variable to hold the info

Something like

java -D com.mycompany.workingDir="%0"

That's not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")...

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

Javascript array value is undefined ... how do I test for that

Check for

if (predQuery[preId] === undefined)

Use the strict equal to operator. See comparison operators

How do you extract classes' source code from a dll file?

Use dotPeek

enter image description here

Select the .dll to decompile

enter image description here

That's it

Getting text from td cells with jQuery

$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});

How do I convert an Array to a List<object> in C#?

Everything everyone is saying is correct so,

int[] aArray = {1,2,3};
List<int> list = aArray.OfType<int> ().ToList();

would turn aArray into a list, list. However the biggest thing that is missing from a lot of comments is that you need to have these 2 using statements at the top of your class

using System.Collections.Generic;
using System.Linq;

I hope this helps!

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

Ant task to run an Ant target only if a file exists?

Since Ant 1.8.0 there's apparently also resourceexists

From http://ant.apache.org/manual/Tasks/conditions.html

Tests a resource for existance. since Ant 1.8.0

The actual resource to test is specified as a nested element.

An example:

<resourceexists>
  <file file="${file}"/>
</resourceexists>

I was about rework the example from the above good answer to this question, and then I found this

As of Ant 1.8.0, you may instead use property expansion; a value of true (or on or yes) will enable the item, while false (or off or no) will disable it. Other values are still assumed to be property names and so the item is enabled only if the named property is defined.

Compared to the older style, this gives you additional flexibility, because you can override the condition from the command line or parent scripts:

<target name="-check-use-file" unless="file.exists">
    <available property="file.exists" file="some-file"/>
</target>
<target name="use-file" depends="-check-use-file" if="${file.exists}">
    <!-- do something requiring that file... -->
</target>
<target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>

from the ant manual at http://ant.apache.org/manual/properties.html#if+unless

Hopefully this example is of use to some. They're not using resourceexists, but presumably you could?.....

Jenkins fails when running "service start jenkins"

Before you install Jenkins you should install JDK:

apt install openjdk-8-jre

After this install Jenkins:

apt-get install jenkins

And check Jenkins status (should be 'active'):

systemctl status jenkins.service

How to delete files older than X hours

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

Limiting number of displayed results when using ngRepeat

Use limitTo filter to display a limited number of results in ng-repeat.

<ul class="phones">
      <li ng-repeat="phone in phones | limitTo:5">
        {{phone.name}}
        <p>{{phone.snippet}}</p>
      </li>
</ul>

How to convert JSON to a Ruby hash

Have you tried: http://flori.github.com/json/?

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.