Programs & Examples On #Malloc

The malloc function performs dynamic memory allocation in C and is part of the standard library. Use this tag for questions about usage, behavior and implementations of malloc.

Initializing C dynamic arrays

Instead of using

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

we can use

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

Using malloc for allocation of multi-dimensional arrays with different row lengths

I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.

C - freeing structs

Simple answer : free(testPerson) is enough .

Remember you can use free() only when you have allocated memory using malloc, calloc or realloc.

In your case you have only malloced memory for testPerson so freeing that is sufficient.

If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually.

Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object.

Freeing each element you can see the demo shown below:

typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName

.
. // do whatever you want

free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);

The reason behind this is, if you free the ptrobj first, then there will be memory leaked which is the memory allocated by firstname and suName pointers.

Difference between malloc and calloc?

Difference 1:

malloc() usually allocates the memory block and it is initialized memory segment.

calloc() allocates the memory block and initialize all the memory block to 0.

Difference 2:

If you consider malloc() syntax, it will take only 1 argument. Consider the following example below:

data_type ptr = (cast_type *)malloc( sizeof(data_type)*no_of_blocks );

Ex: If you want to allocate 10 block of memory for int type,

int *ptr = (int *) malloc(sizeof(int) * 10 );

If you consider calloc() syntax, it will take 2 arguments. Consider the following example below:

data_type ptr = (cast_type *)calloc(no_of_blocks, (sizeof(data_type)));

Ex: if you want to allocate 10 blocks of memory for int type and Initialize all that to ZERO,

int *ptr = (int *) calloc(10, (sizeof(int)));

Similarity:

Both malloc() and calloc() will return void* by default if they are not type casted .!

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

What is a Memory Heap?

Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).

A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc). Memory allocated from the heap will remain allocated until one of the following occurs:

  1. The memory is free'd
  2. The program terminates

If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.

Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).

You can find more information about the heap in this article.

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

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

In my opinion, alloca(), where available, should be used only in a constrained manner. Very much like the use of "goto", quite a large number of otherwise reasonable people have strong aversion not just to the use of, but also the existence of, alloca().

For embedded use, where the stack size is known and limits can be imposed via convention and analysis on the size of the allocation, and where the compiler cannot be upgraded to support C99+, use of alloca() is fine, and I've been known to use it.

When available, VLAs may have some advantages over alloca(): The compiler can generate stack limit checks that will catch out-of-bounds access when array style access is used (I don't know if any compilers do this, but it can be done), and analysis of the code can determine whether the array access expressions are properly bounded. Note that, in some programming environments, such as automotive, medical equipment, and avionics, this analysis has to be done even for fixed size arrays, both automatic (on the stack) and static allocation (global or local).

On architectures that store both data and return addresses/frame pointers on the stack (from what I know, that's all of them), any stack allocated variable can be dangerous because the address of the variable can be taken, and unchecked input values might permit all sorts of mischief.

Portability is less of a concern in the embedded space, however it is a good argument against use of alloca() outside of carefully controlled circumstances.

Outside of the embedded space, I've used alloca() mostly inside logging and formatting functions for efficiency, and in a non-recursive lexical scanner, where temporary structures (allocated using alloca() are created during tokenization and classification, then a persistent object (allocated via malloc()) is populated before the function returns. The use of alloca() for the smaller temporary structures greatly reduces fragmentation when the persistent object is allocated.

How is malloc() implemented internally?

The sbrksystem call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc really gives memory segments back to the kernel with that method). Aside from that, there's also mmap which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap is how you do it).

So you have two methods of getting more memory from the kernel: sbrk and mmap. There are various strategies on how to organize the memory that you've got from the kernel.

One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc could use mmap to allocate directly with the kernel. If the bucket of a certain size is empty malloc could use sbrk to get more space for a new bucket.

There are various malloc designs and there is propably no one true way of implementing malloc as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk/mmap that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc again somehow. You don't just hand out memory without reusing it.

If you're interested, the OpenSER/Kamailio SIP proxy has two malloc implementations (they need their own because they make heavy use of shared memory and the system malloc doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem

Then you could also have a look at the GNU libc malloc implementation, but that one is very complicated, IIRC.

Dynamically create an array of strings with malloc


#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */

orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));

..

Do I cast the result of malloc?

  1. As other stated, it is not needed for C, but for C++.

  2. Including the cast may allow a C program or function to compile as C++.

  3. In C it is unnecessary, as void * is automatically and safely promoted to any other pointer type.

  4. But if you cast then, it can hide an error if you forgot to include stdlib.h. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code).

    Because stdlib.h contains the prototype for malloc is found. In the absence of a prototype for malloc, the standard requires that the C compiler assumes malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug.

When to use malloc for char pointers

malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.

How to dynamically allocate memory space for a string and get that string from user?

realloc is a pretty expensive action... here's my way of receiving a string, the realloc ratio is not 1:1 :

char* getAString()
{    
    //define two indexes, one for logical size, other for physical
    int logSize = 0, phySize = 1;  
    char *res, c;

    res = (char *)malloc(sizeof(char));

    //get a char from user, first time outside the loop
    c = getchar();

    //define the condition to stop receiving data
    while(c != '\n')
    {
        if(logSize == phySize)
        {
            phySize *= 2;
            res = (char *)realloc(res, sizeof(char) * phySize);
        }
        res[logSize++] = c;
        c = getchar();
    }
    //here we diminish string to actual logical size, plus one for \0
    res = (char *)realloc(res, sizeof(char *) * (logSize + 1));
    res[logSize] = '\0';
    return res;
}

In what cases do I use malloc and/or new?

Dynamic allocation is only required when the life-time of the object should be different than the scope it gets created in (This holds as well for making the scope smaller as larger) and you have a specific reason where storing it by value doesn't work.

For example:

 std::vector<int> *createVector(); // Bad
 std::vector<int> createVector();  // Good

 auto v = new std::vector<int>(); // Bad
 auto result = calculate(/*optional output = */ v);
 auto v = std::vector<int>(); // Good
 auto result = calculate(/*optional output = */ &v);

From C++11 on, we have std::unique_ptr for dealing with allocated memory, which contains the ownership of the allocated memory. std::shared_ptr was created for when you have to share ownership. (you'll need this less than you would expect in a good program)

Creating an instance becomes really easy:

auto instance = std::make_unique<Class>(/*args*/); // C++14
auto instance = std::make_unique<Class>(new Class(/*args*/)); // C++11
auto instance = std::make_unique<Class[]>(42); // C++14
auto instance = std::make_unique<Class[]>(new Class[](42)); // C++11

C++17 also adds std::optional which can prevent you from requiring memory allocations

auto optInstance = std::optional<Class>{};
if (condition)
    optInstance = Class{};

As soon as 'instance' goes out of scope, the memory gets cleaned up. Transferring ownership is also easy:

 auto vector = std::vector<std::unique_ptr<Interface>>{};
 auto instance = std::make_unique<Class>();
 vector.push_back(std::move(instance)); // std::move -> transfer (most of the time)

So when do you still need new? Almost never from C++11 on. Most of the you use std::make_unique until you get to a point where you hit an API that transfers ownership via raw pointers.

 auto instance = std::make_unique<Class>();
 legacyFunction(instance.release()); // Ownership being transferred

 auto instance = std::unique_ptr<Class>{legacyFunction()}; // Ownership being captured in unique_ptr

In C++98/03, you have to do manual memory management. If you are in this case, try upgrading to a more recent version of the standard. If you are stuck:

 auto instance = new Class(); // Allocate memory
 delete instance;             // Deallocate
 auto instances = new Class[42](); // Allocate memory
 delete[] instances;               // Deallocate

Make sure that you track the ownership correctly to not have any memory leaks! Move semantics don't work yet either.

So, when do we need malloc in C++? The only valid reason would be to allocate memory and initialize it later via placement new.

 auto instanceBlob = std::malloc(sizeof(Class)); // Allocate memory
 auto instance = new(instanceBlob)Class{}; // Initialize via constructor
 instance.~Class(); // Destroy via destructor
 std::free(instanceBlob); // Deallocate the memory

Even though, the above is valid, this can be done via a new-operator as well. std::vector is a good example for this.

Finally, we still have the elephant in the room: C. If you have to work with a C-library where memory gets allocated in the C++ code and freed in the C code (or the other way around), you are forced to use malloc/free.

If you are in this case, forget about virtual functions, member functions, classes ... Only structs with PODs in it are allowed.

Some exceptions to the rules:

  • You are writing a standard library with advanced data structures where malloc is appropriate
  • You have to allocate big amounts of memory (In memory copy of a 10GB file?)
  • You have tooling preventing you to use certain constructs
  • You need to store an incomplete type

How do malloc() and free() work?

This has nothing specifically to do with malloc and free. Your program exhibits undefined behaviour after you copy the string - it could crash at that point or at any point afterwards. This would be true even if you never used malloc and free, and allocated the char array on the stack or statically.

Why do I get a C malloc assertion failure?

99.9% likely that you have corrupted memory (over- or under-flowed a buffer, wrote to a pointer after it was freed, called free twice on the same pointer, etc.)

Run your code under Valgrind to see where your program did something incorrect.

What REALLY happens when you don't free after malloc?

What's the real result here?

Your program leaked the memory. Depending on your OS, it may have been recovered.

Most modern desktop operating systems do recover leaked memory at process termination, making it sadly common to ignore the problem, as can be seen by many other answers here.)

