Programs & Examples On #Reference

A reference is a value that enables a program to indirectly access a particular datum, such as a variable or a record, in the computer's memory or in some other storage device.

What does the "undefined reference to varName" in C mean?

make sure your doSomething function is not static.

How do I make a relative reference to another workbook in Excel?

Using =worksheetname() and =Indirect() function, and naming the worksheets in the parent Excel file with the name of the externally referenced Excel file. Each externally referenced excel file were in their own folders with same name. These sub-folders were only to create more clarity.


What I did was as follows:-

|----Column B---------------|----Column C------------|

R2) Parent folder --------> "C:\TEMP\Excel\"

R3) Sub folder name ---> =worksheetname()

R5) Full path --------------> ="'"&C2&C3&"["&C3&".xlsx]Sheet1'!$A$1"

R7) Indirect function-----> =INDIRECT(C5,TRUE)

In the main file, I had say, 5 worksheets labeled as Ext-1, Ext-2, Ext-3, Ext-4, Ext-5. Copy pasted the above formulas into all the five worksheets. Opened all the respectively named Excel files in the background. For some reason the results were not automatically computing, hence had to force a change by editing any cell. Volla, the value in cell A1 of each externally referenced Excel file were in the Main file.

Getting "type or namespace name could not be found" but everything seems ok?

Started having this problem after "downgrading" from VS 2019 Enterprise to VS 2019 Professional. Although the error was showing in the Error window, I could build the project without problems. Tried many solutions from this thread and others like equalizing target frameworks, delete and make the reference again, deleting .suo file, etc. What worked for me was simply deleting the project in my local repository and cloning it again from the remote repository.

"Are you missing an assembly reference?" compile error - Visual Studio

In my case it was a project defined using Target Framework: ".NET Framework 4.0 Client Profile " that tried to reference dll projects defined using Target Framework: ".NET Framework 4.0".

Once I changed the project settings to use Target Framework: ".NET Framework 4.0" everything was built nicely.

Right Click the project->Properties->Application->Target Framework

The type or namespace name could not be found

I encountered this issue it turned out to be.

Project B references Project A.

Project A compiled as A.dll (assembly name = A).

Project B compiled as A.dll (assembly name A).

Visual Studio 2010 wasn't catching this. Resharper was okay, but wouldn't compile. WinForms designer gave misleading error message saying likely resulting from incompatbile platform targets.

The solution, after a painful day, was to make sure assemblies don't have same name.

Referencing a string in a string array resource with xml

Maybe this would help:

String[] some_array = getResources().getStringArray(R.array.your_string_array)

So you get the array-list as a String[] and then choose any i, some_array[i].

Reference an Element in a List of Tuples

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

"Can't find Project or Library" for standard VBA functions

In my case, I could not even open "References" in the Visual Basic window. I even tried reinstalling Office 365 and that didn't work. Finally, I tried disabling macros in the "Trust Center" settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on "enable" I no longer got the error message.

Later I re-enabled all macros in the "Trust Center" settings, and the error message didn't show up!

Hey, if nothing else works for you, try the above; it worked for me! :)

Update: The issue returned, and this is how I "fixed" it the second time:

I opened my workbook in Excel online (Office 365, in the browser, which doesn't support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.

Can I pass parameters by reference in Java?

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

When to create variables (memory management)

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

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

Did you forget to add the init.py in your package?

MongoDB relationships: embed or reference?

This is more an art than a science. The Mongo Documentation on Schemas is a good reference, but here are some things to consider:

  • Put as much in as possible

    The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure (this means that you can take the part of the document that you need, so document size shouldn't worry you much) there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.

  • Separate data that can be referred to from multiple places into its own collection.

    This is not so much a "storage space" issue as it is a "data consistency" issue. If many records will refer to the same data it is more efficient and less error prone to update a single record and keep references to it in other places.

  • Document size considerations

    MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document. In a world of GB of data this sounds small, but it is also 30 thousand tweets or 250 typical Stack Overflow answers or 20 flicker photos. On the other hand, this is far more information than one might want to present at one time on a typical web page. First consider what will make your queries easier. In many cases concern about document sizes will be premature optimization.

  • Complex data structures:

    MongoDB can store arbitrary deep nested data structures, but cannot search them efficiently. If your data forms a tree, forest or graph, you effectively need to store each node and its edges in a separate document. (Note that there are data stores specifically designed for this type of data that one should consider as well)

    It has also been pointed out than it is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.

  • Data Consistency

    MongoDB makes a trade off between efficiency and consistency. The rule is changes to a single document are always atomic, while updates to multiple documents should never be assumed to be atomic. There is also no way to "lock" a record on the server (you can build this into the client's logic using for example a "lock" field). When you design your schema consider how you will keep your data consistent. Generally, the more that you keep in a document the better.

For what you are describing, I would embed the comments, and give each comment an id field with an ObjectID. The ObjectID has a time stamp embedded in it so you can use that instead of created at if you like.

How do I pass a variable by reference?

Think of stuff being passed by assignment instead of by reference/by value. That way, it is always clear, what is happening as long as you understand what happens during the normal assignment.

So, when passing a list to a function/method, the list is assigned to the parameter name. Appending to the list will result in the list being modified. Reassigning the list inside the function will not change the original list, since:

a = [1, 2, 3]
b = a
b.append(4)
b = ['a', 'b']
print a, b      # prints [1, 2, 3, 4] ['a', 'b']

Since immutable types cannot be modified, they seem like being passed by value - passing an int into a function means assigning the int to the function's parameter. You can only ever reassign that, but it won't change the original variables value.

Android: failed to convert @drawable/picture into a drawable

If re-starting Eclipse does not correct the problem, make sure that the image name begins with an alpha character (non-numeric).

Why are arrays of references illegal?

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

Why can't I reference my class library?

After confirming the same version of asp.net was being used. I removed the project. cleaned the solution and re-added the project. this is what worked for me.

Creating a copy of an object in C#

The easiest way to do this is writing a copy constructor in the MyClass class.

Something like this:

namespace Example
{
    class MyClass
    {
        public int val;

        public MyClass()
        {
        }

        public MyClass(MyClass other)
        {
            val = other.val;
        }
    }
}

The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value

class Program
{
    static void Main(string[] args)
    {
        MyClass objectA = new MyClass();
        MyClass objectB = new MyClass(objectA);
        objectA.val = 10;
        objectB.val = 20;
        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.ReadKey();
    }
}

output:

objectA.val = 10

objectB.val = 20               

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Difference between const reference and normal parameter

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.

There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.

E.g.

int a;

void DoWork(const int &n)
{
    a = n * 2;  // If n was a reference to a, n will have been doubled 

    f();  // Might change the value of whatever n refers to 
}

int main()
{
    DoWork(a);
}

Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.

e.g.

void DoWork(const int &n)
{
    const_cast<int&>(n) = 22;
}

This would cause undefined behaviour if the object passed in was actually const.

When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.

When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

What's the difference between SoftReference and WeakReference in Java?

The six types of object reachability states in Java:

  1. Strongly reachable objects - GC will not collect (reclaim the memory occupied by) this kind of object. These are reachable via a root node or another strongly reachable object (i.e. via local variables, class variables, instance variables, etc.)
  2. Softly reachable objects - GC may attempt to collect this kind of object depending on memory contention. These are reachable from the root via one or more soft reference objects
  3. Weakly reachable objects - GC must collect this kind of object. These are reachable from the root via one or more weak reference objects
  4. Resurrect-able objects - GC is already in the process of collecting these objects. But they may go back to one of the states - Strong/Soft/Weak by the execution of some finalizer
  5. Phantomly reachable object - GC is already in the process of collecting these objects and has determined to not be resurrect-able by any finalizer (if it declares a finalize() method itself, then its finalizer will have been run). These are reachable from the root via one or more phantom reference objects
  6. Unreachable object - An object is neither strongly, softly, weakly, nor phantom reachable, and is not resurrectable. These objects are ready for reclamation

For more details: https://www.artima.com/insidejvm/ed2/gc16.html « collapse

Reason to Pass a Pointer by Reference in C++?

David's answer is correct, but if it's still a little abstract, here are two examples:

  1. You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:

    void freeAndZero(void** ptr)
    {
        free(*ptr);
        *ptr = 0;
    }
    
    void* ptr = malloc(...);
    
    ...
    
    freeAndZero(&ptr);
    

    In C++ to do the same, you might do:

    template<class T> void freeAndZero(T* &ptr)
    {
        delete ptr;
        ptr = 0;
    }
    
    int* ptr = new int;
    
    ...
    
    freeAndZero(ptr);
    
  2. When dealing with linked-lists - often simply represented as pointers to a next node:

    struct Node
    {
        value_t value;
        Node* next;
    };
    

    In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:

    void insert(Node* &list)
    {
        ...
        if(!list) list = new Node(...);
        ...
    }
    

There's an example in this question.

How to copy a dictionary and only edit the copy

the following code, which is on dicts which follows json syntax more than 3 times faster than deepcopy

def CopyDict(dSrc):
    try:
        return json.loads(json.dumps(dSrc))
    except Exception as e:
        Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
        return deepcopy(dSrc)

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Here is what I had and what caused my "incomplete type error":

#include "X.h" // another already declared class
class Big {...} // full declaration of class A

class Small : Big {
    Small() {}
    Small(X); // line 6
}
//.... all other stuff

What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..

Big.cpp

Small::Big(X my_x) { // line 9 <--- LOOK at this !
}

I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..

Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

For the second part of your question, see the array page of the manual, which states (quoting) :

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

And the given example :

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


For the first part, the best way to be sure is to try ;-)

Consider this example of code :

function my_func($a) {
    $a[] = 30;
}

$arr = array(10, 20);
my_func($arr);
var_dump($arr);

It'll give this output :

array
  0 => int 10
  1 => int 20

Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.

If you want it passed by reference, you'll have to modify the function, this way :

function my_func(& $a) {
    $a[] = 30;
}

And the output will become :

array
  0 => int 10
  1 => int 20
  2 => int 30

As, this time, the array has been passed "by reference".


Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)

Why can't I make a vector of references?

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int> is not allowed.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

Undefined reference to main - collect2: ld returned 1 exit status

In my case it was just because I had not Saved the source file and was trying to compile a empty file .

Pointer vs. Reference

Pass by const reference unless there is a reason you wish to change/keep the contents you are passing in.

This will be the most efficient method in most cases.

Make sure you use const on each parameter you do not wish to change, as this not only protects you from doing something stupid in the function, it gives a good indication to other users what the function does to the passed in values. This includes making a pointer const when you only want to change whats pointed to...

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

Reference member variables as class members

Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.

How to cast/convert pointer to reference in C++

Call it like this:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

How to add a reference programmatically

There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor) and .AddFromFile(Filename). Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.

The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)

If you are having problems getting the code to run, there are two possible issues.

  1. In order to easily use the VBE's object model, you need to add a reference to Microsoft Visual Basic for Application Extensibility. (VBIDE)
  2. In order to run Excel VBA code that changes anything in a VBProject, you need to Trust access to the VBA Project Object Model. (In Excel 2010, it is located in the Trust Center - Macro Settings.)

Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.

C# string reference type?

Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type:

MyClass c = new MyClass(); c.MyProperty = "foo";

CNull(c); // only a copy of the reference is sent 
Console.WriteLine(c.MyProperty); // still foo, we only made the copy null
CPropertyChange(c); 
Console.WriteLine(c.MyProperty); // bar


private void CNull(MyClass c2)
        {          
            c2 = null;
        }
private void CPropertyChange(MyClass c2) 
        {
            c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well.
        }

How to disable Excel's automatic cell reference change after copy/paste?

