Programs & Examples On #Ldflags

LDFLAGS is a variable used in Makefiles. Specifically its value is added to linker command lines when the linker is invoked by an implicit rule.

How to set the LDFLAGS in CMakeLists.txt?

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

How do a LDAP search/authenticate against this LDAP in Java

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    ctx.setRequestControls(null);
    NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
    while (namingEnum.hasMore ()) {
        SearchResult result = (SearchResult) namingEnum.next ();    
        Attributes attrs = result.getAttributes ();
        System.out.println(attrs.get("cn"));

    } 
    namingEnum.close();
} catch (Exception e) {
    e.printStackTrace();
}

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

Dataset - Vehicle make/model/year (free)

Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.

https://github.com/n8barr/automotive-model-year-data

Override and reset CSS style: auto or none don't work

The best way that I've found to revert a min-width setting is:

min-width: 0;
min-width: unset;

unset is in the spec, but some browsers (IE 10) do not respect it, so 0 is a good fallback in most cases. min-width: 0;

Just what is an IntPtr exactly?

A direct interpretation

An IntPtr is an integer which is the same size as a pointer.

You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.

The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.

The name "IntPtr" is confusing -- something like Handle might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.

An alternative perspective

An IntPtr is a pointer with two limitations:

  1. It cannot be directly dereferenced
  2. It doesn't know the type of the data that it points to.

In other words, an IntPtr is just like a void* -- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.

In order to dereference an IntPtr, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal class. Using the Marshal class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.

SQL Server® 2016, 2017 and 2019 Express full download

Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

What is the largest possible heap size with a 64-bit JVM?

I tried -Xmx32255M is accepted by vmargs for compressed oops.

Arrays in unix shell?

The following code creates and prints an array of strings in shell:

#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
    echo "$element"
done

echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"

Result:

A
B
ElementC
ElementE

Number of elements: 4

A B ElementC ElementE

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

This problem can happen if different versions of g++ and gcc are installed.

   g++ --version
   gcc --version

If these don't give the result, you probably have multiple versions of gcc installed. You can check by using:

    dpkg -l | grep gcc | awk '{print $2}'

Usually, /usr/bin/gcc will be sym-linked to /etc/alternatives/gcc which is again sym-linked to say /usr/bin/gcc-4.6 or /usr/bin/gcc-4.8 (In case you have gcc-4.6, gcc-4.8 installed.)

By changing this link you can make gcc and g++ run in the same version and this may resolve your issue!

DateTime2 vs DateTime in SQL Server

I think DATETIME2 is the better way to store the date, because it has more efficiency than the DATETIME. In SQL Server 2008 you can use DATETIME2, it stores a date and time, takes 6-8 bytes to store and has a precision of 100 nanoseconds. So anyone who needs greater time precision will want DATETIME2.

how to save canvas as png image?

Full Working HTML Code. Cut+Paste into new .HTML file:

Contains Two Examples:

  1. Canvas in HTML file.
  2. Canvas dynamically created with Javascript.

Tested In:

  1. Chrome
  2. Internet Explorer
  3. *Edge (title name does not show up)
  4. Firefox
  5. Opera

<!DOCTYPE HTML >
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> #SAVE_CANVAS_TEST# </title>
    <meta 
        name   ="author" 
        content="John Mark Isaac Madison"
    >
    <!-- EMAIL: J4M4I5M7 -[AT]- Hotmail.com -->
</head>
<body>

<div id="about_the_code">
    Illustrates:
    <ol>
    <li>How to save a canvas from HTML page.     </li>
    <li>How to save a dynamically created canvas.</li>
    </ol>
</div>

<canvas id="DOM_CANVAS" 
        width ="300" 
        height="300"
></canvas>

<div id="controls">
    <button type="button" style="width:300px;"
            onclick="obj.SAVE_CANVAS()">
        SAVE_CANVAS ( Dynamically Made Canvas )
    </button>

    <button type="button" style="width:300px;"
            onclick="obj.SAVE_CANVAS('DOM_CANVAS')">
        SAVE_CANVAS ( Canvas In HTML Code )
    </button>
</div>

<script>
var obj = new MyTestCodeClass();
function MyTestCodeClass(){

    //Publically exposed functions:
    this.SAVE_CANVAS = SAVE_CANVAS;

    //:Private:
    var _canvas;
    var _canvas_id = "ID_OF_DYNAMIC_CANVAS";
    var _name_hash_counter = 0;

    //:Create Canvas:
    (function _constructor(){
        var D   = document;
        var CE  = D.createElement.bind(D);
        _canvas = CE("canvas");
        _canvas.width = 300;
        _canvas.height= 300;
        _canvas.id    = _canvas_id;
    })();

    //:Before saving the canvas, fill it so
    //:we can see it. For demonstration of code.
    function _fillCanvas(input_canvas, r,g,b){
        var ctx = input_canvas.getContext("2d");
        var c   = input_canvas;

        ctx.fillStyle = "rgb("+r+","+g+","+b+")";
        ctx.fillRect(0, 0, c.width, c.height);
    }

    //:Saves canvas. If optional_id supplied,
    //:will save canvas off the DOM. If not,
    //:will save the dynamically created canvas.
    function SAVE_CANVAS(optional_id){

        var c = _getCanvas( optional_id );

        //:Debug Code: Color canvas from DOM
        //:green, internal canvas red.
        if( optional_id ){
            _fillCanvas(c,0,255,0);
        }else{
            _fillCanvas(c,255,0,0);
        }

        _saveCanvas( c );
    }

    //:If optional_id supplied, get canvas
    //:from DOM. Else, get internal dynamically
    //:created canvas.
    function _getCanvas( optional_id ){
        var c = null; //:canvas.
        if( typeof optional_id == "string"){
            var id = optional_id;
            var  d = document;
            var c  = d.getElementById( id );
        }else{
            c = _canvas; 
        }
        return c;
    }

    function _saveCanvas( canvas ){
        if(!window){ alert("[WINDOW_IS_NULL]"); }

        //:We want to give the window a unique
        //:name so that we can save multiple times
        //:without having to close previous
        //:windows.
        _name_hash_counter++              ; 
        var NHC = _name_hash_counter      ;
        var URL = 'about:blank'           ;
        var name= 'UNIQUE_WINDOW_ID' + NHC;
        var w=window.open( URL, name )    ;

        if(!w){ alert("[W_IS_NULL]");}

        //:Create the page contents,
        //:THEN set the tile. Order Matters.
        var DW = ""                        ;
        DW += "<img src='"                 ;
        DW += canvas.toDataURL("image/png");
        DW += "' alt='from canvas'/>"      ;
        w.document.write(DW)               ;
        w.document.title = "NHC"+NHC       ;

    }

}//:end class

</script>

</body>
<!-- In IE: Script cannot be outside of body.  -->
</html>

Replace text inside td using jQuery having td containing other elements

Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end()
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));

FIDDLE

IntelliJ: Error:java: error: release version 5 not supported