But you are relying on a safety feature you should not rely upon, and your program (or function) might run on a system where this behaviour does result in a "hard" memory leak, next time.

You might be running in kernel mode, or on vintage / embedded operating systems which do not employ memory protection as a tradeoff. (MMUs take up die space, memory protection costs additional CPU cycles, and it is not too much to ask from a programmer to clean up after himself).

You can use and re-use memory any way you like, but make sure you deallocated all resources before exiting.

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

How to represent a DateTime in Excel

Excel can display a Date type in a similar manner to a DateTime. Right click on the affected cell, select Format Cells, then under Category select Date and under Type select the type that looks something like this:

3/14/01 1:30 PM

That should do what you requested. I tested sorting on some sample data with this format and it seemed to work fine.

Can I run multiple programs in a Docker container?

I agree with the other answers that using two containers is preferable, but if you have your heart set on bunding multiple services in a single container you can use something like supervisord.

in Hipache for instance, the included Dockerfile runs supervisord, and the file supervisord.conf specifies for both hipache and redis-server to be run.

how do I set height of container DIV to 100% of window height?

Did you set the CSS:

html, body
{
    height: 100%;
}

You need this to be able to make the div take up all the space. :)

How to get the url parameters using AngularJS

function GetURLParameter(parameter) {
        var url;
        var search;
        var parsed;
        var count;
        var loop;
        var searchPhrase;
        url = window.location.href;
        search = url.indexOf("?");
        if (search < 0) {
            return "";
        }
        searchPhrase = parameter + "=";
        parsed = url.substr(search+1).split("&");
        count = parsed.length;
        for(loop=0;loop<count;loop++) {
            if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
                return decodeURI(parsed[loop].substr(searchPhrase.length));
            }
        }
        return "";
    }

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

How to call an async method from a getter or setter?

You can use Task like this :

public int SelectedTab
        {
            get => selected_tab;
            set
            {
                selected_tab = value;

                new Task(async () =>
                {
                    await newTab.ScaleTo(0.8);
                }).Start();
            }
        }

:first-child not working as expected

you can also use

.detail_container h1:nth-of-type(1)

By changing the number 1 by any other number you can select any other h1 item.

vertical align middle in <div>

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to #abc the following css:

display:flex;
align-items:center;

Simple Demo

Original question demo updated

Simple Example:

_x000D_
_x000D_
.vertical-align-content {_x000D_
  background-color:#f18c16;_x000D_
  height:150px;_x000D_
  display:flex;_x000D_
  align-items:center;_x000D_
  /* Uncomment next line to get horizontal align also */_x000D_
  /* justify-content:center; */_x000D_
}
_x000D_
<div class="vertical-align-content">_x000D_
  Hodor!_x000D_
</div>
_x000D_
_x000D_
_x000D_

PostgreSQL: Which version of PostgreSQL am I running?

A simple way is to check the version by typing psql --version in terminal

Live video streaming using Java?

Hi not an expert in streaming but my understanding is that it is included in th Java Media Framework JMF http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/support-rtsp.html

Spring Data JPA findOne() change to Optional how to use this?

The method has been renamed to findById(…) returning an Optional so that you have to handle absence yourself:

Optional<Foo> result = repository.findById(…);

result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before

invalid byte sequence for encoding "UTF8"

follow the below steps to solve this issue in pgadmin:

  1. SET client_encoding = 'ISO_8859_5';

  2. COPY tablename(column names) FROM 'D:/DB_BAK/csvfilename.csv' WITH DELIMITER ',' CSV ;

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

JPA Query.getResultList() - use in a generic way

The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.

python JSON object must be str, bytes or bytearray, not 'dict

import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

Echoing the last command run in Bash?

history | tail -2 | head -1 | cut -c8-999

tail -2 returns the last two command lines from history head -1 returns just first line cut -c8-999 returns just command line, removing PID and spaces.

When to use @QueryParam vs @PathParam

The reason is actually very simple. When using a query parameter you can take in characters such as "/" and your client does not need to html encode them. There are other reasons but that is a simple example. As for when to use a path variable. I would say whenever you are dealing with ids or if the path variable is a direction for a query.

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

Programmatically go back to the previous fragment in the backstack

By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.

adding new fragment:

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

As I got the 500.19, I gave IIS_IUSRS full access rights for the mentioned web.config and for the folder of the project. This solved the issue.

You can give permissions by

  1. right click on the folder / file
  2. selecting the tab "security"
  3. add the user IIS_IUSRS - don't forget the i in front of USRS and don't write an "e" as in USERS

Select a row from html table and send values onclick of a button

$("#table tr").click(function(){
   $(this).addClass('selected').siblings().removeClass('selected');    
   var value=$(this).find('td:first').html();
   alert(value);    
});

$('.ok').on('click', function(e){
    alert($("#table tr.selected td:first").html());
});

Demo:

http://jsfiddle.net/65JPw/2/

Save text file UTF-8 encoded with VBA

The traditional way to transform a string to a UTF-8 string is as follows:

StrConv("hello world",vbFromUnicode)

So put simply:

Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum

No special COM objects required

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Turn on Password Authentication

By default, you need to use keys to ssh into your google compute engine machine, but you can turn on password authentication if you do not need that level of security.

Tip: Use the Open in browser window SSH option from your cloud console to gain access to the machine. Then switch to the root user with sudo su - root to make the configuration changes below.

enter image description here

  1. Edit the /etc/ssh/sshd_config file.
  2. Change PasswordAuthentication and ChallengeResponseAuthentication to yes.
  3. Restart ssh /etc/init.d/ssh restart.

How to toggle boolean state of react component?

You could also use React's useState hook to declare local state for a function component. The initial state of the variable toggled has been passed as an argument to the method .useState.

import { render } from 'react-dom';
import React from "react";

type Props = {
  text: string,
  onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};

export function HelloWorldButton(props: Props) {
  const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
  return <button
  onClick={(event) => {
    setToggled(!toggled);
    props.onClick(event);
  }}
  >{props.text} (toggled: {toggled.toString()})</button>;
}


render(<HelloWorldButton text='Hello World' onClick={() => console.log('clicked!')} />, document.getElementById('root'));

https://stackblitz.com/edit/react-ts-qga3vc

Returning http status code from Web Api controller

I know there are several good answers here but this is what I needed so I figured I'd add this code in case anyone else needs to return whatever status code and response body they wanted in 4.7.x with webAPI.

public class DuplicateResponseResult<TResponse> : IHttpActionResult
{
    private TResponse _response;
    private HttpStatusCode _statusCode;
    private HttpRequestMessage _httpRequestMessage;
    public DuplicateResponseResult(HttpRequestMessage httpRequestMessage, TResponse response, HttpStatusCode statusCode)
    {
        _httpRequestMessage = httpRequestMessage;
        _response = response;
        _statusCode = statusCode;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(_statusCode);
        return Task.FromResult(_httpRequestMessage.CreateResponse(_statusCode, _response));
    }
}

Left padding a String with Zeros

Here's my solution:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Output: 00000101

How do I combine two lists into a dictionary in Python?

>>> dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

If they are not the same size, zip will truncate the longer one.

Could not load file or assembly for Oracle.DataAccess in .NET

I switched over to the managed ODP.NET assemblies from Oracle. I also had to purge all the files from the IIS web apps that were using the older assemblies. Now I don't get any conflicts regarding 32 vs 64 bit versions when I debug in IIS Express vs IIS. See the following article.

An Easy Drive to .NET

Why is a primary-foreign key relation required when we can join without it?

You don't need a FK, you can join arbitrary columns.

But having a foreign key ensures that the join will actually succeed in finding something.

Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.

For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.

Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)

Regular expression for 10 digit number without any special characters

An example of how to implement it:

public bool ValidateSocialSecNumber(string socialSecNumber)
{
    //Accepts only 10 digits, no more no less. (Like Mike's answer)
    Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");

    if(pattern.isMatch(socialSecNumber))
    {
        //Do something
        return true;
    }
    else
    {
        return false;
    }
}

You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

Call a Vue.js component method from outside the component

In the end I opted for using Vue's ref directive. This allows a component to be referenced from the parent for direct access.

E.g.

Have a compenent registered on my parent instance:

var vm = new Vue({
    el: '#app',
    components: { 'my-component': myComponent }
});

Render the component in template/html with a reference:

<my-component ref="foo"></my-component>

Now, elsewhere I can access the component externally

<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>

See this fiddle for an example: https://jsfiddle.net/xmqgnbu3/1/

(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)

How to replace NA values in a table for selected columns

it's quite handy with {data.table} and {stringr}

library(data.table)
library(stringr)

x[, lapply(.SD, function(xx) {str_replace_na(xx, 0)})]

FYI

Bootstrap dropdown menu not working (not dropping down when clicked)

Just Remove the type="text/javascript"

<script src="JavaScript/jquery.js" />
<script src="JavaScript/bootstrap-min.js" />

Here is the update - http://jsfiddle.net/andieje/kRX6n/

Form inside a form, is that alright?

Though you can have several <form> elements in one HTML page, you cannot nest them.

How to initialize java.util.date to empty

Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

Edit

After seeing the comment posted to the answer of LastFreeNickname

I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

if(textBox.getText() == null || textBox.getText().equals(""){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

try{
    date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Get Insert Statement for existing row in MySQL

There is a quite easy and useful solution for creating an INSERT Statement for editing without the need to export SQL with just Copy & Paste (Clipboard):

  • Select the row in a query result window of MySQL Workbench, probably even several rows. I use this even if the row does contain different data than I want to insert in my script or when the goal is to create a prepared statement with ? placeholders.
  • Paste the copied row which is in your clipboard now into the same table (query results list is an editor in workbench) into the last free row.
  • Press "Apply" and a windows opens showing you the INSERT statement - DO NOT EXECUTE
  • Copy the SQL from the window to your clipboard
  • CANCEL the execution, thus not changing the database but keeping the SQL in your clipboard.
  • Paste the SQL wherever you want and edit it as you like, like e.g. inserting ? placeholders

What is the difference between tree depth and height?

The “depth” (or equivalently the “level number”) of a node is the number of edges on the “path” from the root node

The “height” of a node is the number of edges on the longest path from the node to a leaf node.

Run MySQLDump without Locking Tables

This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option:

--lock-tables=false

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

How do I sort a table in Excel if it has cell references in it?

this is one good answer to figure out how sorting works from another user and I will add my notes to know how it is not fully correct and what is correct:

The effect on the formula after a sort is the same as copying. A sort does not move the row contents, it copies them. The formula may (or may not depending on the abs/relative references) use new data, just as a copied formula does.

My point is that if the formula can be copied from 1 row to another and the effects don't change, the sorting will not affect the formula results. If the formulas are so complex and so dependent on position that copying them changes the relative contents, then don't sort them.

And my note that I experienced in practice:

The above user is saying right but in fact It has some exception: parts of a columns formula containing sheet name (like sheet1!A1) are treated as absolute references (in spite of copying that changes the references if they are relative ) so that part of formula will be copied without changing references relative to changing the place of formula This includes current sheet cells addressed fully like : sheet1!A2 and will be treated as absolute references(for sorting only) I tested this of excel 2010 and I do not think this issue be solved in other versions. The solution is to copy and past special as value in another place and then use sorting.

How to use ArrayList's get() method

Here is the official documentation of ArrayList.get().

Anyway it is very simple, for example

ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str

Check if a variable is a string in JavaScript

Performance

Today 2020.09.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.

Results

For all browsers (and both test cases)

  • solutions typeof||instanceof (A, I) and x===x+'' (H) are fast/fastest
  • solution _.isString (lodash lib) is medium/fast
  • solutions B and K are slowest

enter image description here

Update: 2020.11.28 I update results for x=123 Chrome column - for solution I there was probably an error value before (=69M too low) - I use Chrome 86.0 to repeat tests.

Details

I perform 2 tests cases for solutions A B C D E F G H I J K L

  • when variable is string - you can run it HERE
  • when variable is NOT string - you can run it HERE

Below snippet presents differences between solutions

_x000D_
_x000D_
// https://stackoverflow.com/a/9436948/860099
function A(x) {
  return (typeof x == 'string') || (x instanceof String)
}

// https://stackoverflow.com/a/17772086/860099
function B(x) {
  return Object.prototype.toString.call(x) === "[object String]"
}

// https://stackoverflow.com/a/20958909/860099
function C(x) {
  return _.isString(x);
}

// https://stackoverflow.com/a/20958909/860099
function D(x) {
  return $.type(x) === "string";
}

// https://stackoverflow.com/a/16215800/860099
function E(x) {
  return x?.constructor === String;
}

// https://stackoverflow.com/a/42493631/860099
function F(x){
  return x?.charAt != null
}


// https://stackoverflow.com/a/57443488/860099
function G(x){
  return String(x) === x
}

// https://stackoverflow.com/a/19057360/860099
function H(x){
  return x === x + ''
}

// https://stackoverflow.com/a/4059166/860099
function I(x) {
  return typeof x == 'string'
}

// https://stackoverflow.com/a/28722301/860099
function J(x){
  return x === x?.toString()
}

// https://stackoverflow.com/a/58892465/860099
function K(x){
  return x && typeof x.valueOf() === "string"
}

// https://stackoverflow.com/a/9436948/860099
function L(x) {
  return x instanceof String
}

// ------------------
//     PRESENTATION
// ------------------

console.log('Solutions results for different inputs \n\n');
console.log("'abc' Str  ''  ' ' '1' '0'  1   0   {} [] true false null undef");

let tests = [ 'abc', new String("abc"),'',' ','1','0',1,0,{},[],true,false,null,undefined];

[A,B,C,D,E,F,G,H,I,J,K,L].map(f=> {  
console.log(
  `${f.name}   ` + tests.map(v=> (1*!!f(v)) ).join`   `
)})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>


This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html

List all kafka topics

Kafka is a distributed system and needs Zookeeper. you have to start zookeeper too. Follow "Quick Start" here : https://kafka.apache.org/0100/documentation.html#quickstart

Linux cmd to search for a class file among jars irrespective of jar path

I have used this small snippet. Might be slower but works every time.

for i in 'find . -type f -name "*.jar"'; do
    jar tvf $i | grep "com.foo.bar.MyClass.clss";
    if [ $? -eq 0 ]; then echo $i; fi;
done

How to add AUTO_INCREMENT to an existing column?

ALTER TABLE Table name ADD column datatype AUTO_INCREMENT,ADD primary key(column);

Java RegEx meta character (.) and ordinary dot?

I am doing some basic array in JGrasp and found that with an accessor method for a char[][] array to use ('.') to place a single dot.

How to get MAC address of client using PHP?

//Simple & effective way to get client mac address
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');

// Capture the output into a variable

    $mycom=ob_get_contents();

// Clean (erase) the output buffer

    ob_clean();

$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);

// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo $mac;

Setting the filter to an OpenFileDialog to allow the typical image formats?

For images, you could get the available codecs from GDI (System.Drawing) and build your list from that with a little work. This would be the most flexible way to go.

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

How do I resolve a TesseractNotFoundError?

You can download tesseract-ocr setup using the following link,

Tesseract for windows

Then add new variable with name tesseract in environment variables with value C:\Program Files (x86)\Tesseract-OCR\tesseract.exe

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

You need to upgrade your pip installation because it is still using http instead of https.

The --index-url (short version: -i) option allows you to specify an index-url in the call to pip itself, there you can use the https-variant. Then you can instruct pip to upgrade itself.

sudo pip install --index-url https://pypi.python.org/simple/ --upgrade pip

Afterwards you should be able to use pip without the --index-url option.


I believe that the release 7.0.0 (2015-05-21) triggered this issue. The release note for that version states the following:

BACKWARD INCOMPATIBLE No longer implicitly support an insecure origin origin, and instead require insecure origins be explicitly trusted with the --trusted-host option.

You can check your pip version with pip --version.

This would mean that issuing sudo pip install --trusted-host --upgrade pip once would also solve this issue, albeit download pip over insecure http. This might also not work at all, because it is possible that the insecure endpoint is no longer accessible on the server (I have not tested this).

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

Copying a local file from Windows to a remote server using scp

I have found it easiest to use a graphical interface on windows (I recommend mobaXTerm it has ssh, scp, ftp, remote desktop, and many more) but if you are set on command line I would recommend cd'ing into the directory with the source folder then
scp -r yourFolder username@server:/path/to/dir
the -r indicates recursive to be used on directories

Font Awesome icon inside text input element

I did achieve this like so

_x000D_
_x000D_
  form i {_x000D_
    left: -25px;_x000D_
    top: 23px;_x000D_
    border: none;_x000D_
    position: relative;_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
    float: left;_x000D_
    color: #29a038;_x000D_
  }
_x000D_
<form>_x000D_
_x000D_
  <i class="fa fa-link"></i>_x000D_
_x000D_
  <div class="form-group string optional profile_website">_x000D_
    <input class="string optional form-control" placeholder="http://your-website.com" type="text" name="profile[website]" id="profile_website">_x000D_
  </div>_x000D_
_x000D_
  <i class="fa fa-facebook"></i>_x000D_
  <div class="form-group url optional profile_facebook_url">_x000D_
    <input class="string url optional form-control" placeholder="http://facebook.com/your-account" type="url" name="profile[facebook_url]" id="profile_facebook_url">_x000D_
  </div>_x000D_
_x000D_
  <i class="fa fa-twitter"></i>_x000D_
  <div class="form-group url optional profile_twitter_url">_x000D_
    <input class="string url optional form-control" placeholder="http://twitter.com/your-account" type="url" name="profile[twitter_url]" id="profile_twitter_url">_x000D_
  </div>_x000D_
_x000D_
  <i class="fa fa-instagram"></i>_x000D_
  <div class="form-group url optional profile_instagram_url">_x000D_
    <input class="string url optional form-control" placeholder="http://instagram.com/your-account" type="url" name="profile[instagram_url]" id="profile_instagram_url">_x000D_
  </div>_x000D_
_x000D_
  <input type="submit" name="commit" value="Add profile">_x000D_
</form>
_x000D_
_x000D_
_x000D_

The result looks like this:

result

Side note

Please note that I am using Ruby on Rails so my resulting code looks a bit blown up. The view code in slim is actually very concise:

i.fa.fa-link
= f.input :website, label: false

i.fa.fa-facebook
= f.input :facebook_url, label: false

i.fa.fa-twitter
= f.input :twitter_url, label: false

i.fa.fa-instagram
= f.input :instagram_url, label: false

Git status shows files as changed even though contents are the same

So, I tried just about everything here and want to contribute one more solution that fixed all of my problems. My issues was not with line endings or actual permissions or anything like that. It was because I had installed Cygwin and whole host of stuff that comes with that, which unbeknownst to me also installed its own version of git. I never noticed this, just that I was having strange issues with users and files being marked as changed (because of perms changes).

It turns out that I figured this out because I thought I should just update Git to the latest version, which I did, but running git --version returned the old version number. After the ensuing hunt for why, I found the cygwin bin directory root in my environment path, which contained a git executable, running at the old version number. Go figure.

This was also hard to find because I have TortoiseGit installed. My command line tools would use the cygwin version due to path fallbacks, and TortoiseGit was configured to use the windows version, making it even more confusing.

Hope this helps somebody.

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

Current date and time as string

I wanted to use the C++11 answer, but I could not because GCC 4.9 does not support std::put_time.

std::put_time implementation status in GCC?

I ended up using some C++11 to slightly improve the non-C++11 answer. For those that can't use GCC 5, but would still like some C++11 in their date/time format:

 std::array<char, 64> buffer;
 buffer.fill(0);
 time_t rawtime;
 time(&rawtime);
 const auto timeinfo = localtime(&rawtime);
 strftime(buffer.data(), sizeof(buffer), "%d-%m-%Y %H-%M-%S", timeinfo);
 std::string timeStr(buffer.data());

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • char: fixed-length character data with a maximum length of 8000 characters.
  • nchar: fixed-length unicode data with a maximum length of 4000 characters.
  • Char = 8 bit length
  • NChar = 16 bit length

How can I change the version of npm using nvm?

EDIT: several years since this question was first answered, as noted in a newer answer, there is now a command for this:

nvm now has a command to update npm. It's nvm install-latest-npm or nvm install --latest-npm.

nvm install-latest-npm: Attempt to upgrade to the latest working npm on the current node version

nvm install --latest-npm: After installing, attempt to upgrade to the latest working npm on the given node version

Below are previous revisions of the correct answer to this question.

Over three years after this question was first asked, it seems like the answer is much simpler now. Just update the version that nvm installed, which lives in ~/.nvm/versions/node/[your-version]/lib/node_modules/npm.

I just installed node 4.2.2, which comes with npm 2.14.7, but I want to use npm 3. So I did:

cd ~/.nvm/versions/node/v4.2.2/lib
npm install npm

Easy!

And yes, this should work for any module, not just npm, that you want to be "global" for a specific version of node.


EDIT 1: In the newest version, npm -g is smart and installs modules into the path above instead of the system global path.


Thanks @philraj for pointing this out in a comment.

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

Javascript switch vs. if...else if...else

Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/else has to be implemented with an O(n) procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?

What does \u003C mean?

It is a unicode char \u003C = <

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Visual Studio Code cannot detect installed git

I found that i had git: false in settings.json. Changed it to true and works now.

pandas groupby sort descending order

As of Pandas 0.18 one way to do this is to use the sort_index method of the grouped data.

Here's an example:

np.random.seed(1)
n=10
df = pd.DataFrame({'mygroups' : np.random.choice(['dogs','cats','cows','chickens'], size=n), 
                   'data' : np.random.randint(1000, size=n)})

grouped = df.groupby('mygroups', sort=False).sum()
grouped.sort_index(ascending=False)
print grouped

data
mygroups      
dogs      1831
chickens  1446
cats       933

As you can see, the groupby column is sorted descending now, indstead of the default which is ascending.

Sending command line arguments to npm script

If you want to pass arguments to the middle of an npm script, as opposed to just having them appended to the end, then inline environment variables seem to work nicely:

"scripts": {
  "dev": "BABEL_ARGS=-w npm run build && cd lib/server && nodemon index.js",
  "start": "npm run build && node lib/server/index.js",
  "build": "mkdir -p lib && babel $BABEL_ARGS -s inline --stage 0 src -d lib",
},

Here, npm run dev passes the -w watch flag to babel, but npm run start just runs a regular build once.

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try using xmltype.createxml(xml).

As in,

select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;

It worked for me.

If you want to improve or manipulate even further.

Try something like this.

Select *
from xmltable(xmlnamespaces('some-name-space' as "ns", 
                                  'another-name-space' as "ns1",
                           ), 
                    '/ns/ns1/foo/bar'
                    passing xmltype.createxml(xml) 
                    columns id varchar2(10) path '//ns//ns1/id',
                            idboss varchar2(500) path '//ns0//ns1/idboss',
                            etc....

                    ) nice_xml_table

Hope it helps someone.

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

How to parse a JSON file in swift?

SwiftJSONParse: Parse JSON like a badass

Dead-simple and easy to read!

Example: get the value "mrap" from nicknames as a String from this JSON response

{
    "other": {
        "nicknames": ["mrap", "Mikee"]
}

It takes your json data NSData as it is, no need to preprocess.

let parser = JSONParser(jsonData)

if let handle = parser.getString("other.nicknames[0]") {
    // that's it!
}

Disclaimer: I made this and I hope it helps everyone. Feel free to improve on it!

Regular expression to match URLs in Java

I'll try a standard "Why are you doing it this way?" answer... Do you know about java.net.URL?

URL url = new URL(stringURL);

The above will throw a MalformedURLException if it can't parse the URL.

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

How to sort a list of objects based on an attribute of the objects?

Add rich comparison operators to the object class, then use sort() method of the list.
See rich comparison in python.


Update: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

CSS styling in Django forms

This can be done using a custom template filter. Consider rendering your form this way:

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subject is an instance of BoundField which has the as_widget() method.

You can create a custom filter addclass in my_app/templatetags/myfilters.py:

from django import template

register = template.Library()

@register.filter(name='addclass')
def addclass(value, arg):
    return value.as_widget(attrs={'class': arg})

And then apply your filter:

{% load myfilters %}

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject|addclass:'MyClass' }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subjects will then be rendered with the MyClass CSS class.

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

Accessing private member variables from prototype-defined functions

You can use a prototype assignment within the constructor definition.

The variable will be visible to the prototype added method but all the instances of the functions will access the same SHARED variable.

function A()
{
  var sharedVar = 0;
  this.local = "";

  A.prototype.increment = function(lval)
  {    
    if (lval) this.local = lval;    
    alert((++sharedVar) + " while this.p is still " + this.local);
  }
}

var a = new A();
var b = new A();    
a.increment("I belong to a");
b.increment("I belong to b");
a.increment();
b.increment();

I hope this can be usefull.

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Windows Scipy Install: No Lapack/Blas Resources Found

My 5 cents; You can just install the entire (pre-compiled) SciPy from https://github.com/scipy/scipy/releases

Good Luck!

Difference between dict.clear() and assigning {} in Python

In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop

How do I enable php to work with postgresql?

  • SO: Windows/Linux
  • HTTP Web Server: Apache
  • Programming language: PHP

Enable PHP to work with PostgreSQL in Apache

In Apache I edit the following configuration file: C:\xampp\php.ini

I make sure to have the following lines uncommented:

extension=php_pgsql.dll 
extension=php_pdo_pgsql.dll

Finally restart Apache before attempting a new connection to the database engine.


Also, I leave my code that ensures that the connection is unique:

private static $pdo = null;

public static function provideDataBaseInstance() {
    if (self::$pdo == null) {
        $dsn = "pgsql:host=" . HOST .
               ";port=5432;dbname=" . DATABASE .
               ";user=" . POSTGRESQL_USER .
               ";password=" . POSTGRESQL_PASSWORD;
        try {
            self::$pdo = new PDO($dsn);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            echo $msg . 
                 ". Do not forget to enable in the web server the database 
                  manager for php and in the database instance authorize the 
                  ip of the server instance if they not in the same 
                  instance.";
        }
    }
    return self::$pdo;
}

GL

background-image: url("images/plaid.jpg") no-repeat; wont show up

You either use :

background-image: url("images/plaid.jpg");
background-repeat: no-repeat;

... or

background: transparent url("images/plaid.jpg") top left no-repeat;

... but definitively not

background-image: url("images/plaid.jpg") no-repeat;

EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).

What's the best way to test SQL Server connection programmatically?

Here is my version based on the @peterincumbria answer:

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);

I'm using Observable for polling health checking by interval and handling return value of the function. try-catch is not needed here because: enter image description here

Visual Studio Code always asking for git credentials

The following steps walk you through how to:

  1. Generate SSH keys (without passphrase**)
  2. Add the public key generated in step 1 to your Git repository
  3. Confirm the above steps have been completed successfully
  4. Make your first commit (without having to provide a username / password)

**Generating SSH keys without a passphrase is unwise if your work is particularly sensitive.

OS - Fedora 28 | Editor - VS Code v1.23.0 | Repository - Git

Generate SSH keys:

  • ssh-keygen -t rsa -C "[email protected]"
  • Enter file in which to save the key: Press Enter
  • Enter passphrase: Press Enter
  • Enter same passphrase again: Press Enter

After completing the above steps, the location of your public key is shown in the terminal window. If the currently logged in user is 'bob' the location of your public key would be /home/bob/.ssh/id_rsa.pub

Copy and import public key to GitHub:

  • cat /home/bob/.ssh/id_rsa.pub

  • Copy the whole public key that is now displayed in your terminal window to the clipboard

  • Go to https://github.com and sign in
  • Click the user icon in the top right corner of the screen and select Settings
  • Click SSH and GPG keys
  • Click New SSH key
  • Enter a title, paste the public key copied to the clipboard in the first bullet point, and click Add SSH key

Confirm the above steps:

  • ssh -T [email protected]

  • yes

  • Hi ! You've successfully authenticated, but GitHub does not provide shell access.

First commit / push without having to enter a username / password: - touch test.txt

  • git add test.txt

  • git commit - opens editor, enter a message and save the file. If vi is your editor, press i once the file opens, enter a message, press esc, and then enter :x to save changes.

  • git push

The only hiccup you may encounter is when you attempt to SSH to GitHub. This link will provide some assistance -

Happy hunting!

How to get key names from JSON using jq

In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:

     cat input.json | jq -r 'keys'

From jq help:

     -r     output raw strings, not JSON texts;

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

Where is the default log location for SharePoint/MOSS?

For Sharepoint 2007

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Let's keep them simple, shall we. First off, using pure HTML + CSS:

<div id="emotion">
    <input type="radio" name="emotion" id="sad" />
        <label for="sad"><img src="sad_image.png" alt="I'm sad" /></label>

    <input type="radio" name="emotion" id="happy" />
        <label for="happy"><img src="happy_image.png" alt="I'm happy" /></label>
</div>

This will degrade nicely if there's no JavaScript. Use id and for attributes to link up the label and radiobutton so that when the image is selected, the corresponding radiobutton will be filled. This is important because we'll need to hide the actual radiobutton using JavaScript. Now for some jQuery goodness. First off, creating the CSS we'll need:

.input_hidden {
    position: absolute;
    left: -9999px;
}

.selected {
    background-color: #ccc;
}

#emotion label {
    display: inline-block;
    cursor: pointer;
}

#emotion label img {
    padding: 3px;
}

Now for the JavaScript:

$('#emotion input:radio').addClass('input_hidden');
$('#emotion label').click(function(){
    $(this).addClass('selected').siblings().removeClass('selected');
});

The reason why we're not using display: none here is for accessibility reasons. See: http://www.jsfiddle.net/yijiang/Zgh24/1 for a live demo, with something more fancy.

Run PowerShell command from command prompt (no ps1 script)

Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).

powershell -command "& {&'some-command' someParam}"

Also, here is a neat way to do multiple commands:

powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"

For example, this is how I ran my 2 commands:

powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"

Adding horizontal spacing between divs in Bootstrap 3

The best solution is not to use the same element for column and panel:

<div class="row">
    <div class="col-md-3">
        <div class="panel" id="gameplay-away-team">Away Team</div>
    </div>
    <div class="col-md-6">
        <div class="panel" id="gameplay-baseball-field">Baseball Field</div>
    </div>
    <div class="col-md-3">
        <div class="panel" id="gameplay-home-team">Home Team</div>
    </div>
</div>

and some more styles:

#gameplay-baseball-field {
  padding-right: 10px;
  padding-left: 10px;
}

Setting Oracle 11g Session Timeout

That's generally controlled by the profile associated with the user Tomcat is connecting as.

SQL> SELECT PROFILE, LIMIT FROM DBA_PROFILES WHERE RESOURCE_NAME = 'IDLE_TIME';

PROFILE                        LIMIT
------------------------------ ----------------------------------------
DEFAULT                        UNLIMITED

SQL> SELECT PROFILE FROM DBA_USERS WHERE USERNAME = USER;

PROFILE
------------------------------
DEFAULT

So the user I'm connected to has unlimited idle time - no time out.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Find where the cv2.so is, for example /usr/local/lib/python2.7/dist-packages, then add this into your ~/.bashrc by doing:

sudo gedit ~/.bashrc

and add

export PYTHONPATH=/usr/local/lib/python2.7/dist-packages:$PYTHONPATH

In the last line

And then remember to open another terminal, this can be work, and I have solve my problem. Hope it can help you.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Based on the other answer by @Mechanical Snail, except without the use of python, which I found to be wildly overkill. Add this to your ~/.gitconfig:

[github]
    user = "your-name-here"
[alias]
    hub-new-repo = "!REPO=$(basename $PWD) GHUSER=$(git config --get github.user); curl -u $GHUSER https://api.github.com/user/repos -d {\\\"name\\\":\\\"$REPO\\\"} --fail; git remote add origin [email protected]:$GHUSER/$REPO.git; git push origin master"

Populate nested array in mongoose

Mongoose 4.5 support this

Project.find(query)
  .populate({ 
     path: 'pages',
     populate: {
       path: 'components',
       model: 'Component'
     } 
  })
  .exec(function(err, docs) {});

And you can join more than one deep level

Convert MFC CString to integer

you can also use good old sscanf.

CString s;
int i;
int j = _stscanf(s, _T("%d"), &i);
if (j != 1)
{
   // tranfer didn't work
}

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

not-null property references a null or transient value

for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).

Determine Whether Two Date Ranges Overlap

Below query gives me the ids for which the supplied date range (start and end dates overlaps with any of the dates (start and end dates) in my table_name

select id from table_name where (START_DT_TM >= 'END_DATE_TIME'  OR   
(END_DT_TM BETWEEN 'START_DATE_TIME' AND 'END_DATE_TIME'))

How can I find where Python is installed on Windows?

It would be either of

  • C:\Python36
  • C:\Users\(Your logged in User)\AppData\Local\Programs\Python\Python36

How to get the last char of a string in PHP?

A string in different languages including C sharp and PHP is also considered an array of characters.

Knowing that in theory array operations should be faster than string ones you could do,

$foo = "bar";


$lastChar = strlen($foo) -1;
echo $foo[$lastChar];

$firstChar = 0;
echo $foo[$firstChar];

However, standard array functions like

count();

will not work on a string.

How do you properly use namespaces in C++?

To avoid saying everything Mark Ingram already said a little tip for using namespaces:

Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.

I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.

Sometimes namespaces are used in bigger C++ projects to hide implementation details.

Additional note to the using directive: Some people prefer using "using" just for single elements:

using std::cout;  
using std::endl;

Sprintf equivalent in Java

Both solutions workto simulate printf, but in a different way. For instance, to convert a value to a hex string, you have the 2 following solutions:

  • with format(), closest to sprintf():

    final static String HexChars = "0123456789abcdef";
    
    public static String getHexQuad(long v) {
        String ret;
        if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";
        ret += String.format("%c%c%c%c",
            HexChars.charAt((int) ((v >> 12) & 0x0f)),
            HexChars.charAt((int) ((v >>  8) & 0x0f)),
            HexChars.charAt((int) ((v >>  4) & 0x0f)),
            HexChars.charAt((int) ( v        & 0x0f)));
        return ret;
    }
    
  • with replace(char oldchar , char newchar), somewhat faster but pretty limited:

        ...
        ret += "ABCD".
            replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).
            replace('B', HexChars.charAt((int) ((v >>  8) & 0x0f))).
            replace('C', HexChars.charAt((int) ((v >>  4) & 0x0f))).
            replace('D', HexChars.charAt((int) ( v        & 0x0f)));
        ...
    
  • There is a third solution consisting of just adding the char to ret one by one (char are numbers that add to each other!) such as in:

    ...
    ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));
    ret += HexChars.charAt((int) ((v >>  8) & 0x0f)));
    ...
    

...but that'd be really ugly.

Likelihood of collision using most significant bits of a UUID in Java

Use Time YYYYDDDD (Year + Day of Year) as prefix. This decreases database fragmentation in tables and indexes. This method returns byte[40]. I used it in a hybrid environment where the Active Directory SID (varbinary(85)) is the key for LDAP users and an application auto-generated ID is used for non-LDAP Users. Also the large number of transactions per day in transactional tables (Banking Industry) cannot use standard Int types for Keys

private static final DecimalFormat timeFormat4 = new DecimalFormat("0000;0000");

public static byte[] getSidWithCalendar() {
    Calendar cal = Calendar.getInstance();
    String val = String.valueOf(cal.get(Calendar.YEAR));
    val += timeFormat4.format(cal.get(Calendar.DAY_OF_YEAR));
    val += UUID.randomUUID().toString().replaceAll("-", "");
    return val.getBytes();
}

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Return array in a function

i used static array so that while returning array it should not throw error as you are returning address of local variable... so now you can send any locally created variable from function by making it as static...as it works as global variable....

#include<iostream>
using namespace std;

char *func(int n)
{
   // char a[26]; /*if we use this then an error will occur because you are 
                        //  returning address of a local variable*/
    static char a[26];
    char temp='A'; 
    for(int i=0;i<n;i++)
    {
     a[i]=temp;temp++;
    }
    return a;
}
int main()
{
    int n=26;
    char *p=func(n);
    for(int i=0;i<n;i++)
     cout<<*(p+i)<<" ";

   //or you can also print like this
  
    for(int i=0;i<n;i++)
     cout<<p[i]<<" ";    

}

How to read xml file contents in jQuery and display in html elements?

_x000D_
_x000D_
 $.get("/folder_name/filename.xml", function (xml) {_x000D_
 var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
 });
_x000D_
_x000D_
_x000D_

JavaScript equivalent of PHP's in_array()

You can simply use the "includes" function as explained in this lesson on w3schools

it looks like

_x000D_
_x000D_
let myArray = ['Kevin', 'Bob', 'Stuart'];_x000D_
if( myArray.includes('Kevin'))_x000D_
console.log('Kevin is here');
_x000D_
_x000D_
_x000D_

finished with non zero exit value

I had the same problem.

Try renaming the files in assets folder with characters other than alphabets, numbers and underlines.

Specially, look for apostrophes and European alphabets not common in English.

How to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

How do I remove blank pages coming between two chapters in Appendix?

I put the \let\cleardoublepage\clearpage before \makeindex. Else, your content page will display page number based on the page number before you clear the blank page.

Set a default parameter value for a JavaScript function

To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.

function read_file(file, delete_after = false) {
    #code
}

In that example Edge will throw an error "Expecting ')'"

To get around this use

function read_file(file, delete_after) {
  if(delete_after == undefined)
  {
    delete_after = false;
  }
  #code
}

As of Aug 08 2016 this is still an issue

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

Visual Studio breakpoints not being hit

The issue was resolved by unchecking the

Properties > Build > Optimize Code

setting on the web page properties screen (under General).

Screenshot.

Updating Anaconda fails: Environment Not Writable Error

Deleting file .condarc (eg./root/.condarc) in the user's home directory before installation, resolved the issue.

How do I use Join-Path to combine more than two strings into a file path?

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')

best way to get the key of a key/value javascript object

Given your Object:

var foo = { 'bar' : 'baz' }

To get bar, use:

Object.keys(foo)[0]

To get baz, use:

foo[Object.keys(foo)[0]]

Assuming a single object

Hadoop: «ERROR : JAVA_HOME is not set»

I tried the above solutions but the following worked on me

export JAVA_HOME=/usr/java/default

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Delete all items from a c++ std::vector

vector.clear() should work for you. In case you want to shrink the capacity of the vector along with clear then

std::vector<T>(v).swap(v);

Excel function to get first word from sentence in other cell

A1                   A2 
Toronto<b> is nice   =LEFT(A1,(FIND("<",A1,1)-1))

Not sure if the syntax is correct but the forumla in A2 will work for you,

How can one display images side by side in a GitHub README.md?

This solution allows you to add space in-between the images as well. It combines the best parts of all the existing solutions and doesn't add any ugly table borders.

<p align="center">
  <img alt="Light" src="https://...light.png" width="45%">
&nbsp; &nbsp; &nbsp; &nbsp;
  <img alt="Dark" src="https://...dark.png" width="45%">
</p>

The key is adding the &nbsp; non-breaking space HTML entities, which you can add and remove in order to customize the spacing.

You can see this example live on GitHub here.

what's data-reactid attribute in html?

data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:

http://ejohn.org/blog/html-5-data-attributes/

You can create a data attribute by prefixing data- to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id or in this case data-reactid

Efficient evaluation of a function at every cell of a NumPy array

You could just vectorize the function and then apply it directly to a Numpy array each time you need it:

import numpy as np

def f(x):
    return x * x + 3 * x - 2 if x > 0 else x * 5 + 8

f = np.vectorize(f)  # or use a different name if you want to keep the original f

result_array = f(A)  # if A is your Numpy array

It's probably better to specify an explicit output type directly when vectorizing:

f = np.vectorize(f, otypes=[np.float])

Negative weights using Dijkstra's Algorithm

"2) Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – one idea can be, calculate the minimum weight value, add a positive value (equal to absolute value of minimum weight value) to all weights and run the Dijksra’s algorithm for the modified graph. Will this algorithm work?"

This absolutely doesn't work unless all shortest paths have same length. For example given a shortest path of length two edges, and after adding absolute value to each edge, then the total path cost is increased by 2 * |max negative weight|. On the other hand another path of length three edges, so the path cost is increased by 3 * |max negative weight|. Hence, all distinct paths are increased by different amounts.

How to get 30 days prior to current date?

Try using the excellent Datejs JavaScript date library (the original is no longer maintained so you may be interested in this actively maintained fork instead):

Date.today().add(-30).days(); // or...
Date.today().add({days:-30});

[Edit]

See also the excellent Moment.js JavaScript date library:

moment().subtract(30, 'days'); // or...
moment().add(-30, 'days');

Detect Android phone via Javascript / jQuery

I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:

var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
    var css = document.createElement("link");
    css.setAttribute("rel", "stylesheet");
    css.setAttribute("type", "text/css");
    css.setAttribute("href", "/css/android.css");
    document.body.appendChild(css);
}

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

What does -save-dev mean in npm install grunt --save-dev

Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

https://docs.npmjs.com/getting-started/using-a-package.json#the-save-and-save-dev-install-flags

A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

Database, Table and Column Naming Conventions?

I'm also in favour of a ISO/IEC 11179 style naming convention, noting they are guidelines rather than being prescriptive.

See Data element name on Wikipedia:

"Tables are Collections of Entities, and follow Collection naming guidelines. Ideally, a collective name is used: eg., Personnel. Plural is also correct: Employees. Incorrect names include: Employee, tblEmployee, and EmployeeTable."

As always, there are exceptions to rules e.g. a table which always has exactly one row may be better with a singular name e.g. a config table. And consistency is of utmost importance: check whether you shop has a convention and, if so, follow it; if you don't like it then do a business case to have it changed rather than being the lone ranger.

Use dynamic variable names in `dplyr`

You may enjoy package friendlyeval which presents a simplified tidy eval API and documentation for newer/casual dplyr users.

You are creating strings that you wish mutate to treat as column names. So using friendlyeval you could write:

multipetal <- function(df, n) {
  varname <- paste("petal", n , sep=".")
  df <- mutate(df, !!treat_string_as_col(varname) := Petal.Width * n)
  df
}

for(i in 2:5) {
  iris <- multipetal(df=iris, n=i)
}

Which under the hood calls rlang functions that check varname is legal as column name.

friendlyeval code can be converted to equivalent plain tidy eval code at any time with an RStudio addin.

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

How to conclude your merge of a file?

If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.

SourceTree version used is 1.6.14.0

Asynchronous vs synchronous execution, what does it really mean?

I created a gif for explain this, hope to be helpful: look, line 3 is asynchronous and others are synchronous. all lines before line 3 should wait until before line finish its work, but because of line 3 is asynchronous, next line (line 4), don't wait for line 3, but line 5 should wait for line 4 to finish its work, and line 6 should wait for line 5 and 7 for 6, because line 4,5,6,7 are not asynchronous. line 3 is asynchronous and others are synchronous

Read a file in Node.js

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());

How to detect running app using ADB command

You can use

adb shell ps | grep apps | awk '{print $9}'

to produce an output like:

com.google.process.gapps
com.google.android.apps.uploader
com.google.android.apps.plus
com.google.android.apps.maps
com.google.android.apps.maps:GoogleLocationService
com.google.android.apps.maps:FriendService
com.google.android.apps.maps:LocationFriendService

adb shell ps returns a list of all running processes on the android device, grep apps searches for any row with contains "apps", as you can see above they are all com.google.android.APPS. or GAPPS, awk extracts the 9th column which in this case is the package name.

To search for a particular package use

adb shell ps | grep PACKAGE.NAME.HERE | awk '{print $9}'

i.e adb shell ps | grep com.we7.player | awk '{print $9}'

If it is running the name will appear, if not there will be no result returned.

Create a tag in a GitHub repository

Creating Tags

Git uses two main types of tags: lightweight and annotated.

Annotated Tags:

To create an annotated tag in Git you can just run the following simple commands on your terminal.

$ git tag -a v2.1.0 -m "xyz feature is released in this tag."
$ git tag
v1.0.0
v2.0.0
v2.1.0

The -m denotes message for that particular tag. We can write summary of features which is going to tag here.

Lightweight Tags:

The other way to tag commits is lightweight tag. We can do it in the following way:

$ git tag v2.1.0
$ git tag
v1.0.0
v2.0.0
v2.1.0

Push Tag

To push particular tag you can use below command:

git push origin v1.0.3

Or if you want to push all tags then use the below command:

git push --tags

List all tags:

To list all tags, use the following command.

git tag

Why do I get "MismatchSenderId" from GCM server side?

InstanceID.getInstance(getApplicationContext()).getToken(authorizedEntity,scope)

authorizedEntity is the project number of the server

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

How to implement the factory method pattern in C++ correctly

I know this question has been answered 3 years ago, but this may be what your were looking for.

Google has released a couple of weeks ago a library allowing easy and flexible dynamic object allocations. Here it is: http://google-opensource.blogspot.fr/2014/01/introducing-infact-library.html

Effective way to find any file's Encoding

The following code works fine for me, using the StreamReader class:

  using (var reader = new StreamReader(fileName, defaultEncodingIfNoBom, true))
  {
      reader.Peek(); // you need this!
      var encoding = reader.CurrentEncoding;
  }

The trick is to use the Peek call, otherwise, .NET has not done anything (and it hasn't read the preamble, the BOM). Of course, if you use any other ReadXXX call before checking the encoding, it works too.

If the file has no BOM, then the defaultEncodingIfNoBom encoding will be used. There is also a StreamReader without this overload method (in this case, the Default (ANSI) encoding will be used as defaultEncodingIfNoBom), but I recommand to define what you consider the default encoding in your context.

I have tested this successfully with files with BOM for UTF8, UTF16/Unicode (LE & BE) and UTF32 (LE & BE). It does not work for UTF7.

HTML tag <a> want to add both href and onclick working

You already have what you need, with a minor syntax change:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)

How to right align widget in horizontal linear layout Android?

Add android:gravity="right" to LinearLayout. Assuming the TextView has layout_width="wrap_content"

php timeout - set_time_limit(0); - don't work

Checkout this, This is from PHP MANUAL, This may help you.

If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>

In DB2 Display a table's definition

In addition to DESCRIBE TABLE, you can use the command below

DESCRIBE INDEXES FOR TABLE *tablename* SHOW DETAIL 

to get information about the table's indexes.

The most comprehensive detail about a table on Db2 for Linux, UNIX, and Windows can be obtained from the db2look utility, which you can run from a remote client or directly on the Db2 server as a local user. The tool produces the DDL and other information necessary to mimic tables and their statistical data. The docs for db2look in Db2 11.5 are here.

The following db2look command will connect to the SALESDB database and obtain the DDL statements necessary to recreate the ORDERS table

db2look -d SALESDB -e -t ORDERS

Why does pycharm propose to change method to static

This error message just helped me a bunch, as I hadn't realized that I'd accidentally written my function using my testing example player

my_player.attributes[item] 

instead of the correct way

self.attributes[item]

Test if object implements interface

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

Fatal error: Call to undefined function pg_connect()

install the package needed. if you use yum:

yum search pgsql

then look at the result and find anything that is something like 'php-pgsql' or something like that. copy the name and then:

yum install *paste the name of the package here*

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

Android Studio - How to increase Allocated Heap Size

Open studio.vmoptions and change JVM options

studio.vmoptions locates at /Applications/Android\ Studio.app/bin/studio.vmoptions (Mac OS). In my machine, it looks like

-Xms128m
-Xmx800m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Change to

-Xms256m
-Xmx1024m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

And restart Android Studio

See more Android Studio website

Elegant way to check for missing packages and install them?

You can simply use the setdiff function to get the packages that aren't installed and then install them. In the sample below, we check if the ggplot2 and Rcpp packages are installed before installing them.

unavailable <- setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages()))
install.packages(unavailable)

In one line, the above can be written as:

install.packages(setdiff(c("ggplot2", "Rcpp"), rownames(installed.packages())))

How to make child element higher z-index than parent?

Nothing is impossible. Use the force.

.parent {
    position: relative;
}

.child {
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
}

Keyboard shortcut to comment lines in Sublime Text 3

For Brazilian ABNT Keyboards you do Ctrl + ; to comment and repeat it to remove the comment.

How do I filter ForeignKey choices in a Django ModelForm?

To do this with a generic view, like CreateView...

class AddPhotoToProject(CreateView):
    """
    a view where a user can associate a photo with a project
    """
    model = Connection
    form_class = CreateConnectionForm


    def get_context_data(self, **kwargs):
        context = super(AddPhotoToProject, self).get_context_data(**kwargs)
        context['photo'] = self.kwargs['pk']
        context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
        return context
    def form_valid(self, form):
        pobj = Photo.objects.get(pk=self.kwargs['pk'])
        obj = form.save(commit=False)
        obj.photo = pobj
        obj.save()

        return_json = {'success': True}

        if self.request.is_ajax():

            final_response = json.dumps(return_json)
            return HttpResponse(final_response)

        else:

            messages.success(self.request, 'photo was added to project!')
            return HttpResponseRedirect(reverse('MyPhotos'))

the most important part of that...

    context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)

, read my post here

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

default select option as blank

This should help :

https://www.w3schools.com/tags/att_select_required.asp

_x000D_
_x000D_
 <form>_x000D_
 <select required>_x000D_
  <option value="">None</option>_x000D_
  <option value="volvo">Volvo</option>_x000D_
  <option value="saab">Saab</option>_x000D_
  <option value="mercedes">Mercedes</option>_x000D_
  <option value="audi">Audi</option>_x000D_
</select>_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

HTML form submit to PHP script

Here is what I find works

  1. Set a form name
  2. Use a default select option, for example...

    <option value="-1" selected>Please Select</option>

So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.

  1. Try to use HTML5 attributes now they are supported.

This input

<input type="submit">

should be

<input name="Submit" type="submit" value="Submit">

whenever I use a form that fails, it is a failure due to the difference in calling the button name submit and name as Submit.

You should also set your enctype attribute for your form as forms fail on my web host if it's not set.

self.tableView.reloadData() not working in Swift

You'll need to reload the table on the UI thread via:

//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 5
DispatchQueue.main.async{
    self.tableView.reloadData()
}

Follow up: An easier alternative to the connection.start() approach is to instead use NSURLConnection.sendAsynchronousRequest(...)

//NSOperationQueue.mainQueue() is the main thread
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
    //check error
    var jsonError: NSError?
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
    //check jsonError
    self.collectionView?.reloadData()
}

This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

jsPDF multi page PDF with HTML renderer

Automatically not split data to multi pages. You may split manually.

If your ( rowCount * rowHeight ) > 420mm ( A3 Height in mm ) add new page function. ( Sorry I can't edit your code without run ) After add new page leftMargin, topMargin = 0; ( start over ) I added sample code with yours. I hope it's right.

else {
    doc.margins = 1;
    doc.setFont("Times  ");
    doc.setFontType("normal ");
    doc.setFontSize(11);
    if ( rowCount * rowHeight > 420 ) {
        doc.addPage();
        rowCount = 3; // skip 1 and 2 above
    } else {
        // now rowcount = 3 ( top of new page for 3 )
        // j is your x axis cell index ( j start from 0 on $.each function ) or you can add cellCount like rowCount and replace with
        // rowcount is your y axis cell index
        left = ( ( j ) * ( cellWidth + leftMargin );
        top = ( ( rowcount - 3 ) * ( rowHeight + topMargin );
        doc.cell( leftMargin, top, cellWidth, rowHeight, cellContent, i);
        // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
    }
}

You can convert html directly to pdf lossless. Youtube video for html => pdf example

Error in setting JAVA_HOME

Just remember to add quotes into the path if you have a space in your path to java home. C:\Program Files\java\javaxxx\ doesn't work but "C:\Program Files\java\javaxxx\" does.

When is a language considered a scripting language?

"A script is what you give the actors. A program is what you give the audience." -- Larry Wall

I really don't think there's much of a difference any more. The so-called "scripting" languages are often compiled -- just very quickly, and at runtime. And some of the "programming" languages are are further compiled at runtime as well (think of JIT) and the first stage of "compiling" is syntax checking and resource resolution.

Don't get hung up on it, it's really not important.

Shell command to tar directory excluding certain files/folders

old question with many answers, but I found that none were quite clear enough for me, so I would like to add my try.

if you have the following structure

/home/ftp/mysite/

with following file/folders

/home/ftp/mysite/file1
/home/ftp/mysite/file2
/home/ftp/mysite/file3
/home/ftp/mysite/folder1
/home/ftp/mysite/folder2
/home/ftp/mysite/folder3

so, you want to make a tar file that contain everyting inside /home/ftp/mysite (to move the site to a new server), but file3 is just junk, and everything in folder3 is also not needed, so we will skip those two.

we use the format

tar -czvf <name of tar file> <what to tar> <any excludes>

where the c = create, z = zip, and v = verbose (you can see the files as they are entered, usefull to make sure none of the files you exclude are being added). and f= file.

so, my command would look like this

cd /home/ftp/
tar -czvf mysite.tar.gz mysite --exclude='file3' --exclude='folder3'

note the files/folders excluded are relatively to the root of your tar (I have tried full path here relative to / but I can not make that work).

hope this will help someone (and me next time I google it)

Injecting $scope into an angular service function()

Got into the same predicament. I ended up with the following. So here I am not injecting the scope object into the factory, but setting the $scope in the controller itself using the concept of promise returned by $http service.

(function () {
    getDataFactory = function ($http)
    {
        return {
            callWebApi: function (reqData)
            {
                var dataTemp = {
                    Page: 1, Take: 10,
                    PropName: 'Id', SortOrder: 'Asc'
                };

                return $http({
                    method: 'GET',
                    url: '/api/PatientCategoryApi/PatCat',
                    params: dataTemp, // Parameters to pass to external service
                    headers: { 'Content-Type': 'application/Json' }
                })                
            }
        }
    }
    patientCategoryController = function ($scope, getDataFactory) {
        alert('Hare');
        var promise = getDataFactory.callWebApi('someDataToPass');
        promise.then(
            function successCallback(response) {
                alert(JSON.stringify(response.data));
                // Set this response data to scope to use it in UI
                $scope.gridOptions.data = response.data.Collection;
            }, function errorCallback(response) {
                alert('Some problem while fetching data!!');
            });
    }
    patientCategoryController.$inject = ['$scope', 'getDataFactory'];
    getDataFactory.$inject = ['$http'];
    angular.module('demoApp', []);
    angular.module('demoApp').controller('patientCategoryController', patientCategoryController);
    angular.module('demoApp').factory('getDataFactory', getDataFactory);    
}());

Importing a GitHub project into Eclipse

When the local git projects are cloned in eclipse and are viewable in git perspective but not in package explorer (workspace), the following steps worked for me:

  • Select the repository in git perspective
  • Right click and select import projects

REST API Login Pattern

A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.

Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.

But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401 "unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.

TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)

An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401 if not provided.

Ways to iterate over a list in Java

You could always switch out the first and third examples with a while loop and a little more code. This gives you the advantage of being able to use the do-while:

int i = 0;
do{
 E element = list.get(i);
 i++;
}
while (i < list.size());

Of course, this kind of thing might cause a NullPointerException if the list.size() returns 0, becuase it always gets executed at least once. This can be fixed by testing if element is null before using its attributes / methods tho. Still, it's a lot simpler and easier to use the for loop

data.frame rows to a list

A couple of more options :

With asplit

asplit(xy.df, 1)
#[[1]]
#     x      y 
#0.1137 0.6936 

#[[2]]
#     x      y 
#0.6223 0.5450 

#[[3]]
#     x      y 
#0.6093 0.2827 
#....

With split and row

split(xy.df, row(xy.df)[, 1])

#$`1`
#       x      y
#1 0.1137 0.6936

#$`2`
#       x     y
#2 0.6223 0.545

#$`3`
#       x      y
#3 0.6093 0.2827
#....

data

set.seed(1234)
xy.df <- data.frame(x = runif(10),  y = runif(10))

Visual Studio keyboard shortcut to display IntelliSense

If you have arrived at this question because IntelliSense has stopped working properly and you are hoping to force it to show you what you need, then most likely none of these solutions are going to work.

Closing and restarting Visual Studio should fix the problem.

How to convert comma-separated String to List?

Same result you can achieve using the Splitter class.

var list = Splitter.on(",").splitToList(YourStringVariable)

(written in kotlin)

Unit testing click event in Angular

I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52) by using the tick function with the same (or greater) amount of milliseconds as in original setTimeout call.

For example, if I had a setTimeout(() => {...}, 2500); (so it will trigger after 2500 ms), I would call tick(2500), and that would solve the problem.

What I had in my component, as a reaction on a Delete button click:

delete() {
    this.myService.delete(this.id)
      .subscribe(
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
            this.router.navigate(['/home']);
          }, 2500); // I wait for 2.5 seconds before redirect
        });
  }

Her is my working test:

it('should delete the entity', fakeAsync(() => {
    component.id = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    expect(myService.getMyThing).toHaveBeenCalledWith(1);
    // more expects here..
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
    deleteButton.click(); // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    expect(myService.delete).toHaveBeenCalledWith(1);
    // more expects here..
  }));

P.S. Great explanation on fakeAsync and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

In Java, how do I get the difference in seconds between 2 dates?

That should do it:

Date a = ...;
Date b = ...;

Math.abs(a.getTime()-b.getTime())/1000;

Here the relevant documentation: Date.getTime(). Be aware that this will only work for dates after January 1, 1970, 00:00:00 GMT

unable to install pg gem

I had to do this on CentOS 5.8. Running bundle install kept causing issues since I couldn't force it to use a particular PG version.

I can't yum erase postgresql postgresql-devel either, because of dependency issues (it would remove php, http etc)

The solution? Mess $PATH temporarily to give preference to the update pgsql instead of the default one:

export PATH=/usr/pgsql-9.2/bin:$PATH
bundle install

Basically, with the above commands, it will look at /usr/pgsql-9.2/bin/pg_config before the one in /usr/bin/pg_config

Markdown and including multiple files

My solution is to use m4. It's supported on most platforms and is included in the binutils package.

First include a macro changequote() in the file to change the quoting characters to what you prefer (default is `'). The macro is removed when the file is processed.

changequote(`{{', `}}')
include({{other_file}})

On the commandline:

m4 -I./dir_containing_other_file/ input.md > _tmp.md
pandoc -o output.html _tmp.md

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

HTML5 Canvas Resize (Downscale) Image High Quality?

Suggestion 1 - extend the process pipe-line

You can use step-down as I describe in the links you refer to but you appear to use them in a wrong way.

Step down is not needed to scale images to ratios above 1:2 (typically, but not limited to). It is where you need to do a drastic down-scaling you need to split it up in two (and rarely, more) steps depending on content of the image (in particular where high-frequencies such as thin lines occur).

Every time you down-sample an image you will loose details and information. You cannot expect the resulting image to be as clear as the original.

If you are then scaling down the images in many steps you will loose a lot of information in total and the result will be poor as you already noticed.

Try with just one extra step, or at tops two.

Convolutions

In case of Photoshop notice that it applies a convolution after the image has been re-sampled, such as sharpen. It's not just bi-cubic interpolation that takes place so in order to fully emulate Photoshop we need to also add the steps Photoshop is doing (with the default setup).

For this example I will use my original answer that you refer to in your post, but I have added a sharpen convolution to it to improve quality as a post process (see demo at bottom).

Here is code for adding sharpen filter (it's based on a generic convolution filter - I put the weight matrix for sharpen inside it as well as a mix factor to adjust the pronunciation of the effect):

Usage:

sharpen(context, width, height, mixFactor);

The mixFactor is a value between [0.0, 1.0] and allow you do downplay the sharpen effect - rule-of-thumb: the less size the less of the effect is needed.

Function (based on this snippet):

function sharpen(ctx, w, h, mix) {

    var weights =  [0, -1, 0,  -1, 5, -1,  0, -1, 0],
        katet = Math.round(Math.sqrt(weights.length)),
        half = (katet * 0.5) |0,
        dstData = ctx.createImageData(w, h),
        dstBuff = dstData.data,
        srcBuff = ctx.getImageData(0, 0, w, h).data,
        y = h;
        
    while(y--) {

        x = w;

        while(x--) {

            var sy = y,
                sx = x,
                dstOff = (y * w + x) * 4,
                r = 0, g = 0, b = 0, a = 0;

            for (var cy = 0; cy < katet; cy++) {
                for (var cx = 0; cx < katet; cx++) {

                    var scy = sy + cy - half;
                    var scx = sx + cx - half;

                    if (scy >= 0 && scy < h && scx >= 0 && scx < w) {

                        var srcOff = (scy * w + scx) * 4;
                        var wt = weights[cy * katet + cx];

                        r += srcBuff[srcOff] * wt;
                        g += srcBuff[srcOff + 1] * wt;
                        b += srcBuff[srcOff + 2] * wt;
                        a += srcBuff[srcOff + 3] * wt;
                    }
                }
            }

            dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix);
            dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix);
            dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix)
            dstBuff[dstOff + 3] = srcBuff[dstOff + 3];
        }
    }

    ctx.putImageData(dstData, 0, 0);
}

The result of using this combination will be:

ONLINE DEMO HERE

Result downsample and sharpen convolution

Depending on how much of the sharpening you want to add to the blend you can get result from default "blurry" to very sharp:

Variations of sharpen

Suggestion 2 - low level algorithm implementation

If you want to get the best result quality-wise you'll need to go low-level and consider to implement for example this brand new algorithm to do this.

See Interpolation-Dependent Image Downsampling (2011) from IEEE.
Here is a link to the paper in full (PDF).

There are no implementations of this algorithm in JavaScript AFAIK of at this time so you're in for a hand-full if you want to throw yourself at this task.

The essence is (excerpts from the paper):

Abstract

An interpolation oriented adaptive down-sampling algorithm is proposed for low bit-rate image coding in this paper. Given an image, the proposed algorithm is able to obtain a low resolution image, from which a high quality image with the same resolution as the input image can be interpolated. Different from the traditional down-sampling algorithms, which are independent from the interpolation process, the proposed down-sampling algorithm hinges the down-sampling to the interpolation process. Consequently, the proposed down-sampling algorithm is able to maintain the original information of the input image to the largest extent. The down-sampled image is then fed into JPEG. A total variation (TV) based post processing is then applied to the decompressed low resolution image. Ultimately, the processed image is interpolated to maintain the original resolution of the input image. Experimental results verify that utilizing the downsampled image by the proposed algorithm, an interpolated image with much higher quality can be achieved. Besides, the proposed algorithm is able to achieve superior performance than JPEG for low bit rate image coding.

Snapshot from paper

(see provided link for all details, formulas etc.)

Can you require two form fields to match with HTML5?

Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:

<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('password').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }
</script>
<br /><br />
<input type="submit" />

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How to install a previous exact version of a NPM package?

First remove old version, then run literally the following:

npm install [email protected]

and for stable or recent

npm install -g npm@latest    // For the last stable version
npm install -g npm@next      // For the most recent release

How should I log while using multiprocessing in Python?

There is this great package

Package: https://pypi.python.org/pypi/multiprocessing-logging/

code: https://github.com/jruere/multiprocessing-logging

Install:

pip install multiprocessing-logging

Then add:

import multiprocessing_logging

# This enables logs inside process
multiprocessing_logging.install_mp_handler()

Laravel Eloquent "WHERE NOT IN"

This is my working variant for Laravel 7

DB::table('user')                 
  ->select('id','name')
  ->whereNotIn('id', DB::table('curses')->where('id_user', $id)->pluck('id_user')->toArray())
  ->get();

How do you check if a variable is an array in JavaScript?

In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

He explains:

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

What is the difference between a static and a non-static initialization code block

You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.

You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..

A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

How to resize image (Bitmap) to a given size?

Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);

Scale down method:

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}