I found another workaround that is very simple: 1. Cut the contents 2. Paste them in the new location 3. Copy the contents that you just pasted into the new location you want. 4. Undo the Cut-Paste operation, putting the original contents back where you got them. 5. Paste the contents from the clipboard to the same location. These contents will have the original references.

It looks like a lot, but is super fast with keyboard shortcuts: 1. Ctrl-x, 2. Ctrl-v, 3. Ctrl-c, 4. Ctrl-z, 5. Ctrl-v

What are the differences between a pointer variable and a reference variable in C++?

It doesn't matter how much space it takes up since you can't actually see any side effect (without executing code) of whatever space it would take up.

On the other hand, one major difference between references and pointers is that temporaries assigned to const references live until the const reference goes out of scope.

For example:

class scope_test
{
public:
    ~scope_test() { printf("scope_test done!\n"); }
};

...

{
    const scope_test &test= scope_test();
    printf("in scope\n");
}

will print:

in scope
scope_test done!

This is the language mechanism that allows ScopeGuard to work.

Does JavaScript pass by reference?

My two cents.... It's irrelevant whether JavaScript passes parameters by reference or value. What really matters is assignment vs. mutation.

I wrote a longer, more detailed explanation in this link.

When you pass anything (whether that be an object or a primitive), all JavaScript does is assign a new variable while inside the function... just like using the equal sign (=).

How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign... Take these simple examples.

_x000D_
_x000D_
var myString = 'Test string 1';

// Assignment - A link to the same place as myString
var sameString = myString;

// If I change sameString, it will not modify myString,
// it just re-assigns it to a whole new string
sameString = 'New string';

console.log(myString); // Logs 'Test string 1';
console.log(sameString); // Logs 'New string';
_x000D_
_x000D_
_x000D_

If I were to pass myString as a parameter to a function, it behaves as if I simply assigned it to a new variable. Now, let's do the same thing, but with a function instead of a simple assignment

_x000D_
_x000D_
function myFunc(sameString) {

  // Reassignment... Again, it will not modify myString
  sameString = 'New string';
}

var myString = 'Test string 1';

// This behaves the same as if we said sameString = myString
myFunc(myString);

console.log(myString); // Again, logs 'Test string 1';
_x000D_
_x000D_
_x000D_

The only reason that you can modify objects when you pass them to a function is because you are not reassigning... Instead, objects can be changed or mutated.... Again, it works the same way.

var myObject = { name: 'Joe'; }

// Assignment - We simply link to the same object
var sameObject = myObject;

// This time, we can mutate it. So a change to myObject affects sameObject and visa versa
myObject.name = 'Jack';
console.log(sameObject.name); // Logs 'Jack'

sameObject.name = 'Jill';
console.log(myObject.name); // Logs 'Jill'

// If we re-assign it, the link is lost
sameObject = { name: 'Howard' };
console.log(myObject.name); // Logs 'Jill'

If I were to pass myObject as a parameter to a function, it behaves as if I simply assigned it to a new variable. Again, the same thing with the exact same behavior but with a function.

_x000D_
_x000D_
function myFunc(sameObject) {
  // We mutate the object, so the myObject gets the change too... just like before.
  sameObject.name = 'Jill';

  // But, if we re-assign it, the link is lost
  sameObject = {
    name: 'Howard'
  };
}

var myObject = {
  name: 'Joe'
};

// This behaves the same as if we said sameObject = myObject;
myFunc(myObject);
console.log(myObject.name); // Logs 'Jill'
_x000D_
_x000D_
_x000D_

Every time you pass a variable to a function, you are "assigning" to whatever the name of the parameter is, just like if you used the equal = sign.

Always remember that the equals sign = means assignment. And passing a parameter to a function also means assignment. They are the same and the two variables are connected in exactly the same way.

The only time that modifying a variable affects a different variable is when the underlying object is mutated.

There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable.

C++ pass an array by reference

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

With new_list = my_list, you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.

To actually copy the list, you have various possibilities:

  • You can use the builtin list.copy() method (available since Python 3.3):

    new_list = old_list.copy()
    
  • You can slice it:

    new_list = old_list[:]
    

    Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).

  • You can use the built in list() function:

    new_list = list(old_list)
    
  • You can use generic copy.copy():

    import copy
    new_list = copy.copy(old_list)
    

    This is a little slower than list() because it has to find out the datatype of old_list first.

  • If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

    import copy
    new_list = copy.deepcopy(old_list)
    

    Obviously the slowest and most memory-needing method, but sometimes unavoidable.

Example:

import copy

class Foo(object):
    def __init__(self, val):
         self.val = val

    def __repr__(self):
        return 'Foo({!r})'.format(self.val)

foo = Foo(1)

a = ['foo', foo]
b = a.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)

# edit orignal list and instance 
a.append('baz')
foo.val = 5

print('original: %r\nlist.copy(): %r\nslice: %r\nlist(): %r\ncopy: %r\ndeepcopy: %r'
      % (a, b, c, d, e, f))

Result:

original: ['foo', Foo(5), 'baz']
list.copy(): ['foo', Foo(5)]
slice: ['foo', Foo(5)]
list(): ['foo', Foo(5)]
copy: ['foo', Foo(5)]
deepcopy: ['foo', Foo(1)]

Pick images of root folder from sub-folder

The relative reference would be

<img src="../images/logo.png">

If you know the location relative to the root of the server, that may be simplest approach for an app with a complex nested directory hierarchy - it would be the same from all folders.

For example, if your directory tree depicted in your question is relative to the root of the server, then index.html and sub_folder/sub.html would both use:

<img src="/images/logo.png">

If the images folder is instead in the root of an application like foo below the server root (e.g. http://www.example.com/foo), then index.html (http://www.example.com/foo/index.html) e.g and sub_folder/sub.html (http://www.example.com/foo/sub_folder/sub.html) both use:

<img src="/foo/images/logo.png">

Meaning of *& and **& in C++

Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"

Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.

Which is better, return value or out parameter?

Both of them have a different purpose and are not treated the same by the compiler. If your method needs to return a value, then you must use return. Out is used where your method needs to return multiple values.

If you use return, then the data is first written to the methods stack and then in the calling method's. While in case of out, it is directly written to the calling methods stack. Not sure if there are any more differences.

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

Namespace not recognized (even though it is there)

Perhaps the project's type table is in an incorrect state. I would try to remove/add the reference and if that didn't work, create another project, import my code, and see if that works.

I ran into this while using VS 2005, one would expect MS to have fixed that particular problem by now though..

What's the difference between primitive and reference types?

From book OCA JAVA SE 7

Just as men and women are fundamentally different (according to John Gray, author of Men Are from Mars, Women Are from Venus), primitive variables and object reference variables differ from each other in multiple ways. The basic difference is that primitive variables store the actual values, whereas reference variables store the addresses of the objects they refer to. Let’s assume that a class Person is already defined. If you create an int variable a, and an object reference variable person, they will store their values in memory as shown in figure 2.13.

int a = 77;
Person person = new Person();

enter image description here

Visual Studio: Relative Assembly References Paths

Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.

I've done this plenty of times in VS 2005 without any problems.

How to return a class object by reference in C++?

You can only return non-local objects by reference. The destructor may have invalidated some internal pointer, or whatever.

Don't be afraid of returning values -- it's fast!

What is the difference between "::" "." and "->" in c++

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

Is the practice of returning a C++ reference variable evil?

return reference is usually used in operator overloading in C++ for large Object, because returning a value need copy operation.(in perator overloading, we usually don't use pointer as return value)

But return reference may cause memory allocation problem. Because a reference to the result will be passed out of the function as a reference to the return value, the return value cannot be an automatic variable.

if you want use returning refernce, you may use a buffer of static object. for example

const max_tmp=5; 
Obj& get_tmp()
{
 static int buf=0;
 static Obj Buf[max_tmp];
  if(buf==max_tmp) buf=0;
  return Buf[buf++];
}
Obj& operator+(const Obj& o1, const Obj& o1)
{
 Obj& res=get_tmp();
 // +operation
  return res;
 }

in this way, you could use returning reference safely.

But you could always use pointer instead of reference for returning value in functiong.

The located assembly's manifest definition does not match the assembly reference

I got this error while building on Team Foundation Server's build-service. It turned out I had multiple projects in my solution using different versions of the same library added with NuGet. I removed all old versions with NuGet and added the new one as reference for all.

Team Foundation Server puts all DLL files in one directory, and there can only be one DLL file of a certain name at a time of course.

Is null reference possible?

References are not pointers.

8.3.2/1:

A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]

1.9/4:

Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer)

As Johannes says in a deleted answer, there's some doubt whether "dereferencing a null pointer" should be categorically stated to be undefined behavior. But this isn't one of the cases that raise doubts, since a null pointer certainly does not point to a "valid object or function", and there is no desire within the standards committee to introduce null references.

Pass by pointer & Pass by reference

Here is a good article on the matter - "Use references when you can, and pointers when you have to."

A reference to the dll could not be added

For anyone else looking for help on this matter, or experiencing a FileNotFoundException or a FirstChanceException, check out my answer here:

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll - windows phone

In general you must be absolutely certain that you are meeting all of the requirements for making the reference - I know it's the obvious answer, but you're probably overlooking a relatively simple requirement.

Meaning of "referencing" and "dereferencing" in C

Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:

int  c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1

Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.

int n1;
n1 = *p1;

Invalid dereferencing may or may not cause crashes:

  • Dereferencing an uninitialized pointer can cause a crash
  • Dereferencing with an invalid type cast will have the potential to cause a crash.
  • Dereferencing a pointer to a variable that was dynamically allocated and was subsequently de-allocated can cause a crash
  • Dereferencing a pointer to a variable that has since gone out of scope can also cause a crash.

Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.

References:

http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators

& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.

http://www.cplusplus.com/doc/tutorial/pointers/

& is the reference operator    
* is the dereference operator

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

The dereference operator * is also called the indirection operator.

Passing references to pointers in C++

Try:

void myfunc(string& val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(s);
    // ...
}

or

void myfunc(string* val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(&s);
    // ...
}

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I'm not sure why it is different when building between Visual Studio and MsBuild, but here is what I have found when I've encountered this problem in MsBuild and Visual Studio.

Explanation

For a sample scenario let's say we have project X, assembly A, and assembly B. Assembly A references assembly B, so project X includes a reference to both A and B. Also, project X includes code that references assembly A (e.g. A.SomeFunction()). Now, you create a new project Y which references project X.

So the dependency chain looks like this: Y => X => A => B

Visual Studio / MSBuild tries to be smart and only bring references over into project Y that it detects as being required by project X; it does this to avoid reference pollution in project Y. The problem is, since project X doesn't actually contain any code that explicitly uses assembly B (e.g. B.SomeFunction()), VS/MSBuild doesn't detect that B is required by X, and thus doesn't copy it over into project Y's bin directory; it only copies the X and A assemblies.

Solution

You have two options to solve this problem, both of which will result in assembly B being copied to project Y's bin directory:

  1. Add a reference to assembly B in project Y.
  2. Add dummy code to a file in project X that uses assembly B.

Personally I prefer option 2 for a couple reasons.

  1. If you add another project in the future that references project X, you won't have to remember to also include a reference to assembly B (like you would have to do with option 1).
  2. You can have explicit comments saying why the dummy code needs to be there and not to remove it. So if somebody does delete the code by accident (say with a refactor tool that looks for unused code), you can easily see from source control that the code is required and to restore it. If you use option 1 and somebody uses a refactor tool to clean up unused references, you don't have any comments; you will just see that a reference was removed from the .csproj file.

Here is a sample of the "dummy code" that I typically add when I encounter this situation.

    // DO NOT DELETE THIS CODE UNLESS WE NO LONGER REQUIRE ASSEMBLY A!!!
    private void DummyFunctionToMakeSureReferencesGetCopiedProperly_DO_NOT_DELETE_THIS_CODE()
    {
        // Assembly A is used by this file, and that assembly depends on assembly B,
        // but this project does not have any code that explicitly references assembly B. Therefore, when another project references
        // this project, this project's assembly and the assembly A get copied to the project's bin directory, but not
        // assembly B. So in order to get the required assembly B copied over, we add some dummy code here (that never
        // gets called) that references assembly B; this will flag VS/MSBuild to copy the required assembly B over as well.
        var dummyType = typeof(B.SomeClass);
        Console.WriteLine(dummyType.FullName);
    }

Could not load file or assembly '***.dll' or one of its dependencies

I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.

Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.

Error message "Strict standards: Only variables should be passed by reference"

Consider the following code:

error_reporting(E_STRICT);
class test {
    function test_arr(&$a) {
        var_dump($a);
    }
    function get_arr() {
        return array(1, 2);
    }
}

$t = new test;
$t->test_arr($t->get_arr());

This will generate the following output:

Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

The reason? The test::get_arr() method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr() method returns an array value.

To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:

function test_arr($a) {
    var_dump($a);
}

Since you can't change the signature of array_shift you can also use an intermediate variable:

$inter = get_arr();
$el = array_shift($inter);

How to reference Microsoft.Office.Interop.Excel dll?

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn't have access to NuGet.

  • Right-click on "References" and select "Add Reference".
  • Select "Extensions" on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type "excel" into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on "References" and select "Add Reference".
  • Select the ".NET" tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

In laymans terms, what does 'static' mean in Java?

In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.

When should I use the new keyword in C++?

Which method should I use?

This is almost never determined by your typing preferences but by the context. If you need to keep the object across a few stacks or if it's too heavy for the stack you allocate it on the free store. Also, since you are allocating an object, you are also responsible for releasing the memory. Lookup the delete operator.

To ease the burden of using free-store management people have invented stuff like auto_ptr and unique_ptr. I strongly recommend you take a look at these. They might even be of help to your typing issues ;-)

What's the difference between the 'ref' and 'out' keywords?

out:

In C#, a method can return only one value. If you like to return more than one value, you can use the out keyword. The out modifier return as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.

  1. You don't need to initialize the value in the calling function.
  2. You must assign the value in the called function, otherwise the compiler will report an error.

ref:

In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.

  1. You need to initialize the variable before you call the function.
  2. It’s not mandatory to assign any value to the ref parameter in the method. If you don’t change the value, what is the need to mark it as “ref”?

What exactly is an instance in Java?

The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.

This statement will just allot memory for the static meber variables, not for the normal member variables.

But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.

When to use references vs. pointers

There is problem with "use references wherever possible" rule and it arises if you want to keep reference for further use. To illustrate this with example, imagine you have following classes.

class SimCard
{
    public:
        explicit SimCard(int id):
            m_id(id)
        {
        }

        int getId() const
        {
            return m_id;
        }

    private:
        int m_id;
};

class RefPhone
{
    public:
        explicit RefPhone(const SimCard & card):
            m_card(card)
        {
        }

        int getSimId()
        {
            return m_card.getId();
        }

    private:
        const SimCard & m_card;
};

At first it may seem to be a good idea to have parameter in RefPhone(const SimCard & card) constructor passed by a reference, because it prevents passing wrong/null pointers to the constructor. It somehow encourages allocation of variables on stack and taking benefits from RAII.

PtrPhone nullPhone(0);  //this will not happen that easily
SimCard * cardPtr = new SimCard(666);  //evil pointer
delete cardPtr;  //muahaha
PtrPhone uninitPhone(cardPtr);  //this will not happen that easily

But then temporaries come to destroy your happy world.

RefPhone tempPhone(SimCard(666));   //evil temporary
//function referring to destroyed object
tempPhone.getSimId();    //this can happen

So if you blindly stick to references you trade off possibility of passing invalid pointers for the possibility of storing references to destroyed objects, which has basically same effect.

edit: Note that I sticked to the rule "Use reference wherever you can, pointers wherever you must. Avoid pointers until you can't." from the most upvoted and accepted answer (other answers also suggest so). Though it should be obvious, example is not to show that references as such are bad. They can be misused however, just like pointers and they can bring their own threats to the code.


There are following differences between pointers and references.

  1. When it comes to passing variables, pass by reference looks like pass by value, but has pointer semantics (acts like pointer).
  2. Reference can not be directly initialized to 0 (null).
  3. Reference (reference, not referenced object) can not be modified (equivalent to "* const" pointer).
  4. const reference can accept temporary parameter.
  5. Local const references prolong the lifetime of temporary objects

Taking those into account my current rules are as follows.

  • Use references for parameters that will be used locally within a function scope.
  • Use pointers when 0 (null) is acceptable parameter value or you need to store parameter for further use. If 0 (null) is acceptable I am adding "_n" suffix to parameter, use guarded pointer (like QPointer in Qt) or just document it. You can also use smart pointers. You have to be even more careful with shared pointers than with normal pointers (otherwise you can end up with by design memory leaks and responsibility mess).

Is there a difference between "==" and "is"?

Python difference between is and equals(==)

The is operator may seem like the same as the equality operator but they are not same.

The is checks if both the variables point to the same object whereas the == sign checks if the values for the two variables are the same.

So if the is operator returns True then the equality is definitely True, but the opposite may or may not be True.

Here is an example to demonstrate the similarity and the difference.

>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> a == b
True
>>> a == c
True
>>> a is b
True
>>> a is c
False
>>> a = [1,2,3]
>>> b = [1,2]
>>> a == b
False
>>> a is b
False
>>> del a[2]
>>> a == b
True
>>> a is b
False
Tip: Avoid using is operator for immutable types such as strings and numbers, the result is unpredictable.

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

How do I copy the contents of one ArrayList into another?

Copy of one list into second is quite simple , you can do that as below:-

ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);

How to write to error log file in PHP

We all know that PHP save errors in php_errors.log file.

But, that file contains a lot of data.

If we want to log our application data, we need to save it to a custom location.

We can use two parameters in the error_log function to achieve this.

http://php.net/manual/en/function.error-log.php

We can do it using:

error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');

Where,

print_r($v, TRUE) : logs $v (array/string/object) to log file. 3: Put log message to custom log file specified in the third parameter.

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS).

OR, you can use file_put_contents()

file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);

Where:

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS). print_r($v, TRUE) : logs $v (array/string/object) to log file. FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.

JavaScript by reference vs. by value

Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

An example:

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};

changeParam(a, b, c);

// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...

python list by value not by reference

I would recommend the following solution:

b = []
b[:] = a

This will copy all the elements from a to b. The copy will be value copy, not reference copy.

Dependent DLL is not getting copied to the build output folder in Visual Studio

It looks slick when you make it an assembly attribute

[AttributeUsage(AttributeTargets.Assembly)]
public class ForceAssemblyReference: Attribute
{        
    public ForceAssemblyReference(Type forcedType)
    {
        //not sure if these two lines are required since 
        //the type is passed to constructor as parameter, 
        //thus effectively being used
        Action<Type> noop = _ => { };
        noop(forcedType);
    }
}

The usage will be:

[assembly: ForceAssemblyReference(typeof(AbcDll.AnyClass))]

Finding moving average from data points in Python

My Moving Average function, without numpy function:

from __future__ import division  # must be on first line of script

class Solution:
    def Moving_Avg(self,A):
        m = A[0]
        B = []
        B.append(m)
        for i in range(1,len(A)):
            m = (m * i + A[i])/(i+1)
            B.append(m)
        return B

How can I reduce the waiting (ttfb) time

The TTFB is not the time to first byte of the body of the response (i.e., the useful data, such as: json, xml, etc.), but rather the time to first byte of the response received from the server. This byte is the start of the response headers.

For example, if the server sends the headers before doing the hard work (like heavy SQL), you will get a very low TTFB, but it isn't "true".

In your case, TTFB represents the time you spend processing data on the server.

To reduce the TTFB, you need to do the server-side work faster.

Initializing multiple variables to the same value in Java

No, it's not possible in java.

You can do this way .. But try to avoid it.

String one, two, three;
one = two = three = "";

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

What's the quickest way to multiply multiple cells by another number?

Are you asking how to do it in excel or how to do it in a VBA application? If you just want to do it in excel, here is one way.

android studio 0.4.2: Gradle project sync failed error

I had same problem but finally I could solve it forever
Steps:

  1. Delete gradle and .gradle folders from your project folder.
  2. In Android Studio: Open your project then: File -> settings -> compiler -> gradle: enable offline mode
    Note: In relatively newer Android Studios, Offline mode has been moved to gradle setting. enter image description here
  3. Close your project: File -> close project
  4. Connect to the Internet and open your project again then let Android Studio downloads what it wants

If success then :)
else

  1. If you encounter gradle project sync failed again please follow these steps:
  2. Download the latest gradle package from this directory
  3. Extract it and put it somewhere (for example f:\gradle-1.10)
  4. Go to your Android Studio and load your project then open File->Settings->gradle, in this page click on Use local gradle distribution
  5. Type your gradle folder address there
    enter image description here

Congratulation you are done!

Get the latest date from grouped MySQL data

Subquery giving dates. We are not linking with the model. So below query solves the problem.

If there are duplicate dates/model can be avoided by the following query.

select t.model, t.date
from doc t
inner join (select model, max(date) as MaxDate from doc  group by model)
tm on t.model = tm.model and t.date = tm.MaxDate

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

XAMPP - MySQL shutdown unexpectedly

What worked for me is:

  1. First I open Logs for MySql in XAMPP panel.
  2. At the end it says you are running another instance of mysqlid in port 3306
  3. I opened my task manager(Ctrl+Shift+Esc) then find mysqlid and End the task.

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

If you are using Java configuration in a spring-data-jpa project, make sure you are scanning the package that the entity is in. For example, if the entity lived com.foo.myservice.things then the following configuration annotation below would not pick it up.

You could fix it by loosening it up to just com.foo.myservice (of course, keep in mind any other effects of broadening your scope to scan for entities).

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.foo.myservice.repositories")
public class RepositoryConfiguration {
}

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had same problem. Just changed the ap.jason to application.jason and it fixed the issue

uncaught syntaxerror unexpected token U JSON

Just incase u didnt understand

e.g is that lets say i have a JSON STRING ..NOT YET A JSON OBJECT OR ARRAY.

so if in javascript u parse the string as

var body={
  "id": 1,
  "deleted_at": null,
  "open_order": {
    "id": 16,
    "status": "open"}

var jsonBody = JSON.parse(body.open_order); //HERE THE ERROR NOW APPEARS BECAUSE THE STRING IS NOT A JSON OBJECT YET!!!! 
//TODO SO
var jsonBody=JSON.parse(body)//PASS THE BODY FIRST THEN LATER USE THE jsonBody to get the open_order

var OpenOrder=jsonBody.open_order;

Great answers above

Show dialog from fragment?

I am a beginner myself and I honestly couldn't find a satisfactory answer that I could understand or implement.

So here's an external link that I really helped me achieved what I wanted. It's very straight forward and easy to follow as well.

http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application

THIS WHAT I TRIED TO ACHIEVE WITH THE CODE:

I have a MainActivity that hosts a Fragment. I wanted a dialog to appear on top of the layout to ask for user input and then process the input accordingly. See a screenshot

Here's what the onCreateView of my fragment looks

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home_activity, container, false);

    Button addTransactionBtn = rootView.findViewById(R.id.addTransactionBtn);

    addTransactionBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Dialog dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.dialog_trans);
            dialog.setTitle("Add an Expense");
            dialog.setCancelable(true);

            dialog.show();

        }
    });