I add the following code to my pom.xml file. It solved my problem.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

Best ways to teach a beginner to program?

I don't know for sure what will be the best for your brother, but I know I started with python. I've been playing various games from a very early age and wanted to make my own, so my uncle introduced me to python with the pygame library. It has many tutorials and makes it all easy (WAY easier than openGL in my opinion). It is limited to 2d, but you should be starting out simple anyway.

My uncle recommended python because he was interested in it at the time, but I recommend it, now fairly knowledgeable, because it's easy to learn, intuitive (or as intuitive as a programming language can get), and simple (but certainly not simplistic).

I personally found basic programming simply to learn programming obscenely boring at the time, but picked up considerable enthusiasm as I went. I really wanted to be learning in order to build something, not just to learn it.

How can I get the count of line in a file in an efficient way?

Quick and dirty, but it does the job:

import java.io.*;

public class Counter {

    public final static void main(String[] args) throws IOException {
        if (args.length > 0) {
            File file = new File(args[0]);
            System.out.println(countLines(file));
        }
    }

    public final static int countLines(File file) throws IOException {
        ProcessBuilder builder = new ProcessBuilder("wc", "-l", file.getAbsolutePath());
        Process process = builder.start();
        InputStream in = process.getInputStream();
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
        String line = reader.readLine();
        if (line != null) {
            return Integer.parseInt(line.trim().split(" ")[0]);
        } else {
            return -1;
        }
    }

}

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

Array Index Out of Bounds Exception (Java)

This is Very Good Example of minus Length of an array in java, i am giving here both examples

 public static int linearSearchArray(){

   int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
   int key = 7;
   int i = 0;
   int count = 0;
   for ( i = 0; i< arrayOFInt.length; i++){
        if ( arrayOFInt[i]  == key ){
         System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
         count ++;
        }
   }

   System.out.println("this Element found the ("+ count +") number of Times");
return i;  
}

this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.

What is an NP-complete in computer science?

NP stands for Non-deterministic Polynomial time.

This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.

The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.

Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.

Time in milliseconds in C

Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

How to search a list of tuples in Python

Your tuples are basically key-value pairs--a python dict--so:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]

Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:

d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

Capitalize words in string

This should cover most basic use cases.

const capitalize = (str) => {
    if (typeof str !== 'string') {
      throw Error('Feed me string')
    } else if (!str) {
      return ''
    } else {
      return str
        .split(' ')
        .map(s => {
            if (s.length == 1 ) {
                return s.toUpperCase()
            } else {
                const firstLetter = s.split('')[0].toUpperCase()
                const restOfStr = s.substr(1, s.length).toLowerCase()
                return firstLetter + restOfStr
            }     
        })
        .join(' ')
    }
}


capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week

Edit: Improved readability of mapping.

How do you use script variables in psql?

FWIW, the real problem was that I had included a semicolon at the end of my \set command:

\set owner_password 'thepassword';

The semicolon was interpreted as an actual character in the variable:

\echo :owner_password thepassword;

So when I tried to use it:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

...I got this:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").

The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

Zip folder in C#

In .NET 4.5 the ZipFile.CreateFromDirectory(startPath, zipPath); method does not cover a scenario where you wish to zip a number of files and sub-folders without having to put them within a folder. This is valid when you wish the unzip to put the files directly within the current folder.

This code worked for me:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

Folders don't need to be "created" in the zip-archive. The second parameter "entryName" in CreateEntryFromFile should be a relative path, and when unpacking the zip-file the directories of the relative paths will be detected and created.

Python Finding Prime Factors

def find_prime_facs(n):
  list_of_factors=[]
  i=2
  while n>1:
    if n%i==0:
      list_of_factors.append(i)
      n=n/i
      i=i-1
    i+=1  
  return list_of_factors

how can the textbox width be reduced?

<input type='text' 
       name='t1'
       id='t1'
       maxlength=10
       placeholder='typing some text' >
<p></p>

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

What does <a href="#" class="view"> mean?

I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.

<a href="#" class="view">

The

href="#"

part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:

<a href="#news">Go to news</a>

will take you to wherever you have the

<a name="news"></a>

code. So if you specify # without any name like in your case, the link leads nowhere.

The

class="view"

part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.

To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.

Search your source code for something like:

<script type="text/javascript"> bla bla bla </script>

or

<script> bla bla bla </script>

and then search for any reference to your "view"-class. An included javascript file can look something like this:

<script type="text/javascript" src="include/javascript.js"></script>

In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head> and </head> or close to the </body>-tag.

A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.

In many text editors you can open all the files at once, and then search in them all for something.

How do I use a C# Class Library in a project?

Add a reference to it in your project and a using clause at the top of the CS file where you want to use it.

Adding a reference:

  1. In Visual Studio, click Project, and then Add Reference.
  2. Click the Browse tab and locate the DLL you want to add a reference to.
    NOTE: Apparently using Browse is bad form if the DLL you want to use is in the same project. Instead, right-click the Project and then click Add Reference, then select the appropriate class from the Project tab:
    enter image description here
  3. Click OK.

Adding a using clause:

Add "using [namespace];" to the CS file where you want to reference your library. So, if the library you want to reference has a namespace called MyLibrary, add the following to the CS file:

using MyLibrary;

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

What is 'Currying'?

Currying is one of the higher-order functions of Java Script.

Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

Confused?

Let see an example,

function add(a,b)
    {
        return a+b;
    }
add(5,6);

This is similar to the following currying function,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }
var curryAdd = add(5);
curryAdd(6);

So what does this code means?

Now read the definition again,

Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

Still, Confused? Let me explain in deep!

When you call this function,

var curryAdd = add(5);

It will return you a function like this,

curryAdd=function(y){return 5+y;}

So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script. So come back to the currying,

This line will pass the second argument to the curryAdd function.

curryAdd(6);

which in turns results,

curryAdd=function(6){return 5+6;}
// Which results in 11

Hope you understand the usage of currying here. So, Coming to the advantages,

Why Currying?

It makes use of code reusability. Less code, Less Error. You may ask how it is less code?

I can prove it with ECMA script 6 new feature arrow functions.

Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }

With the help of the arrow function, we can write the above function as follows,

x=>y=>x+y

Cool right?

So, Less Code and Fewer bugs!!

With the help of these higher-order function one can easily develop a bug-free code.

I challenge you!

Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

Thanks, Have a nice day!

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Restarting Android Studio fix the issue for me.

CSS vertical-align: text-bottom;

if your text doesn't spill over two rows then you can do line-height: ; in your CSS, the more line-height you give, the lower on the container it will hold.

Javascript ES6/ES5 find in array and change

Given a changed object and an array:

const item = {...}
let items = [{id:2}, {id:3}, {id:4}];

Update the array with the new object by iterating over the array:

items = items.map(x => (x.id === item.id) ? item : x)

Cell spacing in UICollectionView

My solution in Swift 3 cell line spacing like in Instagram:

enter image description here

lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.rgb(red: 227, green: 227, blue: 227)
    cv.showsVerticalScrollIndicator = false
    layout.scrollDirection = .vertical
    layout.minimumLineSpacing = 1
    layout.minimumInteritemSpacing = 1
    return cv
}()

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    switch UIDevice.current.modelName {
    case "iPhone 4":
        return CGSize(width: 106, height: 106)
    case "iPhone 5":
        return CGSize(width: 106, height: 106)
    case "iPhone 6,7":
        return CGSize(width: 124, height: 124)
    case "iPhone Plus":
        return CGSize(width: 137, height: 137)
    default:
        return CGSize(width: frame.width / 3, height: frame.width / 3)
    }
}

How to detect device programmaticlly: https://stackoverflow.com/a/26962452/6013170

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

How to send image to PHP file using Ajax?

Use JavaScript's formData API and set contentType and processData to false

$("form[name='uploader']").on("submit", function(ev) {
  ev.preventDefault(); // Prevent browser default submit.

  var formData = new FormData(this);
    
  $.ajax({
    url: "page.php",
    type: "POST",
    data: formData,
    success: function (msg) {
      alert(msg)
    },
    cache: false,
    contentType: false,
    processData: false
  });
    
});

Hashset vs Treeset

One advantage not yet mentioned of a TreeSet is that its has greater "locality", which is shorthand for saying (1) if two entries are nearby in the order, a TreeSet places them near each other in the data structure, and hence in memory; and (2) this placement takes advantage of the principle of locality, which says that similar data is often accessed by an application with similar frequency.

This is in contrast to a HashSet, which spreads the entries all over memory, no matter what their keys are.

When the latency cost of reading from a hard drive is thousands of times the cost of reading from cache or RAM, and when the data really is accessed with locality, the TreeSet can be a much better choice.

How to redirect both stdout and stderr to a file

If you want to log to the same file:

command1 >> log_file 2>&1

If you want different files:

command1 >> log_file 2>> err_file

RecyclerView onClick

The RecyclerView does not have a OnClickListener and will have to implement it ourselves.

I like to add a OnItemClickListener interface in Adapter with an onClick method invoked when you click on the item view from the ViewHolder. Thus the responsibility of managing the click on an item is outside the ViewHolder and Adapter. Will the activity or fragment which will decide what to do

Add an interface to the listener and the listener object.

public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {

  ...

  private static OnItemClickListener onItemClickListener;

  ...

  public static interface OnItemClickListener {
      public void onItemClick(View view, int position);
  }

  ...
}

We capture the click of the root view of the item and when the callback is triggered onClick listener call on the adapter .

public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {

  ...

  private static OnItemClickListener onItemClickListener;

  ...

  public static interface OnItemClickListener {
      public void onItemClick(View view, int position);
  }

  ...

  public static class ViewHolder extends RecyclerView.ViewHolder {
      public ImageView imageView;

      public ViewHolder(View itemRootView) {
          super(itemRootView);
          imageView = (ImageView) itemRootView.findViewById(R.id.itemImage);

          itemRootView.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  int position  = ViewHolder.super.getAdapterPosition();
                  onItemClickListener.onItemClick(view,position);
              }
          });
      }
  }
}

Since the activity or fragment , fragment in our case , we assign a listener to the adapter and the onClick callback we will get the selected item by position and opened a detailed activity of item.

public class ItemsFragment extends Fragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       ...    
        ((ItemsAdapter) adapter).setOnItemClickListener(new ItemsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //Do something when an item has been clicked
            }
        });
        ...
    }
...
}

Spring Rest POST Json RequestBody Content type not supported

I met the same problem which i solved by deserializing myself the posted value :

@RequestMapping(value = "/arduinos/commands/{idArduino}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String sendCommandesJson(@PathVariable("idArduino") String idArduino, HttpServletRequest request) throws IOException {
    // getting the posted value
    String body = CharStreams.toString(request.getReader());
    List<ArduinoCommand> commandes = new ObjectMapper().readValue(body, new TypeReference<List<ArduinoCommand>>() {
    });

with theses gradle dependencies :

  compile('org.springframework.boot:spring-boot-starter-web')
  compile('com.google.guava:guava:16.0.1')

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

How to find if a given key exists in a C++ std::map

Use map::find

if ( m.find("f") == m.end() ) {
  // not found
} else {
  // found
}

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.

However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like

kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987 

it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

How to redirect to Index from another controller?

Tag helpers:

<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>

In the controller.cs have a method:

public async Task<IActionResult> Index()
{
    ViewBag.Title = "Titles";
    return View(await Your_Model or Service method);
}

Adding a user on .htpasswd

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

How do I POST an array of objects with $.ajax (jQuery or Zepto)

I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.

First I stringify the data as

var myData = [];
   allData.forEach((x, index) => {
         // console.log(index);
         myData.push(JSON.stringify({
         "product_id" : x.product_id,
         "product" : x.product,
         "url" : x.url,
         "image_url" : x.image_url,
         "price" : x.price,
         "source": x.source
      }))
   })

Then I sent it like

$.ajax({
        url: '{% url "url_name" %}',
        method: "POST",
        data: {
           'csrfmiddlewaretoken': '{{ csrf_token }}',
           'queryset[]': myData
        },
        success: (res) => {
        // success post work here.
    }
})

And received as :

list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]

pip install returning invalid syntax

Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

Symfony 2 EntityManager injection in service

Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

Is there a limit on an Excel worksheet's name length?

I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear: basename error

And trying to move a not-too-long basename to a too-long-pathname is also very clear:enter image description here

The pathname error is deceptive, though. Quite unhelpful:enter image description here

This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.

How do I clone into a non-empty directory?

this is work for me ,but you should merge remote repository files to the local files:

git init
git remote add origin url-to-git
git branch --set-upstream-to=origin/master master
git fetch
git status

How to use jQuery to call an ASP.NET web service?

I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.

function InfoByDate(sDate, eDate){
    var divToBeWorkedOn = "#AjaxPlaceHolder";
    var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
    var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $(divToBeWorkedOn).html(msg.d);
        },
        error: function(e){
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}

I hope that helps.

Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.

How to set header and options in axios?

_x000D_
_x000D_
axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)
_x000D_
_x000D_
_x000D_

HTML input field hint

With a bit of JavaScript:

<input 
  value="Enter username..." 
  onfocus="if (this.value === 'Enter username...') this.value=''" ... />

HTML5 has a nice attribute for this, called placeholder:

<input placeholder="Enter username.." ... />

but this attribute is not supported in old browsers.

CSS background image to fit width, height should auto-scale in proportion

Just add this one line:

    .your-class {
        height: 100vh;
    }

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: Make div 100% height of browser window

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How to remove Firefox's dotted outline on BUTTONS as well as links?

Simply add this css for select box

select:-moz-focusring {
    color: transparent;
    text-shadow: 0 0 0 #000;
}

This is working fine for me.

array filter in python?

Yes, the filter function:

filter(lambda x: x not in subset_of_A, A)

Append a Lists Contents to another List C#

Try AddRange-method:

GlobalStrings.AddRange(localStrings);

Total size of the contents of all the files in a directory

du is handy, but find is useful in case if you want to calculate the size of some files only (for example, using filter by extension). Also note that find themselves can print the size of each file in bytes. To calculate a total size we can connect dc command in the following manner:

find . -type f -printf "%s + " | dc -e0 -f- -ep

Here find generates sequence of commands for dc like 123 + 456 + 11 +. Although, the completed program should be like 0 123 + 456 + 11 + p (remember postfix notation).

So, to get the completed program we need to put 0 on the stack before executing the sequence from stdin, and print the top number after executing (the p command at the end). We achieve it via dc options:

  1. -e0 is just shortcut for -e '0' that puts 0 on the stack,
  2. -f- is for read and execute commands from stdin (that generated by find here),
  3. -ep is for print the result (-e 'p').

To print the size in MiB like 284.06 MiB we can use -e '2 k 1024 / 1024 / n [ MiB] p' in point 3 instead (most spaces are optional).

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

You are calling local server with http://localhost:8080/foo/bar. Call it with https://localhost:8080/foo/bar. This solves the problem

How to set the size of button in HTML

button { 
  width:1000px; 
} 

or even

 button { 
    width:1000px !important
 } 

If thats what you mean

PHP code to convert a MySQL query to CSV

If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

These functions setup the headers:

function setExcelContentType() {
    if(headers_sent())
        return false;

    header('Content-type: application/vnd.ms-excel');
    return true;
}

function setDownloadAsHeader($filename) {
    if(headers_sent())
        return false;

    header('Content-disposition: attachment; filename=' . $filename);
    return true;
}

This one sends a CSV to a stream using a mysql result

function csvFromResult($stream, $result, $showColumnHeaders = true) {
    if($showColumnHeaders) {
        $columnHeaders = array();
        $nfields = mysql_num_fields($result);
        for($i = 0; $i < $nfields; $i++) {
            $field = mysql_fetch_field($result, $i);
            $columnHeaders[] = $field->name;
        }
        fputcsv($stream, $columnHeaders);
    }

    $nrows = 0;
    while($row = mysql_fetch_row($result)) {
        fputcsv($stream, $row);
        $nrows++;
    }

    return $nrows;
}

This one uses the above function to write a CSV to a file, given by $filename

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
    $fp = fopen($filename, 'w');
    $rc = csvFromResult($fp, $result, $showColumnHeaders);
    fclose($fp);
    return $rc;
}

And this is where the magic happens ;)

function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
    setExcelContentType();
    setDownloadAsHeader($asFilename);
    return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

For example:

$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);

Assign output of os.system to a variable and prevent it from being displayed on the screen

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.


Here's the corresponding code for subprocess:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out

iOS: set font size of UILabel Programmatically

In Swift 3.0, you could use this code below:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView

Does an HTTP Status code of 0 have any meaning?

from documentation http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute means a request was cancelled before going anywhere

Android SharedPreferences in Fragment

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

How to get the next auto-increment id in mysql

This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.

SELECT AUTO_INCREMENT 
FROM information_schema.tables
WHERE table_name = 'your_table_name'
     and table_schema = 'your_database_name';

SELECT AUTO_INCREMENT 
FROM information_schema.tables
WHERE table_name = 'your_table_name'
     and table_schema = database();

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

Delete specific line number(s) from a text file using sed?

This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;

grep -nh error logfile | cut -d: -f1 | deletelines logfile

(where deletelines is the utility you are imagining you need) is the same as

grep -v error logfile

Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed.

sed 's%$%d%' linenumbers

This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d appended after each. This is a valid sed script, which we can save to a file, or (on some platforms) pipe to another sed instance:

sed 's%$%d%' linenumbers | sed -f - logfile

On some platforms, sed -f does not understand the option argument - to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin or /proc/$pid/fd/1 if your OS (or shell) has that.

As always, you can add -i before the -f option to have sed edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i as well; a common idiom is to supply an empty argument; -i ''.

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

Define a global variable in a JavaScript function

Just declare it outside the functions, and assign values inside the functions. Something like:

<script type="text/javascript">
    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage = null ;  // Global variable
    function makeObj(address) {
        trailimage = [address, 50, 50];  // Assign value

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: http://jsfiddle.net/qCrGE/

var globalOne = 3;
testOne();

function testOne()
{
    globalOne += 2;
    alert("globalOne is :" + globalOne );
    globalOne += 1;
}

alert("outside globalOne is: " + globalOne);

testTwo();

function testTwo()
{
    globalTwo = 20;
    alert("globalTwo is " + globalTwo);
    globalTwo += 5;
}

alert("outside globalTwo is:" + globalTwo);

JavaScript: client-side vs. server-side validation

You must always validate on the server.

Also having validation on the client is nice for users, but is utterly insecure.

How do I match any character across multiple lines in a regular expression?

Option 1

One way would be to use the s flag (just like the accepted answer):

/(.*)<FooBar>/s

Demo 1

Option 2

A second way would be to use the m (multiline) flag and any of the following patterns:

/([\s\S]*)<FooBar>/m

or

/([\d\D]*)<FooBar>/m

or

/([\w\W]*)<FooBar>/m

Demo 2

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Wpf control size to content?

If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

VB.net: Date without time

I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.

Code

   Dim d As DateTime = Now
   Debug.WriteLine(d.ToLongDateString)
   Debug.WriteLine(d.ToShortDateString)
   Debug.WriteLine(d.ToString("d"))
   Debug.WriteLine(d.ToString("yyyy-MM-dd"))

Results

Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10

Note that these results will vary depending on the culture settings on your computer.

Staging Deleted files

To stage all manually deleted files you can use:

git rm $(git ls-files --deleted)

To add an alias to this command as git rm-deleted, run:

git config --global alias.rm-deleted '!git rm $(git ls-files --deleted)'

What are the most useful Intellij IDEA keyboard shortcuts?

Some of the time savers:

  1. Alt + Enter : show intention actions (like Eclipse quick fix)
  2. Ctrl + Alt + V : introduce variable (never type the left hand side of an assignment again)
  3. Ctrl + Shift + Space : smart completion ( even two levels down since IntelliJ 8 )
  4. Ctrl + W : select succesively increasing code blocks. Kind of obvious but a real time saver!

The Canoo blog contains some (+8) articles on some more advanced IntelliJ keyboard shortcuts.

The Key Promoter and Shortcut keys list plugins are really helpful for (constantly) learning new IntelliJ keyboard shortcuts.

Change image source in code behind - Wpf

You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

Android: Internet connectivity change listener

This should work:

public class ConnectivityChangeActivity extends Activity {

    private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("app","Network connectivity change");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(networkChangeReceiver);
    }
}

How to code a very simple login system with java

Map<String, String> d = new HashMap<>();

void input(String u, String p, String e) {
    read();
    if (e.equals("login")) login(u, p);
    else if (e.equals("register")) register(u, p);
    write();
}

void read() {
    d = new HashMap<>();
    String s = "";
    try {
        s = new String(Files.readAllBytes(Paths.get("data.txt")));
    }catch(IOException e) {
        e.printStackTrace();
    }
    String [] pairs = s.split("\n");
    for (int i = 0; i < pairs.length; i++) {
        d.put(pairs[i].split(",")[0], pairs[i].split(",")[1]);
    }
}

void write() {
    try (FileWriter m = new FileWriter("data.txt")) {
        for (Map.Entry<String, String> entry : d.entrySet()) {
            m.write(entry.getKey() + "," + entry.getValue() + "\n");    
        }
        m.close();
    }catch (IOException e) {
        e.printStackTrace();
    }
}

boolean login(String u, String p) {
    return (d.get(u).equals(p)) ? true : false;
}

boolean register(String u, String p) {
    if (d.containsKey(u)) return false;
    d.put(u, p);
    return true;
}

Find and replace entire mysql database

I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.

Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.

Mind the collate in SET @stmt, it must match you database collation.

I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().

Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.

Hope it helps someone.

DELIMITER $$

DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
  DECLARE loop_done integer DEFAULT 0;
  DECLARE current_table varchar(255);
  DECLARE current_column varchar(255);
  DECLARE all_columns CURSOR FOR
  SELECT
    t.table_name,
    c.column_name
  FROM information_schema.tables t,
       information_schema.columns c
  WHERE t.table_schema = DATABASE()
  AND c.table_schema = DATABASE()
  AND t.table_name = c.table_name
  AND c.DATA_TYPE IN('varchar', 'text', 'longtext');

  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET loop_done = 1;

  OPEN all_columns;

table_loop:
LOOP
  FETCH all_columns INTO current_table, current_column;
  IF (loop_done > 0) THEN
    LEAVE table_loop;
  END IF;
  SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
  SET @stmt = REPLACE(@stmt, '|table|', current_table);
  SET @stmt = REPLACE(@stmt, '|column|', current_column);
  SET @stmt = REPLACE(@stmt, '|find|', find_string);
  SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
  PREPARE s1 FROM @stmt;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END LOOP;
END
$$

DELIMITER ;

Conditional Count on a field

Using ANSI SQL-92 CASE Statements, you could do something like this (derived table plus case):

 SELECT jobId, jobName, SUM(Priority1)
 AS Priority1, SUM(Priority2) AS
 Priority2, SUM(Priority3) AS
 Priority3, SUM(Priority4) AS
 Priority4,  SUM(Priority5) AS
 Priority5 FROM (
     SELECT jobId, jobName,
     CASE WHEN Priority = 1 THEN 1 ELSE 0 END AS Priority1,
     CASE WHEN Priority = 2 THEN 1 ELSE 0 END AS Priority2,
     CASE WHEN Priority = 3 THEN 1 ELSE 0 END AS Priority3,
     CASE WHEN Priority = 4 THEN 1 ELSE 0 END AS Priority4,
     CASE WHEN Priority = 5 THEN 1 ELSE 0 END AS Priority5
     FROM TableName


)

Can an ASP.NET MVC controller return an Image?

To expland on Dyland's response slightly:

Three classes implement the FileResult class:

System.Web.Mvc.FileResult
      System.Web.Mvc.FileContentResult
      System.Web.Mvc.FilePathResult
      System.Web.Mvc.FileStreamResult

They're all fairly self explanatory:

  • For file path downloads where the file exists on disk, use FilePathResult - this is the easiest way and avoids you having to use Streams.
  • For byte[] arrays (akin to Response.BinaryWrite), use FileContentResult.
  • For byte[] arrays where you want the file to download (content-disposition: attachment), use FileStreamResult in a similar way to below, but with a MemoryStream and using GetBuffer().
  • For Streams use FileStreamResult. It's called a FileStreamResult but it takes a Stream so I'd guess it works with a MemoryStream.

Below is an example of using the content-disposition technique (not tested):

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult GetFile()
    {
        // No need to dispose the stream, MVC does it for you
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
        FileStream stream = new FileStream(path, FileMode.Open);
        FileStreamResult result = new FileStreamResult(stream, "image/png");
        result.FileDownloadName = "image.png";
        return result;
    }

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

How to check the Angular version?

ng --version command returns the details of the version of Angular CLI installed

Increase days to php current Date()

The date_add() function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime object, it's much nicer to work with than the procedural functions in PHP.

HMAC-SHA256 Algorithm for signature calculation

The answer that you got there is correct. One minor thing in the code above, you need to init(key) before you can call doFinal()

    final Charset charSet = Charset.forName("US-ASCII");
    final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

    final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
    try {
        sha256_HMAC.init(secret_key);
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

Can the :not() pseudo-class have multiple arguments?

Starting from CSS Selectors 4 using multiple arguments in the :not selector becomes possible (see here).

In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.

Example:

/* In this example, all p elements will be red, except for 
   the first child and the ones with the class special. */

p:not(:first-child, .special) {
  color: red;
}

Unfortunately, browser support is limited. For now, it only works in Safari.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); 

TSQL: How to convert local time to UTC? (SQL Server 2008)

Here is the code to convert one zone DateTime to another zone DateTime

DECLARE @UTCDateTime DATETIME = GETUTCDATE();
DECLARE @ConvertedZoneDateTime DATETIME;

-- 'UTC' to 'India Standard Time' DATETIME
SET @ConvertedZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'
SELECT @UTCDateTime AS UTCDATE,@ConvertedZoneDateTime AS IndiaStandardTime

-- 'India Standard Time' to 'UTC' DATETIME
SET @UTCDateTime = @ConvertedZoneDateTime AT TIME ZONE 'India Standard Time' AT TIME ZONE 'UTC'
SELECT @ConvertedZoneDateTime AS IndiaStandardTime,@UTCDateTime AS UTCDATE

Note: AT TIME ZONE works only on SQL Server 2016+ and the advantage is that it automatically considers Daylight when converting to a particular Time zone

VBA error 1004 - select method of range class failed

You have to select the sheet before you can select the range.

I've simplified the example to isolate the problem. Try this:

Option Explicit


Sub RangeError()

    Dim sourceBook As Workbook
    Dim sourceSheet As Worksheet
    Dim sourceSheetSum As Worksheet

    Set sourceBook = ActiveWorkbook
    Set sourceSheet = sourceBook.Sheets("Sheet1")
    Set sourceSheetSum = sourceBook.Sheets("Sheet2")

    sourceSheetSum.Select

    sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

End Sub

Replace Sheet1 and Sheet2 with your sheet names.

IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Error Code: 2013. Lost connection to MySQL server during query

Change "read time out" time in Edit->Preferences->SQL editor->MySQL session

how to fetch array keys with jQuery?

console.log( Object.keys( {'a':1,'b':2} ) );

How do I compile a .c file on my Mac?

You will need to install the Apple Developer Tools. Once you have done that, the easiest thing is to either use the Xcode IDE or use gcc, or nowadays better cc (the clang LLVM compiler), from the command line.

According to Apple's site, the latest version of Xcode (3.2.1) only runs on Snow Leopard (10.6) so if you have an earlier version of OS X you will need to use an older version of Xcode. Your Mac should have come with a Developer Tools DVD which will contain a version that should run on your system. Also, the Apple Developer Tools site still has older versions available for download. Xcode 3.1.4 should run on Leopard (10.5).

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Merge (with squash) all changes from another branch as a single commit

git merge --squash <feature branch> is a good option .The "git commit" tells you all feature branch commit message with your choice to keep it .

For less commit merge .

git merge do x times --git reset HEAD^ --soft then git commit .

Risk - deleted files may come back .

How to create hyperlink to call phone number on mobile devices?

I used:

Tel: <a href="tel:+123 123456789">+123 123456789</a>

and the result is:

Tel: +123 123456789

Where "Tel:" stands for pure text and only the number is coded and clickable.

c# open a new form then close the current form?

private void buttonNextForm(object sender, EventArgs e)
{
    NextForm nf = new NextForm();//Object of the form that you want to open
    this.hide();//Hide cirrent form.
    nf.ShowModel();//Display the next form window
    this.Close();//While closing the NextForm, control will come again and will close this form as well
}

How to call a Parent Class's method from Child Class in Python?

I would recommend using CLASS.__bases__ something like this

class A:
   def __init__(self):
        print "I am Class %s"%self.__class__.__name__
        for parentClass in self.__class__.__bases__:
              print "   I am inherited from:",parentClass.__name__
              #parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

How to return a resolved promise from an AngularJS Service using $q?

To return a resolved promise, you can use:

return $q.defer().resolve();

If you need to resolve something or return data:

return $q.defer().resolve(function(){

    var data;
    return data;

});

How to remove all line breaks from a string

This will replace the line break by empty space.

someText = someText.replace(/(\r\n|\n|\r)/gm,"");

Read more on this article.

How to add a jar in External Libraries in android studio

If anyone is looking for another solution without actually copying the jar file(s) into the project directory, e.g. when using a jar in multiple projects:

Open build.gradle and add

def myJarFolder = 'C:/Path/To/My/Jars'

[...]

dependencies {
    [...]
    compile fileTree(dir: myJarFolder + '/jar/Sub/Folder/1', include: ['*.jar'])
    compile fileTree(dir: myJarFolder + '/jar/Sub/Folder/2', include: ['*.jar'])
    [...]
}

Note that of course you don't have to use the myJarFolder variable, I find it useful though. The path can also be relative, e.g. ../../Path/To/My/Jars.
Tested with AndroidStudio 3.0

Update: For Gradle Plugin > 3.0 use implementation instead of compile:

dependencies {
        [...]
        implementation fileTree(dir: myJarFolder + '/jar/Sub/Folder/1', include: ['*.jar'])
        implementation fileTree(dir: myJarFolder + '/jar/Sub/Folder/2', include: ['*.jar'])
        [...]
    }

Textarea that can do syntax highlighting on the fly?

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

_x000D_
_x000D_
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');


var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');
  }

  return text;
}

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);
  $highlights.html(highlightedText);
}

function handleScroll() {
  var scrollTop = $textarea.scrollTop();
  $backdrop.scrollTop(scrollTop);

  var scrollLeft = $textarea.scrollLeft();
  $backdrop.scrollLeft(scrollLeft);
}

function fixIOS() {
  $highlights.css({
    'padding-left': '+=3px',
    'padding-right': '+=3px'
  });
}

function bindEvents() {
  $textarea.on({
    'input': handleInput,
    'scroll': handleScroll
  });
}

if (isIOS) {
  fixIOS();
}

bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;
}

.container,
.backdrop,
textarea {
  width: 460px;
  height: 180px;
}

.highlights,
textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;
}

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;
}

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;
}

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;
}

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;
}

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  </div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
_x000D_
_x000D_

Original Pen: https://codepen.io/lonekorean/pen/gaLEMR

Sound alarm when code finishes

This one seems to work on both Windows and Linux* (from this question):

def beep():
    print("\a")

beep()

In Windows, can put at the end:

import winsound
winsound.Beep(500, 1000)

where 500 is the frequency in Herz
      1000 is the duration in miliseconds

To work on Linux, you may need to do the following (from QO's comment):

  • in a terminal, type 'cd /etc/modprobe.d' then 'gksudo gedit blacklist.conf'
  • comment the line that says 'blacklist pcspkr', then reboot
  • check also that the terminal preferences has the 'Terminal Bell' checked.

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How to edit Docker container files from the host?

The best way is:

  $ docker cp CONTAINER:FILEPATH LOCALFILEPATH
  $ vi LOCALFILEPATH
  $ docker cp LOCALFILEPATH CONTAINER:FILEPATH

Limitations with $ docker exec: it can only attach to a running container.

Limitations with $ docker run: it will create a new container.

HTML: how to make 2 tables with different CSS

<table id="table1"></table>
<table id="table2"></table>

or

<table class="table1"></table>
<table class="table2"></table>

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

First of all: Don't put secrets in clear text unless you know why it is a safe thing to do (i.e. you have assessed what damage can be done by an attacker knowing the secret).

If you are ok with putting secrets in your script, you could ship an ssh key with it and execute in an ssh-agent shell:

#!/usr/bin/env ssh-agent /usr/bin/env bash
KEYFILE=`mktemp`
cat << EOF > ${KEYFILE}
-----BEGIN RSA PRIVATE KEY-----
[.......]
EOF
ssh-add ${KEYFILE}

# do your ssh things here...

# Remove the key file.
rm -f ${KEYFILE}

A benefit of using ssh keys is that you can easily use forced commands to limit what the keyholder can do on the server.

A more secure approach would be to let the script run ssh-keygen -f ~/.ssh/my-script-key to create a private key specific for this purpose, but then you would also need a routine for adding the public key to the server.

How to invoke a Linux shell command from Java

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

Character reading from file in Python

This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.

>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I don‘t like this

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)

Disable submit button on form submit

Do it onSubmit():

$('form#id').submit(function(){
    $(this).find(':input[type=submit]').prop('disabled', true);
});

What is happening is you're disabling the button altogether before it actually triggers the submit event.

You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.

Demonstration: http://jsfiddle.net/userdude/2hgnZ/

(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)

SSL Error: CERT_UNTRUSTED while using npm command

You can bypass https using below commands:

npm config set strict-ssl false

or set the registry URL from https or http like below:

npm config set registry="http://registry.npmjs.org/"

However, Personally I believe bypassing https is not the real solution, but we can use it as a workaround.

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

Check if a variable is null in plsql

Another way:

var := coalesce (var, 5);

COALESCE is the ANSI equivalent (more or less) of Oracle's NVL function.

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Vertically aligning a checkbox

Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.

Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):

input {
    width: 20px;

    position: relative;
    left: 200px;

    vertical-align: middle;
}

