Programs & Examples On #Execv

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

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

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

For windows :

Package.json

  "scripts": {
    "start": "nodemon app.js",
    "test": "mocha"
  },

then run the command

npm run test

Why do I get permission denied when I try use "make" to install something?

On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR make variable, so you can often do:

 make install DESTDIR=/tmp/myinst/
 sudo cp -va /tmp/myinst/ /

The advantage of this approach is that make install don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).

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

  • execve() replaces the current executable image with another one loaded from an executable file.
  • fork() creates a child process.
  • vfork() is a historical optimized version of fork(), meant to be used when execve() is called directly after fork(). It turned out to work well in non-MMU systems (where fork() cannot work in an efficient manner) and when fork()ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()). POSIX has standardized the posix_spawn() to replace these latter two more modern uses of vfork().
  • posix_spawn() does the equivalent of a fork()/execve(), and also allows some fd juggling in between. It's supposed to replace fork()/execve(), mainly for non-MMU platforms.
  • pthread_create() creates a new thread.
  • clone() is a Linux-specific call, which can be used to implement anything from fork() to pthread_create(). It gives a lot of control. Inspired on rfork().
  • rfork() is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.

"No such file or directory" error when executing a binary

It is possible that the executable is statically linked and that is why ldd gzip does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.

I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.

How to duplicate sys.stdout to a log file?

(Ah, just re-read your question and see that this doesn't quite apply.)

Here is a sample program that makes uses the python logging module. This logging module has been in all versions since 2.3. In this sample the logging is configurable by command line options.

In quite mode it will only log to a file, in normal mode it will log to both a file and the console.

import os
import sys
import logging
from optparse import OptionParser

def initialize_logging(options):
    """ Log information based upon users options"""

    logger = logging.getLogger('project')
    formatter = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s')
    level = logging.__dict__.get(options.loglevel.upper(),logging.DEBUG)
    logger.setLevel(level)

    # Output logging information to screen
    if not options.quiet:
        hdlr = logging.StreamHandler(sys.stderr)
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)

    # Output logging information to file
    logfile = os.path.join(options.logdir, "project.log")
    if options.clean and os.path.isfile(logfile):
        os.remove(logfile)
    hdlr2 = logging.FileHandler(logfile)
    hdlr2.setFormatter(formatter)
    logger.addHandler(hdlr2)

    return logger

def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    # Setup command line options
    parser = OptionParser("usage: %prog [options]")
    parser.add_option("-l", "--logdir", dest="logdir", default=".", help="log DIRECTORY (default ./)")
    parser.add_option("-v", "--loglevel", dest="loglevel", default="debug", help="logging level (debug, info, error)")
    parser.add_option("-q", "--quiet", action="store_true", dest="quiet", help="do not log to console")
    parser.add_option("-c", "--clean", dest="clean", action="store_true", default=False, help="remove old log file")

    # Process command line options
    (options, args) = parser.parse_args(argv)

    # Setup logger format and output locations
    logger = initialize_logging(options)

    # Examples
    logger.error("This is an error message.")
    logger.info("This is an info message.")
    logger.debug("This is a debug message.")

if __name__ == "__main__":
    sys.exit(main())

@AspectJ pointcut for all methods of a class with specific annotation

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

How to use z-index in svg elements?

Another solution would be to use divs, which do use zIndex to contain the SVG elements.As here: https://stackoverflow.com/a/28904640/4552494

Android: show/hide a view using an animation

This can reasonably be achieved in a single line statement in API 12 and above. Below is an example where v is the view you wish to animate;

v.animate().translationXBy(-1000).start();

This will slide the View in question off to the left by 1000px. To slide the view back onto the UI we can simply do the following.

v.animate().translationXBy(1000).start();

I hope someone finds this useful.

Detect click outside Angular component

ginalx's answer should be set as the default one imo: this method allows for many optimizations.

The problem

Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click') on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.

You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

And, in *.component.html:


<button (click)="toggle()">Toggle the menu</button>

Javascript Get Values from Multiple Select Option Box

The for loop is getting one extra run. Change

for (x=0;x<=InvForm.SelBranch.length;x++)

to

for (x=0; x < InvForm.SelBranch.length; x++)

Why do abstract classes in Java have constructors?

A constructor in Java doesn't actually "build" the object, it is used to initialize fields.

Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

How to use a switch case 'or' in PHP

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got this from using the Anaconda default environment instead of my custom one with pandas installed.

Changing to the right environment and reopening the Jupyter notebooks did not fix this for me (python 3.7, pandas 0.23.0). Restarting Anaconda did.

Could not load the Tomcat server configuration

The application is trying to load /usr/share/tomcat7/conf/ which doesn't exist. Eclipse assumes conf is in the same directory as bin

In Ubuntu, conf is placed in /etc/tomcat7/ and there is a symbolic link in /var/lib/tomcat7/.

To solve this, you can either

  1. Download package from Apache Tomcat, and place them in a specific directory, say /opt/ or
  2. Create a symbolic link in /usr/share/tomcat7/ pointing to /etc/tomcat7/conf

Device not detected in Eclipse when connected with USB cable

Restarting the adb server, Eclipse, and device did the trick for me.

C:\Android\android-sdk\platform-tools>adb kill-server

C:\Android\android-sdk\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

I had the same problem as mentioned on this question.

How to create a function in SQL Server

This will work for most of the website names :

SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....

Javascript: The prettiest way to compare one value against multiple values

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

Replace input type=file by an image

its really simple you can try this:

$("#image id").click(function(){
    $("#input id").click();
});

Java - Convert integer to string

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

how to bind img src in angular 2 in ngFor?

Angular 2, 4 and Angular 5 compatible!

You have provided so few details, so I'll try to answer your question without them.

You can use Interpolation:

<img src={{imagePath}} />

Or you can use a template expression:

<img [src]="imagePath" />

In a ngFor loop it might look like this:

<div *ngFor="let student of students">
   <img src={{student.ImagePath}} />
</div>

DateTime.Now.ToShortDateString(); replace month and day

Little addition to Jason's answer:

  1. The ToShortDateString() is culture-sensitive.

From MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

That's mean it's better to use the ToString() method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString() is a good solution because it returns string which is familiar to a user.

  1. If you need just today's date you can use DateTime.Today.

Save bitmap to location

outStream = new FileOutputStream(file);

will throw exception without permission in AndroidManifest.xml (at least in os2.2):

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Git says local branch is behind remote branch, but it's not

This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:

git co master
git pull

Which fetched those changes. Then,

git co develop
git pull

Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.

What is the "double tilde" (~~) operator in JavaScript?

It hides the intention of the code.

It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

Some use it as a faster alternative to Math.floor, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

Update 2011-08:

With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.

See: tilde vs floor

Cell spacing in UICollectionView

Swift 3 Version

Simply create a UICollectionViewFlowLayout subclass and paste this method.

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let answer = super.layoutAttributesForElements(in: rect) else { return nil }

        for i in 1..<answer.count {
            let currentAttributes = answer[i]
            let previousAttributes = answer[i - 1]

            let maximumSpacing: CGFloat = 8
            let origin = previousAttributes.frame.maxX

            if (origin + maximumSpacing + currentAttributes.frame.size.width < self.collectionViewContentSize.width && currentAttributes.frame.origin.x > previousAttributes.frame.origin.x) {
                var frame = currentAttributes.frame
                frame.origin.x = origin + maximumSpacing
                currentAttributes.frame = frame
            }
        }

        return answer
}

JavaScript Extending Class

Try this:

Function.prototype.extends = function(parent) {
  this.prototype = Object.create(parent.prototype);
};

Monkey.extends(Monster);
function Monkey() {
  Monster.apply(this, arguments); // call super
}

Edit: I put a quick demo here http://jsbin.com/anekew/1/edit. Note that extends is a reserved word in JS and you may get warnings when linting your code, you can simply name it inherits, that's what I usually do.

With this helper in place and using an object props as only parameter, inheritance in JS becomes a bit simpler:

Function.prototype.inherits = function(parent) {
  this.prototype = Object.create(parent.prototype);
};

function Monster(props) {
  this.health = props.health || 100;
}

Monster.prototype = {
  growl: function() {
    return 'Grrrrr';
  }
};

Monkey.inherits(Monster);
function Monkey() {
  Monster.apply(this, arguments);
}

var monkey = new Monkey({ health: 200 });

console.log(monkey.health); //=> 200
console.log(monkey.growl()); //=> "Grrrr"

How to check if a file exists before creating a new file

you can also use Boost.

 boost::filesystem::exists( filename );

it works for files and folders.

And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).

Git with SSH on Windows

I fought with this problem for a few hours before stumbling on the obvious answer. The problem I had was I was using different ssh implementations between when I generated my keys and when I used git.

I used ssh-keygen from the command prompt to generate my keys and but when I tried "git clone ssh://..." I got the same results as you, a prompt for the password and the message "fatal: The remote end hung up unexpectedly".

Determine which ssh windows is using by executing the Windows "where" command.

C:\where ssh
C:\Program Files (x86)\Git\bin\ssh.exe

The second line tells you which exact program will be executed.

Next you need to determine which ssh that git is using. Find this by:

C:\set GIT_SSH
GIT_SSH=C:\Program Files\TortoiseSVN\bin\TortoisePlink.exe

And now you see the problem.

To correct this simply execute:

C:\set GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

To check if changes are applied:

C:\set GIT_SSH
GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe

Now git will be able to use the keys that you generated earlier.

This fix is so far only for the current window. To fix it completely you need to change your environment variable.

  1. Open Windows explorer
  2. Right-click Computer and select Properties
  3. Click Advanced System Settings link on the left
  4. Click the Environment Variables... button
  5. In the system variables section select the GIT_SSH variable and press the Edit... button
  6. Update the variable value.
  7. Press OK to close all windows

Now any future command windows you open will have the correct settings.

Hope this helps.

How do I activate C++ 11 in CMake?

What works for me is to set the following line in your CMakeLists.txt:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Setting this command activates the C++11 features for the compiler and after executing the cmake .. command, you should be able to use range based for loops in your code and compile it without any errors.

Add vertical whitespace using Twitter Bootstrap?

In v2, there isn't anything built-in for that much vertical space, so you'll want to stick with a custom class. For smaller heights, I usually just throw a <div class="control-group"> around a button.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

Place components which are created dynamically to entryComponents under @NgModuledecorator function.

@NgModule({
    imports: [
        FormsModule,
        CommonModule,
        DashbaordRoutingModule
    ],
    declarations: [
        MainComponent,
        TestDialog
    ],
    entryComponents: [
        TestDialog
    ]
})

How to render an ASP.NET MVC view as a string?

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

MVC2 .ascx style

protected string RenderViewToString<T>(string viewPath, T model) {
  ViewData.Model = model;
  using (var writer = new StringWriter()) {
    var view = new WebFormView(ControllerContext, viewPath);
    var vdd = new ViewDataDictionary<T>(model);
    var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                new TempDataDictionary(), writer);
    viewCxt.View.Render(viewCxt, writer);
    return writer.ToString();
  }
}

Razor .cshtml style

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

Edit: added Razor code.

Should you always favor xrange() over range()?

Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)

What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.

Adding a new value to an existing ENUM Type

Here is a more general but a rather fast-working solution, which apart from changing the type itself updates all columns in the database using it. The method can be applied even if a new version of ENUM is different by more than one label or misses some of the original ones. The code below replaces my_schema.my_type AS ENUM ('a', 'b', 'c') with ENUM ('a', 'b', 'd', 'e'):

CREATE OR REPLACE FUNCTION tmp() RETURNS BOOLEAN AS
$BODY$

DECLARE
    item RECORD;

BEGIN

    -- 1. create new type in replacement to my_type
    CREATE TYPE my_schema.my_type_NEW
        AS ENUM ('a', 'b', 'd', 'e');

    -- 2. select all columns in the db that have type my_type
    FOR item IN
        SELECT table_schema, table_name, column_name, udt_schema, udt_name
            FROM information_schema.columns
            WHERE
                udt_schema   = 'my_schema'
            AND udt_name     = 'my_type'
    LOOP
        -- 3. Change the type of every column using my_type to my_type_NEW
        EXECUTE
            ' ALTER TABLE ' || item.table_schema || '.' || item.table_name
         || ' ALTER COLUMN ' || item.column_name
         || ' TYPE my_schema.my_type_NEW'
         || ' USING ' || item.column_name || '::text::my_schema.my_type_NEW;';
    END LOOP;

    -- 4. Delete an old version of the type
    DROP TYPE my_schema.my_type;

    -- 5. Remove _NEW suffix from the new type
    ALTER TYPE my_schema.my_type_NEW
        RENAME TO my_type;

    RETURN true;

END
$BODY$
LANGUAGE 'plpgsql';

SELECT * FROM tmp();
DROP FUNCTION tmp();

The whole process will run fairly quickly, because if the order of labels persists, no actual change of data will happen. I applied the method on 5 tables using my_type and having 50,000-70,000 rows in each, and the whole process took just 10 seconds.

Of course, the function will return an exception in case if labels that are missing in the new version of the ENUM are used somewhere in the data, but in such situation something should be done beforehand anyway.

Font-awesome, input type 'submit'

Also possible like this

<button type="submit" class="icon-search icon-large"></button>

How do I add 24 hours to a unix timestamp in php?

You probably want to add one day rather than 24 hours. Not all days have 24 hours due to (among other circumstances) daylight saving time:

strtotime('+1 day', $timestamp);

Open file in a relative location in Python

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!

Namespace for [DataContract]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx

DataContractAttribute is in System.Runtime.Serialization namespace and you should reference System.Runtime.Serialization.dll. It's only available in .Net >= 3

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

It looks necessary to put a SET IDENTITY_INSERT Database.dbo.Baskets ON; before every SQL INSERT sending batch.

You can send several INSERT ... VALUES ... commands started with one SET IDENTITY_INSERT ... ON; string at the beginning. Just don't put any batch separator between.

I don't know why the SET IDENTITY_INSERT ... ON stops working after the sending block (for ex.: .ExecuteNonQuery() in C#). I had to put SET IDENTITY_INSERT ... ON; again at the beginning of next SQL command string.

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

How to set DateTime to null

You can write DateTime? newdate = null;

Fatal error: Call to undefined function mysqli_connect()

Simply do it

sudo apt install php-mysqli

It works perfectly and it is version independent

Line break in SSRS expression

In Order to implement Line Break in SSRS, there are 2 ways

  1. Setting HTML Markup Type
    Update the Markup Type of the placeholder to HTML and then make use of <br/> tag to introduce line break within the expression

="first line of text. Param1 value: " & Parameters!Param1.Value & "<br/>" & Parameters!Param1.Value

  1. Using Newline function
    Make use of Environment.NewLine() function to add line break within the expression.

="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine() & Parameters!Param1.Value

Note:- Always remember to leave a space after every "&" (ampersand) in order to evaluate the expression properly

When are static variables initialized?

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
  • These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

How do I delete a Git branch locally and remotely?

git branch -D <name-of-branch>
git branch -D -r origin/<name-of-branch>
git push origin :<name-of-branch>

Initializing select with AngularJS and ng-repeat

Thanks to TheSharpieOne for pointing out the ng-selected option. If that had been posted as an answer rather than as a comment, I would have made that the correct answer.

Here's a working JSFiddle: http://jsfiddle.net/coverbeck/FxM3B/5/.

I also updated the fiddle to use the title attribute, which I had left out in my original post, since it wasn't the cause of the problem (but it is the reason I want to use ng-repeat instead of ng-options).

HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator">
   <option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
</body>

JS:

function AppCtrl($scope) {

    $scope.filterCondition={
        operator: 'eq'
    }

    $scope.operators = [
        {value: 'eq', displayName: 'equals', title: 'The equals operator does blah, blah'},
        {value: 'neq', displayName: 'not equal', title: 'The not equals operator does yada yada'}
     ]
}

JComboBox Selection Change Listener?

I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.

How do I get the previous or last item?

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

system

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

As of Ruby 2.6, passing exception: true will raise an exception instead of returning false or nil:

>> system('invalid')
=> nil

>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013   

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

%x()

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

exec

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Open3.popen3

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

Could not establish secure channel for SSL/TLS with authority '*'

This was exact the problem I was facing. At some other article I got a hint to change the configuration. For me this works:

<bindings>
  <basicHttpBinding>
    <binding name="xxxBinding">
      <security mode="Transport">
        <transport clientCredentialType="Certificate"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

NuGet Package Restore Not Working

None of the other solutions worked in my situation:

AspNetCore dependencies had been installed/uninstalled and were being cached. 'AspNetCore.All' would refuse to properly update/reinstall/remove. And regardless of what i did, it would use the cached dependencies (that it was not compatible with), because they were a higher version.

  1. Backup Everything. Note the list of Dependencies you'll need to reinstall, Exit VisualStudio
  2. Open up all .proj files in a text editor and remove all PackageReference
  3. In each project, delete the bin, obj folders
  4. Delete any "packages" folders you find in the solution.
  5. Open solution, go into Tools > Nuget Package Manager > Package Manager Settings and Clear all Nuget caches. Check the console because it may fail to remove some items - copy the folder path and exit visual studio.
  6. Delete anything from that folder Reopen solution and start installing nuget packages again from scratch.

If that still doesn't work, repeat but also search your drive in windows explorer for nuget and delete anything cachey looking.

Set variable value to array of strings

In SQL you can not have a variable array.
However, the best alternative solution is to use a temporary table.

How can I combine multiple rows into a comma-delimited list in Oracle?

The WM_CONCAT function (if included in your database, pre Oracle 11.2) or LISTAGG (starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:

select listagg(table_name, ', ') within group (order by table_name) 
  from user_tables;

or

select wm_concat(table_name) 
  from user_tables;

More details/options

Link to documentation

Can't connect to MySQL server on 'localhost' (10061)

I got this error when I ran out of space on my drive.

No Activity found to handle Intent : android.intent.action.VIEW

This is the right way to do it.

    try
    {
    Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
    File file = new File(aFile.getAbsolutePath()); 
    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    myIntent.setDataAndType(Uri.fromFile(file),mimetype);
    startActivity(myIntent);
    }
    catch (Exception e) 
    {
        // TODO: handle exception
        String data = e.getMessage();
    }

you need to import import android.webkit.MimeTypeMap;

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to update RecyclerView Adapter Data?

These methods are efficient and good to start using a basic RecyclerView.

private List<YourItem> items;

public void setItems(List<YourItem> newItems)
{
    clearItems();
    addItems(newItems);
}

public void addItem(YourItem item, int position)
{
    if (position > items.size()) return;

    items.add(item);
    notifyItemInserted(position);
}

public void addMoreItems(List<YourItem> newItems)
{
    int position = items.size() + 1;
    newItems.addAll(newItems);
    notifyItemChanged(position, newItems);
}

public void addItems(List<YourItem> newItems)
{
    items.addAll(newItems);
    notifyDataSetChanged();
}

public void clearItems()
{
    items.clear();
    notifyDataSetChanged();
}

public void addLoader()
{
    items.add(null);
    notifyItemInserted(items.size() - 1);
}

public void removeLoader()
{
    items.remove(items.size() - 1);
    notifyItemRemoved(items.size());
}

public void removeItem(int position)
{
    if (position >= items.size()) return;

    items.remove(position);
    notifyItemRemoved(position);
}

public void swapItems(int positionA, int positionB)
{
    if (positionA > items.size()) return;
    if (positionB > items.size()) return;

    YourItem firstItem = items.get(positionA);

    videoList.set(positionA, items.get(positionB));
    videoList.set(positionB, firstItem);

    notifyDataSetChanged();
}

You can implement them inside of an Adapter Class or in your Fragment or Activity but in that case you have to instantiate the Adapter to call the notification methods. In my case I usually implement it in the Adapter.

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

Exploring Docker container's file system

Before Container Creation :

If you to explore the structure of the image that is mounted inside the container you can do

sudo docker image save image_name > image.tar
tar -xvf image.tar

This would give you the visibility of all the layers of an image and its configuration which is present in json files.

After container creation :

For this there are already lot of answers above. my preferred way to do this would be -

docker exec -t -i container /bin/bash

How to open an Excel file in C#?

Imports

 using Excel= Microsoft.Office.Interop.Excel;
 using Microsoft.VisualStudio.Tools.Applications.Runtime;

Here is the code to open an excel sheet using C#.

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
    Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

    wbv.Close(true, Type.Missing, Type.Missing);
    excel.Quit();

Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4

How to use timer in C?

Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:

#include <time.h> 
time_t my_t, fire_t;

Then (for times over 1 second), initialize your timer by reading the current time:

my_t = time(NULL);

Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.

Inside your loop do another

my_t = time(NULL);

if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.

A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.

sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.

If you're trying to sleep and do work at the same time you need threads.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Convert pandas Series to DataFrame

Series.reset_index with name argument

Often the use case comes up where a Series needs to be promoted to a DataFrame. But if the Series has no name, then reset_index will result in something like,

s = pd.Series([1, 2, 3], index=['a', 'b', 'c']).rename_axis('A')
s

A
a    1
b    2
c    3
dtype: int64

s.reset_index()

   A  0
0  a  1
1  b  2
2  c  3

Where you see the column name is "0". We can fix this be specifying a name parameter.

s.reset_index(name='B')

   A  B
0  a  1
1  b  2
2  c  3

s.reset_index(name='list')

   A  list
0  a     1
1  b     2
2  c     3

Series.to_frame

If you want to create a DataFrame without promoting the index to a column, use Series.to_frame, as suggested in this answer. This also supports a name parameter.

s.to_frame(name='B')

   B
A   
a  1
b  2
c  3

pd.DataFrame Constructor

You can also do the same thing as Series.to_frame by specifying a columns param:

pd.DataFrame(s, columns=['B'])

   B
A   
a  1
b  2
c  3

Center-align a HTML table

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work. Cheers

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How can I get the source code of a Python function?

If you're strictly defining the function yourself and it's a relatively short definition, a solution without dependencies would be to define the function in a string and assign the eval() of the expression to your function.

E.g.

funcstring = 'lambda x: x> 5'
func = eval(funcstring)

then optionally to attach the original code to the function:

func.source = funcstring

How to do error logging in CodeIgniter (PHP)

To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.

First, to trigger an error:

trigger_error("Error message here", E_USER_ERROR);

By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:

ini_set('error_log', 'path/to/log/file');

Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)

To e-mail the error, you need to set up a custom error handler:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

Please see the relevant PHP documentation for more info.

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 ...

Get Request and Session Parameters and Attributes from JSF pages

You can either use

<h:outputText value="#{param['id']}" /> or

<h:outputText value="#{request.getParameter('id')}" />

However if you want to pass the parameters to your backing beans, using f:viewParam is probably what you want. "A view parameter is a mapping between a query string parameter and a model value."

<f:viewParam name="id" value="#{blog.entryId}"/>

This will set the id param of the GET parameter to the blog bean's entryId field. See http://java.dzone.com/articles/bookmarkability-jsf-2 for the details.

Newline in JLabel

Surround the string with <html></html> and break the lines with <br/>.

JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);

ImportError: No module named _ssl

I had exactly the same problem. I fixed it without rebuilding python, as follows:

  1. Find another server with the same architecture (i386 or x86_64) and the same python version (example: 2.7.5). Yes, this is the hard part. You can try installing python from sources into another server if you can't find any server with the same python version.

  2. In this another server, check if import ssl works. It should work.

  3. If it works, then try to find the _ssl lilbrary as follows:

    [root@myserver]# find / -iname _ssl.so
    /usr/local/python27/lib/python2.7/lib-dynload/_ssl.so
    
  4. Copy this file into the original server. Use the same destination folder: /usr/local/python27/lib/python2.7/lib-dynload/

  5. Double check owner and permissions:

    [root@myserver]# chown root:root _ssl.so
    [root@myserver]# chmod 755 _ssl.so
    
  6. Now you should be able to import ssl.

This worked for me in a CentOS 6.3 x86_64 environment with python 2.7.3. Also I had python 2.6.6 installed, but with ssl working fine.

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

Config Error: This configuration section cannot be used at this path

For Windows Server 2008 and IIS 7, the procedure is similar. please refer to this: http://msdn.microsoft.com/en-us/library/vstudio/bb763178(v=vs.100).aspx

in add role service, u will see "Application Development Features"

Check (enable) the features. I checked all.

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

javascript code to check special characters

Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.

function isValid(str) {
    var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";

    for (var i = 0; i < str.length; i++) {
       if (iChars.indexOf(str.charAt(i)) != -1) {
           alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
           return false;
       }
    }
    return true;
}

I tried this in my chrome console and it worked well.

jquery how to use multiple ajax calls one after the end of the other

You are somewhat close, but you should put your function inside the document.ready event handler instead of the other-way-around.

Another way to do this is by placing your AJAX call in a generic function and call that function from an AJAX callback to loop through a set of requests in order:

$(function () {

    //setup an array of AJAX options,
    //each object will specify information for a single AJAX request
    var ajaxes  = [
            {
                url      : '<url>',
                data     : {...},
                callback : function (data) { /*do work on data*/ }
            },
            {
                url      : '<url2>',
                data     : {...},
                callback : function (data) { /*maybe something different (maybe not)*/ }
            }
        ],
        current = 0;

    //declare your function to run AJAX requests
    function do_ajax() {

        //check to make sure there are more requests to make
        if (current < ajaxes.length) {

            //make the AJAX request with the given info from the array of objects
            $.ajax({
                url      : ajaxes[current].url,
                data     : ajaxes[current].data,
                success  : function (serverResponse) {

                    //once a successful response has been received,
                    //no HTTP error or timeout reached,
                    //run the callback for this request
                    ajaxes[current].callback(serverResponse);

                },
                complete : function () {

                    //increment the `current` counter
                    //and recursively call our do_ajax() function again.
                    current++;
                    do_ajax();

                    //note that the "success" callback will fire
                    //before the "complete" callback

                }
            });
        }
    }

    //run the AJAX function for the first time once `document.ready` fires
    do_ajax();

});

In this example, the recursive call to run the next AJAX request is being set as the complete callback so that it runs regardless of the status of the current response. Meaning that if the request times out or returns an HTTP error (or invalid response), the next request will still run. If you require subsequent requests to only run when a request is successful, then using the success callback to make your recursive call would likely be best.

Updated 2018-08-21 in regards to good points in comments.

C# delete a folder and all files and folders within that folder

Try this.

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
            foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                    DeleteDirectory(dir.FullName, true);
        }
        public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
        {
            if (Directory.Exists(directoryName))
                Directory.Delete(directoryName, true);
            else if (checkDirectiryExist)
                throw new SystemException("Directory you want to delete is not exist");
        }
    }
}

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

Finalize vs Dispose

The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).

The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.

The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

how to call url of any other website in php

Check out the PHP cURL functions. They should do what you want.

Or if you just want a simple URL GET then:

$lines = file('http://www.example.com/');

Disabled href tag

I see there are already a ton of answers posted here, but I don’t think there’s any clear one yet that combines the already mentioned approaches into the one I’ve found to work. This is to make the link both appear disabled, and also not redirect the user to another page.

This answer assumes you’re using jquery and bootstrap, and uses another property to temporarily store the href property while disabled.

//situation where link enable/disable should be toggled
function toggle_links(enable) {
    if (enable) {
        $('.toggle-link')
        .removeClass('disabled')
        .prop('href', $(this).attr('data-href'))
    }
    else {
        $('.toggle-link')
        .addClass('disabled')
        .prop('data-href', $(this).prop('href'))
        .prop('href','#')
    }
a.disabled {
  cursor: default;
}

How to get the current working directory in Java?

This will give you the path of your current working directory:

Path path = FileSystems.getDefault().getPath(".");

And this will give you the path to a file called "Foo.txt" in the working directory:

Path path = FileSystems.getDefault().getPath("Foo.txt");

Edit : To obtain an absolute path of current directory:

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

* Update * To get current working directory:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

How to place two divs next to each other?

My approach:

<div class="left">Left</div>
<div class="right">Right</div>

CSS:

.left {
    float: left;
    width: calc(100% - 200px);
    background: green;
}

.right {
    float: right;
    width: 200px;
    background: yellow;
}

C++ Fatal Error LNK1120: 1 unresolved externals

In my case, the argument type was different in the header file and .cpp file. In the header file the type was std::wstring and in the .cpp file it was LPCWSTR.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Try forcing updates using the mvn cpu option:

usage: mvn [options] [<goal(s)>] [<phase(s)>]

Options:
 -cpu,--check-plugin-updates            Force upToDate check for any
                                        relevant registered plugins

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

UITableView - change section header color

For swift 5 +

In willDisplayHeaderView Method

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

     //For Header Background Color
     view.tintColor = .black

    // For Header Text Color
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = .white
}

I hope this helps you :]

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

How can I call PHP functions by JavaScript?

If you actually want to send data to a php script for example you can do this:

The php:

<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized

echo $a + $b;
?>

Js (using jquery):

$.post("/path/to/above.php", {a: something, b: something}, function(data){                                          
  $('#somediv').html(data);
});

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

How to avoid 'cannot read property of undefined' errors?

Lodash has a get method which allows for a default as an optional third parameter, as show below:

_x000D_
_x000D_
const myObject = {_x000D_
  has: 'some',_x000D_
  missing: {_x000D_
    vars: true_x000D_
  }_x000D_
}_x000D_
const path = 'missing.const.value';_x000D_
const myValue = _.get(myObject, path, 'default');_x000D_
console.log(myValue) // prints out default, which is specified above
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Tooltip with HTML content without JavaScript

You can use the title attribute, e.g. if you want to have a Tooltip over a text, just make:

_x000D_
_x000D_
<span title="This is a Tooltip">This is a text</span>
_x000D_
_x000D_
_x000D_

How to style a disabled checkbox?

input[type='checkbox'][disabled][checked] {
width:0px; height:0px;
}
input[type='checkbox'][disabled][checked]:after {
 content:'\e013'; position:absolute; 
 margin-top:-10px;
 opacity: 1 !important;
 margin-left:-5px;
 font-family: 'Glyphicons Halflings';
 font-style: normal;
 font-weight: normal;
}

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Sort divs in jQuery based on attribute 'data-sort'?

Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!

Best Practices: working with long, multiline strings in PHP?

You should use heredoc or nowdoc.

$var = "some text";
$text = <<<EOT
  Place your text between the EOT. It's
  the delimiter that ends the text
  of your multiline string.
  $var
EOT;

The difference between heredoc and nowdoc is that PHP code embedded in a heredoc gets executed, while PHP code in nowdoc will be printed out as is.

$var = "foo";
$text = <<<'EOT'
  My $var
EOT;

In this case $text will have the value "My $var", not "My foo".

Notes:

  • Before the closing EOT; there should be no spaces or tabs. otherwise you will get an error.
  • The string/tag (EOT) that enclose the text is arbitrary, that is, one can use other strings, e.g. <<<FOO and FOO;
  • EOT : End of transmission, EOD: End of data. [Q]

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

Adding a new entry to the PATH variable in ZSH

one liner, without opening ~/.zshrc file

echo -n 'export PATH=~/bin:$PATH' >> ~/.zshrc

or

echo -n 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc

To see the effect, do source ~/.zshrc in the same tab or open a new tab

Can a website detect when you are using Selenium with chromedriver?

Example of how it's implemented on wellsfargo.com:

try {
 if (window.document.documentElement.getAttribute("webdriver")) return !+[]
} catch (IDLMrxxel) {}
try {
 if ("_Selenium_IDE_Recorder" in window) return !+""
} catch (KknKsUayS) {}
try {
 if ("__webdriver_script_fn" in document) return !+""

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

It's supposed to be as simple as this:

<select id='multipleSelect' multiple='multiple'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<script type='text/javascript'>
    $('#multipleSelect').val(['1', '2']);
</script>

Check my Fiddle: https://jsfiddle.net/luthrayatin/jaLygLzo/

Sending files using POST with HttpURLConnection

based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :

ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
        byte[] pixels = bos.toByteArray();

jQuery select change event get selected option

I find this shorter and cleaner. Besides, you can iterate through selected items if there are more than one;

$('select').on('change', function () {
     var selectedValue = this.selectedOptions[0].value;
     var selectedText  = this.selectedOptions[0].text;
});

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Anyone getting this error with Azure build pipelines, try the below step to change environment variable of build agent

Add an Azure build pipeline task -> Azure powershell script:Inlinescript before Compile with below settings

- task: AzurePowerShell@3
  displayName: 'Azure PowerShell script: InlineScript'
  inputs:
    azureSubscription: 'NYCSCA Azure Dev/Test (ea91a274-55c6-461c-a11d-758ef02c2698)'
    ScriptType: InlineScript
    Inline: '[Environment]::SetEnvironmentVariable("NODE_OPTIONS", "--max_old_space_size=16384", "Machine")'
    FailOnStandardError: true
    azurePowerShellVersion: LatestVersion

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

I had this issue for 2 days, let me show you how I fixed it.

This was how the code looked when I was getting the error:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.response);
    console.log(data)
}

This is what I changed to get the result I wanted:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.responseText);
    console.log(data)
}

So all I really did was change this.response to this.responseText.

How do I 'git diff' on a certain directory?

To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:

In a Folder Compare ViewRules (Referee Icon):

Enter image description here

And then, enable follow symbolic links and update session defaults:

Enter image description here


OR,

set up the alias like so:

git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"

Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.

Best way to create enum of strings?

Use its name() method:

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Strings.ONE.name());
    }
}

enum Strings {
    ONE, TWO, THREE
}

yields ONE.

Composer update memory limit

In my case none of the answers helped. Finally it turned out, that changing to a 64 bit version of PHP (M$ Windows) fixed the problem immediately. I did not change any settings - it just worked.

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Zip folder in C#

This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

Can I automatically increment the file build version when using Visual Studio?

To get incrementing (DateTime) information into the AssemblyFileVersion property which has the advantage of not breaking any dependencies.


Building on Boog's solution (did not work for me, maybe because of VS2008?), you can use a combination of a pre-build event generating a file, adding that file (including its version properties) and then using a way to read out those values again. That is..

Pre-Build-Event:

echo [assembly:System.Reflection.AssemblyFileVersion("%date:~-4,4%.%date:~-7,2%%date:~-10,2%.%time:~0,2%%time:~3,2%.%time:~-5,2%")] > $(ProjectDir)Properties\VersionInfo.cs

Include the resulting VersionInfo.cs file (Properties subfolder) into your project

Code to get Date back (years down to seconds):

var version = assembly.GetName().Version;
var fileVersionString = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
Version fileVersion = new Version(fileVersionString);
var buildDateTime = new DateTime(fileVersion.Major, fileVersion.Minor/100, fileVersion.Minor%100, fileVersion.Build/100, fileVersion.Build%100, fileVersion.Revision);

Not very comfortable.. also, I do not know if it creates a lot of force-rebuilds (since a file always changes).

You could make it smarter for example if you only update the VersionInfo.cs file every few minutes/hours (by using a temporary file and then copying/overwriting the real VersionInfo.cs if a change large enough is detected). I did this once pretty successfully.

Bad Gateway 502 error with Apache mod_proxy and Tomcat

I know this does not answer this question, but I came here because I had the same error with nodeJS server. I am stuck a long time until I found the solution. My solution just adds slash or /in end of proxyreserve apache.

my old code is:

ProxyPass / http://192.168.1.1:3001
ProxyPassReverse / http://192.168.1.1:3001

the correct code is:

ProxyPass / http://192.168.1.1:3001/
ProxyPassReverse / http://192.168.1.1:3001/

How to close existing connections to a DB

Short Answer:

You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.

Long Answer:

Right Click on the Databases under your Server-Name as shown below:

and select the option: "Restore Database..." from it.

db

In the "Restore Database" wizard,

  1. select one of your databases to restore
  2. in the left vertical menu, click on "Options"

db1

Here you can find the checkbox saying, "close existing connections to destination database"

db3

Just check it, and you can proceed for the restore operation.

It automatically will resume all connections after completion of the Restore.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

What does "request for member '*******' in something not a structure or union" mean?

You are trying to access a member of a structure, but in something that is not a structure. For example:

struct {
    int a;
    int b;
} foo;
int fum;
fum.d = 5;

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

How to copy and edit files in Android shell?

To copy dirs, it seems you can use adb pull <remote> <local> if you want to copy file/dir from device, and adb push <local> <remote> to copy file/dir to device. Alternatively, just to copy a file, you can use a simple trick: cat source_file > dest_file. Note that this does not work for user-inaccessible paths.

To edit files, I have not found a simple solution, just some possible workarounds. Try this, it seems you can (after the setup) use it to edit files like busybox vi <filename>. Nano seems to be possible to use too.

regular expression to validate datetime format (MM/DD/YYYY)

based on this

dd-mm-yy

I modified the original to this:

^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

test the regex here

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL. Here an example: (I used a procedure instead of a function, like @Thilo did)

create or replace procedure myprocedure(retval in out sys_refcursor) is
begin
  open retval for
    select TABLE_NAME from user_tables;
end myprocedure;

 declare 
   myrefcur sys_refcursor;
   tablename user_tables.TABLE_NAME%type;
 begin
   myprocedure(myrefcur);
   loop
     fetch myrefcur into tablename;
     exit when myrefcur%notfound;
     dbms_output.put_line(tablename);
   end loop;
   close myrefcur;
 end;

Get width/height of SVG element

A save method to determine the width and height unit of any element (no padding, no margin) is the following:

let div   = document.querySelector("div");
let style = getComputedStyle(div);

let width  = parseFloat(style.width.replace("px", ""));
let height = parseFloat(style.height.replace("px", ""));

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

I had to close and re-open my windows console (or open a new console), and then open the SDK manager (ran android), after which a bunch of updates and installs had to complete.

SQL - Create view from multiple tables

This works too and you dont have to use join or anything:

DROP VIEW IF EXISTS yourview;

CREATE VIEW yourview AS
    SELECT table1.column1, 
    table2.column2
FROM 
table1, table2 
WHERE table1.column1 = table2.column1;

CSS3 Spin Animation

As of latest Chrome/FF and on IE11 there's no need for -ms/-moz/-webkit prefix. Here's a shorter code (based on previous answers):

div {
    margin: 20px;
    width: 100px;
    height: 100px;
    background: #f00;

    /* The animation part: */
    animation-name: spin;
    animation-duration: 4000ms;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}
@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

Live Demo: http://jsfiddle.net/9Ryvs/3057/

Find distance between two points on map using Google Map API V2

public class GoogleDirection {

    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";
    public final static String MODE_BICYCLING = "bicycling";

    public final static String STATUS_OK = "OK";
    public final static String STATUS_NOT_FOUND = "NOT_FOUND";
    public final static String STATUS_ZERO_RESULTS = "ZERO_RESULTS";
    public final static String STATUS_MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED";
    public final static String STATUS_INVALID_REQUEST = "INVALID_REQUEST";
    public final static String STATUS_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT";
    public final static String STATUS_REQUEST_DENIED = "REQUEST_DENIED";
    public final static String STATUS_UNKNOWN_ERROR = "UNKNOWN_ERROR";

    public final static int SPEED_VERY_FAST = 1;
    public final static int SPEED_FAST = 2;
    public final static int SPEED_NORMAL = 3;
    public final static int SPEED_SLOW = 4;
    public final static int SPEED_VERY_SLOW = 5;

    private OnDirectionResponseListener mDirectionListener = null;
    private OnAnimateListener mAnimateListener = null;

    private boolean isLogging = false;

    private LatLng animateMarkerPosition = null;
    private LatLng beginPosition = null;
    private LatLng endPosition = null;
    private ArrayList<LatLng> animatePositionList = null;
    private Marker animateMarker = null;
    private Polyline animateLine = null;
    private GoogleMap gm = null;
    private int step = -1;
    private int animateSpeed = -1;
    private int zoom = -1;
    private double animateDistance = -1;
    private double animateCamera = -1;
    private double totalAnimateDistance = 0;
    private boolean cameraLock = false;
    private boolean drawMarker = false;
    private boolean drawLine = false;
    private boolean flatMarker = false;
    private boolean isCameraTilt = false;
    private boolean isCameraZoom = false;
    private boolean isAnimated = false;

    private Context mContext = null;

    public GoogleDirection(Context context) { 
        mContext = context;
    }

    public String request(LatLng start, LatLng end, String mode) {
        final String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude  
                + "&destination=" + end.latitude + "," + end.longitude 
                + "&sensor=false&units=metric&mode=" + mode;

        if(isLogging)
            Log.i("GoogleDirection", "URL : " + url);
        new RequestTask().execute(new String[]{ url });
        return url;
    }

    private class RequestTask extends AsyncTask<String, Void, Document> {
        protected Document doInBackground(String... url) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url[0]);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                InputStream in = response.getEntity().getContent();
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                return builder.parse(in);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } 
            return null;
        }

        protected void onPostExecute(Document doc) {
            super.onPostExecute(doc);
            if(mDirectionListener != null)
                mDirectionListener.onResponse(getStatus(doc), doc, GoogleDirection.this);
        }

        private String getStatus(Document doc) {
            NodeList nl1 = doc.getElementsByTagName("status");
            Node node1 = nl1.item(0);
            if(isLogging)
                Log.i("GoogleDirection", "Status : " + node1.getTextContent());
            return node1.getTextContent();
        }
    }

    public void setLogging(boolean state) {
        isLogging = state;
    }

    public String getStatus(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("status");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "Status : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String[] getDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String[] getDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "CopyRights : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude
                            , arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public ArrayList<LatLng> getSection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public PolylineOptions getPolyline(Document doc, int width, int color) {
        ArrayList<LatLng> arr_pos = getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(dpToPx(width)).color(color);
        for(int i = 0 ; i < arr_pos.size() ; i++)        
            rectLine.add(arr_pos.get(i));
        return rectLine;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng((double)lat / 1E5, (double)lng / 1E5);
            poly.add(position);
        }
        return poly;
    }

    private int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
        return px;
    }

    public void setOnDirectionResponseListener(OnDirectionResponseListener listener) {
        mDirectionListener = listener;
    }

    public void setOnAnimateListener(OnAnimateListener listener) {
        mAnimateListener = listener;
    }

    public interface OnDirectionResponseListener {
        public void onResponse(String status, Document doc, GoogleDirection gd);
    }

    public interface OnAnimateListener {
        public void onFinish();
        public void onStart();
        public void onProgress(int progress, int total);
    }

    public void animateDirection(GoogleMap gm, ArrayList<LatLng> direction, int speed
            , boolean cameraLock, boolean isCameraTilt, boolean isCameraZoom
            , boolean drawMarker, MarkerOptions mo, boolean flatMarker
            , boolean drawLine, PolylineOptions po) {
        if(direction.size() > 1) {
            isAnimated = true;
            animatePositionList = direction;
            animateSpeed = speed;
            this.drawMarker = drawMarker;
            this.drawLine = drawLine;
            this.flatMarker = flatMarker;
            this.isCameraTilt = isCameraTilt;
            this.isCameraZoom = isCameraZoom;
            step = 0;
            this.cameraLock = cameraLock;
            this.gm = gm;

            setCameraUpdateSpeed(speed);

            beginPosition = animatePositionList.get(step);
            endPosition = animatePositionList.get(step + 1);
            animateMarkerPosition = beginPosition;

            if(mAnimateListener != null)
                mAnimateListener.onProgress(step, animatePositionList.size());

            if(cameraLock) {
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt) 
                    cameraBuilder.tilt(90);
                else 
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom) 
                    cameraBuilder.zoom(zoom);
                else 
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }

            if(drawMarker) {
                if(mo != null)
                    animateMarker = gm.addMarker(mo.position(beginPosition));
                else 
                    animateMarker = gm.addMarker(new MarkerOptions().position(beginPosition));

                if(flatMarker) {
                    animateMarker.setFlat(true);

                    float rotation = getBearing(animateMarkerPosition, endPosition) + 180;
                    animateMarker.setRotation(rotation);
                }
            }


            if(drawLine) {
                if(po != null) 
                    animateLine = gm.addPolyline(po.add(beginPosition)
                            .add(beginPosition).add(endPosition)
                            .width(dpToPx((int)po.getWidth())));
                else 
                    animateLine = gm.addPolyline(new PolylineOptions()
                            .width(dpToPx(5)));
            }

            new Handler().postDelayed(r, speed);
            if(mAnimateListener != null)
                mAnimateListener.onStart();
        }
    }

    public void cancelAnimated() {
        isAnimated = false;
    }

    public boolean isAnimated() {
        return isAnimated;
    }

    private Runnable r = new Runnable() {
        public void run() {

            animateMarkerPosition = getNewPosition(animateMarkerPosition, endPosition);

            if(drawMarker)
                animateMarker.setPosition(animateMarkerPosition);


            if(drawLine) {
                List<LatLng> points = animateLine.getPoints();
                points.add(animateMarkerPosition);
                animateLine.setPoints(points);
            }

            if((animateMarkerPosition.latitude == endPosition.latitude 
                    && animateMarkerPosition.longitude == endPosition.longitude)) {
                if(step == animatePositionList.size() - 2) {
                    isAnimated = false;
                    totalAnimateDistance = 0;
                    if(mAnimateListener != null)
                        mAnimateListener.onFinish();
                } else {
                    step++;
                    beginPosition = animatePositionList.get(step);
                    endPosition = animatePositionList.get(step + 1);
                    animateMarkerPosition = beginPosition;

                    if(flatMarker && step + 3 < animatePositionList.size() - 1) {
                        float rotation = getBearing(animateMarkerPosition, animatePositionList.get(step + 3)) + 180;
                        animateMarker.setRotation(rotation);
                    }

                    if(mAnimateListener != null)
                        mAnimateListener.onProgress(step, animatePositionList.size());
                }
            }

            if(cameraLock && (totalAnimateDistance > animateCamera || !isAnimated)) {
                totalAnimateDistance = 0;
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt) 
                    cameraBuilder.tilt(90);
                else 
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom) 
                    cameraBuilder.zoom(zoom);
                else 
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }

            if(isAnimated) {
                new Handler().postDelayed(r, animateSpeed);
            }
        }
    };

    public Marker getAnimateMarker() {
        return animateMarker;
    }

    public Polyline getAnimatePolyline() {
        return animateLine;
    }

    private LatLng getNewPosition(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude); 
        double lng = Math.abs(begin.longitude - end.longitude);

        double dis = Math.sqrt(Math.pow(lat, 2) + Math.pow(lng, 2));
        if(dis >= animateDistance) {
            double angle = -1;

            if(begin.latitude <= end.latitude && begin.longitude <= end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat));
            else if(begin.latitude > end.latitude && begin.longitude <= end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 90;
            else if(begin.latitude > end.latitude && begin.longitude > end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat)) + 180;
            else if(begin.latitude <= end.latitude && begin.longitude > end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 270;

            double x = Math.cos(Math.toRadians(angle)) * animateDistance;
            double y = Math.sin(Math.toRadians(angle)) * animateDistance;
            totalAnimateDistance += animateDistance;
            double finalLat = begin.latitude + x;
            double finalLng = begin.longitude + y;

            return new LatLng(finalLat, finalLng);
        } else {
            return end;
        }
    }

    private float getBearing(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude); 
        double lng = Math.abs(begin.longitude - end.longitude);
         if(begin.latitude < end.latitude && begin.longitude < end.longitude)
            return (float)(Math.toDegrees(Math.atan(lng / lat)));
        else if(begin.latitude >= end.latitude && begin.longitude < end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
        else if(begin.latitude >= end.latitude && begin.longitude >= end.longitude)
            return  (float)(Math.toDegrees(Math.atan(lng / lat)) + 180);
        else if(begin.latitude < end.latitude && begin.longitude >= end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
         return -1;
    }

    public void setCameraUpdateSpeed(int speed) {       
        if(speed == SPEED_VERY_SLOW) {
            animateDistance = 0.000005;
            animateSpeed = 20;
            animateCamera = 0.0004;
            zoom = 19;
        } else if(speed == SPEED_SLOW) {
            animateDistance = 0.00001;
            animateSpeed = 20;
            animateCamera = 0.0008;
            zoom = 18;
        } else if(speed == SPEED_NORMAL) {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        } else if(speed == SPEED_FAST) {
            animateDistance = 0.0001;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 15;
        } else if(speed == SPEED_VERY_FAST) {
            animateDistance = 0.0005;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 13;
        } else {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        }
    }
}

//Main Activity

public class MapActivity extends ActionBarActivity {

    GoogleMap map = null;
    GoogleDirection gd;

    LatLng start,end;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        start = new LatLng(13.744246499553903, 100.53428772836924);
        end = new LatLng(13.751279688694071, 100.54316081106663);


        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 15));

        gd = new GoogleDirection(this);
        gd.setOnDirectionResponseListener(new GoogleDirection.OnDirectionResponseListener() {
            public void onResponse(String status, Document doc, GoogleDirection gd) {
                Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();

                gd.animateDirection(map, gd.getDirection(doc), GoogleDirection.SPEED_FAST
                        , true, true, true, false, null, false, true, new PolylineOptions().width(8).color(Color.RED));

                map.addMarker(new MarkerOptions().position(start)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markera)));

                map.addMarker(new MarkerOptions().position(end)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markerb)));

                String TotalDistance = gd.getTotalDistanceText(doc);
                String TotalDuration = gd.getTotalDurationText(doc);
            }
        });

        gd.request(start, end, GoogleDirection.MODE_DRIVING);
    }
}

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

How to view file history in Git?

git log --all -- path/to/file should work

Property 'value' does not exist on type 'Readonly<{}>'

The Component is defined like so:

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

Meaning that the default type for the state (and props) is: {}.
If you want your component to have value in the state then you need to define it like this:

class App extends React.Component<{}, { value: string }> {
    ...
}

Or:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}

How do I login and authenticate to Postgresql after a fresh install?

There are two methods you can use. Both require creating a user and a database.

By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydatabase as the example database name.

  1. Using createuser and createdb, we can be explicit about the database name,

    $ sudo -u postgres createuser -s $USER
    $ createdb mydatabase
    $ psql -d mydatabase
    

    You should probably be omitting that entirely and letting all the commands default to the user's name instead.

    $ sudo -u postgres createuser -s $USER
    $ createdb
    $ psql
    
  2. Using the SQL administration commands, and connecting with a password over TCP

    $ sudo -u postgres psql postgres
    

    And, then in the psql shell

    CREATE ROLE myuser LOGIN PASSWORD 'mypass';
    CREATE DATABASE mydatabase WITH OWNER = myuser;
    

    Then you can login,

    $ psql -h localhost -d mydatabase -U myuser -p <port>
    

    If you don't know the port, you can always get it by running the following, as the postgres user,

    SHOW port;
    

    Or,

    $ grep "port =" /etc/postgresql/*/main/postgresql.conf
    

Sidenote: the postgres user

I suggest NOT modifying the postgres user.

  1. It's normally locked from the OS. No one is supposed to "log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  2. It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  3. By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.

How to get a variable type in Typescript?

Type guards in typescript

To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:

An expression which allows you to narrow down the type of something within a conditional block.

In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.

Example

declare let abc: number | string;

// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
    // abc: string
    console.log('abc is a string here')
} else {
    // abc: number, only option because the previous type guard removed the option of string
    console.log('abc is a number here')
}

Besides the typeof operator there are built in type guards like instanceof, in and even your own type guards.

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:

<system.web>
    <customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>

remove inner shadow of text input

Set border: 1px solid black to make all sides equals and remove any kind of custom border (other than solid). Also, set box-shadow: none to remove any inset shadow applied to it.

Scanner method to get a char

Console cons = System.console();

The above code line creates cons as a null reference. The code and output are given below:

Console cons = System.console();
if (cons != null) {
    System.out.println("Enter single character: ");
    char c = (char) cons.reader().read();
    System.out.println(c);
}else{
    System.out.println(cons);
}

Output :

null

The code was tested on macbook pro with java version "1.6.0_37"

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

There is a single quote in $submitsubject or $submit_message

Why is this a problem?

The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.

Imagine if someone submitted '); DROP TABLE private_messages; in submit message.

Your SQL Command would be:

INSERT INTO private_messages (to_id, from_id, time_sent, subject, message) 
        VALUES('sender_id', 'id', now(),'subjet','');

DROP TABLE private_messages;

Instead you need to properly sanitize your values.

AT A MINIMUM you must run each value through mysql_real_escape_string() but you should really be using prepared statements.

If you were using mysql_real_escape_string() your code would look like this:

if($_POST['submit_message']){

if($_POST['form_subject']==""){
    $submit_subject="(no subject)";
}else{
    $submit_subject=mysql_real_escape_string($_POST['form_subject']); 
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);

Here is a great article on prepared statements and PDO.

Android EditText Hint

You can use the concept of selector. onFocus removes the hint.

android:hint="Email"

So when TextView has focus, or has user input (i.e. not empty) the hint will not display.

Convert integer value to matching Java Enum

You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);
    }
}

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null) 
        return PcapLinkType.DLT_UNKNOWN;
    return type;
}

How to test valid UUID/GUID?

If you want to check or validate a specific UUID version, here are the corresponding regexes.

Note that the only difference is the version number, which is explained in 4.1.3. Version chapter of UUID 4122 RFC.

The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3} :

  • UUID v1 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v2 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v3 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v4 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v5 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    

How do I remove link underlining in my HTML email?

To completely "hide" underline for <a> in both mail application and web browser, can do the following tricky way.

<a href="..."><div style="background-color:red;">
    <span style="color:red; text-decoration:underline;"><span style="color:white;">BUTTON</span></span>
</div></a>
  1. Color in 1st <span> is the one you don't need, MUST set as same as your background color. (red in here)

  2. Color in 2nd <span> is the one for your button text. (white in here)

Getting all documents from one collection in Firestore

I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)

Why does Oracle not find oci.dll?

I notice that recent Oracle client installers change file permissions.

I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.

My application suddenly failed to run.

I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL

I changed the permissions for everything in the Oracle client folders and application works as expected.

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

Read specific columns from a csv file with csv module?

SAMPLE.CSV
a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
print(df)
OUTPUT
  Letter  Number Symbol
0      a       1      +
1      b       2      -
2      c       3      *
3      d       4      /

letters = df.Letter.to_list()
print(letters)
OUTPUT
['a', 'b', 'c', 'd']

PHP How to find the time elapsed since a date time?

Here I am using custom function for finding the time elapsed since a date time.


echo Datetodays('2013-7-26 17:01:10');

function Datetodays($d) {

        $date_start = $d;
        $date_end = date('Y-m-d H:i:s');

        define('SECOND', 1);
        define('MINUTE', SECOND * 60);
        define('HOUR', MINUTE * 60);
        define('DAY', HOUR * 24);
        define('WEEK', DAY * 7);

        $t1 = strtotime($date_start);
        $t2 = strtotime($date_end);
        if ($t1 > $t2) {
            $diffrence = $t1 - $t2;
        } else {
            $diffrence = $t2 - $t1;
        }

        //echo "
".$date_end." ".$date_start." ".$diffrence; $results['major'] = array(); // whole number representing larger number in date time relationship $results1 = array(); $string = ''; $results['major']['weeks'] = floor($diffrence / WEEK); $results['major']['days'] = floor($diffrence / DAY); $results['major']['hours'] = floor($diffrence / HOUR); $results['major']['minutes'] = floor($diffrence / MINUTE); $results['major']['seconds'] = floor($diffrence / SECOND); //print_r($results); // Logic: // Step 1: Take the major result and transform it into raw seconds (it will be less the number of seconds of the difference) // ex: $result = ($results['major']['weeks']*WEEK) // Step 2: Subtract smaller number (the result) from the difference (total time) // ex: $minor_result = $difference - $result // Step 3: Take the resulting time in seconds and convert it to the minor format // ex: floor($minor_result/DAY) $results1['weeks'] = floor($diffrence / WEEK); $results1['days'] = floor((($diffrence - ($results['major']['weeks'] * WEEK)) / DAY)); $results1['hours'] = floor((($diffrence - ($results['major']['days'] * DAY)) / HOUR)); $results1['minutes'] = floor((($diffrence - ($results['major']['hours'] * HOUR)) / MINUTE)); $results1['seconds'] = floor((($diffrence - ($results['major']['minutes'] * MINUTE)) / SECOND)); //print_r($results1); if ($results1['weeks'] != 0 && $results1['days'] == 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' week ago'; } else { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' weeks ago'; } else { $string = '2 weeks ago'; } } } elseif ($results1['weeks'] != 0 && $results1['days'] != 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' week ago'; } else { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' weeks ago'; } else { $string = '2 weeks ago'; } } } elseif ($results1['weeks'] == 0 && $results1['days'] != 0) { if ($results1['days'] == 1) { $string = $results1['days'] . ' day ago'; } else { $string = $results1['days'] . ' days ago'; } } elseif ($results1['days'] != 0 && $results1['hours'] != 0) { $string = $results1['days'] . ' day and ' . $results1['hours'] . ' hours ago'; } elseif ($results1['days'] == 0 && $results1['hours'] != 0) { if ($results1['hours'] == 1) { $string = $results1['hours'] . ' hour ago'; } else { $string = $results1['hours'] . ' hours ago'; } } elseif ($results1['hours'] != 0 && $results1['minutes'] != 0) { $string = $results1['hours'] . ' hour and ' . $results1['minutes'] . ' minutes ago'; } elseif ($results1['hours'] == 0 && $results1['minutes'] != 0) { if ($results1['minutes'] == 1) { $string = $results1['minutes'] . ' minute ago'; } else { $string = $results1['minutes'] . ' minutes ago'; } } elseif ($results1['minutes'] != 0 && $results1['seconds'] != 0) { $string = $results1['minutes'] . ' minute and ' . $results1['seconds'] . ' seconds ago'; } elseif ($results1['minutes'] == 0 && $results1['seconds'] != 0) { if ($results1['seconds'] == 1) { $string = $results1['seconds'] . ' second ago'; } else { $string = $results1['seconds'] . ' seconds ago'; } } return $string; } ?>

Get Bitmap attached to ImageView

For those who are looking for Kotlin solution to get Bitmap from ImageView.

var bitmap = (image.drawable as BitmapDrawable).bitmap

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

You can do something like this, very simple and efficient solution: What i did was actually use a parameter instead of basic placeholder, created a SqlParameter object and used another existing execution method. For e.g in your scenario:

string sql = "INSERT INTO mssqltable (varbinarycolumn) VALUES (@img)";
SqlParameter param = new SqlParameter("img", arraytoinsert); //where img is your parameter name in the query
ExecuteStoreCommand(sql, param);

This should work like a charm, provided you have an open sql connection established.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

Is it possible to append to innerHTML without destroying descendants' event listeners?

Yes it is possible if you bind events using tag attribute onclick="sayHi()" directly in template similar like your <body onload="start()"> - this approach similar to frameworks angular/vue/react/etc. You can also use <template> to operate on 'dynamic' html like here. It is not strict unobtrusive js however it is acceptable for small projects

_x000D_
_x000D_
function start() {_x000D_
  mydiv.innerHTML += "bar";_x000D_
}_x000D_
_x000D_
function sayHi() {_x000D_
  alert("hi");_x000D_
}
_x000D_
<body onload="start()">_x000D_
  <div id="mydiv" style="border: solid red 2px">_x000D_
    <span id="myspan" onclick="sayHi()">foo</span>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

Staging Deleted files

You can use

git rm -r --cached -- "path/to/directory"

to stage a deleted directory.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

please add these codes to your dependencies. It will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Expanding on retrography's answer..: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .parseStrict()
  .appendPattern("uuuuMMdd")
  .toFormatter()
  .withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);

(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :

public static void main(String[] args) {
        ...
    }

Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.

Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.

Then you can spend some time talking about meaning of these IMHO.

You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.

public static void main(String ...args) {
        //...
    }

How to clamp an integer to some range?

Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.

for individual values:

min(clamp_max, max(clamp_min, value))

for lists of values:

map(lambda x: min(clamp_max, max(clamp_min, x)), values)

How can I dismiss the on screen keyboard?

Following code helped me to hide keyboard

   void initState() {
   SystemChannels.textInput.invokeMethod('TextInput.hide');
   super.initState();
   }

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

What is the height of iPhone's onscreen keyboard?

The keyboard height depends on the model, the QuickType bar, user settings... The best approach is calculate dinamically:

Swift 3.0

    var heightKeyboard : CGFloat?

    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    }

    func keyboardShown(notification: NSNotification) {
           if let infoKey  = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
               let rawFrame = (infoKey as AnyObject).cgRectValue {
               let keyboardFrame = view.convert(rawFrame, from: nil)
               self.heightKeyboard = keyboardFrame.size.height
               // Now is stored in your heightKeyboard variable
           }
    }

Change the selected value of a drop-down list with jQuery

Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:

<asp:DropDownList id="MyDropDown" runat="server" />

$("[id* = 'MyDropDown']").append("<option value='-1'>&nbsp;</option>"); //etc

Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.

Change status bar text color to light in iOS 9 with Objective-C

If you want to change Status Bar Style from the launch screen, You should take this way.

  1. Go to Project -> Target,

  2. Set Status Bar Style to Light Project Setting

  3. Set View controller-based status bar appearance to NO in Info.plist.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

If you're using cygwin, the syntax is slightly different for the basename command.

find . -name "*.zip" | while read filename; do unzip -o -d "`basename "$filename" .zip`" "$filename"; done;

Printing with "\t" (tabs) does not result in aligned columns

The "problem" with the tabs is that they indent the text to fixed tab positions, typically multiples of 4 or 8 characters (depending on the console or editor displaying them). Your first filename is 7 chars, so the next tab stop after its end is at position 8. Your subsequent filenames however are 8 chars long, so the next tab stop is at position 12.

If you want to ensure that columns get nicely indented at the same position, you need to take into account the actual length of previous columns, and either modify the number of following tabs, or pad with the required number of spaces instead. The latter can be achieved using e.g. System.out.printf with an appropriate format specification (e.g. "%1$13s" specifies a minimum width of 13 characters for displaying the first argument as a string).

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

How to fix a locale setting warning from Perl

Try to reinstall:

localess apt-get install --reinstall locales

Read more in How to change the default locale

Heap vs Binary Search Tree (BST)

As mentioned by others, Heap can do findMin or findMax in O(1) but not both in the same data structure. However I disagree that Heap is better in findMin/findMax. In fact, with a slight modification, the BST can do both findMin and findMax in O(1).

In this modified BST, you keep track of the the min node and max node everytime you do an operation that can potentially modify the data structure. For example in insert operation you can check if the min value is larger than the newly inserted value, then assign the min value to the newly added node. The same technique can be applied on the max value. Hence, this BST contain these information which you can retrieve them in O(1). (same as binary heap)

In this BST (Balanced BST), when you pop min or pop max, the next min value to be assigned is the successor of the min node, whereas the next max value to be assigned is the predecessor of the max node. Thus it perform in O(1). However we need to re-balance the tree, thus it will still run O(log n). (same as binary heap)

I would be interested to hear your thought in the comment below. Thanks :)

Update

Cross reference to similar question Can we use binary search tree to simulate heap operation? for more discussion on simulating Heap using BST.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .

public static class ThreadHelperClass
{
    delegate void SetTextCallback(Form f, Control ctrl, string text);
    /// <summary>
    /// Set text property of various controls
    /// </summary>
    /// <param name="form">The calling form</param>
    /// <param name="ctrl"></param>
    /// <param name="text"></param>
    public static void SetText(Form form, Control ctrl, string text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (ctrl.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            form.Invoke(d, new object[] { form, ctrl, text });
        }
        else
        {
            ctrl.Text = text;
        }
    }
}

Using the code:

 private void btnTestThread_Click(object sender, EventArgs e)
 {
    Thread demoThread =
       new Thread(new ThreadStart(this.ThreadProcSafe));
            demoThread.Start();
 }

 // This method is executed on the worker thread and makes 
 // a thread-safe call on the TextBox control. 
 private void ThreadProcSafe()
 {
     ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
     ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
 }

Character Limit in HTML

you can set maxlength with jquery which is very fast

jQuery(document).ready(function($){ //fire on DOM ready
 setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

How to return JSON data from spring Controller using @ResponseBody

When I was facing this issue, I simply put just getter setter methods and my issues were resolved.

I am using Spring boot version 2.0.

A child container failed during start java.util.concurrent.ExecutionException

Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.

Remove them all.

The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.

If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.

How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat

Im Maven Project:-

add follwing line in pom.xml file

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${default.javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${default.javax.servlet.jsp.version}</version>
            <scope>provided</scope>
        </dependency>

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:

Class method: Foo
Instance method: Foo

Why can't I reference my class library?

Unfortunately the only thing that worked for me was completely deleting and recreating the class library project, after having temporarily copied the class files in it elsewhere. Only then would the ASP.Net web project recognise the using statements that referred to the class library project. This was with Visual Studio 2010, not using ReSharper.

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

How to use responsive background image in css3 in bootstrap

I found this:

Full

An easy to use, full page image background template for Bootstrap 3 websites

http://startbootstrap.com/template-overviews/full/

or

using in your main div container:

html

<div class="container-fluid full">


</div>

css:

.full {
    background: url('http://placehold.it/1920x1080') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    height:100%;
}

How to convert a string with Unicode encoding to a string of letters

Solution for Kotlin:

val sourceContent = File("test.txt").readText(Charset.forName("windows-1251"))
val result = String(sourceContent.toByteArray())

Kotlin uses UTF-8 everywhere as default encoding.

Method toByteArray() has default argument - Charsets.UTF_8.

How do I add images in laravel view?

normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)

public
    upload_media
         photos
            image.png


$image  = public_path() . '/upload_media/photos/image.png'; // destination path

view PHP

<img src="<?= $image ?>">

View blade

<img src="{{ $image }}">

How to check if the string is empty?

I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

What you should do is compare to a descriptive variable name.

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

A good descriptive variable name is based on its context. You have to think about what the empty string is.

  • Where does it come from.
  • Why is it there.
  • Why do you need to check for it.

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

A good variable name may be not_filled_in

This makes the code very readable

if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

A good variable name may be CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

Compare this to

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

This would tell future coders that an empty string should always be considered as None.

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

There needs to be a separation of concern between the two.

How can I list all cookies for the current page with Javascript?

function listCookies() {
    let cookies = document.cookie.split(';')
    cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}

function findCookie(e) {
  let cookies = document.cookie.split(';')
  cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}

This is specifically for the window you're in. Tried to keep it clean and concise.

How do I create and read a value from cookie?

Through a interface similar to sessionStorage and localStorage:

const cookieStorage = {
  getItem: (key) {
    const cookies = document.cookie.split(';')
      .map(cookie => cookie.split('='))
      .reduce(
        (accumulation, [key, value]) => ({...accumulation, [key.trim()]: value}),
        {}
      )
    
    return cookies[key]
  },
  setItem: (key, value) {
    document.cookie = `${key}=${value}`
  },
}

Its usage cookieStorage.setItem('', '') and cookieStorage.getItem('').

Linux / Bash, using ps -o to get process by specific name?

This will get you the PID of a process by name:

pidof name

Which you can then plug back in to ps for more detail:

ps -p $(pidof name)

How to Extract Year from DATE in POSTGRESQL

Choose one from, where :my_date is a string input parameter of yyyy-MM-dd format:

SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));

or

SELECT DATE_PART('year', CAST(:my_date AS DATE));

Better use CAST than :: as there may be conflicts with input parameters.

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

If you are using Xcode 8.0 to 8.3.3 and swift 2.2 to 3.0

In my case need to change in URL http:// to https:// (if not working then try)

Add an App Transport Security Setting: Dictionary.
Add a NSAppTransportSecurity: Dictionary.
Add a NSExceptionDomains: Dictionary.
Add a yourdomain.com: Dictionary.  (Ex: stackoverflow.com)

Add Subkey named " NSIncludesSubdomains" as Boolean: YES
Add Subkey named " NSExceptionAllowsInsecureHTTPLoads" as Boolean: YES

enter image description here

difference between iframe, embed and object elements

<iframe>

The iframe element represents a nested browsing context. HTML 5 standard - "The <iframe> element"

Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>'s strength is that the embedded code is 'live' and can communicate with the parent document.

<embed>

Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...

The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The <embed> element")

Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.

The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:

svg = document.getElementById("parent_id").getSVGDocument();

From inside an embedded SVG or HTML document you can reach the parent with:

parent = window.parent.document;

For embedded HTML there is no way to get at the embedded document from the parent (that I have found).

<object>

The <object> element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The <object> element")

Conclusion

Unless you are embedding SVG or something static you are probably best of using <iframe>. To include SVG use <embed> (if I remember correctly <object> won't let you script†). Honestly I don't know why you would use <object> unless for older browsers or flash (that I don't work with).

† As pointed out in the comments below; scripts in <object> will run but the parent and child contexts can't communicate directly. With <embed> you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object> or <iframe> where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

python : list index out of range error while iteratively popping elements

I think most solutions talk here about List Comprehension, but if you'd like to perform in place deletion and keep the space complexity to O(1); The solution is:

i = 0
for j in range(len(arr)):
if (arr[j] != 0):
    arr[i] = arr[j]
    i +=1
arr = arr[:i] 

IF statement: how to leave cell blank if condition is false ("" does not work)

Unfortunately, there is no formula way to result in a truly blank cell, "" is the best formulas can offer.

I dislike ISBLANK because it will not see cells that only have "" as blanks. Instead I prefer COUNTBLANK, which will count "" as blank, so basically =COUNTBLANK(C1)>0 means that C1 is blank or has "".

If you need to remove blank cells in a column, I would recommend filtering on the column for blanks, then selecting the resulting cells and pressing Del. After which you can remove the filter.

Tried to Load Angular More Than Once

I was having the exact same error. After some hours, I noticed that there was an extra comma in my .JSON file, on the very last key-value pair.

//doesn't work
{
    "key":"value",
    "key":"value",
    "key":"value",
}

Then I just took it off (the last ',') and that solved the problem.

//works
{
    "key":"value",
    "key":"value",
    "key":"value"
}

jQuery - Getting the text value of a table cell in the same row as a clicked element

Nick has the right answer, but I wanted to add you could also get the cell data without needing the class name

var Something = $(this).closest('tr').find('td:eq(1)').text();

:eq(#) has a zero based index (link).

Write to Windows Application Event Log

As stated in MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(v=vs.110).aspx ), checking an non existing source and creating a source requires admin privilege.

It is however possible to use the source "Application" without. In my test under Windows 2012 Server r2, I however get the following log entry using "Application" source:

The description for Event ID xxxx from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: {my event entry message} the message resource is present but the message is not found in the string/message table

I defined the following method to create the source:

    private string CreateEventSource(string currentAppName)
    {
        string eventSource = currentAppName;
        bool sourceExists;
        try
        {
            // searching the source throws a security exception ONLY if not exists!
            sourceExists = EventLog.SourceExists(eventSource);
            if (!sourceExists)
            {   // no exception until yet means the user as admin privilege
                EventLog.CreateEventSource(eventSource, "Application");
            }
        }
        catch (SecurityException)
        {
            eventSource = "Application";
        }

        return eventSource;
    }

I am calling it with currentAppName = AppDomain.CurrentDomain.FriendlyName

It might be possible to use the EventLogPermission class instead of this try/catch but not sure we can avoid the catch.

It is also possible to create the source externally, e.g in elevated Powershell:

New-EventLog -LogName Application -Source MyApp

Then, using 'MyApp' in the method above will NOT generate exception and the EventLog can be created with that source.

Python creating a dictionary of lists

You can use setdefault:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d.setdefault(j, []).append(i)

print d  # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}

The rather oddly-named setdefault function says "Get the value with this key, or if that key isn't there, add this value and then return it."

As others have rightly pointed out, defaultdict is a better and more modern choice. setdefault is still useful in older versions of Python (prior to 2.5).

How to save a dictionary to a file?

Unless you really want to keep the dictionary, I think the best solution is to use the csv Python module to read the file. Then, you get rows of data and you can change member_phone or whatever you want ; finally, you can use the csv module again to save the file in the same format as you opened it.

Code for reading:

import csv

with open("my_input_file.txt", "r") as f:
   reader = csv.reader(f, delimiter=":")
   lines = list(reader)

Code for writing:

with open("my_output_file.txt", "w") as f:
   writer = csv.writer(f, delimiter=":")
   writer.writerows(lines)

Of course, you need to adapt your change() function:

def change(lines):
    a = input('ID')
    for line in lines:
      if line[0] == a:
        d=str(input("phone"))
        line[3]=d
        break
    else:
      print "not"

Youtube - downloading a playlist - youtube-dl

Removing the v=...& part from the url, and only keep the list=... part. The main problem being the special character &, interpreted by the shell.

You can also quote your 'url' in your command.

More information here (for instance) :

https://askubuntu.com/questions/564567/how-to-download-playlist-from-youtube-dl

What is the format for the PostgreSQL connection string / URL?

server.address=10.20.20.10
server.port=8080
database.user=username
database.password=password
spring.datasource.url=jdbc:postgresql://${server.address}/${server.port}?user=${database.user}&password=${database.password}

Why Does OAuth v2 Have Both Access and Refresh Tokens?

While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation. Another point missing in discussion is from rfc6749#page-55

"For example, the authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response.The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.

XML parsing of a variable string in JavaScript

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}

Finding all the subsets of a set

In case anyone else comes by and was still wondering, here's a function using Michael's explanation in C++

vector< vector<int> > getAllSubsets(vector<int> set)
{
    vector< vector<int> > subset;
    vector<int> empty;
    subset.push_back( empty );

    for (int i = 0; i < set.size(); i++)
    {
        vector< vector<int> > subsetTemp = subset;  //making a copy of given 2-d vector.

        for (int j = 0; j < subsetTemp.size(); j++)
            subsetTemp[j].push_back( set[i] );   // adding set[i] element to each subset of subsetTemp. like adding {2}(in 2nd iteration  to {{},{1}} which gives {{2},{1,2}}.

        for (int j = 0; j < subsetTemp.size(); j++)
            subset.push_back( subsetTemp[j] );  //now adding modified subsetTemp to original subset (before{{},{1}} , after{{},{1},{2},{1,2}}) 
    }
    return subset;
}

Take into account though, that this will return a set of size 2^N with ALL possible subsets, meaning there will possibly be duplicates. If you don't want this, I would suggest actually using a set instead of a vector(which I used to avoid iterators in the code).

What's the simplest way of detecting keyboard input in a script from the terminal?

The Python Documentation provides this snippet to get single characters from the keyboard:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            if c:
                print("Got character", repr(c))
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

You can also use the PyHook module to get your job done.