I hope it will help you

Let me know if there's any confusion. :)

Javascript - User input through HTML input tag to set a Javascript variable?

Late reading this, but.. The way I read your question, you only need to change two lines of code:

Accept user input, function writes back on screen.

<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>

<!-- add this line for function to write into -->
<p id="demo"></p>   

<script type="text/javascript">
function test(){
    var userInput = document.getElementById("userInput").value;
    document.getElementById("demo").innerHTML = userInput;
}
</script>

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Apk location in New Android Studio

First the apk has to be built. In Android Studio, Build > Build Bundle(s) / APK(s) > Build APK(s). Then find the apk in C:\Users\AndroidStudioProjects\app\build\outputs\apk\debug.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to check if a json key exists?

I used hasOwnProperty('club')

var myobj = { "regatta_name":"ProbaRegatta",
    "country":"Congo",
    "status":"invited"
 };

 if ( myobj.hasOwnProperty("club"))
     // do something with club (will be false with above data)
     var data = myobj.club;
 if ( myobj.hasOwnProperty("status"))
     // do something with the status field. (will be true with above ..)
     var data = myobj.status;

works in all current browsers.

How to animate CSS Translate

There's an interesting way which this can be achieved by using jQuery animate method in a unique way, where you call the animate method on a javascript Object which describes the from value and then you pass as the first parameter another js object which describes the to value, and a step function which handles each step of the animation according to the values described earlier.

Example - Animate transform translateY:

_x000D_
_x000D_
var $elm = $('h1'); // element to be moved_x000D_
_x000D_
function run( v ){_x000D_
  // clone the array (before "animate()" modifies it), and reverse it_x000D_
  var reversed = JSON.parse(JSON.stringify(v)).reverse();_x000D_
  _x000D_
  $(v[0]).animate(v[1], {_x000D_
      duration: 500,_x000D_
      step: function(val) {_x000D_
          $elm.css("transform", `translateY(${val}px)`); _x000D_
      },_x000D_
      done: function(){_x000D_
          run( reversed )_x000D_
      }_x000D_
  })_x000D_
};_x000D_
_x000D_
// "y" is arbitrary used as the key name _x000D_
run( [{y:0}, {y:80}] )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>jQuery animate <pre>transform:translateY()</pre></h1>
_x000D_
_x000D_
_x000D_

Use a JSON array with objects with javascript

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

In Python, what does dict.pop(a,b) mean?

>>> def func(a, *args, **kwargs):
...   print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
... 
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}

>>> def anotherfunct(beta, *args):
...   print 'beta %s, args %s' % (beta, args)
... 
>>> def func(a, *args, **kwargs):
...   anotherfunct(a, *args)
... 
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>> 

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

encodeURI()/decodeURI and encodeURIComponent()/decodeURIComponent are utility functions to handle this. Read more here https://stackabuse.com/javascripts-encodeuri-function/

How to preserve request url with nginx proxy_pass

for my auth server... this works. i like to have options for /auth for my own humanized readability... or also i have it configured by port/upstream for machine to machine.

.

at the beginning of conf

####################################################
upstream auth {
    server 127.0.0.1:9011 weight=1 fail_timeout=300s;
    keepalive 16;
  }

Inside my 443 server block

          if (-d $request_filename) {
          rewrite [^/]$ $scheme://$http_host$uri/ permanent;
      }

  location /auth {
          proxy_pass http://$http_host:9011;
          proxy_set_header Origin           http://$host;
          proxy_set_header Host             $http_host:9011;
          proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade          $http_upgrade;
          proxy_set_header Connection       $http_connection;
          proxy_http_version 1.1;
      }

At the bottom of conf

#####################################################################
#                                                                   #
#     Proxies for all the Other servers on other ports upstream     #
#                                                                   #
#####################################################################


#######################
#        Fusion       #
#######################

server {
    listen 9001 ssl;

#############  Lock it down  ################

# SSL certificate locations
    ssl_certificate /etc/letsencrypt/live/allineed.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/allineed.app/privkey.pem;

# Exclusions

    include snippets/exclusions.conf;

# Security

    include snippets/security.conf;
    include snippets/ssl.conf;

# Fastcgi cache rules

    include snippets/fastcgi-cache.conf;
    include snippets/limits.conf;
    include snippets/nginx-cloudflare.conf;

###########  Location upstream ##############

    location  ~ / {
        proxy_pass http://auth;
        proxy_set_header Origin           http://$host;
        proxy_set_header Host             $host:$server_port;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade          $http_upgrade;
        proxy_set_header Connection       $http_connection;
        proxy_http_version 1.1;
    }
        if (-d $request_filename) {
        rewrite [^/]$ $scheme://$http_host$uri/ permanent;
    }
}

How to calculate the number of occurrence of a given character in each row of a column of strings?

nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))
[1] 2 1 0

Notice that I coerce the factor variable to character, before passing to nchar. The regex functions appear to do that internally.

Here's benchmark results (with a scaled up size of the test to 3000 rows)

 q.data<-q.data[rep(1:NROW(q.data), 1000),]
 str(q.data)
'data.frame':   3000 obs. of  3 variables:
 $ number     : int  1 2 3 1 2 3 1 2 3 1 ...
 $ string     : Factor w/ 3 levels "greatgreat","magic",..: 1 2 3 1 2 3 1 2 3 1 ...
 $ number.of.a: int  2 1 0 2 1 0 2 1 0 2 ...

 benchmark( Dason = { q.data$number.of.a <- str_count(as.character(q.data$string), "a") },
 Tim = {resT <- sapply(as.character(q.data$string), function(x, letter = "a"){
                            sum(unlist(strsplit(x, split = "")) == letter) }) }, 

 DWin = {resW <- nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))},
 Josh = {x <- sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)}, replications=100)
#-----------------------
   test replications elapsed  relative user.self sys.self user.child sys.child
1 Dason          100   4.173  9.959427     2.985    1.204          0         0
3  DWin          100   0.419  1.000000     0.417    0.003          0         0
4  Josh          100  18.635 44.474940    17.883    0.827          0         0
2   Tim          100   3.705  8.842482     3.646    0.072          0         0

Auto insert date and time in form input field?

Another option is:

<script language="JavaScript" type="text/javascript"> 
document.getElementById("my_date:box").value = ( Stamp.getDate()+"/"+(Stamp.getMonth() + 1)+"/"+(Stamp.getYear()) );
</script>

clear data inside text file in c++

If you simply open the file for writing with the truncate-option, you'll delete the content.

std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();

http://www.cplusplus.com/reference/fstream/ofstream/open/

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How to mount a host directory in a Docker container

Here's an example with a Windows path:

docker run -P -it --name organizr --mount src="/c/Users/MyUserName/AppData/Roaming/DockerConfigs/Organizr",dst=/config,type=bind organizrtools/organizr-v2:latest

As a side note, during all of this hair pulling, having to wrestle with figuring out, and retyping paths over and over and over again, I decided to whip up a small AutoHotkey script to convert a Windows path to a "Docker Windows" formatted path. This way all I have to do is copy any Windows path that I want to use as a mount point to the clipboard, press the "Apps Key" on the keyboard, and it'll format it into a path format that Docker appreciates.

For example:

Copy this to your clipboard:

C:\Users\My PC\AppData\Roaming\DockerConfigs\Organizr

press the Apps Key while the cursor is where you want it on the command-line, and it'll paste this there:

"/c/Users/My PC/AppData/Roaming/DockerConfigs/Organizr"

Saves a lot to time for me. Here it is for anyone else who may find it useful.

; --------------------------------------------------------------------------------------------------------------
;
; Docker Utility: Convert a Windows Formatted Path to a Docker Formatter Path
;                   Useful for (example) when mounting Windows volumes via the command-line.
;
; By:       J. Scott Elblein
; Version:  1.0
; Date:     2/5/2019
;
; Usage:    Cut or Copy the Windows formatted path to the clipboard, press the AppsKey on your keyboard
;           (usually right next to the Windows Key), it'll format it into a 'docker path' and enter it
;           into the active window. Easy example usage would be to copy your intended volume path via
;           Explorer, place the cursor after the "-v" in your Docker command, press the Apps Key and
;           then it'll place the formatted path onto the line for you.
;
; TODO::    I may or may not add anything to this depending on needs. Some ideas are:
;           
;           - Add a tray menu with the ability to do some things, like just replace the unformatted path
;               on the clipboard with the formatted one rather than enter it automatically.
;           - Add 'smarter' handling so the it first confirms that the clipboard text is even a path in
;               the first place. (would need to be able to handle Win + Mac + Linux)
;           - Add command-line handling so the script doesn't need to always be in the tray, you could
;               just pass the Windows path to the script, have it format it, then paste and close.
;               Also, could have it just check for a path on the clipboard upon script startup, if found
;               do it's job, then exit the script.
;           - Add an 'all-in-one' action, to copy the selected Windows path, and then output the result.
;           - Whatever else comes to mind.
;
; --------------------------------------------------------------------------------------------------------------

#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%

AppsKey::

    ; Create a new var, store the current clipboard contents (should be a Windows path)
    NewStr := Clipboard

    ; Rip out the first 2 chars (should be a drive letter and colon) & convert the letter to lowercase
    ; NOTE: I could probably replace the following 3 lines with a regexreplace, but atm I'm lazy and in a rush.
    tmpVar := SubStr(NewStr, 1, 2)
    StringLower, tmpVar, tmpVar

    ; Replace the uppercase drive letter and colon with the lowercase drive letter and colon
    NewStr := StrReplace(NewStr, SubStr(NewStr, 1, 2), tmpVar)

    ; Replace backslashes with forward slashes
    NewStr := StrReplace(NewStr,  "\", "/")

    ; Replace all colons with nothing
    NewStr := StrReplace(NewStr, ":", "")

    ; Remove the last char if it's a trailing forward slash
    NewStr :=  RegExReplace(NewStr, "/$")

    ; Append a leading forward slash if not already there
    if RegExMatch(NewStr, "^/") == 0
        NewStr :=  "/" . NewStr

    ; If there are any spaces in the path ... wrap in double quotes
    if RegExMatch(NewStr, " ") > 0
        NewStr :=  """" . NewStr . """"

    ; Send the result to the active window
    SendInput % NewStr 

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

Unlocking tables if thread is lost

how will I know that some tables are locked?

You can use SHOW OPEN TABLES command to view locked tables.

how do I unlock tables manually?

If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

How to copy Docker images from one host to another without using a repository

To save an image to any file path or shared NFS place see the following example.

Get the image id by doing:

docker images

Say you have an image with id "matrix-data".

Save the image with id:

docker save -o /home/matrix/matrix-data.tar matrix-data

Copy the image from the path to any host. Now import to your local Docker installation using:

docker load -i <path to copied image file>

How to define custom configuration variables in rails

Check out this neat gem doing exactly that: https://github.com/mislav/choices

This way your sensitive data won't be exposed in open source projects

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

You can replace nan with None in your numpy array:

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

Remove redundant paths from $PATH variable

How did you add these duplicate paths to your PATH variable? You must have edited one of your . files. (.tcshrc, or .bashrc, etc depending on your particular system/shell). The way to fix it is to edit the file again and remove the duplicate paths.

If you didn't edit any files, and you you must have modified the PATH interactively. In that case the changes won't "stick", ie if you open another shell, or log out and log back in, the changes will be gone automatically.

Note that there are some system wide config files too, but it's unlikely you modified those, so most likely you'll be changing files in your personal home directory (if you want to make those changes permanent once you settle on a set of paths)

How to use UIPanGestureRecognizer to move object? iPhone/iPad

if ([recognizer state] == UIGestureRecognizerStateChanged)    
{
    CGPoint translation1 = [recognizer translationInView:main_view];
    img12.center=CGPointMake(img12.center.x+translation1.x, img12.center.y+ translation1.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:main_view];

    recognizer.view.center=CGPointMake(recognizer.view.center.x+translation1.x, recognizer.view.center.y+ translation1.y);
}

-(void)move:(UIPanGestureRecognizer*)recognizer
{
    if ([recognizer state] == UIGestureRecognizerStateChanged)    
    {
        CGPoint translation = [recognizer translationInView:self.view];
        recognizer.view.center=CGPointMake(recognizer.view.center.x+translation.x, recognizer.view.center.y+ translation.y);
        [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    }
}

javascript create empty array of a given size

You can use both javascript methods repeat() and split() together.

" ".repeat(10).split(" ")

This code will create an array that has 10 item and each item is empty string.

_x000D_
_x000D_
const items = " ".repeat(10).split(" ")

document.getElementById("context").innerHTML = items.map((item, index) => index)

console.log("items: ", items)
_x000D_
<pre id="context">

</pre>
_x000D_
_x000D_
_x000D_

Redirecting from cshtml page

You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } ).. Note:- you can add as many parameter as required.

@Html.ActionLink("MethodName", new { parameter = Model.parameter })

ld: framework not found Pods

in my case, my problem was the following: ld: framework not found UserMessagingPlatform.xcframework

for me, the solution was the following:

  1. open a finder window and go to the ios folder
  2. look for the following files:

Pods-[YOUR PROJECT NAME].release.xcconfig

Pods-[YOUR PROJECT NAME].debug.xcconfig

enter image description here

  1. open those files and remove the following text: -framework "UserMessagingPlatform.xcframework" in both files

How to type ":" ("colon") in regexp?

Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

For more info about Java regular expressions, see the docs.

Creating a simple login form

Using <table> is not a bad choice. Of course it is bit old fashioned. 

But still not obsolete. But if you prefer you can use "Boostrap". There you have options for panels and enhanced forms.

This is the sample code for your requirement. Used minimal styles to simplify.

<!DOCTYPE html>
<html>
   <head>
      <title>Simple Login Form</title>
   </head>
   <style>
      table{
      border-style: solid;
      position: absolute;
      top: 40%;
      left : 40%;
      padding:10px;
      }
   </style>
   <body>
      <form method="post" action="login.php">
         <table>
            <tr bgcolor="black">
               <th colspan="3"><font color="white">Enter login details</th>
            </tr>
            <tr height="20"></tr>
            <tr>
               <td>User Name</td>
               <td>:</td>
               <td>
                  <input type="text" name="username"/>
               </td>
            </tr>
            <tr>
               <td>Password</td>
               <td>:</td>
               <td>
                  <input type="password" name="password"/>
               </td>
            </tr>
            <tr height="10"></tr>
            <tr>
               <td></td>
               <td></td>
               <td align="center"><input type="submit" value="Submit"></td>
            </tr>
         </table>
      </form>
   </body>
</html>

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

How to make an empty div take space

Why not just add "min-width" to your css-class?

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

http://plnkr.co/edit/d6yDka?p=preview

You could also see the README and check the documentation here https://github.com/mgonto/restangular

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

pycharm running way slow

In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

How SID is different from Service name in Oracle tnsnames.ora

I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:

mySID, mySID.whereever.com =
(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
  )
  (CONNECT_DATA =
    (SERVICE_NAME = mySID.whereever.com)
    (SID = mySID)
    (SERVER = DEDICATED)
  )
)

I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.

Not showing placeholder for input type="date" field

Im working with ionicframework and solution provided by @Mumthezir is almost perfect. In case if somebody would have same problem as me(after change, input is still focused and when scrolling, value simply dissapears) So I added onchange to make input.blur()

<input placeholder="Date" class="textbox-n" type="text" onfocus=" (this.type='date')" onchange="this.blur();"  id="date"> 

How to find the socket connection state in C?

You should try to use: getpeername function.

now when the connection is down you will get in errno: ENOTCONN - The socket is not connected. which means for you DOWN.

else (if no other failures) there the return code will 0 --> which means UP.

resources: man page: http://man7.org/linux/man-pages/man2/getpeername.2.html

Using jquery to get all checked checkboxes with a certain class name

$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});

Best way to access a control on another form in Windows Forms?

public void Enable_Usercontrol1()
{
    UserControl1 usercontrol1 = new UserControl1();
    usercontrol1.Enabled = true;
} 
/*
    Put this Anywhere in your Form and Call it by Enable_Usercontrol1();
    Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal
*/

How to get substring from string in c#?

Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs

string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);

How to add a border just on the top side of a UIView

//MARK:- Add LeftBorder For View

(void)prefix_addLeftBorder:(UIView *) viewName
{
    CALayer *leftBorder = [CALayer layer];
    leftBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    leftBorder.frame = CGRectMake(0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:leftBorder];
}

//MARK:- Add RightBorder For View

(void)prefix_addRightBorder:(UIView *) viewName
{
    CALayer *rightBorder = [CALayer layer];
    rightBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    rightBorder.frame = CGRectMake(viewName.frame.size.width - 1.0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:rightBorder];
}

//MARK:- Add Bottom Border For View

(void)prefix_addbottomBorder:(UIView *) viewName
{
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    bottomBorder.frame = CGRectMake(0,viewName.frame.size.height - 1.0,viewName.frame.size.width,1.0);
    [viewName.layer addSublayer:bottomBorder];
}

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

Convert a timedelta to days, hours and minutes

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

Free FTP Library

I like Alex FTPS Client which is written by a Microsoft MVP name Alex Pilotti. It's a C# library you can use in Console apps, Windows Forms, PowerShell, ASP.NET (in any .NET language). If you have a multithreaded app you will have to configure the library to run syncronously, but overall a good client that will most likely get you what you need.

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

Replace string in text file using PHP

Thanks to your comments. I've made a function that give an error message when it happens:

/**
 * Replaces a string in a file
 *
 * @param string $FilePath
 * @param string $OldText text to be replaced
 * @param string $NewText new text
 * @return array $Result status (success | error) & message (file exist, file permissions)
 */
function replace_in_file($FilePath, $OldText, $NewText)
{
    $Result = array('status' => 'error', 'message' => '');
    if(file_exists($FilePath)===TRUE)
    {
        if(is_writeable($FilePath))
        {
            try
            {
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                {
                    $Result["status"] = 'success';
                }
                else
                {
                   $Result["message"] = 'Error while writing file';
                }
            }
            catch(Exception $e)
            {
                $Result["message"] = 'Error : '.$e;
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        }
    }
    else
    {
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    }
    return $Result;
}

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

How to embed small icon in UILabel

You can do this with iOS 7's text attachments, which are part of TextKit. Some sample code:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];

myLabel.attributedText = myString;

What is the list of valid @SuppressWarnings warning names in Java?

The list is compiler specific. But here are the values supported in Eclipse:

  • allDeprecation deprecation even inside deprecated code
  • allJavadoc invalid or missing javadoc
  • assertIdentifier occurrence of assert used as identifier
  • boxing autoboxing conversion
  • charConcat when a char array is used in a string concatenation without being converted explicitly to a string
  • conditionAssign possible accidental boolean assignment
  • constructorName method with constructor name
  • dep-ann missing @Deprecated annotation
  • deprecation usage of deprecated type or member outside deprecated code
  • discouraged use of types matching a discouraged access rule
  • emptyBlock undocumented empty block
  • enumSwitch, incomplete-switch incomplete enum switch
  • fallthrough possible fall-through case
  • fieldHiding field hiding another variable
  • finalBound type parameter with final bound
  • finally finally block not completing normally
  • forbidden use of types matching a forbidden access rule
  • hiding macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
  • indirectStatic indirect reference to static member
  • intfAnnotation annotation type used as super interface
  • intfNonInherited interface non-inherited method compatibility
  • javadoc invalid javadoc
  • localHiding local variable hiding another variable
  • maskedCatchBlocks hidden catch block
  • nls non-nls string literals (lacking of tags //$NON-NLS-)
  • noEffectAssign assignment with no effect
  • null potential missing or redundant null check
  • nullDereference missing null check
  • over-ann missing @Override annotation
  • paramAssign assignment to a parameter
  • pkgDefaultMethod attempt to override package-default method
  • raw usage a of raw type (instead of a parametrized type)
  • semicolon unnecessary semicolon or empty statement
  • serial missing serialVersionUID
  • specialParamHiding constructor or setter parameter hiding another field
  • static-access macro for indirectStatic and staticReceiver
  • staticReceiver if a non static receiver is used to get a static field or call a static method
  • super overriding a method without making a super invocation
  • suppress enable @SuppressWarnings
  • syntheticAccess, synthetic-access when performing synthetic access for innerclass
  • tasks enable support for tasks tags in source code
  • typeHiding type parameter hiding another type
  • unchecked unchecked type operation
  • unnecessaryElse unnecessary else clause
  • unqualified-field-access, unqualifiedField unqualified reference to field
  • unused macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
  • unusedArgument unused method argument
  • unusedImport unused import reference
  • unusedLabel unused label
  • unusedLocal unused local variable
  • unusedPrivate unused private member declaration
  • unusedThrown unused declared thrown exception
  • uselessTypeCheck unnecessary cast/instanceof operation
  • varargsCast varargs argument need explicit cast
  • warningToken unhandled warning token in @SuppressWarnings

Sun JDK (1.6) has a shorter list of supported warnings:

  • deprecation Check for use of depreciated items.
  • unchecked Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
  • serial Warn about missing serialVersionUID definitions on serializable classes.
  • finally Warn about finally clauses that cannot complete normally.
  • fallthrough Check switch blocks for fall-through cases and provide a warning message for any that are found.
  • path Check for a nonexistent path in environment paths (such as classpath).

The latest available javac (1.6.0_13) for mac have the following supported warnings

  • all
  • cast
  • deprecation
  • divzero
  • empty
  • unchecked
  • fallthrough
  • path
  • serial
  • finally
  • overrides

Render HTML in React Native

React Native has updated the WebView component to allow for direct html rendering. Here's an example that works for me

var htmlCode = "<b>I am rendered in a <i>WebView</i></b>";

<WebView
  ref={'webview'}
  automaticallyAdjustContentInsets={false}
  style={styles.webView}
  html={htmlCode} />

Why do I have to "git push --set-upstream origin <branch>"?

If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

Get git branch name in Jenkins Pipeline/Jenkinsfile

Just getting the name from scm.branches is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}. You need to expand that string into a real name:

scm.branches.first().getExpandedName(env.getEnvironment())

Note that getEnvironment() must be an explicit getter otherwise env will look up for an environment variable called environment.

Don't forget that you need to approve those methods to make them accessible from the sandbox.

Struct with template variables in C++

From the other answers, the problem is that you're templating a typedef. The only "way" to do this is to use a templated class; ie, basic template metaprogramming.

template<class T> class vector_Typedefs {
    /*typedef*/ struct array { //The typedef isn't necessary
        size_t x; 
        T *ary; 
    }; 

    //Any other templated typedefs you need. Think of the templated class like something
    // between a function and namespace.
}

//An advantage is:
template<> class vector_Typedefs<bool>
{
    struct array {
        //Special behavior for the binary array
    }
}

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

MySQL select 10 random rows from 600K rows fast

From book :

Choose a Random Row Using an Offset

Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set

$rand = "SELECT ROUND(RAND() * (SELECT COUNT(*) FROM Bugs))";
$offset = $pdo->query($rand)->fetch(PDO::FETCH_ASSOC);
$sql = "SELECT * FROM Bugs LIMIT 1 OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->execute( $offset );
$rand_bug = $stmt->fetch();

Use this solution when you can’t assume contiguous key values and you need to make sure each row has an even chance of being selected.

How can I tell gcc not to inline a function?

A portable way to do this is to call the function through a pointer:

void (*foo_ptr)() = foo;
foo_ptr();

Though this produces different instructions to branch, which may not be your goal. Which brings up a good point: what is your goal here?

SQL Query - Using Order By in UNION

I think this does a good job of explaining.

The following is a UNION query that uses an ORDER BY clause:

select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;

Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.

In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".

The supplier_name / company_name fields are in position #2 in the result set.

Taken from here: http://www.techonthenet.com/sql/union.php

Suppress warning messages using mysql from within Terminal, but password written in bash script

Define the helper:

remove-warning () {
    grep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
}

Use it:

mysql -u $user -p$password -e "statement" 2>&1 | remove-warning

Tachaan! Your code is clean and nice to read

(tested with bash)

How to get all groups that a user is a member of?

Single line, no modules necessary, uses current logged user:

(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf

Kudos to this vbs/powershell article: http://technet.microsoft.com/en-us/library/ff730963.aspx

Get MIME type from filename extension

You can use MimeMappings class. I think this is the easiest way. I give import of MimeMappings too. because I felt lots of trouble to find import of those classes.

import org.springframework.boot.web.server.MimeMappings;    
MimeMappings mm=new MimeMappings();
String mimetype = mm.get(fileExtension);
System.out.println(mimetype);

Read .mat files in Python

An import is required, import scipy.io...

import scipy.io
mat = scipy.io.loadmat('file.mat')

Interview Question: Merge two sorted singly linked lists without creating new nodes

This could be done without creating the extra node, with just an another Node reference passing to the parameters (Node temp).

private static Node mergeTwoLists(Node nodeList1, Node nodeList2, Node temp) {
    if(nodeList1 == null) return nodeList2;
    if(nodeList2 == null) return nodeList1;

    if(nodeList1.data <= nodeList2.data){
        temp = nodeList1;
        temp.next = mergeTwoLists(nodeList1.next, nodeList2, temp);
    }
    else{
        temp = nodeList2;
        temp.next = mergeTwoLists(nodeList1, nodeList2.next, temp);
    }
    return temp;
}

Faking an RS232 Serial Port

If you are developing for Windows, the com0com project might be, what you are looking for.

It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.

EDIT:

As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).

There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.

Concatenating strings doesn't work as expected

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

How to create my json string by using C#?

To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.

The below code demonstrates the use of JSON in an ASP.NET environment:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace JSONFromCS
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e1)
        {
            List<Employee> eList = new List<Employee>();
            Employee e = new Employee();
            e.Name = "Minal";
            e.Age = 24;

            eList.Add(e);

            e = new Employee();
            e.Name = "Santosh";
            e.Age = 24;

            eList.Add(e);

            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            string script = "var employeeList = {\"Employee\": " + ans+"};";
            script += "for(i = 0;i<employeeList.Employee.length;i++)";
            script += "{";
            script += "alert ('Name : ='+employeeList.Employee[i].Name+' 
            Age : = '+employeeList.Employee[i].Age);";
            script += "}";

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
        }
    }
    public class Employee
    {
        public string Name;
        public int Age;
    }
}  

After running this program, you will get two alerts

In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:

{ "Maths" : [ {"Name"     : "Minal",        // First element
                             "Marks"     : 84,
                             "age"       : 23 },
                             {
                             "Name"      : "Santosh",    // Second element
                             "Marks"     : 91,
                             "age"       : 24 }
                           ],                       
              "Science" :  [ 
                             {
                             "Name"      : "Sahoo",     // First Element
                             "Marks"     : 74,
                             "age"       : 27 }, 
                             {                           
                             "Name"      : "Santosh",    // Second Element
                             "Marks"     : 78,
                             "age"       : 41 }
                           ] 
            } 

Syntax:

  • {} - acts as 'containers'

  • [] - holds arrays

  • : - Names and values are separated by a colon

  • , - Array elements are separated by commas

This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.

You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.

In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.

The following code demonstrates how to use that class to convert into JSON in C#3.5.

JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);   

So, try to create a List of arrays with Questions and then serialize this list into JSON

How to insert element into arrays at specific position?

I needed something that could do an insert before, replace, after the key; and add at the start or end of the array if target key is not found. Default is to insert after the key.

New Function

/**
 * Insert element into an array at a specific key.
 *
 * @param array $input_array
 *   The original array.
 * @param array $insert
 *   The element that is getting inserted; array(key => value).
 * @param string $target_key
 *   The key name.
 * @param int $location
 *   1 is after, 0 is replace, -1 is before.
 *
 * @return array
 *   The new array with the element merged in.
 */
function insert_into_array_at_key(array $input_array, array $insert, $target_key, $location = 1) {
  $output = array();
  $new_value = reset($insert);
  $new_key = key($insert);
  foreach ($input_array as $key => $value) {
    if ($key === $target_key) {
      // Insert before.
      if ($location == -1) {
        $output[$new_key] = $new_value;
        $output[$key] = $value;
      }
      // Replace.
      if ($location == 0) {
        $output[$new_key] = $new_value;
      }
      // After.
      if ($location == 1) {
        $output[$key] = $value;
        $output[$new_key] = $new_value;
      }
    }
    else {
      // Pick next key if there is an number collision.
      if (is_numeric($key)) {
        while (isset($output[$key])) {
          $key++;
        }
      }
      $output[$key] = $value;
    }
  }
  // Add to array if not found.
  if (!isset($output[$new_key])) {
    // Before everything.
    if ($location == -1) {
      $output = $insert + $output;
    }
    // After everything.
    if ($location == 1) {
      $output[$new_key] = $new_value;
    }

  }
  return $output;
}

Input code

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);
$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);

$array_1 = insert_into_array_at_key($array_1, array('sample_key' => 'sample_value'), 2, 1);
print_r($array_1);
$array_2 = insert_into_array_at_key($array_2, array('sample_key' => 'sample_value'), 'two', 1);
print_r($array_2);

Output

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [sample_key] => sample_value
    [3] => three
)
Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [sample_key] => sample_value
    [three] => 3
)

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

If you wanted to pre-process your DOCX files, rather than waiting until runtime you could convert them into HTML first by using a file conversion API such as Zamzar. You could use the API to programatically convert from DOCX to HMTL, save the output to your server and then serve that HTML up to your end users.

Conversion is pretty easy:

curl https://api.zamzar.com/v1/jobs \
-u API_KEY: \
-X POST \
-F "[email protected]" \
-F "target_format=html5"

This would remove any runtime dependencies on Google & Microsoft's services (for example if they were down, or you were rate limited by them).

It also has the benefit that you could extend to other filetypes if you wanted (PPTX, XLS, DOC etc)

The view or its master was not found or no view engine supports the searched locations

Be careful if your model type is String because the second parameter of View(string, string) is masterName, not model. You may need to call the overload with object(model) as the second paramater:

Not correct :

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",msg);
}

Correct :

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",(object)msg);
}

OR (provided by bradlis7):

protected ActionResult ShowMessageResult(string msg)
{
    return View("Message",model:msg);
}

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

How to get relative path from absolute path

Use:

RelPath = AbsPath.Replace(ApplicationPath, ".")

How to get a list of installed android applications and pick one to run

public static List<ApplicationInfo> getApplications(Context context) {
    return context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try the following commands in terminal, this will work better:

apt-get install curl

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

Can MySQL convert a stored UTC time to local timezone?

select convert_tz(now(),@@session.time_zone,'+03:00')

For get the time only use:

time(convert_tz(now(),@@session.time_zone,'+03:00'))

Append integer to beginning of list in Python

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

Reset AutoIncrement in SQL Server after Delete

You do not want to do this in general. Reseed can create data integrity problems. It is really only for use on development systems where you are wiping out all test data and starting over. It should not be used on a production system in case all related records have not been deleted (not every table that should be in a foreign key relationship is!). You can create a mess doing this and especially if you mean to do it on a regular basis after every delete. It is a bad idea to worry about gaps in you identity field values.

What is the default scope of a method in Java?

The default scope is "default". It's weird--see these references for more info.

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

Upgrading PHP on CentOS 6.5 (Final)

Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6

To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Now install yum-utils, a group of useful tools that enhance yum’s default package management features

yum install yum-utils

In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.

yum-config-manager --enable remi-php70

If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.

yum-config-manager --enable remi-php71 
yum-config-manager --enable remi-php72

Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.

yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo

Double check the installed version of PHP on your system as follows.

php -V 

Set select option 'selected', by value

There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.

Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:

window.document.getElementById('my_stuff').selectedIndex = 4;

But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:

$("#my_stuff").prop('selectedIndex', 4);

Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

Force Intellij IDEA to reread all maven dependencies

run this command mvn -U clean install

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

Best way to alphanumeric check in JavaScript

I would create a String prototype method:

String.prototype.isAlphaNumeric = function() {
  var regExp = /^[A-Za-z0-9]+$/;
  return (this.match(regExp));
};

Then, the usage would be:

var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()

To get total number of columns in a table in sql

It can be done using:-

SELECT COUNT(COLUMN_NAME) 'NO OF COLUMN' FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address'

How to list all functions in a Python module?

If you want to get the list of all the functions defined in the current file, you can do it that way:

# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")

# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)

# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)

As an application example, I use that for calling all the functions defined in my unit testing scripts.

This is a combination of codes adapted from the answers of Thomas Wouters and adrian here, and from Sebastian Rittau on a different question.

gcc makefile error: "No rule to make target ..."

In my case the path is not set in VPATH, after added the error gone.

How to get last 7 days data from current datetime to last 7 days in sql server

Try something like:

 SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
 FROM News 
 WHERE CreatedDate >= DATEADD(day,-7, GETDATE())

How to use OrderBy with findAll in Spring Data

Simple way:

repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));

Source: https://www.baeldung.com/spring-data-sorting

Converting String array to java.util.List

On Java 14 you can do this

List<String> strings = Arrays.asList("one", "two", "three");

Add string in a certain position in Python

Simple function to accomplish this:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 

So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         HttpResponseMessage response = await client.GetAsync(subUrl);
         response.EnsureSuccessStatusCode();
         var responseAsString = await response.Content.ReadAsStringAsync();
         var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
         return responseAsConcreteType;
      }
}

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

Warning: Cannot modify header information - headers already sent by ERROR

Lines 45-47:

?>

<?php

That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.

Notice that the error message you got actually gives you a lot of information to help you find this yourself:

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\speedycms\deleteclient.php:47) in C:\xampp\htdocs\speedycms\deleteclient.php on line 106

The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

exception in initializer error in java when using Netbeans

You get an ExceptionInInitializerError if something goes wrong in the static initializer block.

class C
{
  static
  {
     // if something does wrong -> ExceptionInInitializerError
  }
}

Because static variables are initialized in static blocks there are a source of these errors too. An example:

class C
{
  static int v = D.foo();
}

=>

class C
{
  static int v;

  static
  {
    v = D.foo();
  }
}

So if foo() goes wild, you get a ExceptionInInitializerError.

Making the Android emulator run faster

Just wanted to say that after I installed the Intel HAXM accelerator and use the Intel Atom image the emulator seems to run 50 times faster. The difference is amazing, check it out!

http://www.developer.com/ws/android/development-tools/haxm-speeds-up-the-android-emulator.html

Removing multiple classes (jQuery)

There are many ways can do that!

jQuery

  1. remove all class
    $("element").removeClass();
    OR
    $("#item").removeAttr('class');
    OR
    $("#item").attr('class', '');
    OR
    $('#item')[0].className = '';

  2. remove multi class
    $("element").removeClass("class1 ... classn");
    OR
    $("element").removeClass("class1").removeClass("...").removeClass("classn");

Vanilla Javascript

  1. remove all class

_x000D_
_x000D_
// remove all items all class  _x000D_
const items = document.querySelectorAll('item');_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
    items[i].className = '';_x000D_
}
_x000D_
_x000D_
_x000D_

  1. remove multi class

_x000D_
_x000D_
// only remove all class of first item_x000D_
const item1 = document.querySelector('item');_x000D_
item1.className = '';
_x000D_
_x000D_
_x000D_

SQL WHERE.. IN clause multiple columns

Why use WHERE EXISTS or DERIVED TABLES when you can just do a normal inner join:

SELECT t.*
FROM table1 t
INNER JOIN CRM_VCM_CURRENT_LEAD_STATUS s
    ON t.CM_PLAN_ID = s.CM_PLAN_ID
    AND t.Individual_ID = s.Individual_ID
WHERE s.Lead_Key = :_Lead_Key

If the pair of (CM_PLAN_ID, Individual_ID) isn't unique in the status table, you might need a SELECT DISTINCT t.* instead.

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

How can I correctly format currency using jquery?

I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

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

Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" /> and it will format it perfectly in any browser.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

How to represent empty char in Java Character class

If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

How to set a selected option of a dropdown list control using angular JS

Simple way

If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:

$scope.Users = ["Suresh","Mahesh","Ramesh"]; 
$scope.selectedUser = $scope.Users[0];

Your HTML

<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>

complex example
Inside Controller:

$scope.JSON = {
       "ResponseObject":
           [{
               "Name": "Suresh",
               "userID": 1
           },
           {
               "Name": "Mahesh",
               "userID": 2
           }]
   };
   $scope.selectedUser = $scope.JSON.ResponseObject[0];

Your HTML

<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>    

How to split long commands over multiple lines in PowerShell

Another way to break a string across multiple lines is to put an empty expression in the middle of the string, and break it across lines:

sample string:

"stackoverflow stackoverflow stackoverflow stackoverflow stackoverflow"

broken across lines:

"stackoverflow stackoverflow $(
)stackoverflow stack$(
)overflow stackoverflow"

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

Regular expression to match a dot

A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.

How to increase heap size of an android application?

Increasing Java Heap unfairly eats deficit mobile resurces. Sometimes it is sufficient to just wait for garbage collector and then resume your operations after heap space is reduced. Use this static method then.

Creating instance list of different objects

You could create a list of Object like List<Object> list = new ArrayList<Object>(). As all classes implementation extends implicit or explicit from java.lang.Object class, this list can hold any object, including instances of Employee, Integer, String etc.

When you retrieve an element from this list, you will be retrieving an Object and no longer an Employee, meaning you need to perform a explicit cast in this case as follows:

List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());

Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    }
    return self;
}

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];

}

- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

Code shamelessly borrowed from: saving class in nsuserdefaults

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

Alternative to the HTML Bold tag

A very old thread, I know. - but for completeness:

I use <span class="bold">my text</span>    

as I upload the four font styles: normal; bold; italic and bold italic into my web-site via css.

I feel the resulting output is better than simply modifying a font and is closer to the designers intention of how the boldened font should look.

The same applies for italic and bolditalic of course, which gives me additional flexibility.

Python: Fetch first 10 results from a list

check this

 list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Read each line of txt file to new array element

    $file = file("links.txt");
print_r($file);

This will be accept the txt file as array. So write anything to the links.txt file (use one line for one element) after, run this page :) your array will be $file

What is the correct way to represent null XML elements?

In many cases the purpose of a Null value is to serve for a data value that was not present in a previous version of your application.

So say you have an xml file from your application "ReportMaster" version 1.

Now in ReportMaster version 2 a some more attributes have been added that may or not be defined.

If you use the 'no tag means null' representation you get automatic backward compatibility for reading your ReportMaster 1 xml file.

Python: finding lowest integer

l is a list of strings. When you put numbers between single quotes like that, you are creating strings, which are just a sequence of characters. To make your code work properly, you would have to do this:

l = [-1.2, 0.0, 1]  # no quotation marks

x = 100.0
for i in l:
    if i < x:
        x = i
print x

If you must use a list of strings, you can try to let Python try to make a number out of each string. This is similar to Justin's answer, except it understands floating-point (decimal) numbers correctly.

l = ['-1.2', '0.0', '1']

x = 100.0
for i in l:
    inum = float(i)
    if inum < x:
        x = inum
print x

I hope that this is code that you are writing to learn either Python or programming in general. If this is the case, great. However, if this is production code, consider using Python's built-in functions.

l = ['-1.2', '0.0', '1']
lnums = map(float, l)  # turn strings to numbers
x = min(lnums)  # find minimum value
print x

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

How to add a downloaded .box file to Vagrant?

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

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

Then run vagrant box add command with parameter:

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

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Most likely you should increase Timeout parameter in apache conf (default value 120 sec)

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

Converting NSData to NSString in Objective c

NSString *string = [NSString stringWithUTF8String:[Data bytes]];

Git - Ignore files during merge

.gitattributes - is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.

You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml for our branch. We need to set the merge=foo to config.xml in .gitattributes file.

merge=foo tell git to use our(current branch) file, if a merge conflict occurs.

  1. Add a .gitattributes file at the root level of the repository

  2. You can set up an attribute for confix.xml in the .gitattributes file

     <pattern> merge=foo
    

    Let's take an example for config.xml

     config.xml merge=foo
    
  3. And then define a dummy foo merge strategy with:

     $ git config --global merge.foo.driver true
    

If you merge the stag form dev branch, instead of having the merge conflicts with the config.xml file, the stag branch's config.xml preserves at whatever version you originally had.

for more reference: merge_strategies

How to open .dll files to see what is written inside?

*.dll files are archive files open with winzip/7zip etc. That isnt to say that all .dll files are archives you can save anything with the .dll extension however most windows .dll files are generated to be archives examples of this are windows>twain_32.dll which is an archive file however twain.dll is not if you look at twain.dll you will see an MZŽ as the first three notepad characters which denotes a Compiled C file/program or part of a program. Whereas MZ seems to be an archive.

Also most .exe files are archives mostly containing an icon image etc for the file and the windows installer packages as well they contain all the information the program needs to run images,movies etc and also directories including installation information and plain text file.

I have a game here game.exe and it contains java class files an image a pointer directing the .exe to run a .bat file. Obviously your .bat file will run a javac call from the archive and run the game there is also a few .dll archives containing java class files also.

[autorun]
ICON=AUTORUN\MINCRAFTLOGO.ICO

standard icon redirect here .ico is an image file within a .dll file within a .exe file. So the image seen on the .exe file is the minecraft logo. This is in a file called autorun.inf. Second example

[discstarter]
    startpage=Autostart\Disk1.html
    uselanguagestartpage=1
    windowcaption=Solid Edge
    licensee=Siemens PLM Software
    productguid=05B227DF-DB00-4934-B3C8-40B7D8FAA54A
    singleinstance=1
    hidesplashscreen=1
    noscrollbars=0
    showstatusbar=1
    splashscreentime=0
    windowwidth=750
    windowheight=775
    buttondir=Autostart
    toolbarcolor=16777215
    toolbar=goback,goforward,gohome,print,exit
    [autorun]
    open=autostart.exe
    icon=Autostart\ENGINE.ICO

This is the solid edge autorun.inf file contained in solidedge.exe Autostart\ is the Autostart.dll directory. open=autostart.exe specifies the autostart.exe file to run from within the original solidedge.exe archive. Here is a sample program using the .dll (dynamic link library) files http://www.flipcode.com/archives/Creating_And_Using_DLLs.shtml.

It also shows how they are created. As you can see the contents of the dll file is called by an exe file as I previously explained also there is a tutorial here http://msdn.microsoft.com/en-us/library/ms235636.aspx and as i said before 7zip or winzip will open a dynamic link library as an archive as long as you have the .dll file. If the contents of the dynamic link library have been compiled obviously you need a program which can read the file.

However since .dll files are by definition just archive library files the dll itself should be readable and not a compiled C,C# file etc etc Basically .dll files are archives well should be when a .dll file is created in visual studio the dll is created and any information you store in the dll file is encrypted. Mostly this encryption is handled by visual studio itself and generally isn't edited by hand. When you read a .dll file contents as a .exe the contents are automatically decrypted. Now when we talk about compiling a program we are changing the contents into bytecode the machine easily interprets.

This filesize would be smaller than the original file of the same contents. However the filesize is larger suggesting that the file has actually been encrypted. Probably to stop people reading their code. As a result the reading of .dll contents is termed decryption and not decompilation. Decompilation would convert the already compiled txt files to unreadable byte code. The use of standard .dll files is by definition not opensource because it involves the deliberate obfuscation of byte code.

How can I delete an item from an array in VB.NET?

One line using LINQ:

Dim arr() As String = {"uno", "dos", "tres", "cuatro", "cinco"}
Dim indx As Integer = 2
arr = arr.Where(Function(item, index) index <> indx).ToArray 'arr = {"uno", "dos", "cuatro", "cinco"}

Remove first element:

arr = arr.Skip(1).ToArray

Remove last element:

arr = arr.Take(arr.length - 1).ToArray

Get the contents of a table row with a button click

You need to change your code to find the row relative to the button which was clicked. Try this:

$(".use-address").click(function() {
    var id = $(this).closest("tr").find(".nr").text();
    $("#resultas").append(id);
});

Example fiddle

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

PHP class: Global variable as property in class

If you want to access a property from inside a class you should:

private $classNumber = 8;

Copy filtered data to another sheet using VBA

I suggest you do it a different way.

In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.

I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification

Sub TestThat()

'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long

'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")

Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
    'I went from the cell row3/column6 (or F3) and go down until the last non empty cell

    i = 2

    For Each rCell In SportsRange 'loop through each cell in the range

        If rCell = "hockey" Then 'check if the cell is equal to "hockey"

            i = i + 1                                'Row number (+1 everytime I found another "hockey")
            HokySh.Cells(i, 2) = i - 2               'S No.
            HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
            HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
            HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age

        End If

    Next rCell

End Sub

How to retrieve a single file from a specific revision in Git?

If you wish to replace/overwrite the content of a file in your current branch with the content of the file from a previous commit or a different branch, you can do so with these commands:

git checkout 08618129e66127921fbfcbc205a06153c92622fe path/to/file.txt

or

git checkout mybranchname path/to/file.txt

You will then have to commit those changes in order for them to be effective in the current branch.

Swift GET request with parameters

Swift 3:

extension URL {
    func getQueryItemValueForKey(key: String) -> String? {
        guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
              return nil
        }

        guard let queryItems = components.queryItems else { return nil }
     return queryItems.filter {
                 $0.name.lowercased() == key.lowercased()
                 }.first?.value
    }
}

I used it to get the image name for UIImagePickerController in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]):

var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
    originalFilename = imageIdentifier + ".png"
    print("file name : \(originalFilename)")
}

Read line with Scanner

This code reads the file line by line.

public static void readFileByLine(String fileName) {
  try {
   File file = new File(fileName);
   Scanner scanner = new Scanner(file);
   while (scanner.hasNext()) {
    System.out.println(scanner.next());
   }
   scanner.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } 
 }

You can also set a delimiter as a line separator and then perform the same.

 scanner.useDelimiter(System.getProperty("line.separator"));

You have to check whether there is a next token available and then read the next token. You will also need to doublecheck the input given to the Scanner. i.e. dico.txt. By default, Scanner breaks its input based on whitespace. Please ensure that the input has the delimiters in right place

UPDATED ANSWER for your comment:

I just tried to create an input file with the content as below

a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait

tried to read it with the below code.it just worked fine.

 File file = new File("/home/keerthivasan/Desktop/input.txt");
     Scanner scr = null;
         try {
            scr = new Scanner(file);
            while(scr.hasNext()){
                System.out.println("line : "+scr.next());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScannerTest.class.getName()).log(Level.SEVERE, null, ex);
        }

Output:

line : a
line : à
line : abaissa
line : abaissable
line : abaissables
line : abaissai
line : abaissaient
line : abaissais
line : abaissait

so, I am sure that this should work. Since you work in Windows ennvironment, The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. if you set your Scanner instance to use delimiter as follows, it will pick up probably

 scr = new Scanner(file);
 scr.useDelimiter("\r\n");

and then do your looping to read lines. Hope this helps!

How do I flush the cin buffer?

I have found two solutions to this.

The first, and simplest, is to use std::getline() for example:

std::getline(std::cin, yourString);

... that will discard the input stream when it gets to a new-line. Read more about this function here.

Another option that directly discards the stream is this...

#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Good luck!

Java Look and Feel (L&F)

You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:

<dependency>
        <groupId>com.jtattoo</groupId>
        <artifactId>JTattoo</artifactId>
        <version>1.6.11</version>
</dependency>

Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aero.AeroLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.fast.FastLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.mint.MintLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.smart.SmartLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel

Regards

Can't use System.Windows.Forms

Adding System.Windows.Forms reference requires .NET Framework project type:

I was using .NET Core project type. This project type doesn't allow us to add assemblies into its project references. I had to move to .NET Framework project type before adding System.Windows.Forms assembly to my references as described in Kendall Frey answer.

Note: There is reference System_Windows_Forms available under COM tab (for both .NET Core and .NET Framework). It is not the right one. It has to be System.Windows.Forms under Assemblies tab.

Cross-browser custom styling for file upload button

I'm posting this because (to my surprise) there was no other place I could find that recommended this.

There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label> tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].

The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:

_x000D_
_x000D_
label.myLabel input[type="file"] {_x000D_
    position:absolute;_x000D_
    top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
    border: 2px solid #AAA;_x000D_
    border-radius: 4px;_x000D_
    padding: 2px 5px;_x000D_
    margin: 2px;_x000D_
    background: #DDD;_x000D_
    display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
    background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
    background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
    color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
    color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
    <input type="file" required/>_x000D_
    <span>My Label</span>_x000D_
</label>
_x000D_
_x000D_
_x000D_

I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden or display:none file-input). I've tested in emulated IE7 and up, and it worked perfectly.


  1. You can't use <button>s inside <label> tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.
  2. If the for attribute is defined, its value is used to trigger the input with the same id as the for attribute on the <label>.

Eclipse won't compile/run java file

This worked for me:

  1. Create a new project
  2. Create a class in it
  3. Add erroneous code, let error come
  4. Now go to your project
  5. Go to Problems window
  6. Double click on a error

It starts showing compilation errors in the code.

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

Setting up a cron job in Windows

If you don't want to use Scheduled Tasks you can use the Windows Subsystem for Linux which will allow you to use cron jobs like on Linux.

To make sure cron is actually running you can type service cron status from within the Linux terminal. If it isn't currently running then type service cron start and you should be good to go.

Get folder name of the file in Python

os.path.dirname is what you are looking for -

os.path.dirname(r"C:\folder1\folder2\filename.xml")

Make sure you prepend r to the string so that its considered as a raw string.

Demo -

In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\\folder1\\folder2'

If you just want folder2 , you can use os.path.basename with the above, Example -

os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))

Demo -

In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

As c-smile mentioned: Just need to remove the apostrophes in the url():

<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>

Demo here

Redirect From Action Filter Attribute

Try the following snippet, it should be pretty clear:

public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(FilterExecutingContext filterContext)
  {
    HttpSessionStateBase session = filterContext.HttpContext.Session;
    Controller controller = filterContext.Controller as Controller;

    if (controller != null)
    {
      if (session["Login"] == null)
      {
        filterContext.Cancel = true;
        controller.HttpContext.Response.Redirect("./Login");
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

Get the value of input text when enter key pressed

Listen the change event.

document.querySelector("input")
  .addEventListener('change', (e) => {
    console.log(e.currentTarget.value);
 });

Connect to mysql on Amazon EC2 from a remote server

The error I was experiencing was that my database network settings allowed outbound traffic to the web – but inbound only from select IP addresses.

I added an inbound rule to allow traffic from my ec2's private IP and it worked.

How to remove listview all items

You can do this:

listView.setAdapter(null);

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I solved this problem very easily after finding out this happens when you aren't outputting a proper JSON object, I simply used the echo json_encode($arrayName); instead of print_r($arrayName); With my php api.

Every programming language or at least most programming languages should have their own version of the json_encode() and json_decode() functions.

Temporary tables in stored procedures

According SQL Server 2008 Books You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions.

'#table_temporal

'##table_global

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name.

Then there occurs no problem.

What size should apple-touch-icon.png be for iPad and iPhone?

The icon on Apple's site is 152x152 pixels.
http://www.apple.com/apple-touch-icon.png

Hope that answers your question.

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Switch tabs using Selenium WebDriver with Java

Please see below:

WebDriver driver = new FirefoxDriver();

driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();

//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);

// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();

// Switch driver control to focused tab window
driver.switchTo().window(oldTab);

driver.findElement(By.id("textfield")).sendKeys("bangalore");

Hope this is helpful!

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====          
Class<?>    reference           =   vector.get(0).getClass();
Object      obj                 =   reference.newInstance();
Field[]     objFields           =   obj.getClass().getFields(); 

What is the first character in the sort order used by Windows Explorer?

I had the same problem. I wanted to 'bury' a folder at the bottom of the sort instead of bringing it to the top with the '!' character. Windows recognizes most special characters as just that, 'special', and therefore they ALL are sorted at the top.

However, if you think outside of the English characters, you will find a lot of luck. I used Character Map and the arial font, scrolled down past '~' and the others to the greek alphabet. Capitol Xi, ?, worked best for me, but I didn't check to see which was the actual 'lowest' in the sort.

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

How can I access Google Sheet spreadsheets only with Javascript?

There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.

First up, you need an Google API key. Head here: https://developers.google.com/places/web-service/get-api-key NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037

Get all data for a spreadsheet - warning, this can be a lot of data.

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true

Get sheet metadata

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}

Get a range of cells

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}

Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.

var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";                                                             
axios.get(url)
  .then(function (response) {
    console.log(response);                                                                                                                                                    
  })
  .catch(function (error) {
    console.log(error);                                                                                                                                                       
  });                

How to multiply a BigDecimal by an integer in Java

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
           BigDecimal   itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

How to delete multiple files at once in Bash on Linux?

I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf. I have used something like this in the past with good results. Test on a sample directory first!

EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs would be the way to go.

How can I use ":" as an AWK field separator?

-F is an argument to awk itself:

$echo "1: " | awk -F":" '/1/ {print $1}'
1

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

How to add new elements to an array?

You need to use a Collection List. You cannot re-dimension an array.

remove duplicates from sql union

Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

Real time data graphing on a line chart with html5

I would suggest Smoothie Charts.

It's very simple to use, easily and widely configurable, and does a great job of streaming real time data.

There's a builder that lets you explore the options and generate code.

Disclaimer: I am a contributor to the library.

java.io.FileNotFoundException: the system cannot find the file specified

Your file should directly be under the project folder, and not inside any other sub-folder.

If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.

Aproject
        src
        word.txt

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Eclipse returns error message "Java was started but returned exit code = 1"

This can be resolved by adding the following line to the eclipse.ini file -XX:-UseCompressedOops

How to format a Java string with leading zero?

I've been in a similar situation and I used this; It is quite concise and you don't have to deal with length or another library.

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

Simple and neat. String format returns " Apple" so after replacing space with zeros, it gives the desired result.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The Html.TextboxFor always creates a textbox (<input type="text" ...).

While the EditorFor looks at the type and meta information, and can render another control or a template you supply.

For example for DateTime properties you can create a template that uses the jQuery DatePicker.

How can I specify a [DllImport] path at runtime?

As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll would be present inside myLibFolder directory inside temporary folder of the current user.

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 

Now you can continue using the DllImport statement using a const string as shown below:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Just at run time before you call the DLLFunction function (present in C++ library) add this line of code in C# code:

string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
Directory.SetCurrentDirectory(assemblyProbeDirectory);

This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory call sets the application's current working directory to the specified directory. If your myDLL.dll is present at path represented by assemblyProbeDirectory path then it will get loaded and the desired function will get called through p/invoke.

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Error in spring application context schema

use this:

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"

How to add fonts to create-react-app based projects?

I spent the entire morning solving a similar problem after having landed on this stack question. I used Dan's first solution in the answer above as the jump off point.

Problem

I have a dev (this is on my local machine), staging, and production environment. My staging and production environments live on the same server.

The app is deployed to staging via acmeserver/~staging/note-taking-app and the production version lives at acmeserver/note-taking-app (blame IT).

All the media files such as fonts were loading perfectly fine on dev (i.e., react-scripts start).

However, when I created and uploaded staging and production builds, while the .css and .js files were loading properly, fonts were not. The compiled .css file looked to have a correct path but the browser http request was getting some very wrong pathing (shown below).

The compiled main.fc70b10f.chunk.css file:

@font-face {
  font-family: SairaStencilOne-Regular;
  src: url(note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf) ("truetype");
}

The browser http request is shown below. Note how it is adding in /static/css/ when the font file just lives in /static/media/ as well as duplicating the destination folder. I ruled out the server config being the culprit.

The Referer is partly at fault too.

GET /~staging/note-taking-app/static/css/note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf HTTP/1.1
Host: acmeserver
Origin: http://acmeserver
Referer: http://acmeserver/~staging/note-taking-app/static/css/main.fc70b10f.chunk.css

The package.json file had the homepage property set to ./note-taking-app. This was causing the problem.

{
  "name": "note-taking-app",
  "version": "0.1.0",
  "private": true,
  "homepage": "./note-taking-app",
  "scripts": {
    "start": "env-cmd -e development react-scripts start",
    "build": "react-scripts build",
    "build:staging": "env-cmd -e staging npm run build",
    "build:production": "env-cmd -e production npm run build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
  //...
}

Solution

That was long winded — but the solution is to:

  1. change the PUBLIC_URL env variable depending on the environment
  2. remove the homepage property from the package.json file

Below is my .env-cmdrc file. I use .env-cmdrc over regular .env because it keeps everything together in one file.

{
  "development": {
    "PUBLIC_URL": "",
    "REACT_APP_API": "http://acmeserver/~staging/note-taking-app/api"
  },
  "staging": {
    "PUBLIC_URL": "/~staging/note-taking-app",
    "REACT_APP_API": "http://acmeserver/~staging/note-taking-app/api"
  },
  "production": {
    "PUBLIC_URL": "/note-taking-app",
    "REACT_APP_API": "http://acmeserver/note-taking-app/api"
  }
}

Routing via react-router-dom works fine too — simply use the PUBLIC_URL env variable as the basename property.

import React from "react";
import { BrowserRouter } from "react-router-dom";

const createRouter = RootComponent => (
  <BrowserRouter basename={process.env.PUBLIC_URL}>
    <RootComponent />
  </BrowserRouter>
);

export { createRouter };

The server config is set to route all requests to the ./index.html file.

Finally, here is what the compiled main.fc70b10f.chunk.css file looks like after the discussed changes were implemented.

@font-face {
  font-family: SairaStencilOne-Regular;
  src: url(/~staging/note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf)
    format("truetype");
}

Reading material