label {  
    width: 200px;

    position: relative;
    left: -20px;

    display: inline-block;
    vertical-align: middle;
}

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

The method shouldShowRequestPermissionRationale() can be used to check whether the user selected the 'never asked again' option and denied the permission. There's plenty of code examples, so I would rather explain how to use it for such a purpose, because I think its name and its implementation makes this more complicated that it actually is.

As explained in Requesting Permissions at Run Time, that method returns true if the option 'never ask again' is visible, false otherwise; so it returns false the very first time a dialog is shown, then from the second time on it returns true, and only if the user deny the permission selecting the option, at that point it returns false again.

To detect such a case, either you can detect the sequence false-true-false, or (more simple) you can have a flag which keeps track of the initial time the dialog is shown. After that, that method returns either true or false, where the false will allow you to detect when the option is selected.

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Is "delete this" allowed in C++?

Yes, delete this; has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete (§[expr.delete]) doesn't mention delete this; specifically at all. The section on destrucors does mention delete this in one place (§[class.dtor]/13):

At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).

That tends to support the idea that the standard considers delete this; to be valid--if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this; at all, as far as I know.

Anyway, some consider delete this a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.

The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When start to you make a phone call, something takes note of that and creates a phone_call object. From that point onward, the phone_call object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call object is based on when the first person starts the call and when the last people leave the call--from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.

For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Parsing JSON objects for HTML table

Here is an another way to parse json object into Html table

_x000D_
_x000D_
//EXTRACT VALUE FOR HTML HEADER._x000D_
// ('Book ID', 'Book Name', 'Category' and 'Price')_x000D_
var col = [];_x000D_
_x000D_
for (var i = 0; i < d.length; i++) {_x000D_
  for (var key in d[i]) {_x000D_
if (col.indexOf(key) === -1) {_x000D_
  col.push(key);_x000D_
}_x000D_
  }_x000D_
}_x000D_
_x000D_
// CREATE DYNAMIC TABLE._x000D_
var table = document.createElement("table");_x000D_
_x000D_
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE._x000D_
var tr = table.insertRow(-1);    // TABLE ROW.               _x000D_
                 _x000D_
for (var i = 0; i < col.length; i++) {_x000D_
  var th = document.createElement("th");// TABLE HEADER._x000D_
  th.innerHTML = col[i];_x000D_
  tr.appendChild(th);_x000D_
}_x000D_
_x000D_
// ADD JSON DATA TO THE TABLE AS ROWS._x000D_
for (var i = 0; i < d.length; i++) {_x000D_
  tr = table.insertRow(-1);_x000D_
_x000D_
  for (var j = 0; j < col.length; j++) {_x000D_
var tabCell = tr.insertCell(-1);_x000D_
tabCell.innerHTML = d[i][col[j]];_x000D_
  }_x000D_
}_x000D_
_x000D_
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER._x000D_
var divContainer = document.getElementById("showData");_x000D_
divContainer.innerHTML = "";_x000D_
divContainer.appendChild(table);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Protect image download

There is no way to protect image downloading. This is because the image has to be downloaded by the browser for it to be seen by the user. There are tricks (like the transparent background you specified) to restrict certain operations like image right click and saving to browser cache folder, but there isn't a way for truly protecting the images.

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

Converting a column within pandas dataframe from int to string

Use the following code:

df.column_name = df.column_name.astype('str')

Count cells that contain any text

The criterium should be "?*" and not "<>" because the latter will also count formulas that contain empty results, like ""

So the simplest formula would be

=COUNTIF(Range,"?*")

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

With thymeleaf you may add:

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I was facing a similar issue. Actually the command is :

java -version and not java --version.

You will get output something like this:

java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

Difference between F5, Ctrl + F5 and click on refresh button?

F5 is a standard page reload.

and

Ctrl + F5 refreshes the page by clearing the cached content of the page.

Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.

Twitter Bootstrap modal on mobile devices

Found a very hacky solution to this problem, but it works. I added a class to the link that is used to open the modal (With the data-target), then using Jquery, added a click event to that class that gets the data-target, finds the modal it is supposed to open, and then opens it via Javascript. Works just fine for me. I also added a mobile check on mine so that it only runs on mobile, but that's not required.

$('.forceOpen').click(function() {
  var id = $(this).attr('data-target');
  $('.modal').modal('hide');
  $(id).modal('show');
});

launch sms application with an intent

Intent eventIntentMessage =getPackageManager()
 .getLaunchIntentForPackage(Telephony.Sms.getDefaultSmsPackage(getApplicationContext));
startActivity(eventIntentMessage);

How to pass ArrayList<CustomeObject> from one activity to another?

you need implements Parcelable in your ContactBean class, I put one example for you:

public class ContactClass implements Parcelable {

private String id;
private String photo;
private String firstname;
private String lastname;

public ContactClass()
{

}

private ContactClass(Parcel in) {
    firstname = in.readString();
    lastname = in.readString();
    photo = in.readString();
    id = in.readString();

}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(firstname);
    dest.writeString(lastname);
    dest.writeString(photo);
    dest.writeString(id);

}

 public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
        public ContactClass createFromParcel(Parcel in) {
            return new ContactClass(in);
        }

        public ContactClass[] newArray(int size) {
            return new ContactClass[size];

        }
    };

   // all get , set method 
 }

and this get and set for your code:

Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);

second class:

ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");

How to downgrade Node version

If you are on macOS and are not using NVM, the simplest way is to run the installer that comes from node.js web site. It it clever enough to manage substitution of your current installation with the new one, even if it is an older one. At least this worked for me.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Get the last item in an array

Here's more Javascript art if you came here looking for it

In the spirit of another answer that used reduceRight(), but shorter:

[3, 2, 1, 5].reduceRight(a => a);

It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.

Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.

And now for the serious answer

The best way I see (considering you want it more concise than array[array.length - 1]) is this:

const last = a => a[a.length - 1];

Then just use the function:

last([3, 2, 1, 5])

The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:

[3, 2, 1, 5][[3, 2, 1, 5].length - 1]

Ugh.

For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:

last("1.2.3".split("."));

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

Is there a performance difference between a for loop and a for-each loop?

It's always better to use the iterator instead of indexing. This is because iterator is most likely optimzied for the List implementation while indexed (calling get) might not be. For example LinkedList is a List but indexing through its elements will be slower than iterating using the iterator.

Bypass invalid SSL certificate errors when calling web services in .Net

I solved it this way:

Call the following just before calling your ssl webservice that cause that error:

using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

/// <summary>
/// solution for exception
/// System.Net.WebException: 
/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
/// </summary>
public static void BypassCertificateError()
{
    ServicePointManager.ServerCertificateValidationCallback +=

        delegate(
            Object sender1,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };
}

Less than or equal to

In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

where compare-op may be one of:

    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal

That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.

How to prevent ENTER keypress to submit a web form?

You will find this more simple and useful :D

$(document).on('submit', 'form', function(e){
    /* on form submit find the trigger */
    if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
        /* if the trigger is not between selectors list, return super false */
        e.preventDefault();
        return false;
    } 
});

Environment variable substitution in sed

Actually, the simplest thing (in GNU sed, at least) is to use a different separator for the sed substitution (s) command. So, instead of s/pattern/'$mypath'/ being expanded to s/pattern//my/path/, which will of course confuse the s command, use s!pattern!'$mypath'!, which will be expanded to s!pattern!/my/path!. I’ve used the bang (!) character (or use anything you like) which avoids the usual, but-by-no-means-your-only-choice forward slash as the separator.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

How do I know if jQuery has an Ajax request pending?

$.active returns the number of active Ajax requests.

More info here

How to add icons to React Native app

If you're using expo just place an 1024 x 1024 png file in your project and add an icon property to your app.json i.e. "icon": "./src/assets/icon.png"

https://docs.expo.io/versions/latest/guides/app-icons

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

When to use DataContract and DataMember attributes?

  1. Data contract: It specifies that your entity class is ready for Serialization process.

  2. Data members: It specifies that the particular field is part of the data contract and it can be serialized.

Angular2: Cannot read property 'name' of undefined

This worked for me:

export class Hero{
   id: number;
   name: string;

   public Hero(i: number, n: string){
     this.id = 0;
     this.name = '';
   }
 }

and make sure you initialize as well selectedHero

selectedHero: Hero = new Hero();

JavaScript Array to Set

What levi said about passing it into the constructor is correct, but you could also use an object.

I think what Veverke is trying to say is that you could easily use the delete keyword on an object to achieve the same effect.

I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).

Try something like this:

var obj = {
    "bob": "dole",
    "mr.": "peabody",
    "darkwing": "duck"
};

Then, you could just do this:

delete obj["bob"];

The structure of the object would then be this:

{
    "mr.": "peabody",
    "darkwing": "duck"
}

Which has the same effect.

Generic Property in C#

You just declare the property the normal way using a generic type:

public MyType<string> PropertyName { get; set; }

If you want to call predefined methods to do something in the get or set, implement the property getter/setter to call those methods.

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

How to check a not-defined variable in JavaScript

Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}

Recursively add the entire folder to a repository

I just needed to do this, and I found that you can easily add files in subdirectories. You only need to be on the "top directory" of the repo, and then run something like:

$ git add ./subdir/file_in_subdir.txt

How to reenable event.preventDefault?

You can re-activate the actions by adding

this.delegateEvents();  // Re-activates the events for all the buttons

If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

tar: Error is not recoverable: exiting now

use sudo

sudo tar -zxvf xxxxxxxxx.tar.gz

Number of occurrences of a character in a string

Why use regex for that. String implements IEnumerable<char>, so you can just use LINQ.

test.Count(c => c == '&')

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

How to debug (only) JavaScript in Visual Studio?

Yes you can put the break-point on client side page in Visual studio

First Put the debugger in java-script code and run the page in browser

debugger

enter image description here

After that open your page in browser and view the inspect element you see the following view

enter image description here

How do I reverse a C++ vector?

You can use std::reverse like this

std::reverse(str.begin(), str.end());

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

None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...

How to convert a single char into an int

You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).

Therefore the integer value for any digit is the digit minus '0' (or 48).

char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'

is synonymous to

char c = '1';
int i = c - 48; // i is now equal to 1, not '1'

However I find the first c - '0' far more readable.

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

Here's my 2 cents:

function range(start, count) {
  return Array.apply(0, Array(count))
    .map((element, index) => index + start);
}

How should I cast in VB.NET?

Cstr() is compiled inline for better performance.

CType allows for casts between types if a conversion operator is defined

ToString() Between base type and string throws an exception if conversion is not possible.

TryParse() From String to base typeif possible otherwise returns false

DirectCast used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast will return nothing in this instance

Table with 100% width with equal size columns

table {
    width: 100%;

    th, td {
        width: 1%;
    }
}

SCSS syntax

Java 8 Stream API to find Unique Object matching a property value

Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Refer the below code for usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

Person matchingPerson = objects.stream
                        .filter(p -> p.email().equals("testemail"))
                        .collect(onlyElement());

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

What is the difference between active and passive FTP?

Active mode: -server initiates the connection.

Passive mode: -client initiates the connection.

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

Disable resizing of a Windows Forms form

There is far more efficient answer: just put the following instructions in the Form_Load:

Me.MinimumSize = New Size(Width, Height)
Me.MaximumSize = Me.MinimumSize

You must enable the openssl extension to download files via https

I use XAMPP. In C:\xampp\php\php.ini, the entry for openssl did not exist, so I added "extension=php_openssl.dll" on line 989, and composer worked.

Eclipse java debugging: source not found

Click -> Edit Source Lookup Path

after then

Click -> Add finally select Java project and select project path.

Source: https://www.youtube.com/watch?v=IGIKPY6q1Qw

Vue.js data-bind style backgroundImage not working

I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.

Note the escaped \' in my example below.

<div :style="{
    height: '100px',
    backgroundColor: '#323232',
    backgroundImage: 'url(\'' + event.image + '\')',
    backgroundPosition: 'center center',
    backgroundSize: 'cover'
    }">
</div>

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

How do I measure time elapsed in Java?

i found this code to be useful when timing things:

public class Et {
    public Et() {
    reset();
    }
    public void reset() {
    t0=System.nanoTime();
    }
    public long t0() {
        return t0;
    }
    public long dt() {
        return System.nanoTime()-t0();
    }
    public double etms() {
    return etms(dt());
    }
    @Override public String toString() {
        return etms()+" ms.";
    }
    public static double etms(long dt) {
        return dt/1000000.; // 1_000_000. breaks cobertura
    }
    private Long t0;
}

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

What I have found is that TensorFlow 2.0 (I am using 2.0.0-alpha0) is not compatible with the latest version of Numpy i.e. v1.17.0 (and possibly v1.16.5+). As soon as TF2 is imported, it throws a huge list of FutureWarning, that looks something like this:

FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.

This also resulted in the allow_pickle error when tried to load imdb dataset from keras

I tried to use the following solution which worked just fine, but I had to do it every single project where I was importing TF2 or tf.keras.

np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)

The easiest solution I found was to either install numpy 1.16.1 globally, or use compatible versions of tensorflow and numpy in a virtual environment.

My goal with this answer is to point out that its not just a problem with imdb.load_data, but a larger problem vaused by incompatibility of TF2 and Numpy versions and may result in many other hidden bugs or issues.

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

OS X Terminal shortcut: Jump to beginning/end of line

I use a handy app called Karabiner to do this, and many other things. It's free and open source.

It's a keyboard remapper, with a lot of handy presets for many common remaps that people may want to do.

As you can see from the screenshot, this remap is included as a preset in Karabiner.

Screenshot of Karabiner preferences showing the preset to map cmd+left/right to ctrl+a/e

Hope this helps. Happy remapping!

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql