Programs & Examples On #Exec

This tag refers to the starting of another, subsidiary program. It is named after the family of POSIX system calls whose name starts with “exec” (notably “execve”) though similar concepts exist on other platforms as well, especially when combined with the starting up of another process.

PHP shell_exec() vs exec()

Here are the differences. Note the newlines at the end.

> shell_exec('date')
string(29) "Wed Mar  6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar  6 14:18:12 PST 2013"

> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"

> shell_exec('ifconfig')
string(1244) "eth0      Link encap:Ethernet  HWaddr 10:bf:44:44:22:33  \n          inet addr:192.168.0.90  Bcast:192.168.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n          TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:13151177627 (13.1 GB)  TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""

Note that use of the backtick operator is identical to shell_exec().

Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec only returns the last line, and ifconfig's last line happens to be blank.

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

php exec command (or similar) to not wait for result

This uses wget to notify a URL of something without waiting.

$command = 'wget -qO- http://test.com/data=data';
exec('nohup ' . $command . ' >> /dev/null 2>&1 & echo $!', $pid);

This uses ls to update a log without waiting.

$command = 'ls -la > content.log';
exec('nohup ' . $command . ' >> /dev/null 2>&1 & echo $!', $pid);

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Differences between fork and exec

Fork creates a copy of a calling process. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{

  //child code

  exit(0);

}

//parent code

wait(cpid);

// end

(for child process text(code),data,stack is same as calling process) child process executes code in if block.

EXEC replaces the current process with new process's code,data,stack. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{   
  //child code

  exec(foo);

  exit(0);    
}

//parent code

wait(cpid);

// end

(after exec call unix kernel clears the child process text,data,stack and fills with foo process related text/data) thus child process is with different code (foo's code {not same as parent})

How to execute cmd commands via Java

Try this link

You do not use "cd" to change the directory from which to run your commands. You need the full path of the executable you want to run.

Also, listing the contents of a directory is easier to do with the File/Directory classes

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

How do you run a .bat file from PHP?

on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL

$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");

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

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

How do I execute a Shell built-in command with a C function?

You can use the excecl command

int execl(const char *path, const char *arg, ...);

Like shown here

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

Alternatively, you can use the getcwd() function to get the current working directory:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

node.js execute system command synchronously

Native Node.js solution is:

const {execSync} = require('child_process');

const result = execSync('node -v'); //  this do the trick 

Just be aware that some commands returns Buffer instead of string. And if you need string just add encoding to execSync options:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8'});

... and it is also good to have timeout on sync exec:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8', timeout: 10000});

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

Redirecting exec output to a buffer or file

For sending the output to another file (I'm leaving out error checking to focus on the important details):

if (fork() == 0)
{
    // child
    int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    dup2(fd, 1);   // make stdout go to file
    dup2(fd, 2);   // make stderr go to file - you may choose to not do this
                   // or perhaps send stderr to another file

    close(fd);     // fd no longer needed - the dup'ed handles are sufficient

    exec(...);
}

For sending the output to a pipe so you can then read the output into a buffer:

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

How do I execute a string containing Python code in Python?

eval() is just for expressions, while eval('x+1') works, eval('x=1') won't work for example. In that case, it's better to use exec, or even better: try to find a better solution :)

Running a Python script from PHP

The above methods seem to be complex. Use my method as a reference.

I have these two files:

  • run.php

  • mkdir.py

Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.

run.php

_x000D_
_x000D_
<html>_x000D_
 <body>_x000D_
  <head>_x000D_
   <title>_x000D_
     run_x000D_
   </title>_x000D_
  </head>_x000D_
_x000D_
   <form method="post">_x000D_
_x000D_
    <input type="submit" value="GO" name="GO">_x000D_
   </form>_x000D_
 </body>_x000D_
</html>_x000D_
_x000D_
<?php_x000D_
 if(isset($_POST['GO']))_x000D_
 {_x000D_
  shell_exec("python /var/www/html/lab/mkdir.py");_x000D_
  echo"success";_x000D_
 }_x000D_
?>
_x000D_
_x000D_
_x000D_

mkdir.py

#!/usr/bin/env python    
import os    
os.makedirs("thisfolder");

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

How to execute an external program from within Node.js?

From the Node.js documentation:

Node provides a tri-directional popen(3) facility through the ChildProcess class.

See http://nodejs.org/docs/v0.4.6/api/child_processes.html

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

find: missing argument to -exec

For anyone else having issues when using GNU find binary in a Windows command prompt. The semicolon needs to be escaped with ^

find.exe . -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 ^;

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

I also got this problem and found quite simple solution. I have Samsung adb driver installed on my system. I tried "Update driver" -> "Let me pick" -> "Already installed drivers" -> Samsung adb driver. That worked well.

How to automatically crop and center an image

I created an angularjs directive using @Russ's and @Alex's answers

Could be interesting in 2014 and beyond :P

html

<div ng-app="croppy">
  <cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>

js

angular.module('croppy', [])
  .directive('croppedImage', function () {
      return {
          restrict: "E",
          replace: true,
          template: "<div class='center-cropped'></div>",
          link: function(scope, element, attrs) {
              var width = attrs.width;
              var height = attrs.height;
              element.css('width', width + "px");
              element.css('height', height + "px");
              element.css('backgroundPosition', 'center center');
              element.css('backgroundRepeat', 'no-repeat');
              element.css('backgroundImage', "url('" + attrs.src + "')");
          }
      }
  });

fiddle link

Abort Ajax requests using jQuery

We just had to work around this problem and tested three different approaches.

  1. does cancel the request as suggested by @meouw
  2. execute all request but only processes the result of the last submit
  3. prevents new requests as long as another one is still pending

_x000D_
_x000D_
var Ajax1 = {_x000D_
  call: function() {_x000D_
    if (typeof this.xhr !== 'undefined')_x000D_
      this.xhr.abort();_x000D_
    this.xhr = $.ajax({_x000D_
      url: 'your/long/running/request/path',_x000D_
      type: 'GET',_x000D_
      success: function(data) {_x000D_
        //process response_x000D_
      }_x000D_
    });_x000D_
  }_x000D_
};_x000D_
var Ajax2 = {_x000D_
  counter: 0,_x000D_
  call: function() {_x000D_
    var self = this,_x000D_
      seq = ++this.counter;_x000D_
    $.ajax({_x000D_
      url: 'your/long/running/request/path',_x000D_
      type: 'GET',_x000D_
      success: function(data) {_x000D_
        if (seq === self.counter) {_x000D_
          //process response_x000D_
        }_x000D_
      }_x000D_
    });_x000D_
  }_x000D_
};_x000D_
var Ajax3 = {_x000D_
  active: false,_x000D_
  call: function() {_x000D_
    if (this.active === false) {_x000D_
      this.active = true;_x000D_
      var self = this;_x000D_
      $.ajax({_x000D_
        url: 'your/long/running/request/path',_x000D_
        type: 'GET',_x000D_
        success: function(data) {_x000D_
          //process response_x000D_
        },_x000D_
        complete: function() {_x000D_
          self.active = false;_x000D_
        }_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
};_x000D_
$(function() {_x000D_
  $('#button').click(function(e) {_x000D_
    Ajax3.call();_x000D_
  });_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="button" type="button" value="click" />
_x000D_
_x000D_
_x000D_

In our case we decided to use approach #3 as it produces less load for the server. But I am not 100% sure if jQuery guarantees the call of the .complete()-method, this could produce a deadlock situation. In our tests we could not reproduce such a situation.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Can I use DIV class and ID together in CSS?

You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.

<p id="unique" class="x y z">Styled paragraph</p>

intl extension: installing php_intl.dll

I resolved this issue by adding PHP directory to PATH variable. I just appended ;C:\xampp\php to Path variable in Windows Environment Variables.

*.h or *.hpp for your class definitions

I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.

This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension

.hpp : C++ Headers

(Or .hxx, or .hh, or whatever)

This header is for C++ only.

If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.).

.h : C/C++ compatible or pure C Headers

This header can be included by both a C source, and a C++ source, directly or indirectly.

It can included directly, being protected by the __cplusplus macro:

  • Which mean that, from a C++ viewpoint, the C-compatible code will be defined as extern "C".
  • From a C viewpoint, all the C code will be plainly visible, but the C++ code will be hidden (because it won't compile in a C compiler).

For example:

#ifndef MY_HEADER_H
#define MY_HEADER_H

   #ifdef __cplusplus
      extern "C"
      {
   #endif

   void myCFunction() ;

   #ifdef __cplusplus
      } // extern "C"
   #endif

#endif // MY_HEADER_H

Or it could be included indirectly by the corresponding .hpp header enclosing it with the extern "C" declaration.

For example:

#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP

extern "C"
{
#include "my_header.h"
}

#endif // MY_HEADER_HPP

and:

#ifndef MY_HEADER_H
#define MY_HEADER_H

void myCFunction() ;

#endif // MY_HEADER_H

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

We could do without any xxxFactory, xxxManager or xxxRepository classes if we modeled the real world correctly:

Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
        .Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
        .OfType<User>().CreateNew("John Doe");

;-)

OS X Terminal UTF-8 issues

My terminal was just acting silly, not printing out åäö. I found (and set) this setting: enter image description here

Under Terminal -> Preferences... -> Profiles -> Advanced.

Seems to have fixed my problem.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

What are the most-used vim commands/keypresses?

Here's a tip sheet I wrote up once, with the commands I actually use regularly:

References

General

  • Nearly all commands can be preceded by a number for a repeat count. eg. 5dd delete 5 lines
  • <Esc> gets you out of any mode and back to command mode
  • Commands preceded by : are executed on the command line at the bottom of the screen
  • :help help with any command

Navigation

  • Cursor movement: ?h ?j ?k l?
  • By words:
    • w next word (by punctuation); W next word (by spaces)
    • b back word (by punctuation); B back word (by spaces)
    • e end word (by punctuation); E end word (by spaces)
  • By line:
    • 0 start of line; ^ first non-whitespace
    • $ end of line
  • By paragraph:
    • { previous blank line; } next blank line
  • By file:
    • gg start of file; G end of file
    • 123G go to specific line number
  • By marker:
    • mx set mark x; 'x go to mark x
    • '. go to position of last edit
    • ' ' go back to last point before jump
  • Scrolling:
    • ^F forward full screen; ^B backward full screen
    • ^D down half screen; ^U up half screen
    • ^E scroll one line up; ^Y scroll one line down
    • zz centre cursor line

Editing

  • u undo; ^R redo
  • . repeat last editing command

Inserting

All insertion commands are terminated with <Esc> to return to command mode.

  • i insert text at cursor; I insert text at start of line
  • a append text after cursor; A append text after end of line
  • o open new line below; O open new line above

Changing

  • r replace single character; R replace multiple characters
  • s change single character
  • cw change word; C change to end of line; cc change whole line
  • c<motion> changes text in the direction of the motion
  • ci( change inside parentheses (see text object selection for more examples)

Deleting

  • x delete char
  • dw delete word; D delete to end of line; dd delete whole line
  • d<motion> deletes in the direction of the motion

Cut and paste

  • yy copy line into paste buffer; dd cut line into paste buffer
  • p paste buffer below cursor line; P paste buffer above cursor line
  • xp swap two characters (x to delete one character, then p to put it back after the cursor position)

Blocks

  • v visual block stream; V visual block line; ^V visual block column
    • most motion commands extend the block to the new cursor position
    • o moves the cursor to the other end of the block
  • d or x cut block into paste buffer
  • y copy block into paste buffer
  • > indent block; < unindent block
  • gv reselect last visual block

Global

  • :%s/foo/bar/g substitute all occurrences of "foo" to "bar"
    • % is a range that indicates every line in the file
    • /g is a flag that changes all occurrences on a line instead of just the first one

Searching

  • / search forward; ? search backward
  • * search forward for word under cursor; # search backward for word under cursor
  • n next match in same direction; N next match in opposite direction
  • fx forward to next character x; Fx backward to previous character x
  • ; move again to same character in same direction; , move again to same character in opposite direction

Files

  • :w write file to disk
  • :w name write file to disk as name
  • ZZ write file to disk and quit
  • :n edit a new file; :n! edit a new file without saving current changes
  • :q quit editing a file; :q! quit editing without saving changes
  • :e edit same file again (if changed outside vim)
  • :e . directory explorer

Windows

  • ^Wn new window
  • ^Wj down to next window; ^Wk up to previous window
  • ^W_ maximise current window; ^W= make all windows equal size
  • ^W+ increase window size; ^W- decrease window size

Source Navigation

  • % jump to matching parenthesis/bracket/brace, or language block if language module loaded
  • gd go to definition of local symbol under cursor; ^O return to previous position
  • ^] jump to definition of global symbol (requires tags file); ^T return to previous position (arbitrary stack of positions maintained)
  • ^N (in insert mode) automatic word completion

Show local changes

Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff

Conversion from List<T> to array T[]

List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

 $("#test").keyup(
     function () {
         this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
     }
 );

@ViewChild in *ngIf

Angular 8+

You should add { static: false } as a second option for @ViewChild. This causes the query results to be resolved after change detection runs, allowing your @ViewChild to be updated after the value changes.

Example:

export class AppComponent {
    @ViewChild('contentPlaceholder', { static: false }) contentPlaceholder: ElementRef;

    display = false;

    constructor(private changeDetectorRef: ChangeDetectorRef) {
    }

    show() {
        this.display = true;
        this.changeDetectorRef.detectChanges(); // not required
        console.log(this.contentPlaceholder);
    }
}

Stackblitz example: https://stackblitz.com/edit/angular-d8ezsn

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

How do I get an empty array of any size in python?

If by "array" you actually mean a Python list, you can use

a = [0] * 10

or

a = [None] * 10

Draw horizontal rule in React Native

Why don't you do something like this?

<View
  style={{
    borderBottomWidth: 1,
    borderBottomColor: 'black',
    width: 400,
  }}
/>

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Add a shortcut:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

Start reacting to shortcuts:

$.Shortcuts.start();

Add a shortcut to “another” list:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

Activate “another” list:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

Stop (unbind event handlers):

$.Shortcuts.stop();


Tutorial:
http://www.stepanreznikov.com/js-shortcuts/

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

How do I enable EF migrations for multiple contexts to separate databases?

To update database type following codes in PowerShell...

Update-Database -context EnrollmentAppContext

*if more than one databases exist only use this codes,otherwise not necessary..

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

How to reduce the space between <p> tags?

Reduce space between paragraphs. If you are using blogger, you'd go to template, 'customize' then find 'add css' and paste this: p {margin:.7em 0 .7em 0} /*Reduces space between

from full line to approx. 1/2 line */ If you are just tagging your webpage, that's still what you would use, just put it into your css file(s).

I was an sgml template designer in the late 70s/early 80s and all this tagging is just a dtd within sgml (even if they are now trying to say that html5/css3 is 'not', YES IT STILL IS.) :)

You can find all this basic info at w3schools too you know. Really if you are learning how to do layout using tagging or even javascript, etc. you should start with w3schools. Some people say it is 'not always' right, but folks, I've been in IT since 1960 (age 12) and w3schools is best for beginners. Are some things wrong there? Ah, I dunno, I haven't found any mistake, although sometimes if you are a beginner you might need to read two viewpoints to truly grasp the sense of something. But do remember that you are NOT programming when you code a webpage, you are simply doing layout work. (Yell all you want folks, that's the truth of it.)

Convert Text to Uppercase while typing in Text box

set your CssClass property in textbox1 to "cupper", then in page content create new css class :

<style type="text/css">.cupper {text-transform:uppercase;}</style>

Then, enjoy it ...

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

How to get current domain name in ASP.NET

You can try the following code :

 Request.Url.Host +
    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)

How to deselect a selected UITableView cell?

Use the following method in the table view delegate's didSelectRowAtIndexpath (Or from anywhere)

[myTable deselectRowAtIndexPath:[myTable indexPathForSelectedRow] animated:YES];

TypeError: 'list' object is not callable while trying to access a list

To get elements of a list you have to use list[i] instead of list(i).

Changing upload_max_filesize on PHP

You can use also in the php file like this

<?php ini_set('upload_max_filesize', '200M'); ?>

Permissions for /var/www/html

I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.

1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)

2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.

3) add your user account to the group that has permission on the folder (mine was www-data).

go to link on button click - jquery

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:


Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <hr>
   <div ng-if="showFrom(message)">
       <div>From: {{message.from.name}}</div>
   </div>    
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{message.createdBy.name}}</div>
   </div>    
   <div ng-if="showTo(message)">
      <div>To: {{message.to.name}}</div>
   </div>    
</div>

Fiddle.

replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

Pinging an IP address using PHP and echoing the result

This works fine with hostname, reverse IP (for internal networks) and IP.

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

how to get the cookies from a php curl into a variable

Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.

I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.

You can use a code like this (adapted from TML response):

$cookies = Array();
$ch = curl_init('http://www.google.com/');
// Ask for the callback.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$result = curl_exec($ch);
var_dump($cookies);

function curlResponseHeaderCallback($ch, $headerLine) {
    global $cookies;
    if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
        $cookies[] = $cookie;
    return strlen($headerLine); // Needed by curl
}

This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.

OpenCV - Apply mask to a color image

The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:

assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3

alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb

Note that mask needs to be in range 0..1 for the operation to succeed. It is also assumed that 1.0 encodes keeping the foreground only, while 0.0 means keeping only the background.

If the mask may have the shape (h, w, 1), this helps:

alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))

Here np.atleast_3d(mask) makes the mask (h, w, 1) if it is (h, w) and np.squeeze(...) reshapes the result from (h, w, 3, 1) to (h, w, 3).

How to center a subview of UIView

This worked for me

childView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
childView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true

Return list using select new in LINQ

Your method's return value has to be a List<Project>.

Using select new you are creating an instance of an anonymous type, instead of a Project.

How to launch multiple Internet Explorer windows/tabs from batch file?

Try this so you allow enough time for the first process to start.. else it will spawn 2 processes because the first one is not still running when you run the second one... This can happen if your computer is too fast..

@echo off
start /d iexplore.exe http://google.com
PING 1.1.1.1 -n 1 -w 2000 >NUL
START /d iexplore.exe blablabla

replace blablabla with another address

Creating an XmlNode/XmlElement in C# without an XmlDocument?

XmlNodes come with an OwnerDocument property.

Perhaps you can just do:

//Node is an XmlNode pulled from an XmlDocument
XmlElement e = node.OwnerDocument.CreateElement("MyNewElement");
e.InnerText = "Some value";
node.AppendChild(e);

How do I use dataReceived event of the SerialPort Port Object in C#?

I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.

"static const" vs "#define" vs "enum"

It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:

  1. static const int var = 5;
  2. #define var 5
  3. enum { var = 5 };

Ignoring issues about the choice of name, then:

  • If you need to pass a pointer around, you must use (1).
  • Since (2) is apparently an option, you don't need to pass pointers around.
  • Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is.
  • (1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can.
  • (1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can.
  • Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5.
  • (1) cannot be used in places like switch statements; both (2) and (3) can.
  • (1) cannot be used to initialize static variables; both (2) and (3) can.
  • (2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that.
  • You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.

So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.

If you were asking about C++, then you'd use option (1) — the static const — every time.

Drop all data in a pandas dataframe

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

Write a function that returns the longest palindrome in a given string

This Solution is of O(n^2) complexity. O(1) is the space complexity.

public class longestPalindromeInAString {

        public static void main(String[] args) {
            String a =  "xyMADAMpRACECARwl"; 
            String res = "";
            //String longest = a.substring(0,1);
            //System.out.println("longest => " +longest);
            for (int i = 0; i < a.length(); i++) {
                String temp = helper(a,i,i);//even palindrome
                if(temp.length() > res.length()) {res = temp ;}
                temp = helper(a,i,i+1);// odd length palindrome
                if(temp.length() > res.length()) { res = temp ;}

            }//for
            System.out.println(res);
            System.out.println("length of " + res + " is " + res.length());

        }

        private static String helper(String a, int left, int right) {
            while(left>= 0 && right <= a.length() -1  &&  a.charAt(left) == a.charAt(right)) {
                left-- ;right++ ;
            }
            String curr = a.substring(left + 1 , right);
            System.out.println("curr =>" +curr);
            return curr ;
        }

    }

Using jQuery, Restricting File Size Before Uploading

I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('loadfile').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').size;
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           alert(imgkbytes+' KB');
    }else {
           var fileInput = $("#loadfile")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
                   alert(imgkbytes+' KB');
     }
}    
</script>

Add Jquery library also.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.

So in your code you could have:

strFolder = Wscript.Arguments.Item(0) 

Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing

Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.

MS Technet examples

Date Difference in php on days?

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

Grant Select on a view not base table when base table is in a different database

I tried this in one of my databases.

To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.

Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.

npm - how to show the latest version of a package

As of October 2014:

npm view illustration

For latest remote version:

npm view <module_name> version  

Note, version is singular.

If you'd like to see all available (remote) versions, then do:

npm view <module_name> versions

Note, versions is plural. This will give you the full listing of versions to choose from.

To get the version you actually have locally you could use:

npm list --depth=0 | grep <module_name>

Note, even with package.json declaring your versions, the installed version might actually differ slightly - for instance if tilda was used in the version declaration

Should work across NPM versions 1.3.x, 1.4.x, 2.x and 3.x

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

How do I add a auto_increment primary key in SQL Server database?

In SQL Server 2008:

  • Right click on table
  • Go to design
  • Select numeric datatype
  • Add Name to the new column
  • Make Identity Specification to 'YES'

How do I get the old value of a changed cell in Excel VBA?

I needed this feature and I did not like all the solutions above after trying most as they are either

  1. Slow
  2. Have complex implications like using application.undo.
  3. Do not capture if they were not selected
  4. Do not captures values if they were not changed before
  5. Too complex

Well I thought very hard about it and I completed a solution for a full UNDO,REDO history.

To capture the old value it is actually very easy and very fast.

My solution is to capture all values once the user open the sheet is open into a variable and it gets updated after each change. this variable will be used to check the old value of the cell. In the solutions above all of them used for loop. Actually there is way easier method.

To capture all the values I used this simple command

SheetStore = sh.UsedRange.Formula

Yeah, just that, Actually excel will return an array if the range is a multiple cells so we do not need to use FOR EACH command and it is very fast

The following sub is the full code which should be called in Workbook_SheetActivate. Another sub should be created to capture the changes. Like, I have a sub called "catchChanges" that runs on Workbook_SheetChange. It will capture the changes then save them on another a change history sheet. then runs UpdateCache to update the cache with the new values

' should be added at the top of the module
Private SheetStore() As Variant 
Private SheetStoreName As String  ' I use this variable to make sure that the changes I captures are in the same active sheet to prevent overwrite

Sub UpdateCache(sh As Object)
      If sh.Name = ActiveSheet.Name Then ' update values only if the changed values are in the activesheet
          SheetStoreName = sh.Name
          ReDim SheetStore(1 To sh.UsedRange.Rows.count, 1 To sh.UsedRange.Columns.count) ' update the dimension of the array to match used range
          SheetStore = sh.UsedRange.Formula
      End If
End Sub

now to get the old value it is very easy as the array have the same address of cells

examples if we want cell D12 we can use the following

SheetStore(row_number,column_number)
'example
return = SheetStore(12,4)
' or the following showing how I used it. 
set cell = activecell ' the cell that we want to find the old value for
newValue = cell.value ' you can ignore this line, it is just a demonstration
oldValue = SheetStore(cell.Row, cell.Column)

these are snippet explaining the method, I hope everyone like it

Start HTML5 video at a particular position when loading?

WITHOUT USING JAVASCRIPT

Just add #t=[(start_time), (end_time)] to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time. Example:

<video>
    <source src="splash.mp4#t=10,20" type="video/mp4">
</video>

Notes: Not supported in IE

Log4j, configuring a Web App to use a relative path

Just a comment on Iker's solution.

ServletContext is a good solution for your problem. But I don't think it is good for maintains. Most of the time log files are required to be saved for long time.

Since ServletContext makes the file under the deployed file, it will be removed when server is redeployed. My suggest is to go with rootPath's parent folder instead of child one.

Disable and later enable all table indexes in Oracle

Combining the two answers:

First create sql to make all index unusable:

alter session set skip_unusable_indexes = true;
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;

Do import...

select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;

Remove all whitespace from C# string with regex

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

Return a "NULL" object if search result not found

In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:

Attr *getAttribute(const string& attribute_name) const {
   //search collection
   //if found at i
        return &attributes[i];
   //if not found
        return nullptr;
}

Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.

(By the way, I'm a little worried about your method being const and returning a non-const attribute. For philosophical reasons, I'd suggest returning const Attr *. If you also may want to modify this attribute, you can overload with a non-const method returning a non-const attribute as well.)

Retrieve specific commit from a remote Git repository

I did a pull on my git repo:

git pull --rebase <repo> <branch>

Allowing git to pull in all the code for the branch and then I went to do a reset over to the commit that interested me.

git reset --hard <commit-hash>

Hope this helps.

Replacing last character in a String with java

You can simply use substring:

if(fieldName.endsWith(","))
{
  fieldName = fieldName.substring(0,fieldName.length() - 1);
}

Make sure to reassign your field after performing substring as Strings are immutable in java

Can we instantiate an abstract class directly?

According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.

    public class MyCustomClass extends YourAbstractClass {

/// attributes, methods ,...
}
  1. work with interfaces.

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

How to submit a form using Enter key in react.js?

Use keydown event to do it:

   input: HTMLDivElement | null = null;

   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
      // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopPropagation();
        this.onSubmit();
      }
    }

    onSubmit = (): void => {
      if (input.textContent) {
         this.props.onSubmit(input.textContent);
         input.focus();
         input.textContent = '';
      }
    }

    render() {
      return (
         <form className="commentForm">
           <input
             className="comment-input"
             aria-multiline="true"
             role="textbox"
             contentEditable={true}
             onKeyDown={this.onKeyDown}
             ref={node => this.input = node} 
           />
           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
         </form>
      );
    }

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I found the answer!

I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).

The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS

#ActionBox {
  position: relative;
  float: right;
}

Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)

I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.

Bootstrap 4 navbar color

you can write !important in front of background-color property value like this it will change the color of links.

.nav-link {
    color: white !important;
}

Namespace not recognized (even though it is there)

I resolved this issue by right clicking on the folder containing the files and choosing Exclude From Project and then right clicking again and selecting Include In Project (you first have to enable Show All Files to make the excluded folder visible)

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Can I scroll a ScrollView programmatically in Android?

private int totalHeight = 0;

ViewTreeObserver ScrollTr = loutMain.getViewTreeObserver();
ScrollTr.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            loutMain.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } else {
            loutMain.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
        TotalHeight = loutMain.getMeasuredHeight();

    }
});

scrollMain.smoothScrollTo(0, totalHeight);

COPY with docker but with exclusion

Create file .dockerignore in your docker build context directory (so in this case, most likely a directory that is a parent to node_modules) with one line in it:

**/node_modules

although you probably just want:

node_modules

Info about dockerignore: https://docs.docker.com/engine/reference/builder/#dockerignore-file

react native get TextInput value

constructor(props) {
        super(props);

        this.state ={
            commentMsg: ''         
        }
    }

 onPress = () => {
          alert("Hi " +this.state.commentMsg)
      }

 <View style={styles.sendCommentContainer}>

     <TextInput
        style={styles.textInput}
        multiline={true}
        onChangeText={(text) => this.setState({commentMsg: text})}
        placeholder ='Comment'/>

       <Button onPress={this.onPress} 
           title="OK!"
           color="#841584"
        />

  </TouchableOpacity>

</View>

Openssl : error "self signed certificate in certificate chain"

You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.

To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.

Have a look at this link about installing self-signed certificates.

Windows 7 SDK installation failure

I'd like to add that removing the Visual C++ 2012 Redistributable may be necessary, too. I removed both the Visual C++ 2012 Redistributable x84 and x64 and then my installation worked.

/etc/apt/sources.list" E212: Can't open file for writing

I referenced to Zsolt in level 2, I input:

:w !sudo tee % > /dev/null

and then in my situation, I still can't modify the file, so it prompted that add "!". so I input

:q! 

then it works

How to part DATE and TIME from DATETIME in MySQL

Try:

SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`

How to use XPath contains() here?

This is a new answer to an old question about a common misconception about contains() in XPath...

Summary: contains() means contains a substring, not contains a node.

Detailed Explanation

This XPath is often misinterpreted:

//ul[contains(li, 'Model')]

Wrong interpretation: Select those ul elements that contain an li element with Model in it.

This is wrong because

  1. contains(x,y) expects x to be a string, and
  2. the XPath rule for converting multiple elements to a string is this:

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

Examples

XML

<r>
  <ul id="one">
    <li>Model A</li>
    <li>Foo</li>
  </ul>
  <ul id="two">
    <li>Foo</li>
    <li>Model A</li>
  </ul>
</r> 

XPaths

  • //ul[contains(li, 'Model')] selects the one ul element.

    Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

  • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

    Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

See also

How to get ERD diagram for an existing database?

ERBuilder can generate ER diagram from PostgreSQL databases (reverse engineer feature).

Below step to follow to generate an ER diagram:

• Click on Menu -> File -> reverse engineer

• Click on new connection

• Fill in PostgresSQL connection information

• Click on OK

• Click on next

• Select objects (tables, triggers, sequences…..) that you want to reverse engineer.

• Click on next.

  • If you are using trial version, your ERD will be displayed automatically.
  • If your are using the free edition you need to drag and drop the tables from the treeview placed in the left side of application

enter image description here

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

What exactly does an #if 0 ..... #endif block do?

Lines beginning with a # are preprocessor directives. #if 0 [...] #endif blocks do not make it to the compiler and will generate no machine code.

You can demonstrate what happens with the preprocessor with a source file ifdef.cxx:

#if 0
This code will not be compiled
#else
int i = 0;
#endif

Running gcc -E ifdef.cxx will show you what gets compiled.

You may choose to use this mechanism to prevent a block of code being compiled during the development cycle, but you would probably not want to check it in to your source control as it just adds cruft to your code and reduces readability. If it's a historical piece of code that has been commented out, then it should be removed: source control contains the history, right?

Also, the answer may be the same for both C and C++ but there is no language called C/C++ and it's not a good habit to refer to such a language.

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you don't want to zoom in/out UIImage. Instead try to zoom in/out the View which contains the UIImage View Controller.

I have made a solution for this problem. Take a look at my code:

@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
        self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
        sender.scale = 1
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.blackColor()
    }

N.B.: Don't forget to hook up the PinchGestureRecognizer.

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Responsive design with media query : screen size?

i will provide mine because @muni s solution was a bit overkill for me

note: if you want to add custom definitions for several resolutions together, say something like this:

//mobile generally   
 @media screen and (max-width: 1199)  {

      .irns-desktop{
        display: none;
      }

      .irns-mobile{
        display: initial;
      }

    }

Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')

//here all definitions to apply globally


//desktop
@media only screen
and (min-width : 1200) {


}

//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px)  {

} // end media query

//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px)  {

}//end media definition


//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px)  {

}//end media query



//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {

}

//end media query

What are "res" and "req" parameters in Express functions?

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

How to close TCP and UDP ports via windows command line

you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.

Tainted canvases may not be exported

If someone views on my answer, you maybe in this condition:

1. Trying to get a map screenshot in canvas using openlayers (version >= 3)
2. And viewed the example of exporting map
3. Using ol.source.XYZ to render map layer

Bingo!

Using ol.source.XYZ.crossOrigin = 'Anonymous' to solve your confuse. Or like following code:

     var baseLayer = new ol.layer.Tile({
         name: 'basic',
         source: new ol.source.XYZ({
             url: options.baseMap.basic,
             crossOrigin: "Anonymous"
         })
     });

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Most of the times, the issue is with the paths you have mentioned for 'java home' and 'javac' tags in settings.xml which is present in your .m2 repository and the issue is not with your path variable or Java_Home variable. If you check and correct the same, you should be able to execute your commands successfully. - Jaihind

How do I view executed queries within SQL Server Management Studio?

Run the following query from Management Studio on a running process:

DBCC inputbuffer( spid# )

This will return the SQL currently being run against the database for the SPID provided. Note that you need appropriate permissions to run this command.

This is better than running a trace since it targets a specific SPID. You can see if it's long running based on its CPUTime and DiskIO.

Example to get details of SPID 64:

DBCC inputbuffer(64)

Failed to allocate memory: 8

Referring to Android: failed to allocate memory and its first comment under accepted answer, changing "1024" to "1024MB" helped me. Pathetic, but works.

Calling stored procedure with return value

This is a very short sample of returning a single value from a procedure:

SQL:

CREATE PROCEDURE [dbo].[MakeDouble] @InpVal int AS BEGIN 
SELECT @InpVal * 2; RETURN 0; 
END

C#-code:

int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
    "Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
    sqlCon.Open();
    retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";", 
        sqlCon).ExecuteScalar().ToString();
    sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal); 
//> 11 * 2 = 22

Retrieving an element from array list in Android?

U cant try this

for (WordList i : words) {
     words.get(words.indexOf(i));
 }

How can I center text (horizontally and vertically) inside a div block?

Add the line display: table-cell; to your CSS content for that div.

Only table cells support the vertical-align: middle;, but you can give that [table-cell] definition to the div...

A live example is here: http://jsfiddle.net/tH2cc/

div{
    height: 90px;
    width: 90px;
    text-align: center;
    border: 1px solid silver;
    display: table-cell; // This says treat this element like a table cell
    vertical-align:middle; // Now we can center vertically like in a TD
}

Python Dictionary contains List as Value - How to update?

for i,j in dictionary .items():
    if i=='C1':
        c=[]
        for k in j:
            j=k+10
            c.append(j)
            dictionary .update({i:c})

Tomcat in Intellij Idea Community Edition

You can use tomcat plugin with gradle. For more information, you here.

apply plugin: 'tomcat'

dependencies {
    classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:1.2.4'
}

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

[tomcatRun, tomcatRunWar, tomcatStop]*.stopPort = 8090
[tomcatRun, tomcatRunWar, tomcatStop]*.stopKey = 'stfu'
tomcatRunWar.contextPath = "/$rootProject.name"
tomcatRunWar.ajpPort = 8000

if (checkBeforeRun.toBoolean()) {
    tomcatRunWar { dependsOn += ['check'] }
}

How do you delete a column by name in data.table?

I simply do it in the data frame kind of way:

DT$col = NULL

Works fast and as far as I could see doesn't cause any problems.

UPDATE: not the best method if your DT is very large, as using the $<- operator will lead to object copying. So better use:

DT[, col:=NULL]

How to set the JDK Netbeans runs on?

Go to Tools -> Java Platforms. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25. You can either set the another JDK version or remove existing versions.

Another solution suggested in the oracle (sun) site is,

netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"

I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms dialog. Then, go to Run -> Set Project Configuration -> Customize. After that, in the opened Dialog box go to Build -> Compile. Set the version.

Create whole path automatically when writing to a new file

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

How to parse date string to Date?

The pattern is wrong. You have a 3-letter day abbreviation, so it must be EEE. You have a 3-letter month abbreviation, so it must be MMM. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the SimpleDateFormat locale to English as well, otherwise it will use the platform default locale which may not be English per se.

public static void main(String[] args) throws Exception {
    String target = "Thu Sep 28 20:29:30 JST 2000";
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    Date result =  df.parse(target);  
    System.out.println(result);
}

This prints here

Thu Sep 28 07:29:30 BOT 2000

which is correct as per my timezone.

I would also reconsider if you wouldn't rather like to use HH instead of kk. Read the javadoc for details about valid patterns.

Convert UTC datetime string to local datetime

Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

PHP Create and Save a txt file to root directory

It's creating the file in the same directory as your script. Try this instead.

$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

Launch Failed. Binary not found. CDT on Eclipse Helios

First you need to make sure that the project has been built. You can build a project with the hammer icon in the toolbar. You can choose to build either a Debug or Release version. If you cannot build the project then the problem is that you either don't have a compiler installed or that the IDE does not find the compiler.

To see if you have a compiler installed in a Mac you can run the following command from the command line:

g++ --version

If you have it already installed (it gets installed when you install the XCode tools) you can see its location running:

which g++

If you were able to build the project but you still get the "binary not found" message then the issue might be that a default launch configuration is not being created for the project. In that case do this:

Right click project > Run As > Run Configurations... > 

Then create a new configuration under the "C/C++ Application" section > Enter the full path to the executable file (the file that was created in the build step and that will exist in either the Debug or Release folder). Your launch configuration should look like this:

enter image description here

Alternative to the HTML Bold tag

Maybe you want to use CSS classes?

p.bold { font-weight:bold; }

That way you can still use <p> as normal.

<p>This is normal text</p>
<p class="bold">This is bold text</p>

Gives you:

This is normal text.

This is Bold Text.

Changing column names of a data frame

The new recommended way to do this is to use the setNames function. See ?setNames. Since this creates a new copy of the data.frame, be sure to assign the result to the original data.frame, if that is your intention.

data_frame <- setNames(data_frame, c("premium","change","newprice"))

Newer versions of R will give you warning if you use colnames in some of the ways suggested by earlier answers.

If this were a data.table instead, you could use the data.table function setnames, which can modify specific column names or a single column name by reference:

setnames(data_table, "old-name", "new-name")

Compare two Timestamp in java

Just convert the timestamp in millisec representation. Use getTime() method.

MySQL LIMIT on DELETE statement

Use row_count - your_desired_offset

So if we had 10 rows and want to offset 3

 10 - 3 = 7

Now the query delete from table where this = that order asc limit 7 keeps the last 3, and order desc to keep the first 3:

$row_count - $offset = $limit

Delete from table where entry = criteria order by ts asc limit $limit

jQuery Call to WebService returns "No Transport" error

For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.

I built jquery myself with webpack picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.

After a long debugging, the problem turns out to be XMLHttpRequest is pluggable in jquery and it not include by default.

You have to explicitly include jquery/src/ajax/xhr file in order to make the ajax working in browsers.

How to return first 5 objects of Array in Swift?

The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:

let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
  for i in array{
    iterationNumber += 1
    if iterationNumber <= maxNum{
      firstNumbers.append(i)
    }
  }
  firstNumbers.remove(at: 0)
  print(firstNumbers)
} else {
  print("There were not \(maxNum) items in the array.")
}

This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem. This solution uses many basic functions including array.count, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append, which adds things onto the end of the array. Lastly, it uses array.remove, which removes the array's item that has a specified position.

I have tested it it and it works for at least swift 5.

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

Spring .properties file: get element as an Array

If you need to pass the asterisk symbol, you have to wrap it with quotes.

In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.

In yml file I have:

websocket:
  cors: "*"

In Config class I have:

@Value("${websocket.cors}")
private String[] cors;

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

What LaTeX Editor do you suggest for Linux?

There is a pretty good list at linuxappfinder.com.

My personal preference for LaTeX on Linux has been the KDE-based editor Kile.

Pan & Zoom Image

The answer was posted above but wasn't complete. here is the completed version:

XAML

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
x:Name="Window"
Title="Window1"
Width="1950" Height="1546" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions" mc:Ignorable="d" Background="#FF000000">

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="52.92"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Border Grid.Row="1" Name="border">
        <Image Name="image" Source="map3-2.png" Opacity="1" RenderTransformOrigin="0.5,0.5"  />
    </Border>

</Grid>

Code Behind

using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace MapTest
{
    public partial class Window1 : Window
    {
        private Point origin;
        private Point start;

        public Window1()
        {
            InitializeComponent();

            TransformGroup group = new TransformGroup();

            ScaleTransform xform = new ScaleTransform();
            group.Children.Add(xform);

            TranslateTransform tt = new TranslateTransform();
            group.Children.Add(tt);

            image.RenderTransform = group;

            image.MouseWheel += image_MouseWheel;
            image.MouseLeftButtonDown += image_MouseLeftButtonDown;
            image.MouseLeftButtonUp += image_MouseLeftButtonUp;
            image.MouseMove += image_MouseMove;
        }

        private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            image.ReleaseMouseCapture();
        }

        private void image_MouseMove(object sender, MouseEventArgs e)
        {
            if (!image.IsMouseCaptured) return;

            var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
            Vector v = start - e.GetPosition(border);
            tt.X = origin.X - v.X;
            tt.Y = origin.Y - v.Y;
        }

        private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            image.CaptureMouse();
            var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
            start = e.GetPosition(border);
            origin = new Point(tt.X, tt.Y);
        }

        private void image_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            TransformGroup transformGroup = (TransformGroup) image.RenderTransform;
            ScaleTransform transform = (ScaleTransform) transformGroup.Children[0];

            double zoom = e.Delta > 0 ? .2 : -.2;
            transform.ScaleX += zoom;
            transform.ScaleY += zoom;
        }
    }
}

I have an example of a full wpf project using this code on my website: Jot the sticky note app.

How to avoid pressing Enter with getchar() for reading a single character only?

Can create a new function that checks for Enter:

#include <stdio.h>

char getChar()
{
    printf("Please enter a char:\n");

    char c = getchar();
    if (c == '\n')
    {
        c = getchar();
    }

    return c;
}

int main(int argc, char *argv[])
{
    char ch;
    while ((ch = getChar()) != '.')
    {
        printf("Your char: %c\n", ch);
    }

    return 0;
}

How to find all occurrences of a substring?

This is solution of a similar question from hackerrank. I hope this could help you.

import re
a = input()
b = input()
if b not in a:
    print((-1,-1))
else:
    #create two list as
    start_indc = [m.start() for m in re.finditer('(?=' + b + ')', a)]
    for i in range(len(start_indc)):
        print((start_indc[i], start_indc[i]+len(b)-1))

Output:

aaadaa
aa
(0, 1)
(1, 2)
(4, 5)

How to trigger event when a variable's value is changed?

you can use generic class:

class Wrapped<T>  {
    private T _value;

    public Action ValueChanged;

    public T Value
    {
        get => _value;

        set
        {
            _value = value;
            OnValueChanged();
        }
    }

    protected virtual void OnValueChanged() => ValueChanged?.Invoke() ;
}

and will be able to do the following:

var i = new Wrapped<int>();

i.ValueChanged += () => { Console.WriteLine("changed!"); };

i.Value = 10;
i.Value = 10;
i.Value = 10;
i.Value = 10;

Console.ReadKey();

result:

changed!
changed!
changed!
changed!
changed!
changed!
changed!

Invert "if" statement to reduce nesting

It is not only aesthetic, but it also reduces the maximum nesting level inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, many static analysis tools provide a measure of this as one of the indicators of code quality).

On the other hand, it also makes your method have multiple exit points, something that another group of people believes is a no-no.

Personally, I agree with ReSharper and the first group (in a language that has exceptions I find it silly to discuss "multiple exit points"; almost anything can throw, so there are numerous potential exit points in all methods).

Regarding performance: both versions should be equivalent (if not at the IL level, then certainly after the jitter is through with the code) in every language. Theoretically this depends on the compiler, but practically any widely used compiler of today is capable of handling much more advanced cases of code optimization than this.

What is the meaning of "$" sign in JavaScript

Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).

There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier.

JavaScript allows upper and lower letters, numbers, and $ and _. The $ was intended to be used for machine-generated variables (such as $0001).

Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.

show distinct column values in pyspark dataframe: python

collect_set can help to get unique values from a given column of pyspark.sql.DataFrame df.select(F.collect_set("column").alias("column")).first()["column"]

MySQL selecting yesterday's date

Last or next date, week, month & year calculation. It might be helpful for anyone.

Current Date:

select curdate();

Yesterday:

select subdate(curdate(), 1)

Tomorrow:

select adddate(curdate(), 1)

Last 1 week:

select between subdate(curdate(), 7) and subdate(curdate(), 1)

Next 1 week:

between adddate(curdate(), 7) and adddate(curdate(), 1)

Last 1 month:

between subdate(curdate(), 30) and subdate(curdate(), 1)

Next 1 month:

between adddate(curdate(), 30) and adddate(curdate(), 1)

Current month:

subdate(curdate(),day(curdate())-1) and last_day(curdate());

Last 1 year:

between subdate(curdate(), 365) and subdate(curdate(), 1)

Next 1 year:

between adddate(curdate(), 365) and adddate(curdate(), 1)

Paste text on Android Emulator

With v25.3.x of the Android Emulator & x86 Google API Emulator system images API Level 19 (Android 4.4 - Kitkat) and higher, you can simply copy and paste from your desktop with your mouse or keyboard.

This feature was announced with Android Studio 2.3

Copy and Paste with the Android Emulator

convert an enum to another type of enum

I know that's an old question and have a lot of answers, However I find that using a switch statement as in the accepted answer is somewhat cumbersome, so here are my 2 cents:

My personal favorite method is to use a dictionary, where the key is the source enum and the value is the target enum - so in the case presented on the question my code would look like this:

var genderTranslator = new Dictionary<TheirGender, MyGender>();
genderTranslator.Add(TheirGender.Male, MyGender.Male);
genderTranslator.Add(TheirGender.Female, MyGender.Female);
genderTranslator.Add(TheirGender.Unknown, MyGender.Unknown);

// translate their to mine    
var myValue = genderTranslator[TheirValue];

// translate mine to their
var TheirValue = genderTranslator .FirstOrDefault(x => x.Value == myValue).Key;;

Of course, this can be wrapped in a static class and be used as an extension methods:

public static class EnumTranslator
{

    private static Dictionary<TheirGender, MyGender> GenderTranslator = InitializeGenderTranslator();

    private static Dictionary<TheirGender, MyGender> InitializeGenderTranslator()
    {
        var translator = new Dictionary<TheirGender, MyGender>();
        translator.Add(TheirGender.Male, MyGender.Male);
        translator.Add(TheirGender.Female, MyGender.Female);
        translator.Add(TheirGender.Unknown, MyGender.Unknown);
        return translator;
    }

    public static MyGender Translate(this TheirGender theirValue)
    {
        return GenderTranslator[theirValue];
    }

    public static TheirGender Translate(this MyGender myValue)
    {
        return GenderTranslator.FirstOrDefault(x => x.Value == myValue).Key;
    }

}

npm install error - unable to get local issuer certificate

Use the command

npm config set strict-ssl false

SQL Combine Two Columns in Select Statement

If you don't want to change your database schema (and I would not for this simple query) you can just combine them in the filter like this: WHERE (Address1 + Address2) LIKE '%searchstring%'

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

Retrieving Data from SQL Using pyodbc

Just do this:

import pandas as pd
import pyodbc

cnxn = pyodbc.connect("Driver={SQL Server}\
                    ;Server=SERVER_NAME\
                    ;Database=DATABASE_NAME\
                    ;Trusted_Connection=yes")

df = pd.read_sql("SELECT * FROM myTableName", cnxn) 
df.head()

How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it

What version of Python is on my Mac?

To check third version, we can use,

python3 --version

How can I execute a python script from an html button?

This would require knowledge of a backend website language.

Fortunately, Python's Flask Library is a suitable backend language for the project at hand.

Check out this answer from another thread.

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

Which HTTP methods match up to which CRUD methods?

Generally speaking, this is the pattern I use:

  • HTTP GET - SELECT/Request
  • HTTP PUT - UPDATE
  • HTTP POST - INSERT/Create
  • HTTP DELETE - DELETE

How to get error information when HttpWebRequest.GetResponse() fails

I faced a similar situation:

I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.

However, when reading the response using GetResponseStream(), got the error:

Stream not readable

So, this code worked for me:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Search code inside a Github project

To seach within a repository, add the URL parametes /search?q=search_terms at the root of the repo, for example:

https://github.com/bmewburn/vscode-intelephense/search?q=phpstorm

enter image description here

In the above example, it returns 2 results in Code and 160 results in Issues.

How to run a program in Atom Editor?

  1. Click on Packages --> Commmand Palette --> Select Toggle.
  2. Type Install Packages and Themes.
  3. Search for Script and then install it.
  4. Press Command + I to run the code (on Mac)

:last-child not working as expected?

:last-child will not work if the element is not the VERY LAST element

In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."

Suppose this is my selector: a:last-child {}

This works:

<div>
    <a></a>
    <a>This will be selected</a>
</div>

This doesn't:

<div>
    <a></a>
    <a>This will no longer be selected</a>
    <div>This is now the last child :'( </div>
</div>

It doesn't because the a element is not the last element inside its parent.

It may be obvious, but it was not for me...

What is SOA "in plain english"?

A traditional application architecture is:

  • A user interface
  • Undefined stuff (implementation) that's encapsulated/hidden behind the user interface

If you want to access the data programmatically, you might need to resort to screen-scraping.

SOA seems to me to be an architecture which focus on exposing machine-readable data and/or APIs, instead of on exposing UIs.

How to add minutes to my Date

There's an error in the pattern of your SimpleDateFormat. it should be

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Reorder HTML table rows using drag-and-drop

Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:

_x000D_
_x000D_
$(".grab").mousedown(function(e) {
  var tr = $(e.target).closest("TR"),
    si = tr.index(),
    sy = e.pageY,
    b = $(document.body),
    drag;
  if (si == 0) return;
  b.addClass("grabCursor").css("userSelect", "none");
  tr.addClass("grabbed");

  function move(e) {
    if (!drag && Math.abs(e.pageY - sy) < 10) return;
    drag = true;
    tr.siblings().each(function() {
      var s = $(this),
        i = s.index(),
        y = s.offset().top;
      if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
        if (i < tr.index())
          tr.insertAfter(s);
        else
          tr.insertBefore(s);
        return false;
      }
    });
  }

  function up(e) {
    if (drag && si != tr.index()) {
      drag = false;
      alert("moved!");
    }
    $(document).unbind("mousemove", move).unbind("mouseup", up);
    b.removeClass("grabCursor").css("userSelect", "none");
    tr.removeClass("grabbed");
  }
  $(document).mousemove(move).mouseup(up);
});
_x000D_
.grab {
  cursor: grab;
}

.grabbed {
  box-shadow: 0 0 13px #000;
}

.grabCursor,
.grabCursor * {
  cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th></th>
    <th>Table Header</th>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 1</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 2</td>
  </tr>
  <tr>
    <td class="grab">&#9776;</td>
    <td>Table Cell 3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Note si == 0 and i > 0 ignores the first row, which for me contains TH tags. Replace the alert with your "drag finished" logic.

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

Laravel blade check empty foreach

You should use empty()

@if (!empty($status->replies)) 

<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>

@endif

You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.

init-param and context-param

<init-param> will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init method will be called then doGet/doPost whereas if you want to initialize some variable for whole application you will need to use <context-param> . Every servlet will have access to the context variable.

Laravel Advanced Wheres how to pass variable into function?

You can pass the necessary variables from the parent scope into the closure with the use keyword.

For example:

DB::table('users')->where(function ($query) use ($activated) {
    $query->where('activated', '=', $activated);
})->get();

More on that here.

EDIT (2019 update):

PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.

An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):

DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();

Differences compared to the regular syntax:

  • fn keyword instead of function.
  • No need to explicitly list all variables which should be captured from the parent scope - this is now done automatically by-value. See the lack of use keyword in the latter example.
  • Arrow functions always return a value. This also means that it's impossible to use void return type when declaring them.
  • The return keyword must be omitted.
  • Arrow functions must have a single expression which is the return statement. Multi-line functions aren't supported at the moment. You can still chain methods though.

Understanding implicit in Scala

I'll explain the main use cases of implicits below, but for more detail see the relevant chapter of Programming in Scala.

Implicit parameters

The final parameter list on a method can be marked implicit, which means the values will be taken from the context in which they are called. If there is no implicit value of the right type in scope, it will not compile. Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose, e.g. don't require your methods to find an implicit Int!

example:

  // probably in a library
class Prefixer(val prefix: String)
def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s

  // then probably in your application
implicit val myImplicitPrefixer = new Prefixer("***")
addPrefix("abc")  // returns "***abc"

Implicit conversions

When the compiler finds an expression of the wrong type for the context, it will look for an implicit Function value of a type that will allow it to typecheck. So if an A is required and it finds a B, it will look for an implicit value of type B => A in scope (it also checks some other places like in the B and A companion objects, if they exist). Since defs can be "eta-expanded" into Function objects, an implicit def xyz(arg: B): A will do as well.

So the difference between your methods is that the one marked implicit will be inserted for you by the compiler when a Double is found but an Int is required.

implicit def doubleToInt(d: Double) = d.toInt
val x: Int = 42.0

will work the same as

def doubleToInt(d: Double) = d.toInt
val x: Int = doubleToInt(42.0)

In the second we've inserted the conversion manually; in the first the compiler did the same automatically. The conversion is required because of the type annotation on the left hand side.


Regarding your first snippet from Play:

Actions are explained on this page from the Play documentation (see also API docs). You are using

apply(block: (Request[AnyContent]) ? Result): Action[AnyContent]

on the Action object (which is the companion to the trait of the same name).

So we need to supply a Function as the argument, which can be written as a literal in the form

request => ...

In a function literal, the part before the => is a value declaration, and can be marked implicit if you want, just like in any other val declaration. Here, request doesn't have to be marked implicit for this to type check, but by doing so it will be available as an implicit value for any methods that might need it within the function (and of course, it can be used explicitly as well). In this particular case, this has been done because the bindFromRequest method on the Form class requires an implicit Request argument.

Get min and max value in PHP Array

It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.

The problem of finding min and max can easily be solved with just two extra memory slots

$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;

foreach($input as $data) {
    $weight = intval($data['Weight']);

    if($weight <= $min ) {
        $min =  $weight ;
    }

    if($weight > $max ) {
        $max =  $weight ;
    }

}

echo " min = $min and max = $max \n " ;

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.

how to add value to a tuple?

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

Why do we need virtual functions in C++?

I've my answer in form of a conversation to be a better read:


Why do we need virtual functions?

Because of Polymorphism.

What is Polymorphism?

The fact that a base pointer can also point to derived type objects.

How does this definition of Polymorphism lead into the need for virtual functions?

Well, through early binding.

What is early binding?

Early binding(compile-time binding) in C++ means that a function call is fixed before the program is executed.

So...?

So if you use a base type as the parameter of a function, the compiler will only recognize the base interface, and if you call that function with any arguments from derived classes, it gets sliced off, which is not what you want to happen.

If it's not what we want to happen, why is this allowed?

Because we need Polymorphism!

What's the benefit of Polymorphism then?

You can use a base type pointer as the parameter of a single function, and then in the run-time of your program, you can access each of the derived type interfaces(e.g. their member functions) without any issues, using dereferencing of that single base pointer.

I still don't know what virtual functions are good for...! And this was my first question!

well, this is because you asked your question too soon!

Why do we need virtual functions?

Assume that you called a function with a base pointer, which had the address of an object from one of its derived classes. As we've talked about it above, in the run-time, this pointer gets dereferenced, so far so good, however, we expect a method(== a member function) "from our derived class" to be executed! However, a same method(one that has a same header) is already defined in the base class, so why should your program bother to choose the other method? In other words I mean, how can you tell this scenario off from what we used to see normally happen before?

The brief answer is "a Virtual member function in base", and a little longer answer is that, "at this step, if the program sees a virtual function in the base class, it knows(realizes) that you're trying to use polymorphism" and so goes to derived classes(using v-table, a form of late binding) to find that another method with the same header, but with -expectedly- a different implementation.

Why a different implementation?

You knuckle-head! Go read a good book!

OK, wait wait wait, why would one bother to use base pointers, when he/she could simply use derived type pointers? You be the judge, is all this headache worth it? Look at these two snippets:

//1:

Parent* p1 = &boy;
p1 -> task();
Parent* p2 = &girl;
p2 -> task();

//2:

Boy* p1 = &boy;
p1 -> task();
Girl* p2 = &girl;
p2 -> task();

OK, although I think that 1 is still better than 2, you could write 1 like this either:

//1:

Parent* p1 = &boy;
p1 -> task();
p1 = &girl;
p1 -> task();

and moreover, you should be aware that this is yet just a contrived use of all the things I've explained to you so far. Instead of this, assume for example a situation in which you had a function in your program that used the methods from each of the derived classes respectively(getMonthBenefit()):

double totalMonthBenefit = 0;    
std::vector<CentralShop*> mainShop = { &shop1, &shop2, &shop3, &shop4, &shop5, &shop6};
for(CentralShop* x : mainShop){
     totalMonthBenefit += x -> getMonthBenefit();
}

Now, try to re-write this, without any headaches!

double totalMonthBenefit=0;
Shop1* branch1 = &shop1;
Shop2* branch2 = &shop2;
Shop3* branch3 = &shop3;
Shop4* branch4 = &shop4;
Shop5* branch5 = &shop5;
Shop6* branch6 = &shop6;
totalMonthBenefit += branch1 -> getMonthBenefit();
totalMonthBenefit += branch2 -> getMonthBenefit();
totalMonthBenefit += branch3 -> getMonthBenefit();
totalMonthBenefit += branch4 -> getMonthBenefit();
totalMonthBenefit += branch5 -> getMonthBenefit();
totalMonthBenefit += branch6 -> getMonthBenefit();

And actually, this might be yet a contrived example either!

How to highlight cell if value duplicate in same column for google spreadsheet?

Try this:

  1. Select the whole column
  2. Click Format
  3. Click Conditional formatting
  4. Click Add another rule (or edit the existing/default one)
  5. Set Format cells if to: Custom formula is
  6. Set value to: =countif(A:A,A1)>1 (or change A to your chosen column)
  7. Set the formatting style.
  8. Ensure the range applies to your column (e.g., A1:A100).
  9. Click Done

Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.

For locales using comma (,) as a decimal separator, the argument separator is most likely a semi-colon (;). That is, try: =countif(A:A;A1)>1, instead.

For multiple columns, use countifs.

How to know elastic search installed version from kibana?

The user @manoj has provided the correct answer to the question. From Kibana host, a request to http://localhost:9200/ will not be answered, unless ElasticSearch is also running on the same node. Kibana listens on port 5601 not 9200.

In most cases, except for DEV, ElasticSearch will not be on the same node as Kibana, for a number of reasons. Therefore, to get information about your ElasticSearch from Kibana, you should select the "Dev Tools" tab on the left and in the console issue the command: GET /

Length of string in bash

To get the length of a string stored in a variable, say:

myvar="some string"
size=${#myvar} 

To confirm it was properly saved, echo it:

$ echo "$size"
11

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

You just need to enter this command:

sudo apt-get install gcc

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

auto create database in Entity Framework Core

If you have created the migrations, you could execute them in the Startup.cs as follows.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
      }
      
      ...

This will create the database and the tables using your added migrations.

If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
      }
      
      ...

Instead.

If you need to delete your database prior to making sure it's created, call:

            context.Database.EnsureDeleted();

Just before you call EnsureCreated()

Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

Compiling simple Hello World program on OS X via command line

Use the following for multiple .cpp files

g++ *.cpp
./a.out

Put quotes around a variable string in JavaScript

var text = "\"http://example.com\""; 

Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

"http://example.com"

Clear text input on click with AngularJS

Easiest way to clear/reset the text field on click is to clear/reset the scope

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>

In Controller

$scope.clearfunction=function(event){
   event.searchAll=null;
}

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

What is event bubbling and capturing?

As other said, bubbling and capturing describe in which order some nested elements receive a given event.

I wanted to point out that for the innermost element may appear something strange. Indeed, in this case the order in which the event listeners are added does matter.

In the following example, capturing for div2 will be executed first than bubbling; while bubbling for div4 will be executed first than capturing.

_x000D_
_x000D_
function addClickListener (msg, num, type) {
  document.querySelector("#div" + num)
    .addEventListener("click", () => alert(msg + num), type);
}
bubble  = (num) => addClickListener("bubble ", num, false);
capture = (num) => addClickListener("capture ", num, true);

// first capture then bubble
capture(1);
capture(2);
bubble(2);
bubble(1);

// try reverse order
bubble(3);
bubble(4);
capture(4);
capture(3);
_x000D_
#div1, #div2, #div3, #div4 {
  border: solid 1px;
  padding: 3px;
  margin: 3px;
}
_x000D_
<div id="div1">
  div 1
  <div id="div2">
    div 2
  </div>
</div>
<div id="div3">
  div 3
  <div id="div4">
    div 4
  </div>
</div>
_x000D_
_x000D_
_x000D_

Why does ASP.NET webforms need the Runat="Server" attribute?

I usually don't like to guess, but I'm going to on this one...

If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.

So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.

Remember those weird ads?

Related: Article from The Register with some .NET history.

How to send an email with Python?

There is indentation problem. The code below will work:

import textwrap

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    import smtplib
    """this is some test documentation in the function"""
    message = textwrap.dedent("""\
        From: %s
        To: %s
        Subject: %s
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT))
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

Does HTTP use UDP?

Typically, no.

Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.

For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".

As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.

How to amend a commit without changing commit message (reusing the previous one)?

git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

"could not find stored procedure"

Could not find stored procedure?---- means when you get this.. our code like this

String sp="{call GetUnitReferenceMap}";

stmt=conn.prepareCall(sp);

ResultSet rs = stmt.executeQuery();

while (rs.next()) {

currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim()); 

I have 4 DBs(sample1, sample2, sample3) But stmt will search location is master Default DB then we will get Exception.

we should provide DB name then problem resolves::

String sp="{call sample1..GetUnitReferenceMap}";

How can I find the number of elements in an array?

If we don't know the number of elements in the array and when the input is given by the user at the run time. Then we can write the code as

C CODE:

while(scanf("%d",&array[count])==1) { 
  count++;
}

C++ CODE:

while(cin>>a[count]) {
  count++;
}

Now the count will be having the count of number of array elements which are entered.

What is the "hasClass" function with plain JavaScript?

The attribute that stores the classes in use is className.

So you can say:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}

If you want a location that shows you how jQuery does everything, I would suggest:

http://code.jquery.com/jquery-1.5.js

Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

How to do case insensitive search in Vim

You can set ignorecase by default, run this in shell

echo "set ic" >> ~/.vimrc

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

no pg_hba.conf entry for host

To resolved this problem, you can try this.

first you have find out your pg_hba.conf and write :

local all all md5

after that restart pg server:

postgresql restart

or

sudo /etc/init.d/postgresql restart

How do I configure modprobe to find my module?

Follow following steps:

  1. Copy hello.ko to /lib/modules/'uname-r'/misc/
  2. Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep
  3. sudo depmod
  4. sudo modprobe hello

modprobe will check modules.dep file for any dependency.

WCF ServiceHost access rights

Open a command prompt as the administrator and you write below command to add your URL:

netsh http add urlacl url=http://+:8000/YourServiceLibrary/YourService user=Everyone

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Can't find how to use HttpContent

For JSON Post:

var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Non-JSON:

var stringContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("field1", "value1"),
    new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/

3 column layout HTML/CSS

CSS:

.container {
    position: relative;
    width: 500px;
}
.container div {
    height: 300px;
}

.column-left {
    width: 33%;
    left: 0;
    background: #00F;
    position: absolute;
}
.column-center {
    width: 34%;
    background: #933;
    margin-left: 33%;
    position: absolute;
}
.column-right {
    width: 33%;
    right: 0;
    position: absolute;
    background: #999;
}

HTML:

<div class="container">
   <div class="column-center">Column center</div>
   <div class="column-left">Column left</div>
   <div class="column-right">Column right</div>
</div>

Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

How can I initialize an ArrayList with all zeroes in Java?

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

Best practice to return errors in ASP.NET Web API

ASP.NET Web API 2 really simplified it. For example, the following code:

public HttpResponseMessage GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        var message = string.Format("Product with id = {0} not found", id);
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

returns the following content to the browser when the item is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51

{
  "Message": "Product with id = 12 not found"
}

Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)

Links:

Why does Google prepend while(1); to their JSON responses?

After authentication is in place, JSON hijacking protection can take a variety of forms. Google appends while(1) into their JSON data, so that if any malicious script evaluates it, the malicious script enters an infinite loop.

Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

How can I iterate over files in a given directory?

You can use glob for referring the directory and the list :

import glob
import os

#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):   
    dir_name = get_dir_name(f)
    image_file_name = dir_name + '.jpg'
    #To print the file name with path (path will be in string)
    print (image_file_name)

To get the list of all directory in array you can use os :

os.listdir(directory)

Spring Boot how to hide passwords in properties file

To the already proposed solutions I can add an option to configure an external Secrets Manager such as Vault.

  1. Configure Vault Server vault server -dev (Only for DEV and not for PROD)
  2. Write secrets vault write secret/somename key1=value1 key2=value2
  3. Verify secrets vault read secret/somename

Add the following dependency to your SpringBoot project:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>

Add Vault config properties:

spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
spring.cloud.vault.scheme=http
spring.cloud.vault.authentication=token
spring.cloud.vault.token=${VAULT_TOKEN}

Pass VAULT_TOKEN as an environment variable.

Refer to the documentation here.

There is a Spring Vault project which is also can be used for accessing, storing and revoking secrets.

Dependency:

<dependency>
    <groupId>org.springframework.vault</groupId>
    <artifactId>spring-vault-core</artifactId>
</dependency>

Configuring Vault Template:

@Configuration
class VaultConfiguration extends AbstractVaultConfiguration {

  @Override
  public VaultEndpoint vaultEndpoint() {
    return new VaultEndpoint();
  }

  @Override
  public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("…");
  }
}

Inject and use VaultTemplate:

public class Example {

  @Autowired
  private VaultOperations operations;

  public void writeSecrets(String userId, String password) {
      Map<String, String> data = new HashMap<String, String>();
      data.put("password", password);
      operations.write(userId, data);
  }

  public Person readSecrets(String userId) {
      VaultResponseSupport<Person> response = operations.read(userId, Person.class);
      return response.getBody();
  }
}

Use Vault PropertySource:

@VaultPropertySource(value = "aws/creds/s3",
  propertyNamePrefix = "aws."
  renewal = Renewal.RENEW)
public class Config {

}

Usage example:

public class S3Client {

  // inject the actual values
  @Value("${aws.access_key}")
  private String awsAccessKey;
  @Value("${aws.secret_key}")
  private String awsSecretKey;

  public InputStream getFileFromS3(String filenname) {
    // …
  }
}

String "true" and "false" to boolean

You could add to the String class to have the method of to_boolean. Then you could do 'true'.to_boolean or '1'.to_boolean

class String
  def to_boolean
    self == 'true' || self == '1'
  end
end

to_string not declared in scope

You need to make some changes in the compiler. In Dev C++ Compiler: 1. Go to compiler settings/compiler Options. 2. Click on General Tab 3. Check the checkbox (Add the following commands when calling the compiler. 4. write -std=c++11 5. click Ok

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Note that if you are installing this through Anaconda, you will need to open Anaconda as an administrator and then launch the command prompt from there.

Otherwise, you can also run "Anaconda prompt" directly as an administrator to uninstall and install packages.

PHP strtotime +1 month adding an extra month

This should be

$endOfCycle=date('Y-m-d', strtotime("+30 days"));

strtotime

expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

while

date

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.

See the manual pages for:

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

You can use noConflict function:

var JJ= jQuery.noConflict(); 
JJ('.back').click(function (){
    window.history.back();
}); 

Change all $ to JJ.

Simplest way to read json from a URL in java

The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I would honestly suggest neither. I would use a stylized <button></button> for that behavior.

_x000D_
_x000D_
button.link {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  background-color: transparent;_x000D_
  cursor: pointer;_x000D_
  border: 0;_x000D_
  padding: 0;_x000D_
  color: #00f;_x000D_
  text-decoration: underline;_x000D_
  font: inherit;_x000D_
}
_x000D_
<p>A button that looks like a <button type="button" class="link">link</button>.</p>
_x000D_
_x000D_
_x000D_

This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.


If you MUST use an A element, use javascript:void(0); for reasons already mentioned.

  • Will always intercept in case your onclick event fails.
  • Will not have errant load calls happen, or trigger other events based on a hash change
  • The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.

NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.

JAXB: how to marshall map into <key>value</key>

the code provided didn't work for me. I found another way to Map :

MapElements :

package com.cellfish.mediadb.rest.lucene;

import javax.xml.bind.annotation.XmlElement;

class MapElements
{
  @XmlElement public String  key;
  @XmlElement public Integer value;

  private MapElements() {} //Required by JAXB

  public MapElements(String key, Integer value)
  {
    this.key   = key;
    this.value = value;
  }
}

MapAdapter :

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

class MapAdapter extends XmlAdapter<MapElements[], Map<String, Integer>> {
    public MapElements[] marshal(Map<String, Integer> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, Integer> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, Integer> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, Integer> r = new HashMap<String, Integer>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

The rootElement :

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, Integer> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, Integer>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, Integer> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, Integer> map) {
        this.mapProperty = map;
    }

}

I found the code in this website : http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/

AngularJS : Clear $watch

$watch returns a deregistration function. Calling it would deregister the $watcher.

var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch