Programs & Examples On #Switching

A switch is a telecommunication device that receives a message from any device connected to it and then transmits the message only to the device for which the message was meant. This makes the switch a more intelligent device than a hub (which receives a message and then transmits it to all the other devices on its network). The network switch plays an integral part in most modern Ethernet local area networks (LANs)

How do I install Java on Mac OSX allowing version switching?

You can use asdf to install and switch between multiple java versions. It has plugins for other languages as well. You can install asdf with Homebrew

brew install asdf

When asdf is configured, install java plugin

asdf plugin-add java

Pick a version to install

asdf list-all java

For example to install and configure adoptopenjdk8

asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10

And finally if needed, configure JAVA_HOME for your shell. Just add to your shell init script such as ~/.zshrc in case of zsh:

. ~/.asdf/plugins/java/set-java-home.zsh

How to Determine the Screen Height and Width in Flutter

Hey you can use this class to get Screen Width and Height in percentage

import 'package:flutter/material.dart';
class Responsive{
  static width(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.width*(p/100);
  }
  static height(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.height*(p/100);
  }
}

and to Use like this

Container(height: Responsive.width(100, context), width: Responsive.width(50, context),);

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

Uninstalling(version: 2.19.2) and installing(version: 2.21.0) git client fixed the issue for me.

Laravel: PDOException: could not find driver

In window OS. I have uncomment extension=pdo_mysql for php.ini file that locate at same directory of php.exe. after that it work fine.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Python Pandas - Missing required dependencies ['numpy'] 1

you are running python 3.7

create environment for python 3.6

python3.6 filename.py

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

Problem solved! I just figured out how to solve the issue, but I would still like to know if this is normal behavior or not.

It seems that even though the Websocket connection establishes correctly (indicated by the 101 Switching Protocols request), it still defaults to long-polling. The fix was as simple as adding this option to the Socket.io connection function:

{transports: ['websocket']}

So the code finally looks like this:

const app = express();
const server = http.createServer(app);
var io = require('socket.io')(server);

io.on('connection', function(socket) {
  console.log('connected socket!');

  socket.on('greet', function(data) {
    console.log(data);
    socket.emit('respond', { hello: 'Hey, Mr.Client!' });
  });
  socket.on('disconnect', function() {
    console.log('Socket disconnected');
  });
});

and on the client:

var socket = io('ws://localhost:3000', {transports: ['websocket']});
socket.on('connect', function () {
  console.log('connected!');
  socket.emit('greet', { message: 'Hello Mr.Server!' });
});

socket.on('respond', function (data) {
  console.log(data);
});

And the messages now appear as frames:

working websockets

This Github issue pointed me in the right direction. Thanks to everyone who helped out!

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But i couldn't find such a constructor in your DbContext. So adding below constructor probably solves your problem.

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }

Edit for comment

If you don't register IHttpContextAccessor explicitly, use below code:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

Angular2 dynamic change CSS property

Angular 6 + Alyle UI

With Alyle UI you can change the styles dynamically

Here a demo stackblitz

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AlyleUIModule.forRoot(
      {
        name: 'myTheme',
        primary: {
          default: '#00bcd4'
        },
        accent: {
          default: '#ff4081'
        },
        scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
        lightGreen: '#8bc34a',
        colorSchemes: {
          light: {
            myColor: 'teal',
          },
          dark: {
            myColor: '#FF923D'
          },
          myCustomScheme: {
            background: {
              primary: '#dde4e6',
            },
            text: {
              default: '#fff'
            },
            myColor: '#C362FF'
          }
        }
      }
    ),
    LyCommonModule, // for bg, color, raised and others
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Html

<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>

For change Style

import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';

@Component({ ... })
export class AppComponent  {
  classes = {
    card: this.theme.setStyle(
      'card', // key
      () => (
        // style
        `background-color: ${this.theme.palette.myColor};` +
        `position: relative;` +
        `margin: 1em;` +
        `text-align: center;`
         ...
      )
    )
  }
  constructor(
    public theme: LyTheme
  ) { }

  changeScheme() {
    const scheme = this.theme.palette.scheme === 'light' ?
    'dark' : this.theme.palette.scheme === 'dark' ?
    'myCustomScheme' : 'light';
    this.theme.setScheme(scheme);
  }
}

Github Repository

Is there any way to configure multiple registries in a single npmrc file

You can use multiple repositories syntax for the registry entry in your .npmrc file:

registry=http://serverA.url/repository-uri/
//serverB.url/repository-uri/
//serverC.url/repository-uri/:_authToken=00000000-0000-0000-0000-0000000000000
//registry.npmjs.org/

That would make your npm look for packages in different servers.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Because switching to HTTPS can be painful or impossible depending on your architecture, I found a workaround solution: you can use the Google Maps Geolocation API. Although it has usage limits, it does the job. You will need an browser API key, so don't forget to limit it's usage to your page hostname.

I use it as a fallback method to the getCurrentPosition() method if it fails. It allows me to make it work until I switch to HTTPS.

Here's the JSFiddles:

  • HTTP: getCurrentPosition() will fail and fall back to the API
  • HTTPS: getCurrentPosition() will succeed

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Android Studio is slow (how to speed up)?

Starting from Android Studio 3.5 some of the settings can be configured via:

Preferences > Appearance & Behavior > System Settings > Memory Settings

Preferences

Laravel 5 – Remove Public from URL

I found the most working solution to this problem.

Just edit your .htaccess in the root folder and write the following code. Nothing else required

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit -1
   php_value post_max_size 8M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php71"
   php_value upload_max_filesize 2M
   php_flag zlib.output_compression Off
</IfModule>

React Checkbox not sending onChange

It's better not to use refs in such cases. Use:

<input
    type="checkbox"
    checked={this.state.active}
    onClick={this.handleClick}
/>

There are some options:

checked vs defaultChecked

The former would respond to both state changes and clicks. The latter would ignore state changes.

onClick vs onChange

The former would always trigger on clicks. The latter would not trigger on clicks if checked attribute is present on input element.

How to have stored properties in Swift, the same way I had on Objective-C?

How about storing static map to class that is extending like this :

extension UIView {

    struct Holder {
        static var _padding:[UIView:UIEdgeInsets] = [:]
    }

    var padding : UIEdgeInsets {
        get{ return UIView.Holder._padding[self] ?? .zero}
        set { UIView.Holder._padding[self] = newValue }
    }

}

Programmatically switching between tabs within Swift

Swift 5

//MARK:- if you are in UITabBarController 
self.selectedIndex = 1

or

tabBarController?.selectedIndex = 1

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Switching users inside Docker image to a non-root user

Add this line to docker file

USER <your_user_name>

Use docker instruction USER

Java 8 stream reverse order

List newStream = list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
        newStream.forEach(System.out::println);

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

How to change indentation mode in Atom?

Adding @Manbroski answer here that worked for me:

try Ctrl-Shift-P Editor: Toggle Soft Tabs

Why and how to fix? IIS Express "The specified port is in use"

Just to add to this, I had the full IIS feature turned on for one of my machines and it seemed to cause this to happen intermittently.

I also got random complaints about needing Admin rights to bind sites after a while, I assume that somehow it was looking at the full IIS config (Which does require admin as it's not a per-user file).

If you are stuck and nothing else is helping (and you don't want to just choose another port) then check you have removed this if it is present.

How to get week numbers from dates?

if you want to get the week number with the year use: "%Y-W%V":

e.g    yearAndweeks <- strftime(dates, format = "%Y-W%V")

so

> strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%Y-W%V")

becomes:

[1] "2014-W11" "2014-W12" "2014-W12" "2014-W01"

Invalidating JSON Web Tokens

I am going to answer If we need to provide logout from all devices feature when we are using JWT. This approach will use database look-ups for each requests. Because we need a persistence security state even if there is a server crash. In the user table we will have two columns

  1. LastValidTime (default: creation time)
  2. Logged-In (default: true)

Whenever there is a log out request from the user we will update the LastValidTime to current time and Logged-In to false. If there is a log in request we wont change LastValidTime but Logged-In will be set to true.

When we create the JWT we will have the JWT creation time in the payload. When we authorize for a service we will check 3 conditions

  1. Is JWT valid
  2. Is JWT payload creation time is greater than User LastValidTime
  3. Is user Logged-In

Lets see a practical scenario.

User X has two devices A, B. He logged in to our server at 7 pm using device A and device B. (lets say JWT expire time is 12 hrs). A and B both have JWT with createdTime : 7pm

At 9 pm he lost his device B. He immediately log out from the device A. That means Now our database X user entry has LastValidTime as "ThatDate:9:00:xx:xxx" and Logged-In as "false".

At 9:30 the Mr.Thief tries to log in using device B. We will check the database even the Logged-In is false so we wont allow.

At 10 pm Mr.X log in from his device A. Now device A has JWT with created time : 10pm. Now database Logged-In is set to "true"

At 10:30 pm Mr.Thief tries to log in. Even though the Logged-In is true. The LastValidTime is 9 pm in the database but B's JWT has created time as 7pm. So he wont be allowed to access the service. So using device B without having the password he cannot use already created JWT after one device log out.

How to use Monitor (DDMS) tool to debug application

1 use eclipse bar to install a Mat plug-in to analyze, is a good choice. Studio Memory provides the Monitor 2.Android studio to display the memory occupancy of the application in real time.

How to get $HOME directory of different user in bash script?

Update: Based on this question's title, people seem to come here just looking for a way to find a different user's home directory, without the need to impersonate that user.

In that case, the simplest solution is to use tilde expansion with the username of interest, combined with eval (which is needed, because the username must be given as an unquoted literal in order for tilde expansion to work):

eval echo "~$different_user"    # prints $different_user's home dir.

Note: The usual caveats regarding the use of eval apply; in this case, the assumption is that you control the value of $different_user and know it to be a mere username.

By contrast, the remainder of this answer deals with impersonating a user and performing operations in that user's home directory.


Note:

  • Administrators by default and other users if authorized via the sudoers file can impersonate other users via sudo.
  • The following is based on the default configuration of sudo - changing its configuration can make it behave differently - see man sudoers.

The basic form of executing a command as another user is:

sudo -H -u someUser someExe [arg1 ...]
  # Example:
sudo -H -u root env  # print the root user's environment

Note:

  • If you neglect to specify -H, the impersonating process (the process invoked in the context of the specified user) will report the original user's home directory in $HOME.
  • The impersonating process will have the same working directory as the invoking process.
  • The impersonating process performs no shell expansions on string literals passed as arguments, since no shell is involved in the impersonating process (unless someExe happens to be a shell) - expansions by the invoking shell - prior to passing to the impersonating process - can obviously still occur.

Optionally, you can have an impersonating process run as or via a(n impersonating) shell, by prefixing someExe either with -i or -s - not specifying someExe ... creates an interactive shell:

  • -i creates a login shell for someUser, which implies the following:

    • someUser's user-specific shell profile, if defined, is loaded.
    • $HOME points to someUser's home directory, so there's no need for -H (though you may still specify it)
    • The working directory for the impersonating shell is the someUser's home directory.
  • -s creates a non-login shell:

    • no shell profile is loaded (though initialization files for interactive nonlogin shells are; e.g., ~/.bashrc)
    • Unless you also specify -H, the impersonating process will report the original user's home directory in $HOME.
    • The impersonating shell will have the same working directory as the invoking process.

Using a shell means that string arguments passed on the command line MAY be subject to shell expansions - see platform-specific differences below - by the impersonating shell (possibly after initial expansion by the invoking shell); compare the following two commands (which use single quotes to prevent premature expansion by the invoking shell):

  # Run root's shell profile, change to root's home dir.
sudo -u root -i eval 'echo $SHELL - $USER - $HOME - $PWD'
  # Don't run root's shell profile, use current working dir.
  # Note the required -H to define $HOME as root`s home dir.
sudo -u root -H -s eval 'echo $SHELL - $USER - $HOME - $PWD'

What shell is invoked is determined by "the SHELL environment variable if it is set or the shell as specified in passwd(5)" (according to man sudo). Note that with -s it is the invoking user's environment that matters, whereas with -i it is the impersonated user's.

Note that there are platform differences regarding shell-related behavior (with -i or -s):

  • sudo on Linux apparently only accepts an executable or builtin name as the first argument following -s/-i, whereas OSX allows passing an entire shell command line; e.g., OSX accepts sudo -u root -s 'echo $SHELL - $USER - $HOME - $PWD' directly (no need for eval), whereas Linux doesn't (as of sudo 1.8.95p).

  • Older versions of sudo on Linux do NOT apply shell expansions to arguments passed to a shell; for instance, with sudo 1.8.3p1 (e.g., Ubuntu 12.04), sudo -u root -H -s echo '$HOME' simply echoes the string literal "$HOME" instead of expanding the variable reference in the context of the root user. As of at least sudo 1.8.9p5 (e.g., Ubuntu 14.04) this has been fixed. Therefore, to ensure expansion on Linux even with older sudo versions, pass the the entire command as a single argument to eval; e.g.: sudo -u root -H -s eval 'echo $HOME'. (Although not necessary on OSX, this will work there, too.)

  • The root user's $SHELL variable contains /bin/sh on OSX 10.9, whereas it is /bin/bash on Ubuntu 12.04.

Whether the impersonating process involves a shell or not, its environment will have the following variables set, reflecting the invoking user and command: SUDO_COMMAND, SUDO_USER, SUDO_UID=, SUDO_GID.

See man sudo and man sudoers for many more subtleties.

Tip of the hat to @DavidW and @Andrew for inspiration.

Dilemma: when to use Fragments vs Activities:

My philosophy is this:

Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

It's just my philosophy since fragments were introduced.

When to use Task.Delay, when to use Thread.Sleep?

if the current thread is killed and you use Thread.Sleep and it is executing then you might get a ThreadAbortException. With Task.Delay you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx

I also agree efficiency is not paramount in this case.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

To make this simple: PyPy provides the speed that's lacked by CPython but sacrifices its compatibility. Most people, however, choose Python for its flexibility and its "battery-included" feature (high compatibility), not for its speed (it's still preferred though).

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Try changing the contentInset property that UITableView inherits from UIScrollView.

self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);

It's a workaround, but it works

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.

So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.

My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Git push hangs when pushing to Github?

Try creating a script like ~/sshv.sh that will show you what ssh is up to:

#!/bin/bash
ssh -vvv "$@"

Allow execution of the ~/sshv.sh file for the owner of the file:

chmod u+x ~/sshv.sh

Then invoke your git push with:

GIT_SSH=~/sshv.sh git push ...

In my case, this helped me figure out that I was using ssh shared connections that needed to be closed, so I killed those ssh processes and it started working.

How to send a “multipart/form-data” POST in Android with Volley

As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:

    HttpPost req = new HttpPost(composeTargetUrl());
    MultipartEntity entity = new MultipartEntity();
    entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
    try {
        entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    req.setEntity(entity);

You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient

$location / switching between html5 and hashbang mode / link rewriting

Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('');
}]);

Don't forget to set the base in your HTML <head>:

<head>
    <base href="/">
    ...
</head>

More info about the changelog here.

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

node.js: cannot find module 'request'

ReferenceError: Can't find variable: require.

You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".

When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.

A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).

Can't connect to local MySQL server through socket '/tmp/mysql.sock

The socket is located in /tmp. On Unix system, due to modes & ownerships on /tmp, this could cause some problem. But, as long as you tell us that you CAN use your mysql connexion normally, I guess it is not a problem on your system. A primal check should be to relocate mysql.sock in a more neutral directory.

The fact that the problem occurs "randomly" (or not every time) let me think that it could be a server problem.

  • Is your /tmp located on a standard disk, or on an exotic mount (like in the RAM) ?

  • Is your /tmp empty ?

  • Does iotopshow you something wrong when you encounter the problem ?

sqlplus how to find details of the currently connected database session

show user

to get connected user

 select instance_name from v$instance

to get instance or set in sqlplus

set sqlprompt "_USER'@'_CONNECT_IDENTIFIER> "

Can't access Eclipse marketplace

Go to the folder where eclipse is installed

open eclipse.ini file
look for the line -vmargs
put -Djava.net.preferIPv4Stack=true below the -vmargs line and restart eclipse

How to handle anchor hash linking in AngularJS

In my case, I noticed that the routing logic was kicking in if I modified the $location.hash(). The following trick worked..

$scope.scrollTo = function(id) {
    var old = $location.hash();
    $location.hash(id);
    $anchorScroll();
    //reset to old to keep any additional routing logic from kicking in
    $location.hash(old);
};

How to create websockets server in PHP

<?php

// server.php

$server = stream_socket_server("tcp://127.0.0.1:8001", $errno, $errorMessage);

if($server == false) {
    throw new Exception("Could not bind to socket: $errorMessage");

}

for(;;) {
    $client = @stream_socket_accept($server);

    if($client) {
        stream_copy_to_stream($client, $client);
        fclose($client);
    }
}

from one terminal run : php server.php

from another terminal run: echo "hello woerld" | nc 127.0.0.1 8002

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I have lost hours today to find the reason, fortunately this issue is not because of MapFragment implementation, fnfortunately, this does not work because nested fragments are only supported through support library from rev 11.

My implementation has an activity with actionbar (in tabbed mode) with two tabs (no viewpager), one having the map and the other having a list of entries. Of course I've been quite naive to use MapFragment inside my tab-fragments, et voila the app crashed everytime I switched back to map-tab.

( The same issue I also would have in case my tab-fragment would inflate any layout containing any other fragment ).

One option is to use the MapView (instead of MapFragment), with some overhead though ( see MapView Docs as drop-in replacement in the layout.xml, another option is to use support-library up from rev. 11 but then take programmatic approach since nested fragments are neither supported via layout. Or just working around programmatically by explicitely destroying the fragment (like in the answer from Matt / Vidar), btw: same effect is achieved using the MapView (option 1).

But actually, I did not want to loose the map everytime I tab away, that is, I wanted to keep it in memory and cleanup only upon activity close, so I decided to simply hide/show the map while tabbing, see FragmentTransaction / hide

How do I switch between command and insert mode in Vim?

Looks like your Vim is launched in easy mode. See :help easy.

This happens when Vim is invoked with the -y argument or as evim, or maybe you have a :set insertmode somewhere in your .vimrc configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim Enter.

OraOLEDB.Oracle provider is not registered on the local machine

If you are getting this in a C# projet, check if you are running in 64-bit or 32-bit mode with the following code:

        if (IntPtr.Size == 4)
        {
            Console.WriteLine("This is 32-Bit!");
        }
        else if (IntPtr.Size == 8)
        {
            Console.WriteLine("This is 64 Bit!");
        }

If you find that you are running in 64-Bit mode, you may want to try switching to 32-Bit (or vice versa). You can follow this guide to force your application to run as 64 or 32 bit (X64 and X86 respectively). You have to make sure that Platform Target in your project properties is not set to Any CPU and that it is explicitley set.

enter image description here

Switching that option from Any CPU to X86 resolved my error and I was able to connect to the Oracle provider.

How to automatically update an application without ClickOnce?

This is the code to update the file but not to install This program is made through dos for copying files to the latest date and run your program automatically. may help you

open notepad and save file below with ext .bat

xcopy \\IP address\folder_share_name\*.* /s /y /d /q  
start "label" /b "youraplicationname.exe"

How to completely uninstall Visual Studio 2010?

Put in your CD or mount your ISO. Run the setup program from the command prompt using the flags /uninstall /force

I actually had ran into this issue the other day and it worked wonders. =)

Fatal error: Out of memory, but I do have plenty of memory (PHP)

The following two facts definitely point to memory leaks:

  1. The error appears at different lines in your code,
  2. The error reports a relatively small memory allocation.

I would first single out PDO, disabling all the other extensions and let it run overnight using something like Siege / Apache Bench (ab). You could also try running it using the cli interface (just make sure you keep the same memory limits).

You could use the memory_get_peak_usage() function at the end of your script to see how much memory PHP thinks it has been using.

From your comment that's 800 kB, which is okay; definitely not the gigantic amount of memory that would cause an out-of-memory ;-)

Lastly, though I wouldn't recommend upgrading to 5.4 at this point, upgrading to the latest 5.3.x is probably worth it due to multiple vulnerabilities and leaks that have been addressed since 5.3.1

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

Xcode: failed to get the task for process

Just get the same problem by installing my app on iPhone 5S with Distribution Profile

-> my solution was to activate Capabilities wich are set in Distribution Profile(in my case "Keychain Sharing","In-App Purchase" and "Game Center")

Hope this helps someone...

rbenv not changing ruby version

I fixed this by adding the following to my ~/.bash_profile:

#PATH for rbenv
export PATH="$HOME/.rbenv/shims:$PATH"

This is what is documented at https://github.com/sstephenson/rbenv.

From what I can tell there isn't ~/.rbenv/bin directory, which was mentioned in the post by @rodowi.

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

Switching from zsh to bash on OSX, and back again?

you can just type bash or if you always want to use bash:

on "iTerm2"

  • Go to preferences > Profiles > Command
  • Select "Command" from the dropdown
  • Type bash

Test by closing iTerm and open it again

Show history of a file?

Have you tried this:

gitk path/to/file

How can I change the version of npm using nvm?

In windows, run your terminal as admin (in case there are permission issues as I had). Then use a specific node version (say 7.8.0) by

nvm use 7.8.0

then update your npm to desired specific version by

npm install -g [email protected]

WebSocket with SSL

1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.

presentViewController and displaying navigation bar

It is true that if you present a view controller modally on the iPhone, it will always be presented full screen no matter how you present it on the top view controller of a navigation controller or any other way around. But you can always show the navigation bar with the following workaround way:

Rather than presenting that view controller modally present a navigation controller modally with its root view controller set as the view controller you want:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = 
    [[UINavigationController alloc] initWithRootViewController:myViewController];

//now present this navigation controller modally 
[self presentViewController:navigationController
                   animated:YES
                   completion:^{

                        }];

You should see a navigation bar when your view is presented modally.

How to iterate over a JSONObject?

Below code worked fine for me. Please help me if tuning can be done. This gets all the keys even from the nested JSON objects.

public static void main(String args[]) {
    String s = ""; // Sample JSON to be parsed

    JSONParser parser = new JSONParser();
    JSONObject obj = null;
    try {
        obj = (JSONObject) parser.parse(s);
        @SuppressWarnings("unchecked")
        List<String> parameterKeys = new ArrayList<String>(obj.keySet());
        List<String>  result = null;
        List<String> keys = new ArrayList<>();
        for (String str : parameterKeys) {
            keys.add(str);
            result = this.addNestedKeys(obj, keys, str);
        }
        System.out.println(result.toString());
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
public static List<String> addNestedKeys(JSONObject obj, List<String> keys, String key) {
    if (isNestedJsonAnArray(obj.get(key))) {
        JSONArray array = (JSONArray) obj.get(key);
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject arrayObj = (JSONObject) array.get(i);
                List<String> list = new ArrayList<>(arrayObj.keySet());
                for (String s : list) {
                    putNestedKeysToList(keys, key, s);
                    addNestedKeys(arrayObj, keys, s);
                }
            } catch (JSONException e) {
                LOG.error("", e);
            }
        }
    } else if (isNestedJsonAnObject(obj.get(key))) {
        JSONObject arrayObj = (JSONObject) obj.get(key);
        List<String> nestedKeys = new ArrayList<>(arrayObj.keySet());
        for (String s : nestedKeys) {
            putNestedKeysToList(keys, key, s);
            addNestedKeys(arrayObj, keys, s);
        }
    }
    return keys;
}

private static void putNestedKeysToList(List<String> keys, String key, String s) {
    if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
        keys.add(key + Constants.JSON_KEY_SPLITTER + s);
    }
}



private static boolean isNestedJsonAnObject(Object object) {
    boolean bool = false;
    if (object instanceof JSONObject) {
        bool = true;
    }
    return bool;
}

private static boolean isNestedJsonAnArray(Object object) {
    boolean bool = false;
    if (object instanceof JSONArray) {
        bool = true;
    }
    return bool;
}

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

ps ax | grep tmux
17685 pts/22   S+     0:00 tmux a -t 13g2
17920 pts/11   S+     0:00 tmux a -t 13g2
18065 pts/19   S+     0:00 grep tmux

kill the other one.

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Whenever you are trying to load a fragment in your activity make sure that activity is in resume and not going to pause state.In pause state you may end up losing commit operation that is done.

You can use transaction.commitAllowingStateLoss() instead of transaction.commit() to load fragment

or

Create a boolean and check if activity is not going to onpause

@Override
public void onResume() {
    super.onResume();
    mIsResumed = true;
}

@Override
public void onPause() {
    mIsResumed = false;
    super.onPause();
}

then while loading fragment check

if(mIsResumed){
//load the your fragment
}

Eclipse - "Workspace in use or cannot be created, chose a different one."

for windows users: In case of you can't remove .lock file and it gives you the following:

enter image description here

And you know that eclipse is already closed, just open Task Manager then processes then end precess for all eclipse.exe occurrences in the processes list.

Switching the order of block elements with CSS

Hows this for low tech...

put the ad at the top and bottom and use media queries to display:none as appropriate.

If the ad wasn't too big, it wouldn't add too much size to the download, you could even customise where the ad sent you for iPhone/pc.

Add and remove multiple classes in jQuery

Add multiple classes:

$("p").addClass("class1 class2 class3");

or in cascade:

$("p").addClass("class1").addClass("class2").addClass("class3");

Very similar also to remove more classes:

$("p").removeClass("class1 class2 class3");

or in cascade:

$("p").removeClass("class1").removeClass("class2").removeClass("class3");

Switching between GCC and Clang/LLVM using CMake

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

Also see this CMake FAQ on make override files.

How to switch activity without animation in Android?

The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:

<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>

Import SQL dump into PostgreSQL database

If you are using a file with .dump extension use:

pg_restore -h hostname -d dbname -U username filename.dump

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

Recover SVN password from local cache

In ~/.subversion/auth/svn.simple/ you should find a file with a long hexadecimal name. The password is in there in plaintext.

If there is more than one file you'll need to find that one that references the server you need the password for.

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

How to get a json string from url?

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

Switching to a TabBar tab view programmatically?

Note that the tabs are indexed starting from 0. So the following code snippet works

tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];

goes to the fifth tab in the bar.

C# switch on type

I have used this form of switch-case on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.

If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.

Here is a little example expanding on Mark's solution. I think it is a great way to work with types:

Dictionary<Type, Action> typeTests;

public ClassCtor()
{
    typeTests = new Dictionary<Type, Action> ();

    typeTests[typeof(int)] = () => DoIntegerStuff();
    typeTests[typeof(string)] = () => DoStringStuff();
    typeTests[typeof(bool)] = () => DoBooleanStuff();
}

private void DoBooleanStuff()
{
   //do stuff
}

private void DoStringStuff()
{
    //do stuff
}

private void DoIntegerStuff()
{
    //do stuff
}

public Action CheckTypeAction(Type TypeToTest)
{
    if (typeTests.Keys.Contains(TypeToTest))
        return typeTests[TypeToTest];

    return null; // or some other Action delegate
}

Can "git pull --all" update all my local branches?

It looks like many others have contributed similar solutions, but I thought I'd share what I came up with and invite others to contribute. This solution has a nice colorful output, gracefully handles your current working directory, and is fast because it doesn't do any checkouts, and leaves your working directory in tact. Also, it is just a shell script with no dependencies other than git. (only tested on OSX so far)

#!/usr/bin/env bash

gitup(){    
RED='\033[33;31m'
YELLO='\033[33;33m'
GREEN='\033[33;32m'
NC='\033[0m' # No Color

HEAD=$(git rev-parse HEAD)
CHANGED=$(git status --porcelain | wc -l)

echo "Fetching..."
git fetch --all --prune &>/dev/null
for branch in `git for-each-ref --format='%(refname:short)' refs/heads`; do

    LOCAL=$(git rev-parse --quiet --verify $branch)
    if [ "$HEAD" = "$LOCAL" ] && [ $CHANGED -gt 0 ]; then
        echo -e "${YELLO}WORKING${NC}\t\t$branch"
    elif git rev-parse --verify --quiet $branch@{u}&>/dev/null; then
        REMOTE=$(git rev-parse --quiet --verify $branch@{u})
        BASE=$(git merge-base $branch $branch@{u})

        if [ "$LOCAL" = "$REMOTE" ]; then
           echo -e "${GREEN}OK${NC}\t\t$branch" 
        elif [ "$LOCAL" = "$BASE" ]; then
            if [ "$HEAD" = "$LOCAL" ]; then
                git merge $REMOTE&>/dev/null
            else
                git branch -f $branch $REMOTE
            fi
            echo -e "${GREEN}UPDATED${NC}\t\t$branch"
        elif [ "$REMOTE" = "$BASE" ]; then
            echo -e "${RED}AHEAD${NC}\t\t$branch"
        else
            echo -e "${RED}DIVERGED${NC}\t\t$branch"
        fi
    else
        echo -e "${RED}NO REMOTE${NC}\t$branch"
    fi
done
}

https://github.com/davestimpert/gitup

Sorry I also seem to have come up with the same name as the other tool above.

IntelliJ shortcut to show a popup of methods in a class that can be searched

You can type "this." and wait a second, a popup with methods and properties will display.

Not a shortcut, but it works for me.

PS: if you are in a static method, type the class name.

Adding machineKey to web.config on web-farm sites

This should answer:

How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations

Web Farm Deployment Considerations

If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.

With manually generated key values, the settings should be similar to the following example.

<machineKey  
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
               AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"       

decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>

If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.

In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.

Setting Up the Machine Key Using IIS Manager

If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.

Start the management console and then select the web site. Open the machine key configuration: The IIS web site configuration panel

The machine key control panel has the following settings:

The machine key configuration panel

Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.

Click "Generate Keys" under "Actions" on the right side of the panel.

Click "Apply".

and add the following line to the web.config file in all the webservers under system.web tag if it does not exist.

<machineKey  
    validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
                   AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
    decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1"
    decryption="AES"
/>

Please make sure that you have a permanent backup of the machine keys and web.config file

Automatically add all files in a folder to a target using CMake?

As of CMake 3.1+ the developers strongly discourage users from using file(GLOB or file(GLOB_RECURSE to collect lists of source files.

Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.

See the documentation here.

There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.


It is possible. E.g. with file(GLOB:

cmake_minimum_required(VERSION 2.8)

file(GLOB helloworld_SRC
     "*.h"
     "*.cpp"
)

add_executable(helloworld ${helloworld_SRC})

Note that this requires manual re-running of cmake if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.

As of CMake 3.12, you can pass the CONFIGURE_DEPENDS flag to file(GLOB to automatically check and reset the file lists any time the build is invoked. You would write:

cmake_minimum_required(VERSION 3.12)

file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")

This at least lets you avoid manually re-running CMake every time a file is added.

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Switching to landscape mode in Android Emulator

Here are some ways to move landscape on Android Emulator:

1. Mac:

  • Ctrl + Fn + F11
  • Keypad 7 or Keypad 9
  • Ctrl + F12 or Ctrl + Fn + F12
  • Command + 7 or Command + 9

2. Windows:

  • Left Ctrl + F11 or Ctrl + F12

3. Linux:

  • Ctrl + F11

4. Android studio :

We can write screenOrientation = "landscape" in the androidManifest.xml file.

5. Keyboard:

in side the emulator, turn off the Num-Lock and press Keypad 7 and Keypad 9.

6. Emulator:

  • click the rotate button on the screen shown below.

enter image description here

  • click the rotate button on the screen shown below.

    enter image description here

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

MobileSafari supports the orientationchange event on the window object. Unfortunately there doesn't seem to be a way to directly control the zoom via JavaScript. Perhaps you could dynamically write/change the meta tag which controls the viewport — but I doubt that would work, it only affects the initial state of the page. Perhaps you could use this event to actually resize your content using CSS. Good luck!

Are 64 bit programs bigger and faster than 32 bit versions?

In the specific case of x68 to x68_64, the 64 bit program will be about the same size, if not slightly smaller, use a bit more memory, and run faster. Mostly this is because x86_64 doesn't just have 64 bit registers, it also has twice as many. x86 does not have enough registers to make compiled languages as efficient as they could be, so x86 code spends a lot of instructions and memory bandwidth shifting data back and forth between registers and memory. x86_64 has much less of that, and so it takes a little less space and runs faster. Floating point and bit-twiddling vector instructions are also much more efficient in x86_64.

In general, though, 64 bit code is not necessarily any faster, and is usually larger, both for code and memory usage at runtime.

How to prevent gcc optimizing some statements in C?

Instead of using the new pragmas, you can also use __attribute__((optimize("O0"))) for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.

Usage example:

void __attribute__((optimize("O0"))) foo(unsigned char data) {
    // unmodifiable compiler code
}

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

I have been reading about Android Service very recently and got a chance to deep dive on it. I have encountered a service leak, for my situation it happened because I had an unbound Service which was starting a bound Service, but in this my unbound Service is replaced by an Activity.

So when I was stopping my unbound Service by using stopSelf() the leak occurred, the reason was I was stopping the parent service without unbinding the bound service. Now the bound service is running and it doesn't know to whom does it belong.

The easy and straight forward fix is you should call unbindService(YOUR_SERVICE); in your onDestroy() function of your parent Activity/Service. This way the lifecycle will ensure that your bound services are stopped or cleaned up before your parent Activity/Services go down.

There is one other variation of this problem. Sometimes in your bound service you want certain functions to work only if the service is bound so we end up putting a bound flag in the onServiceConnected like:

public void onServiceConnected(ComponentName name, IBinder service) {
            bounded = true;
            // code here
        }

This works fine till here but the problem comes when we treat onServiceDisconnected function as a callback for unbindService function call, this by documentation is only called when a service is killed or crashed. And you will never get this callback in the same thread. Hence, we end up doing something like:

public void onServiceDisconnected(ComponentName name) {
            bounded = false;
        }

Which creates major bug in the code because our bound flag never gets reset to false and when this service is connected back again most of the times it is true. So in order to avoid this scenario you should set the bound to false the moment you are calling unbindService.

This is cover in more detail in Erik's blog.

Hope who ever came here got his curiosity satisfied.

How do I use su to execute the rest of the bash script as that user?

This worked for me

I split out my "provisioning" from my "startup".

 # Configure everything else ready to run 
  config.vm.provision :shell, path: "provision.sh"
  config.vm.provision :shell, path: "start_env.sh", run: "always"

then in my start_env.sh

#!/usr/bin/env bash

echo "Starting Server Env"
#java -jar /usr/lib/node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-2.40.0.jar  &
#(cd /vagrant_projects/myproj && sudo -u vagrant -H sh -c "nohup npm install 0<&- &>/dev/null &;bower install 0<&- &>/dev/null &")
cd /vagrant_projects/myproj
nohup grunt connect:server:keepalive 0<&- &>/dev/null &
nohup apimocker -c /vagrant_projects/myproj/mock_api_data/config.json 0<&- &>/dev/null &

How do I clone a specific Git branch?

Create a branch on the local system with that name. e.g. say you want to get the branch named branch-05142011

git branch branch-05142011 origin/branch-05142011

It'll give you a message:

$ git checkout --track origin/branch-05142011
Branch branch-05142011 set up to track remote branch refs/remotes/origin/branch-05142011.
Switched to a new branch "branch-05142011"

Now just checkout the branch like below and you have the code

git checkout branch-05142011

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

ASP.NET MVC View Engine Comparison

My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.

To provide a simple sample:

@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>

And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.

As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.

Thanks Nathj07

How can I simulate a click to an anchor tag?

There is a simpler way to achieve it,

HTML

<a href="https://getbootstrap.com/" id="fooLinkID" target="_blank">Bootstrap is life !</a>

JavaScript

// Simulating click after 3 seconds
setTimeout(function(){
  document.getElementById('fooLinkID').click();
}, 3 * 1000);

Using plain javascript to simulate a click along with addressing the target property.

You can check working example here on jsFiddle.

How to switch from POST to GET in PHP CURL

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

How to fix "Incorrect string value" errors?

Although your collation is set to utf8_general_ci, I suspect that the character encoding of the database, table or even column may be different.

ALTER TABLE tabale_name MODIFY COLUMN column_name VARCHAR(255)  
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

Maven2: Best practice for Enterprise Project (EAR file)

NetBeans IDE automatically defines the structure which is almost similar to one suggested by Patrick Garner. For NetBeans users

File->New Project ->In left side select Maven and In right side select Maven Enterprise Application and press Next -> Asks for project names for both war,ejb and settings.

The IDE will automatically create the structure for you.

Git checkout: updating paths is incompatible with switching branches

Could your issue be linked to this other SO question "checkout problem"?

i.e.: a problem related to:

  • an old version of Git
  • a curious checkout syntax, which should be: git checkout -b [<new_branch>] [<start_point>], with [<start_point>] referring to the name of a commit at which to start the new branch, and 'origin/remote-name' is not that.
    (whereas git branch does support a start_point being the name of a remote branch)

Note: what the checkout.sh script says is:

  if test '' != "$newbranch$force$merge"
  then
    die "git checkout: updating paths is incompatible with switching branches/forcing$hint"
  fi

It is like the syntax git checkout -b [] [remote_branch_name] was both renaming the branch and resetting the new starting point of the new branch, which is deemed incompatible.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

The reason your original code doesn't compile is that <? extends Serializable> does not mean, "any class that extends Serializable," but "some unknown but specific class that extends Serializable."

For example, given the code as written, it is perfectly valid to assign new TreeMap<String, Long.class>() to expected. If the compiler allowed the code to compile, the assertThat() would presumably break because it would expect Date objects instead of the Long objects it finds in the map.

delete word after or around cursor in VIM

Since there are so many ways to delete a word, let's illustrate them.

Assuming you edit:

foo-bar quux

and invoke a command while the cursor is on the 'a' in 'bar':

foo-bquux  # dw:  letters then spaces right of cursor
foo-quux   # daw: letters on both sides of cursor then spaces on the right 
foo- quux  # diw: letters on both sides of cursor
foo-bquux  # dW:  non-whitespace then spaces right of cursor
quux       # daW: non-whitespace on both sides of cursor then spaces on the right
 quux      # diW: non-whitespace on both sides of cursor

PostgreSQL Autoincrement

Since PostgreSQL 10

CREATE TABLE test_new (
    id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    payload text
);

Rails Active Record find(:all, :order => ) issue

I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails

This is very simple.

@variable=Model.order('columnName DESC')

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

Are you passing myClass out of a function, or expecting it to exist outside that function? As some others said, it is all about scope when you aren't allocating on the heap. When you leave the function, it goes away (eventually). One of the classic mistakes made by beginners is the attempt to create a local object of some class in a function and return it without allocating it on the heap. I can remember debugging this kind of thing back in my earlier days doing c++.

Is PowerShell ready to replace my Cygwin shell on Windows?

Tools are just tools.
They help or they don't.
You need help or you don't.

If you know Unix and those tools do what you need them to do on Windows - then you are a happy guy and there is no need to learn PowerShell (unless you want to explore).

My original intent was to include a set of Unix tools in Windows and be done with it (a number of us on the team have deep Unix backgrounds and a healthy dose of respect for that community.)

What I found was that this didn't really help much. The reason for that is that AWK/grep/sed don't work against COM, WMI, ADSI, the Registry, the certificate store, etc., etc.

In other words, UNIX is an entire ecosystem self-tuned around text files. As such, text processing tools are effectively management tools. Windows is a completely different ecosystem self-tuned around APIs and Objects. That's why we invented PowerShell.

What I think you'll find is that there will be lots of occasions when text-processing won't get you what you want on Windows. At that point, you'll want to pick up PowerShell. NOTE - it is not an all or nothing deal. Within PowerShell, you can call out to your Unix tools (and use their text process or PowerShell's text processing). Also you can call PowerShell from your Unix tools and get text.

Again - there is no religion here - our focus is on giving you the tools you need to succeed. That is why we are so passionate about feedback. Let us know where we are falling down on the job or where you don't have a tool you need and we'll put it on the list and get to it.

In all honesty, we are digging ourselves out of a 30-year-hole, so it is going to take a while. That said, if you pick up the beta of Windows Server 2008 /R2 and/or the betas of our server products, I think you'll be shocked at how quickly that hole is getting filled.

With regard to usage - we've had > 3.5 million downloads to date. That does not include the people using it in Windows Server 2008, because it is included as an optional component and does not need a download.

V2 will ship in all versions of Windows. It will be on-by-default for all editions except Server core where it is an optional component. Shortly after Windows 7/Windows Server 2008 R2 ships, we'll make V2 available on all platforms, Windows XP and above. In other words - your investment in learning will be applicable to a very large number of machines/environments.

One last comment. If/when you start to learn PowerShell, I think you'll be pretty happy. Much of the design is heavily influenced by our Unix backgrounds, so while we are quite different, you'll pick it up very quickly (after you get over cussing that it isn't Unix :-) ).

We know that people have a very limited budget for learning - that is why we are super hard-core about consistency. You are going to learn something, and then you'll use it over and over and over again.

Experiment! Enjoy! Engage!

Where do you include the jQuery library from? Google JSAPI? CDN?

One reason you might want to host on an external server is to work around the browser limitations of concurent connections to particular server.

However, given that the jQuery file you are using will likely not change very often, the browser cache will kick in and make that point moot for the most part.

Second reason to host it on external server is to lower the traffic to your own server.

However, given the size of jQuery, chances are it will be a small part of your traffic. You should probably try to optimize your actual content.

Using Git with Visual Studio

I find that Git, working on whole trees as it does, benefits less from IDE integration than source control tools that are either file based or follow a checkout-edit-commit pattern. Of course there are instances when it can be nice to click on a button to do some history examination, but I don't miss that very much.

The real must-do is to get your .gitignore file full of the things that shouldn't be in a shared repository. Mine generally contain (amongst other stuff) the following:

*.vcproj.*.user
*.ncb
*.aps
*.suo

but this is heavily C++ biased with little or no use of any class wizard style functionality.

My usage pattern is something like the following.

  1. Code, code, code in Visual Studio.

  2. When happy (sensible intermediate point to commit code, switch to Git, stage changes and review diffs. If anything's obviously wrong switch back to Visual Studio and fix, otherwise commit.

Any merge, branch, rebase or other fancy SCM stuff is easy to do in Git from the command prompt. Visual Studio is normally fairly happy with things changing under it, although it can sometimes need to reload some projects if you've altered the project files significantly.

I find that the usefulness of Git outweighs any minor inconvenience of not having full IDE integration but it is, to some extent, a matter of taste.

Is try-catch like error handling possible in ASP Classic?

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.

If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.

If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.

Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

SVN Error - Not a working copy

Delete .svn folder that is present in your local machine. Press windows icon and type .svn, delete the entire folder. It worked for me.

Is there a replacement for unistd.h for Windows (Visual C)?

No, IIRC there is no getopt() on Windows.

Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.

How to prevent long words from breaking my div?

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

Is there a better alternative than this to 'switch on type'?

I such cases I usually end up with a list of predicates and actions. Something along these lines:

class Mine {
    static List<Func<object, bool>> predicates;
    static List<Action<object>> actions;

    static Mine() {
        AddAction<A>(o => o.Hop());
        AddAction<B>(o => o.Skip());
    }

    static void AddAction<T>(Action<T> action) {
        predicates.Add(o => o is T);
        actions.Add(o => action((T)o);
    }

    static void RunAction(object o) {
        for (int i=0; o < predicates.Count; i++) {
            if (predicates[i](o)) {
                actions[i](o);
                break;
            }
        }
    }

    void Foo(object o) {
        RunAction(o);
    }
}

Switching a DIV background image with jQuery

There are two different ways to change a background image CSS with jQuery.

  1. $('selector').css('backgroundImage','url(images/example.jpg)');
  2. $('selector').css({'background-image':'url(images/example.jpg)'});

Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.

Using Vim's tabs like buffers

Vim :help window explains the confusion "tabs vs buffers" pretty well.

A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.

Opening multiple files is achieved in vim with buffers. In other editors (e.g. notepad++) this is done with tabs, so the name tab in vim maybe misleading.

Windows are for the purpose of splitting the workspace and displaying multiple files (buffers) together on one screen. In other editors this could be achieved by opening multiple GUI windows and rearranging them on the desktop.

Finally in this analogy vim's tab pages would correspond to multiple desktops, that is different rearrangements of windows.

As vim help: tab-page explains a tab page can be used, when one wants to temporarily edit a file, but does not want to change anything in the current layout of windows and buffers. In such a case another tab page can be used just for the purpose of editing that particular file.

Of course you have to remember that displaying the same file in many tab pages or windows would result in displaying the same working copy (buffer).

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

How do I get next month date from today's date and insert it in my database?

Adding my solution here, as this is the thread that comes in google search. This is to get the next date of month, fixing any skips, keeping the next date within next month.

PHP adds current months total number of days to current date, if you do +1 month for example.

So applying +1 month to 30-01-2016 will return 02-03-2016. (Adding 31 days)

For my case, I needed to get 28-02-2016, so as to keep it within next month. In such cases you can use the solution below.

This code will identify if the given date's day is greater than next month's total days. If so It will subtract the days smartly and return the date within the month range.

Do note the return value is in timestamp format.

function getExactDateAfterMonths($timestamp, $months){
    $day_current_date            = date('d', $timestamp);
    $first_date_of_current_month = date('01-m-Y', $timestamp);
    // 't' gives last day of month, which is equal to no of days
    $days_in_next_month          = date('t',  strtotime("+".$months." months", strtotime($first_date_of_current_month)));

    $days_to_substract = 0;
    if($day_current_date > $days_in_next_month)
         $days_to_substract = $day_current_date - $days_in_next_month;

    $php_date_after_months   = strtotime("+".$months." months", $timestamp);
    $exact_date_after_months = strtotime("-".$days_to_substract." days", $php_date_after_months);

    return $exact_date_after_months;
}

getExactDateAfterMonths(strtotime('30-01-2016'), 1);
// $php_date_after_months   => 02-03-2016
// $exact_date_after_months => 28-02-2016

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Search code inside a Github project

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

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

enter image description here

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

Convert hexadecimal string (hex) to a binary string

BigInteger.toString(radix) will do what you want. Just pass in a radix of 2.

static String hexToBin(String s) {
  return new BigInteger(s, 16).toString(2);
}

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.

How do I remove an object from an array with JavaScript?

Use delete-keyword.

delete obj[1];

EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

If you are using ionic in config.xml update widget tag with "xmlns:android="http://schemas.android.com/apk/res/android"

_x000D_
_x000D_
<widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0">_x000D_
_x000D_
_x000D_
<widget/>
_x000D_
_x000D_
_x000D_

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

Get user's non-truncated Active Directory groups from command line

Based on answer by P.Brian.Mackey-- I tried using gpresult /user <UserName> /r command, but it only seemed to work for my user account; for other users accounts I got this result: The user "userNameHere" does not have RSOP data.

So I read through this blog-- https://blog.thesysadmins.co.uk/group-policy-gpresult-examples.html-- and came upon a solution. You have to know the users computer name:

gpresult /s <UserComputer> /r /user:<UserName>

After running the command, you have to ENTER a few times for the program to complete because it will pause in the middle of the ouput. Also, the results gave a bunch of data including a section for "COMPUTER SETTINGS> Applied Group Policy Objects" and then "COMPUTER SETTINGS> Security groups" and finally "USER SETTINGS> security groups" (this is what we are looking for with the AD groups listed with non-truncated descriptions!).

Interesting to note that GPRESULT had some extra members not seen in NET USER command. Also, the sort order does not match and is not alphabetical. Any body who can add more insights in the comments that would be great.

RESULTS: gpresult (with ComputerName, UserName)

For security reasons, I have included only a subset of the membership results. (36 TOTAL, 12 SAMPLE)

The user is a part of the following security groups
---------------------------------------------------
..
 Internet Email 
 GEVStandardPSMViewers  
 GcoFieldServicesEditors    
 AnimalWelfare_Readers  
 Business Objects   
 Zscaler_Standard_Access    
..
 GCM    
..
 GcmSharesEditors   
 GHVStandardPSMViewers  
 IntranetReportsViewers 
 JetDWUsers     -- (NOTE: this one was deleted today, the other "Jet" one was added)
..
 Time and Attendance Users  
..

RESULTS: net user /DOMAIN (with UserName)

For security reasons, I have included only a subset of the membership results. (23 TOTAL, 12 SAMPLE)

Local Group Memberships  
Global Group memberships    ...
                             *Internet Email       *GEVStandardPSMViewers
                             *GcoFieldServicesEdito*AnimalWelfare_Readers
                             *Business Objects     *Zscaler_Standard_Acce
                             ...
                             *Time and Attendance U*GCM
                             ...
                             *GcmSharesEditors     *GHVStandardPSMViewers
                             *IntranetReportsViewer*JetPowerUsers
The command completed successfully.

How to check if a String contains another String in a case insensitive manner in Java?

String x="abCd";
System.out.println(Pattern.compile("c",Pattern.CASE_INSENSITIVE).matcher(x).find());

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

How to execute cmd commands via Java

Try this link

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

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

Is JavaScript a pass-by-reference or pass-by-value language?

A very detailed explanation about copying, passing and comparing by value and by reference is in this chapter of the "JavaScript: The Definitive Guide" book.

Before we leave the topic of manipulating objects and arrays by reference, we need to clear up a point of nomenclature.

The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book.

Here, we mean simply that a reference to an object or array -- not the object itself -- is passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside of the function.

Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself.

MySQL Creating tables with Foreign Keys giving errno: 150

For people who are viewing this thread with the same problem:

There are a lot of reasons for getting errors like this. For a fairly complete list of causes and solutions of foreign key errors in MySQL (including those discussed here), check out this link:

MySQL Foreign Key Errors and Errno 150

How to split a string in Java

String Split with multiple characters using Regex

public class StringSplitTest {
     public static void main(String args[]) {
        String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
        //String[] strs = s.split("[,\\s\\;]");
        String[] strs = s.split("[,\\;]");
        System.out.println("Substrings length:"+strs.length);
        for (int i=0; i < strs.length; i++) {
            System.out.println("Str["+i+"]:"+strs[i]);
        }
     }
  }

Output:

Substrings length:17
Str[0]:
Str[1]:String
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[7]:
Str[8]:String
Str[9]:String
Str[10]: String
Str[11]: String
Str[12]:
Str[13]:String
Str[14]:String
Str[15]:String
Str[16]:String

But do not expect the same output across all JDK versions. I have seen one bug which exists in some JDK versions where the first null string has been ignored. This bug is not present in the latest JDK version, but it exists in some versions between JDK 1.7 late versions and 1.8 early versions.

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

The following method may work:

git rebase HEAD master
git checkout master

This will rebase your current HEAD changes on top of the master. Then you can switch the branch.


Alternative way is to checkout the branch first:

git checkout master

Then Git should display SHA1 of your detached commits, then you can cherry pick them, e.g.

git cherry-pick YOURSHA1

Or you can also merge the latest one:

git merge YOURSHA1

To see all of your commits from different branches (to make sure you've them), run: git reflog.

What is the best way to auto-generate INSERT statements for a SQL Server table?

This can be done using Visual Studio too (at least in version 2013 onwards).

In VS 2013 it is also possible to filter the list of rows the inserts statement are based on, this is something not possible in SSMS as for as I know.

Perform the following steps:

  • Open the "SQL Server Object Explorer" window (menu: /View/SQL Server Object Explorer)
  • Open / expand the database and its tables
  • Right click on the table and choose "View data" from context menu
  • This will display the data in the main area
  • Optional step: Click on the filter icon "Sort and filter data set" (the fourth icon from the left on the row above the result) and apply some filter to one or more columns
  • Click on the "Script" or "Script to File" icons (the icons on the right of the top row, they look like little sheets of paper)

This will create the (conditional) insert statements for the selected table to the active window or file.


The "Filter" and "Script" buttons Visual Studio 2013:

enter image description here

Get file name from URL

How about this:

String filenameWithoutExtension = null;
String fullname = new File(
    new URI("http://www.xyz.com/some/deep/path/to/abc.png").getPath()).getName();

int lastIndexOfDot = fullname.lastIndexOf('.');
filenameWithoutExtension = fullname.substring(0, 
    lastIndexOfDot == -1 ? fullname.length() : lastIndexOfDot);

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

How to make a <div> or <a href="#"> to align center

<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
    </head>
    <body>
        <h4 align="center"> 
              <a href="Demo2.html">Center</a>  
        </h4>
    </body>
    
</html>

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?

/^my/

How do I check if a string is unicode or ascii?

use:

import six
if isinstance(obj, six.text_type)

inside the six library it is represented as:

if PY3:
    string_types = str,
else:
    string_types = basestring,

from list of integers, get number closest to a given value

If I may add to @Lauritz's answer

In order not to have a run error don't forget to add a condition before the bisect_left line:

if (myNumber > myList[-1] or myNumber < myList[0]):
    return False

so the full code will look like:

from bisect import bisect_left

def takeClosest(myList, myNumber):
    """
    Assumes myList is sorted. Returns closest value to myNumber.
    If two numbers are equally close, return the smallest number.
    If number is outside of min or max return False
    """
    if (myNumber > myList[-1] or myNumber < myList[0]):
        return False
    pos = bisect_left(myList, myNumber)
    if pos == 0:
            return myList[0]
    if pos == len(myList):
            return myList[-1]
    before = myList[pos - 1]
    after = myList[pos]
    if after - myNumber < myNumber - before:
       return after
    else:
       return before

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

How to randomize two ArrayLists in the same fashion?

Use Collections.shuffle() twice, with two Random objects initialized with the same seed:

long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));

Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

I had the same issue because I didn't define Procfile. Commit a text file to your app's root directory that is named Procfile without a file extension. This file tells Heroku which command(s) to run to start your app.

web: node app.js

Calling a PHP function from an HTML form in the same file

You have a big misunderstanding of how the web works.

Basically, things happen this way:

  • User (well, the browser) requests test.php from your server
  • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
  • The browser displays the form, the user can interact with it.
  • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).

Convert HTML + CSS to PDF

After some investigation and general hair-pulling the solution seems to be HTML2PDF. DOMPDF did a terrible job with tables, borders and even moderately complex layout and htmldoc seems reasonably robust but is almost completely CSS-ignorant and I don't want to go back to doing HTML layout without CSS just for that program.

HTML2PDF looked the most promising but I kept having this weird error about null reference arguments to node_type. I finally found the solution to this. Basically, PHP 5.1.x worked fine with regex replaces (preg_replace_*) on strings of any size. PHP 5.2.1 introduced a php.ini config directive called pcre.backtrack_limit. What this config parameter does is limits the string length for which matching is done. Why this was introduced I don't know. The default value was chosen as 100,000. Why such a low value? Again, no idea.

A bug was raised against PHP 5.2.1 for this, which is still open almost two years later.

What's horrifying about this is that when the limit is exceeded, the replace just silently fails. At least if an error had been raised and logged you'd have some indication of what happened, why and what to change to fix it. But no.

So I have a 70k HTML file to turn into PDF. It requires the following php.ini settings:

  • pcre.backtrack_limit = 2000000; # probably more than I need but that's OK
  • memory_limit = 1024M; # yes, one gigabyte; and
  • max_execution_time = 600; # yes, 10 minutes.

Now the astute reader may have noticed that my HTML file is smaller than 100k. The only reason I can guess as to why I hit this problem is that html2pdf does a conversion into xhtml as part of the process. Perhaps that took me over (although nearly 50% bloat seems odd). Whatever the case, the above worked.

Now, html2pdf is a resource hog. My 70k file takes approximately 5 minutes and at least 500-600M of RAM to create a 35 page PDF file. Not quick enough (by far) for a real-time download unfortunately and the memory usage puts the memory usage ratio in the order of 1000-to-1 (600M of RAM for a 70k file), which is utterly ridiculous.

Unfortunately, that's the best I've come up with.

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

aspx page to redirect to a new page

Or you can use javascript to redirect to another page:

<script type="text/javascript">
    function toRedirect() {
        window.location.href="new.aspx";
    }
</script>

Call this toRedirect() function from client (for ex: onload event of body tag) or from server using:

ClientScript.RegisterStartupScript(this.gettype(),"Redirect","toRedirect()",true);

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

Integrating the ZXing library directly into my Android application

Have you seen the wiki pages on the zxing website? It seems you might find GettingStarted, DeveloperNotes and ScanningViaIntent helpful.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

In LINQ2SQL you seldom need to join explicitly when using inner joins.

If you have proper foreign key relationships in your database you will automatically get a relation in the LINQ designer (if not you can create a relation manually in the designer, although you should really have proper relations in your database)

parent-child relation

Then you can just access related tables with the "dot-notation"

var q = from child in context.Childs
        where child.Parent.col2 == 4
        select new
        {
            childCol1 = child.col1,
            parentCol1 = child.Parent.col1,
        };

will generate the query

SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

In my opinion this is much more readable and lets you concentrate on your special conditions and not the actual mechanics of the join.

Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson

Keep overflow div scrolled to bottom unless user scrolls up

$('#div1').scrollTop($('#div1')[0].scrollHeight);

Or animated:

$("#div1").animate({ scrollTop: $('#div1')[0].scrollHeight}, 1000);

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

android EditText - finished typing event

both @Reno and @Vinayak B answers together if you want to hide the keyboard after the action

textView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);
            return true;
        }
        return false;
    }
});

textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
             // your action here
        }
    }
});

How to run a single test with Mocha?

If you are using npm test (using package.json scripts) use an extra -- to pass the param through to mocha

e.g. npm test -- --grep "my second test"

EDIT: Looks like --grep can be a little fussy (probably depending on the other arguments). You can:

Modify the package.json:

"test:mocha": "mocha --grep \"<DealsList />\" .",

Or alternatively use --bail which seems to be less fussy

npm test -- --bail

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

If I understand your issue this should work

&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.

Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

Is this very likely to create a memory leak in Tomcat?

I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pf;

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Administrator
 * 
 * google-gson issue # 402: Memory Leak in web application; comment # 25
 * https://code.google.com/p/google-gson/issues/detail?id=402
 */
public class ThreadLocalImmolater {

    final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);

    Boolean debug;

    public ThreadLocalImmolater() {
        debug = true;
    }

    public Integer immolate() {
        int count = 0;
        try {
            final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inheritableThreadLocalsField.setAccessible(true);
            for (final Thread thread : Thread.getAllStackTraces().keySet()) {
                    count += clear(threadLocalsField.get(thread));
                    count += clear(inheritableThreadLocalsField.get(thread));
            }
            logger.info("immolated " + count + " values in ThreadLocals");
        } catch (Exception e) {
            throw new Error("ThreadLocalImmolater.immolate()", e);
        }
        return count;
    }

    private int clear(final Object threadLocalMap) throws Exception {
        if (threadLocalMap == null)
                return 0;
        int count = 0;
        final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
        tableField.setAccessible(true);
        final Object table = tableField.get(threadLocalMap);
        for (int i = 0, length = Array.getLength(table); i < length; ++i) {
            final Object entry = Array.get(table, i);
            if (entry != null) {
                final Object threadLocal = ((WeakReference)entry).get();
                if (threadLocal != null) {
                    log(i, threadLocal);
                    Array.set(table, i, null);
                    ++count;
                }
            }
        }
        return count;
    }

    private void log(int i, final Object threadLocal) {
        if (!debug) {
            return;
        }
        if (threadLocal.getClass() != null &&
            threadLocal.getClass().getEnclosingClass() != null &&
            threadLocal.getClass().getEnclosingClass().getName() != null) {

            logger.info("threadLocalMap(" + i + "): " +
                        threadLocal.getClass().getEnclosingClass().getName());
        }
        else if (threadLocal.getClass() != null &&
                 threadLocal.getClass().getName() != null) {
            logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
        }
        else {
            logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
        }
    }

}

Angular 2 http post params and body

Let said our backend looks like this:

public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}

We have a HttpService like this:

    post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
        return this.http.post<T>(url, body, { headers: headers, params});
    }

Following is how we can pass the body and the notes as parameter: // how to call it

const headers: HttpHeaders = new HttpHeaders({
    'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});

const bodyData = this.getBodyData(); // get whatever we want to send as body

let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');

this.httpService.post<any>(url, bodyData, headers, params);

It worked for me (using angular 7^), I hope is useful for somebody.

Sending email from Azure

If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.

Disclaimer: I’m working at Mailjet as a Developer Evangelist.

How to code a very simple login system with java

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

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

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

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

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

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

MySQL 'create schema' and 'create database' - Is there any difference

So, there is no difference between MySQL "database" and MySQL "schema": these are two names for the same thing - a namespace for tables and other DB objects.

For people with Oracle background: MySQL "database" a.k.a. MySQL "schema" corresponds to Oracle schema. The difference between MySQL and Oracle CREATE SCHEMA commands is that in Oracle the CREATE SCHEMA command does not actually create a schema but rather populates it with tables and views. And Oracle's CREATE DATABASE command does a very different thing than its MySQL counterpart.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

After heavy testing we came to the conclusion that GROUP BY is faster

SELECT sql_no_cache opnamegroep_intern FROM telwerken WHERE opnemergroep IN (7,8,9,10,11,12,13) group by opnamegroep_intern

635 totaal 0.0944 seconds Weergave van records 0 - 29 ( 635 totaal, query duurde 0.0484 sec)

SELECT sql_no_cache distinct (opnamegroep_intern) FROM telwerken WHERE opnemergroep IN (7,8,9,10,11,12,13)

635 totaal 0.2117 seconds ( almost 100% slower ) Weergave van records 0 - 29 ( 635 totaal, query duurde 0.3468 sec)

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

A simple algorithm for polygon intersection

If you do not care about predictable run time you could try by first splitting your polygons into unions of convex polygons and then pairwise computing the intersection between the sub-polygons.

This would give you a collection of convex polygons such that their union is exactly the intersection of your starting polygons.

Passing a String by Reference in Java?

String is a special class in Java. It is Thread Safe which means "Once a String instance is created, the content of the String instance will never changed ".

Here is what is going on for

 zText += "foo";

First, Java compiler will get the value of zText String instance, then create a new String instance whose value is zText appending "foo". So you know why the instance that zText point to does not changed. It is totally a new instance. In fact, even String "foo" is a new String instance. So, for this statement, Java will create two String instance, one is "foo", another is the value of zText append "foo". The rule is simple: The value of String instance will never be changed.

For method fillString, you can use a StringBuffer as parameter, or you can change it like this:

String fillString(String zText) {
    return zText += "foo";
}

custom facebook share button

Well, I use this method on my site:

<a class="share-btn" href="https://www.facebook.com/sharer/sharer.php?app_id=[your_app_id]&sdk=joey&u=[full_article_url]&display=popup&ref=plugin&src=share_button" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=580')">

Works perfectly.

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

Why calling react setState method doesn't mutate the state immediately?

async-await syntax works perfectly for something like the following...

changeStateFunction = () => {
  // Some Worker..

  this.setState((prevState) => ({
  year: funcHandleYear(),
  month: funcHandleMonth()
}));

goNextMonth = async () => {
  await this.changeStateFunction();
  const history = createBrowserHistory();
  history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}

goPrevMonth = async () => {
  await this.changeStateFunction();
  const history = createBrowserHistory();
  history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

Webdriver and proxy server for firefox

Here's a java example using DesiredCapabilities. I used it for pumping selenium tests into jmeter. (was only interested in HTTP requests)

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

String myProxy = "localhost:7777";  //example: proxy host=localhost port=7777
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY,
                           new Proxy().setHttpProxy(myProxy));
WebDriver webDriver = new FirefoxDriver(capabilities); 

Invoking a jQuery function after .each() has completed

Ok, this might be a little after the fact, but .promise() should also achieve what you're after.

Promise documentation

An example from a project i'm working on:

$( '.panel' )
    .fadeOut( 'slow')
    .promise()
    .done( function() {
        $( '#' + target_panel ).fadeIn( 'slow', function() {});
    });

:)

Using OpenSSL what does "unable to write 'random state'" mean?

I have come accross this problem today on AWS Lambda. I created an environment variable RANDFILE = /tmp/.random

That did the trick.

How can I pass data from Flask to JavaScript in a template?

<script>
    const geocodeArr = JSON.parse('{{ geocode | tojson }}');
    console.log(geocodeArr);
</script>

This uses jinja2 to turn the geocode tuple into a json string, and then the javascript JSON.parse turns that into a javascript array.

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

How to remove anaconda from windows completely?

It looks that some files are still left and some registry keys are left. So you can run revocleaner tool to remove those entries as well. Do a reboot and install again it should be doing it now. I also faced issue and by complete cleaning I got Rid of it.

How can I initialize a MySQL database with schema in a Docker container?

For the ones not wanting to create an entrypoint script like me, you actually can start mysqld at build-time and then execute the mysql commands in your Dockerfile like so:

RUN mysqld_safe & until mysqladmin ping; do sleep 1; done && \
    mysql -uroot -e "CREATE DATABASE somedb;" && \
    mysql -uroot -e "CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'somepassword';" && \
    mysql -uroot -e "GRANT ALL PRIVILEGES ON somedb.* TO 'someuser'@'localhost';"

The key here is to send mysqld_safe to background with the single & sign.

How do you set a default value for a MySQL Datetime column?

I was able to solve this using this alter statement on my table that had two datetime fields.

ALTER TABLE `test_table`
  CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.

CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`
    FOR EACH ROW SET NEW.created_dt = NOW();

The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]

Posting form to different MVC post action depending on the clicked submit button

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionName attribute as an alias

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How can a windows service programmatically restart itself?

You can't be sure that the user account that your service is running under even has permissions to stop and restart the service.

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

Getting the screen resolution using PHP

You can set window width in cookies using JS in front end and you can get it in PHP:

<script type="text/javascript">
   document.cookie = 'window_width='+window.innerWidth+'; expires=Fri, 3 Aug 2901 20:47:11 UTC; path=/';
</script>

<?PHP
    $_COOKIE['window_width'];
?>

How do I install imagemagick with homebrew?

The quickest fix for me was doing the following:

cd /usr/local
git reset --hard FETCH_HEAD

Then I retried brew install imagemagick and it correctly pulled the package from the new mirror, instead of adamv.

If that does not work, ensure that /Library/Caches/Homebrew does not contain any imagemagick files or folders. Delete them if it does.

403 Forbidden error when making an ajax Post request in Django framework

The fastest solution if you are not embedding js into your template is:

Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary:

$.ajax({
            type: 'POST',
            url: somepathname + "do_it/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

If you do embed your js into the template, it's as simple as: data: {csrfmiddlewaretoken: '{{ csrf_token }}'}

Randomize numbers with jQuery?

You don't need jQuery, just use javascript's Math.random function.

edit: If you want to have a number from 1 to 6 show randomly every second, you can do something like this:

<span id="number"></span>

<script language="javascript">
  function generate() {
    $('#number').text(Math.floor(Math.random() * 6) + 1);
  }
  setInterval(generate, 1000);
</script>

Remove part of string in Java

Kotlin Solution

If you are removing a specific string from the end, use removeSuffix (Documentation)

var text = "one(two"
text = text.removeSuffix("(two") // "one"

If the suffix does not exist in the string, it just returns the original

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

If you want to remove after a character, use

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

The Full List is here: (Documentation)

Hexadecimal To Decimal in Shell Script

I have this handy script on my $PATH to filter 0x1337-like; 1337; or "0x1337" lines of input into decimal strings (expanded for clarity):

#!/usr/bin/env bash

while read data; do
  withoutQuotes=`echo ${data} | sed s/\"//g`
  without0x=`echo ${withoutQuotes} | sed s/0x//g`
  clean=${without0x}
  echo $((16#${clean}))
done

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

CXF: No message body writer found for class - automatically mapping non-simple resources

I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:

Included the following in my pom.xml

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.0</version>
    </dependency>

and added the following provider

    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
    </jaxrs:providers>

What's the fastest way to do a bulk insert into Postgres?

There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

The above code inserts two rows, but you can extend it arbitrarily, until you hit the maximum number of prepared statement tokens (it might be $999, but I'm not 100% sure about that). Sometimes one cannot use COPY, and this is a worthy replacement for those situations.

Explain ggplot2 warning: "Removed k rows containing missing values"

Just for the shake of completing the answer given by eipi10.

I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

Removed 8 rows containing missing values (geom_bar)

Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

How to run function in AngularJS controller on document ready?

Here's my attempt inside of an outer controller using coffeescript. It works rather well. Please note that settings.screen.xs|sm|md|lg are static values defined in a non-uglified file I include with the app. The values are per the Bootstrap 3 official breakpoints for the eponymous media query sizes:

xs = settings.screen.xs // 480
sm = settings.screen.sm // 768
md = settings.screen.md // 992
lg = settings.screen.lg // 1200

doMediaQuery = () ->

    w = angular.element($window).width()

    $scope.xs = w < sm
    $scope.sm = w >= sm and w < md
    $scope.md = w >= md and w < lg
    $scope.lg = w >= lg
    $scope.media =  if $scope.xs 
                        "xs" 
                    else if $scope.sm
                        "sm"
                    else if $scope.md 
                        "md"
                    else 
                        "lg"

$document.ready () -> doMediaQuery()
angular.element($window).bind 'resize', () -> doMediaQuery()

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

In Python, what is the difference between ".append()" and "+= []"?

let's take an example first

list1=[1,2,3,4]
list2=list1     (that means they points to same object)

if we do 
list1=list1+[5]    it will create a new object of list
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4]

but if we append  then 
list1.append(5)     no new object of list created
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4,5]

extend(list) also do the same work as append it just append a list instead of a 
single variable 

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.

[SOLUTION] What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

How to redirect to another page using PHP

Although not secure, (no offense or anything), just stick the header function after you set the session variable

 while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
header('Location: /profile.php');

Dynamic SELECT TOP @var In SQL Server

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

HTML: how to make 2 tables with different CSS

Of course, just assign seperate css classes to both tables.

<table class="style1"></table>
<table class="style2"></table>

.css

table.style1 { //your css here}
table.style2 { //your css here}

Elegant solution for line-breaks (PHP)

\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.

str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.

How to implement the Java comparable interface?

While you are in it, I suggest to remember some key facts about compareTo() methods

  1. CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.

  2. CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.

Read more: http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3

run program in Python shell

For newer version of python:

exec(open(filename).read())

Difference between abstraction and encapsulation?

Information hiding is not strictly required for abstraction or encapsulation. Information might be ignored, but does not have to be hidden.

Encapsulation is the ability to treat something as a single thing, even though it may be composed of many complex parts or ideas. For example, I can say that I'm sitting in a "chair" rather than referring to the many various parts of that chair each with a specific design and function, all fitting together precisely for the purpose of comfortably holding my butt a few feet away from the floor.

Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think about them as things which relate to each other in some way rather than getting bogged down in the subtle details of internal object structure. Abstraction is the ability to consider the bigger picture, removed from concern over little details. The root of the word is abstract as in the summary that appears at the top of a scholarly paper, not abstract as in a class which can only be instantiated as a derived subclass.

I can honestly say that when I plop my butt down in my chair, I never think about how the structure of that chair will catch and hold my weight. It's a decent enough chair that I don't have to worry about those details. So I can turn my attention toward my computer. And again, I don't think about the component parts of my computer. I'm just looking at a part of a webpage that represents a text area that I can type in, and I'm communicating in words, barely even thinking about how my fingers always find the right letters so quickly on the keyboard, and how the connection is ultimately made between tapping these keys and posting to this forum. This is the great power of abstraction. Because the lower levels of the system can be trusted to work with consistency and precision, we have attention to spare for greater work.

Angular JS break ForEach

As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use

jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration
})

See http://api.jquery.com/jquery.each/

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

no target device found android studio 2.1.1

go to "Run>edit configuration>" and select "Open select deployment target dialog" from deployment target option then run your app it will show you a dialog box you can choose your target device from there, enjoy it.

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

git clone through ssh

Upfront, I am a bit lacking in my GIT skills.

That is going to clone a bare repository on your machine, which only contains the folders within .git which is a hidden directory. execute ls -al and you should see .git or cd .git inside your repository.

Can you add a description of your intent so that someone with more GIT skills can help? What is it you really want to do not how you plan on doing it?

What port is used by Java RMI connection?

With reference to other answers above, here is my view -

there are ports involved on both client and server side.

  • for server/remote side, if you export the object without providing a port , remote object would use a random port to listen.

  • a client, when looks up the remote object, it would always use a random port on its side and will connect to the remote object port as listed above.

Python IndentationError unindent does not match any outer indentation level

I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.

However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Thoughts (based on pain in the past):

  • do you have DNS and line-of-sight to the server?
  • are you using the correct name from the certificate?
  • is the certificate still valid?
  • is a badly configured load balancer messing things up?
  • does the new server machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP?
  • is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL?
  • related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities)
  • is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc)

MVC 4 Data Annotations "Display" Attribute

Also internationalization.

I fooled around with this some a while back. Did this in my model:

[Display(Name = "XXX", ResourceType = typeof(Labels))]

I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.

In there I had key = XXX, value = "meaningful string in that culture."

Newtonsoft JSON Deserialize

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
    // Do something with typeStr
} 

string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Variables not showing while debugging in Eclipse

It's possible your Java compiler is configured not to preserve variable information. Right-click on the project in Project Explorer, then select Properties > Java Compiler > Add variable attributes to generated class files (used by the debugger). Without this option set, you will only see fields in the Variables view, not local variables.

How to pass data from child component to its parent in ReactJS?

You can even avoid the function at the parent updating the state directly

In Parent Component:

render(){
 return(<Child sendData={ v => this.setState({item: v}) } />);
}

In the Child Component:

demoMethod(){
   this.props.sendData(value);
}

Redis command to get all available keys?

In order to get all the keys available in redis server, you should open redis-cli and type: KEYS * In order to get more help please visit this page: This Link

SQL Inner Join On Null Values

This article has a good discussion on this issue. You can use

SELECT * 
FROM Y
INNER JOIN X ON EXISTS(SELECT X.QID 
                       INTERSECT 
                       SELECT y.QID);

Append a dictionary to a dictionary

dict.update() looks like it will do what you want...

>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>> 

Perhaps, though, you don't want to update your original dictionary, but work on a copy:

>>> dest = orig.copy()
>>> dest.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2}
>>> dest
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}

Check if number is decimal

is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.

How can I display a messagebox in ASP.NET?

This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!

protected void Addstaff_Click(object sender, EventArgs e)    
    {   
 if (intClassCapcity < intCurrentstaffNumber)     
                {                  
            MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");    
        }    
else    
    {   
            sqlClassList.Insert();    
    }    
}

private void MsgBox(string sMessage)    
    {    
        string msg = "<script language=\"javascript\">";    
        msg += "alert('" + sMessage + "');";    
        msg += "</script>";    
        Response.Write(msg);    
    }

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

How to compile Tensorflow with SSE4.2 and AVX instructions?

I have recently installed it from source and bellow are all the steps needed to install it from source with the mentioned instructions available.

Other answers already describe why those messages are shown. My answer gives a step-by-step on how to isnstall, which may help people struglling on the actual installation as I did.

  1. Install Bazel

Download it from one of their available releases, for example 0.5.2. Extract it, go into the directory and configure it: bash ./compile.sh. Copy the executable to /usr/local/bin: sudo cp ./output/bazel /usr/local/bin

  1. Install Tensorflow

Clone tensorflow: git clone https://github.com/tensorflow/tensorflow.git Go to the cloned directory to configure it: ./configure

It will prompt you with several questions, bellow I have suggested the response to each of the questions, you can, of course, choose your own responses upon as you prefer:

Using python library path: /usr/local/lib/python2.7/dist-packages
Do you wish to build TensorFlow with MKL support? [y/N] y
MKL support will be enabled for TensorFlow
Do you wish to download MKL LIB from the web? [Y/n] Y
Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: 
Do you wish to use jemalloc as the malloc implementation? [Y/n] n
jemalloc disabled
Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N
No Google Cloud Platform support will be enabled for TensorFlow
Do you wish to build TensorFlow with Hadoop File System support? [y/N] N
No Hadoop File System support will be enabled for TensorFlow
Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] N
No XLA JIT support will be enabled for TensorFlow
Do you wish to build TensorFlow with VERBS support? [y/N] N
No VERBS support will be enabled for TensorFlow
Do you wish to build TensorFlow with OpenCL support? [y/N] N
No OpenCL support will be enabled for TensorFlow
Do you wish to build TensorFlow with CUDA support? [y/N] N
No CUDA support will be enabled for TensorFlow
  1. The pip package. To build it you have to describe which instructions you want (you know, those Tensorflow informed you are missing).

Build pip script: bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.1 --copt=-msse4.2 -k //tensorflow/tools/pip_package:build_pip_package

Build pip package: bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

Install Tensorflow pip package you just built: sudo pip install /tmp/tensorflow_pkg/tensorflow-1.2.1-cp27-cp27mu-linux_x86_64.whl

Now next time you start up Tensorflow it will not complain anymore about missing instructions.

Using Linq to get the last N elements of a collection?

I tried to combine efficiency and simplicity and end up with this :

public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int count)
{
    if (source == null) { throw new ArgumentNullException("source"); }

    Queue<T> lastElements = new Queue<T>();
    foreach (T element in source)
    {
        lastElements.Enqueue(element);
        if (lastElements.Count > count)
        {
            lastElements.Dequeue();
        }
    }

    return lastElements;
}

About performance : In C#, Queue<T> is implemented using a circular buffer so there is no object instantiation done each loop (only when the queue is growing up). I did not set queue capacity (using dedicated constructor) because someone might call this extension with count = int.MaxValue . For extra performance you might check if source implement IList<T> and if yes, directly extract the last values using array indexes.

How to solve npm error "npm ERR! code ELIFECYCLE"

Its weird but it works for me

Go to

control panel -->System and Security--> System --> Advanced System Security--> Environment Variables

In Environment Variable popup you will edit the user variable PATH and add "C:\Windows\System32" value as semicolon separated to the existing value.

Not but not least restart the Machine.

enter image description here

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

How to Get JSON Array Within JSON Object?

  Gson gson = new Gson();
                Type listType = new TypeToken<List<Data>>() {}.getType();
                List<Data>     cartProductList = gson.fromJson(response.body().get("data"), listType);
                Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();

Error inflating class android.support.v7.widget.Toolbar?

For me it worked after I did:

  • Cleaning solution.
  • Deleting the app from the phone I've debugged it at.
  • Closing Visual Studio.
  • Deleting folders /bin/ and /obj/ in android projects.
  • Launching solution again.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is part of C, so it's not Objective-C specific. Here's a translation into an if statement:

if (inPseudoEditMode)
    label.frame = kLabelIndentedRec;
else
    label.frame = kLabelRect;

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

access key and value of object using *ngFor

Use index:

<div *ngFor="let value of Objects; index as key">

Usage:

{{key}} -> {{value}}

Display filename before matching line

grep 'search this' *.txt

worked for me to search through all .txt files (enter your own search value, of course).

How might I schedule a C# Windows Service to perform a task daily?

For those that found the above solutions not working, it's because you may have a this inside your class, which implies an extension method which, as the error message says, only makes sense on a non-generic static class. Your class isn't static. This doesn't seem to be something that makes sense as an extension method, since it's acting on the instance in question, so remove the this.

jquery/javascript convert date string to date

I would grab date.js or else you will need to roll your own formatting function.

Save attachments to a folder and rename them

I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.

I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
        saveFolder = "C:\PathToDirectory\"
    Dim dateFormat As String
        dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Thanks a ton for the other solutions, many of them go above an beyond :)

Converting between strings and ArrayBuffers

You can use TextEncoder and TextDecoder from the Encoding standard, which is polyfilled by the stringencoding library, to convert string to and from ArrayBuffers:

var uint8array = new TextEncoder().encode(string);
var string = new TextDecoder(encoding).decode(uint8array);

How to split large text file in windows?

If you have installed Git for Windows, you should have Git Bash installed, since that comes with Git.

Use the split command in Git Bash to split a file:

  • into files of size 500MB each: split myLargeFile.txt -b 500m

  • into files with 10000 lines each: split myLargeFile.txt -l 10000

Tips:

  • If you don't have Git/Git Bash, download at https://git-scm.com/download

  • If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe

That's it!


I always like examples though...

Example:

enter image description here

You can see in this image that the files generated by split are named xaa, xab, xac, etc.

These names are made up of a prefix and a suffix, which you can specify. Since I didn't specify what I want the prefix or suffix to look like, the prefix defaulted to x, and the suffix defaulted to a two-character alphabetical enumeration.

Another Example:

This example demonstrates

  • using a filename prefix of MySlice (instead of the default x),
  • the -d flag for using numerical suffixes (instead of aa, ab, ac, etc...),
  • and the option -a 5 to tell it I want the suffixes to be 5 digits long:

enter image description here

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How to open a new tab in GNOME Terminal from command line?

A bit more elaborate version (to use from another window):

#!/bin/bash

DELAY=3

TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id

xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return

wmctrl -i -a $WID # go to that window (WID is numeric)

# vim:ai
# EOF #

What is the behavior of integer division?

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Find full path of the Python interpreter?

sys.executable contains full path of the currently running Python interpreter.

import sys

print(sys.executable)

which is now documented here

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How do you discover model attributes in Rails?

For Schema related stuff

Model.column_names         
Model.columns_hash         
Model.columns 

For instance variables/attributes in an AR object

object.attribute_names                    
object.attribute_present?          
object.attributes

For instance methods without inheritance from super class

Model.instance_methods(false)

The multi-part identifier could not be bound

In my case the issue turned out to be the alias name I had given to the table. "oa" seems to be not acceptable for SQL Server.

List of remotes for a Git repository?

You can get a list of any configured remote URLs with the command git remote -v.

This will give you something like the following:

base    /home/***/htdocs/base (fetch)
base    /home/***/htdocs/base (push)
origin  [email protected]:*** (fetch)
origin  [email protected]:*** (push)

How to make a .NET Windows Service start right after the installation?

Visual Studio

If you are creating a setup project with VS, you can create a custom action who called a .NET method to start the service. But, it is not really recommended to use managed custom action in a MSI. See this page.

ServiceController controller  = new ServiceController();
controller.MachineName = "";//The machine where the service is installed;
controller.ServiceName = "";//The name of your service installed in Windows Services;
controller.Start();

InstallShield or Wise

If you are using InstallShield or Wise, these applications provide the option to start the service. Per example with Wise, you have to add a service control action. In this action, you specify if you want to start or stop the service.

Wix

Using Wix you need to add the following xml code under the component of your service. For more information about that, you can check this page.

<ServiceInstall 
    Id="ServiceInstaller"  
    Type="ownProcess"  
    Vital="yes"  
    Name=""  
    DisplayName=""  
    Description=""  
    Start="auto"  
    Account="LocalSystem"   
    ErrorControl="ignore"   
    Interactive="no">  
        <ServiceDependency Id="????"/> ///Add any dependancy to your service  
</ServiceInstall>

How to pass parameter to a promise function

Another way(Must Try):

_x000D_
_x000D_
var promise1 = new Promise(function(resolve, reject) {_x000D_
  resolve('Success!');_x000D_
});_x000D_
var extraData = 'ImExtraData';_x000D_
promise1.then(function(value) {_x000D_
  console.log(value, extraData);_x000D_
  // expected output: "Success!" "ImExtraData"_x000D_
}, extraData);
_x000D_
_x000D_
_x000D_

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Warn user before leaving web page with unsaved changes

via jquery

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Determine the number of NA values in a column

A quick and easy Tidyverse solution to get a NA count for all columns is to use summarise_all() which I think makes a much easier to read solution than using purrr or sapply

library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA), 
             col2 = c(NA, NA, "a", "b"))

df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#>    col1  col2
#>   <int> <int>
#> 1     1     2

Upload files with HTTPWebrequest (multipart/form-data)

VB Example (converted from C# example on another post):

Private Sub HttpUploadFile( _
    ByVal uri As String, _
    ByVal filePath As String, _
    ByVal fileParameterName As String, _
    ByVal contentType As String, _
    ByVal otherParameters As Specialized.NameValueCollection)

    Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
    Dim newLine As String = System.Environment.NewLine
    Dim boundaryBytes As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
    Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)

    request.ContentType = "multipart/form-data; boundary=" & boundary
    request.Method = "POST"
    request.KeepAlive = True
    request.Credentials = Net.CredentialCache.DefaultCredentials

    Using requestStream As IO.Stream = request.GetRequestStream()

        Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"

        For Each key As String In otherParameters.Keys

            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
            Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
            Dim formItemBytes As Byte() = Text.Encoding.UTF8.GetBytes(formItem)
            requestStream.Write(formItemBytes, 0, formItemBytes.Length)

        Next key

        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)

        Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
        Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
        Dim headerBytes As Byte() = Text.Encoding.UTF8.GetBytes(header)
        requestStream.Write(headerBytes, 0, headerBytes.Length)

        Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)

            Dim buffer(4096) As Byte
            Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)

            Do While (bytesRead > 0)

                requestStream.Write(buffer, 0, bytesRead)
                bytesRead = fileStream.Read(buffer, 0, buffer.Length)

            Loop

        End Using

        Dim trailer As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
        requestStream.Write(trailer, 0, trailer.Length)

    End Using

    Dim response As Net.WebResponse = Nothing

    Try

        response = request.GetResponse()

        Using responseStream As IO.Stream = response.GetResponseStream()

            Using responseReader As New IO.StreamReader(responseStream)

                Dim responseText = responseReader.ReadToEnd()
                Diagnostics.Debug.Write(responseText)

            End Using

        End Using

    Catch exception As Net.WebException

        response = exception.Response

        If (response IsNot Nothing) Then

            Using reader As New IO.StreamReader(response.GetResponseStream())

                Dim responseText = reader.ReadToEnd()
                Diagnostics.Debug.Write(responseText)

            End Using

            response.Close()

        End If

    Finally

        request = Nothing

    End Try

End Sub

How can I use pickle to save a dict?

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normally it's preferable to use the cPickle implementation

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I was getting this and was stumped (using Visual Studio 2013 Premium).

Normally our apps at work reference .dlls in a particular common/app directory, like this: C:\OurCompanyApps\xxxxxx.dll. This was happening in a solution that has a bunch of WinForm and .dll projects in it. The .dll projects compile to C:\OurCompanyApps\ and the WinForm projects reference the compiled .dll files in that location.

The problem: I found that the app in question was referencing the .dll project in the Source Control bin\Debug location instead of the compiled .dll file in C:\OurCompanyApps.

Solution: I deleted the reference and re-added it from the C:\OurCompanyApps\ location. Then I could step-through the breakpoints I had added in the .dll code.

Hope this helps someone.

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

Why can't I define a default constructor for a struct in .NET?

A struct is a value type and a value type must have a default value as soon as it is declared.

MyClass m;
MyStruct m2;

If you declare two fields as above without instantiating either, then break the debugger, m will be null but m2 will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

VBA code to set date format for a specific column as "yyyy-mm-dd"

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

Determine on iPhone if user has enabled push notifications

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
    // blah blah blah
{
    NSLog(@"Notification Enabled");
}
else
{
    NSLog(@"Notification not enabled");
}

Here we get the UIRemoteNotificationType from UIApplication. It represents the state of push notification of this app in the setting, than you can check on its type easily

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Why does javascript map function return undefined?

var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

Define constant variables in C++ header

Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.

Constants.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class GlobalConstants {
  public:
    static const int myConstant;
    static const int myOtherConstant;
};

#endif

Constants.cpp

#include "Constants.h"

const int GlobalConstants::myConstant = 1;
const int GlobalConstants::myOtherConstant = 3;

Then you can use this like so:

#include "Constants.h"

void foo() {
  int foo = GlobalConstants::myConstant;
}

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

How can I make an svg scale with its parent container?

After like 48 hours of research, I ended up doing this to get proportional scaling:

NOTE: This sample is written with React. If you aren't using that, change the camel case stuff back to hyphens (ie: change backgroundColor to background-color and change the style Object back to a String).

<div
  style={{
    backgroundColor: 'lightpink',
    resize: 'horizontal',
    overflow: 'hidden',
    width: '1000px',
    height: 'auto',
  }}
>
  <svg
    width="100%"
    viewBox="113 128 972 600"
    preserveAspectRatio="xMidYMid meet"
  >
    <g> ... </g>
  </svg>
</div>

Here's what is happening in the above sample code:

VIEWBOX

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

min-x, min-y, width and height

ie: viewbox="0 0 1000 1000"

Viewbox is an important attribute because it basically tells the SVG what size to draw and where. If you used CSS to make the SVG 1000x1000 px but your viewbox was 2000x2000, you would see the top-left quarter of your SVG.

The first two numbers, min-x and min-y, determine if the SVG should be offset inside the viewbox.

My SVG needs to shift up/down or left/right

Examine this: viewbox="50 50 450 450"

The first two numbers will shift your SVG left 50px and up 50px, and the second two numbers are the viewbox size: 450x450 px. If your SVG is 500x500 but it has some extra padding on it, you can manipulate those numbers to move it around inside the "viewbox".

Your goal at this point is to change one of those numbers and see what happens.

You can also completely omit the viewbox, but then your milage will vary depending on every other setting you have at the time. In my experience, you will encounter issues with preserving aspect ratio because the viewbox helps define the aspect ratio.

PRESERVE ASPECT RATIO

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

Based on my research, there are lots of different aspect ratio settings, but the default one is called xMidYMid meet. I put it on mine to explicitly remind myself. xMidYMid meet makes it scale proportionately based on the midpoint X and Y. This means it stays centered in the viewbox.

WIDTH

MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width

Look at my example code above. Notice how I set only width, no height. I set it to 100% so it fills the container it is in. This is what is probably contributing the most to answering this Stack Overflow question.

You can change it to whatever pixel value you want, but I'd recommend using 100% like I did to blow it up to max size and then control it with CSS via the parent container. I recommend this because you will get "proper" control. You can use media queries and you can control the size without crazy JavaScript.

SCALING WITH CSS

Look at my example code above again. Notice how I have these properties:

resize: 'horizontal', // you can safely omit this
overflow: 'hidden',   // if you use resize, use this to fix weird scrollbar appearance
width: '1000px',
height: 'auto',

This is additional, but it shows you how to allow the user to resize the SVG while maintaining the proper aspect ratio. Because the SVG maintains its own aspect ratio, you only need to make width resizable on the parent container, and it will resize as desired.

We leave height alone and/or set it to auto, and we control the resizing with width. I picked width because it is often more meaningful due to responsive designs.

Here is an image of these settings being used:

enter image description here

If you read every solution in this question and are still confused or don't quite see what you need, check out this link here. I found it very helpful:

https://css-tricks.com/scale-svg/

It's a massive article, but it breaks down pretty much every possible way to manipulate an SVG, with or without CSS. I recommend reading it while casually drinking a coffee or your choice of select liquids.

GoogleTest: How to skip a test?

I had the same need for conditional tests, and I figured out a good workaround. I defined a macro TEST_C that works like a TEST_F macro, but it has a third parameter, which is a boolean expression, evaluated runtime in main.cpp BEFORE the tests are started. Tests that evaluate false are not executed. The macro is ugly, but it look like:

#pragma once
extern std::map<std::string, std::function<bool()> >* m_conditionalTests;
#define TEST_C(test_fixture, test_name, test_condition)\
class test_fixture##_##test_name##_ConditionClass\
{\
    public:\
    test_fixture##_##test_name##_ConditionClass()\
    {\
        std::string name = std::string(#test_fixture) + "." + std::string(#test_name);\
        if (m_conditionalTests==NULL) {\
            m_conditionalTests = new std::map<std::string, std::function<bool()> >();\
        }\
        m_conditionalTests->insert(std::make_pair(name, []()\
        {\
            DeviceInfo device = Connection::Instance()->GetDeviceInfo();\
            return test_condition;\
        }));\
    }\
} test_fixture##_##test_name##_ConditionInstance;\
TEST_F(test_fixture, test_name)

Additionally, in your main.cpp, you need this loop to exclude the tests that evaluate false:

// identify tests that cannot run on this device
std::string excludeTests;
for (const auto& exclusion : *m_conditionalTests)
{
    bool run = exclusion.second();
    if (!run)
    {
        excludeTests += ":" + exclusion.first;
    }
}

// add the exclusion list to gtest
std::string str = ::testing::GTEST_FLAG(filter);
::testing::GTEST_FLAG(filter) = str + ":-" + excludeTests;

// run all tests
int result = RUN_ALL_TESTS();

How to do SVN Update on my project using the command line

From the command line it would be just:

svn update

(in the directory you've got a copy of a SVN project).

How to find the 'sizeof' (a pointer pointing to an array)?

No, you can't use sizeof(ptr) to find the size of array ptr is pointing to.

Though allocating extra memory(more than the size of array) will be helpful if you want to store the length in extra space.

How to run vbs as administrator from vbs?

fun lil batch file

@set E=ECHO &set S=SET &set CS=CScript //T:3 //nologo %~n0.vbs /REALTIME^>nul^& timeout 1 /NOBREAK^>nul^& del /Q %~n0.vbs&CLS
@%E%off&color 4a&title %~n0&%S%CX=CLS^&EXIT&%S%BS=^>%~n0.vbs&%S%G=GOTO &%S%H=shell&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    %G%2
) ELSE (
    if not "%minimized%"=="" %G%1
)
%S%minimized=true & start /min cmd /C "%~dpnx0"&%CX%
:1
%E%%S%%H%=CreateObject("%H%.Application"):%H%.%H%Execute "%~dpnx0",,"%CD%", "runas", 1:%S%%H%=nothing%BS%&%CS%&%CX%
:2
%E%%~dpnx0 fvcLing admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"& timeout 3 /NOBREAK>nul
:3
%E%x=msgbox("end of line" ,48, "%~n0")%BS%&%CS%&%CX%

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How to remove specific object from ArrayList in Java?

or you can use java 8 lambda

test.removeIf(i -> i==2);

it will simply remove all object that meet the condition

Resolve promises one after another (i.e. in sequence)?

This is a slight variation of another answer above. Using native Promises:

function inSequence(tasks) {
    return tasks.reduce((p, task) => p.then(task), Promise.resolve())
}

Explanation

If you have these tasks [t1, t2, t3], then the above is equivalent to Promise.resolve().then(t1).then(t2).then(t3). It's the behavior of reduce.

How to use

First You need to construct a list of tasks! A task is a function that accepts no argument. If you need to pass arguments to your function, then use bind or other methods to create a task. For example:

var tasks = files.map(file => processFile.bind(null, file))
inSequence(tasks).then(...)

How to make full screen background in a web page

I have followed this tutorial: https://css-tricks.com/perfect-full-page-background-image/

Specifically, the first Demo was the one that helped me out a lot!

CSS
 {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}

this might help!

JSON array get length

The JSONArray.length() returns the number of elements in the JSONObject contained in the Array. Not the size of the array itself.

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

You may need to do AndroidStudio - Build - Clean

If you updated manifest through the filesystem or Git it won't pick up the changes.

How do I set the eclipse.ini -vm option?

I know that there exists a command line option, -vm, to specify the path to the executable of the Java runtime. This may be the same as in eclipse.ini.

Javascript: console.log to html

This post has helped me a lot, and after a few iterations, this is what we use.

The idea is to post log messages and errors to HTML, for example if you need to debug JS and don't have access to the console.

You do need to change 'console.log' with 'logThis', as it is not recommended to change native functionality.

What you'll get:

  • A plain and simple 'logThis' function that will display strings and objects along with current date and time for each line
  • A dedicated window on top of everything else. (show it only when needed)
  • Can be used inside '.catch' to see relevant errors from promises.
  • No change of default console.log behavior
  • Messages will appear in the console as well.

_x000D_
_x000D_
function logThis(message) {
  // if we pass an Error object, message.stack will have all the details, otherwise give us a string
  if (typeof message === 'object') {
    message = message.stack || objToString(message);
  }

  console.log(message);

  // create the message line with current time
  var today = new Date();
  var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  var dateTime = date + ' ' + time + ' ';

  //insert line
  document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}

function objToString(obj) {
  var str = 'Object: ';
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str += p + '::' + obj[p] + ',\n';
    }
  }
  return str;
}

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
_x000D_
#logWindow {
  overflow: auto;
  position: absolute;
  width: 90%;
  height: 90%;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;
}
_x000D_
<div id="logWindow">
  <pre id="logger"></pre>
</div>
_x000D_
_x000D_
_x000D_

Thanks this answer too, JSON.stringify() didn't work for this.

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

Converting a year from 4 digit to 2 digit and back again in C#

The answer is already given. But here I want to add something. Some person told that it did not work.

May be you are using

DateTime.Now.Year.ToString("yy");

that is why it is not working. I also made the same the mistake.

Change it to

DateTime.Now.ToString("yy");

MySQL - how to front pad zip code with "0"?

CHAR(5)

or

MEDIUMINT (5) UNSIGNED ZEROFILL

The first takes 5 bytes per zip code.

The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.

Server unable to read htaccess file, denying access to be safe

In my case apache was somehow configured wrong(?) so I had to set permissions to all parent dirs too. Just setting permission to .htaccess (and it's parent dir) didn't work.

How to grep, excluding some patterns?

Simply use! grep -v multiple times.

Content of file

[root@server]# cat file
1
2
3
4
5

Exclude the line or match

[root@server]# cat file |grep -v 3
1
2
4
5

Exclude the line or match multiple

[root@server]# cat file |grep -v 3 |grep -v 5
1
2
4

How to verify if nginx is running or not?

For Mac users

I found out one more way: You can check if /usr/local/var/run/nginx.pid exists. If it is - nginx is running. Useful way for scripting.

Example:

if [ -f /usr/local/var/run/nginx.pid ]; then
   echo "Nginx is running"

fi

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

Simple export and import of a SQLite database on Android

To export db rather it is SQLITE or ROOM:

Firstly, add this permission in AndroidManifest.xml file:

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

Secondly, we drive to code the db functions:

private void exportDB() {
    try {
        File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = DirectoryName + File.separator +
                DATABASE_NAME + ".db";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);

        // Transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        // Close the streams
        output.flush();
        output.close();
        fis.close();


    } catch (IOException e) {
        Log.e("dbBackup:", e.getMessage());
    }
}

Create Folder on Daily basis with name of folder is Current date:

public void createBackup() {

    sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
    editor = sharedPref.edit();

    String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

    if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
        editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

        editor.commit();
    }

    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {

        DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
        folder = new File(DirectoryName);
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            exportDB();
        }
    } else {
        Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
    }

}

Assign the DATABASE_NAME without .db extension and its data type is string

HTML character codes for this ? or this ?

&#9650; is the Unicode black up-pointing triangle (?) while &#9660; is the black down-pointing triangle (?).

You can just plug the characters (copied from the web) into this site for a lookup.

How do you use script variables in psql?

One final word on PSQL variables:

  1. They don't expand if you enclose them in single quotes in the SQL statement. Thus this doesn't work:

    SELECT * FROM foo WHERE bar = ':myvariable'
    
  2. To expand to a string literal in a SQL statement, you have to include the quotes in the variable set. However, the variable value already has to be enclosed in quotes, which means that you need a second set of quotes, and the inner set has to be escaped. Thus you need:

    \set myvariable '\'somestring\''  
    SELECT * FROM foo WHERE bar = :myvariable
    

    EDIT: starting with PostgreSQL 9.1, you may write instead:

    \set myvariable somestring
    SELECT * FROM foo WHERE bar = :'myvariable'
    

How to do a SOAP wsdl web services call from the command line

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:ACTION_YOU_WANT_TO_CALL" --data @FILE_NAME URL_OF_THE_SERVICE 

Above command was helpful for me

Example

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:urn:GetVehicleLimitedInfo" --data @request.xml http://11.22.33.231:9080/VehicleInfoQueryService.asmx 

More info

How to get Tensorflow tensor dimensions (shape) as int values?

2.0 Compatible Answer: In Tensorflow 2.x (2.1), you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:

Method 1 (using tf.shape):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape)   # [2,3]

Method 2 (using tf.get_shape()):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape)   # [2,3]

"Bitmap too large to be uploaded into a texture"

Addition of the following 2 attributes in (AndroidManifest.xml) worked for me:

android:largeHeap="true"
android:hardwareAccelerated="false"

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

Change MySQL default character set to UTF-8 in my.cnf?

On Fedora 21

$ vi /etc/my.cnf

Add follow:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci 
skip-character-set-client-handshake

Save and exit.

Final remember restart service mysqld with service mysqld restart.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

You shold use the keys() or names() method. keys() will give you an iterator containing all the String property names in the object while names() will give you an array of all key String names.

You can get the JSONObject documentation here

http://developer.android.com/reference/org/json/JSONObject.html

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Trying Gradle build - "Task 'build' not found in root project"

run

gradle clean 

then try

gradle build 

it worked for me

How can I set multiple CSS styles in JavaScript?

You can write a function that will set declarations individually in order not to overwrite any existing declarations that you don't supply. Let's say you have this object parameter list of declarations:

const myStyles = {
  'background-color': 'magenta',
  'border': '10px dotted cyan',
  'border-radius': '5px',
  'box-sizing': 'border-box',
  'color': 'yellow',
  'display': 'inline-block',
  'font-family': 'monospace',
  'font-size': '20px',
  'margin': '1em',
  'padding': '1em'
};

You might write a function that looks like this:

function applyStyles (el, styles) {
  for (const prop in styles) {
    el.style.setProperty(prop, styles[prop]);
  }
};

which takes an element and an object property list of style declarations to apply to that object. Here's a usage example:

const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});

_x000D_
_x000D_
// styles to apply_x000D_
const myStyles = {_x000D_
  'background-color': 'magenta',_x000D_
  'border': '10px dotted cyan',_x000D_
  'border-radius': '5px',_x000D_
  'box-sizing': 'border-box',_x000D_
  'color': 'yellow',_x000D_
  'display': 'inline-block',_x000D_
  'font-family': 'monospace',_x000D_
  'font-size': '20px',_x000D_
  'margin': '1em',_x000D_
  'padding': '1em'_x000D_
};_x000D_
_x000D_
function applyStyles (el, styles) {_x000D_
  for (const prop in styles) {_x000D_
    el.style.setProperty(prop, styles[prop]);_x000D_
  }_x000D_
};_x000D_
_x000D_
// create example paragraph and append it to the page body_x000D_
const p = document.createElement('p');_x000D_
p.textContent = 'This is a paragraph.';_x000D_
document.body.appendChild(p);_x000D_
_x000D_
// when the paragraph is clicked, call the function, providing the_x000D_
// paragraph and myStyles object as arguments_x000D_
p.onclick = (ev) => {_x000D_
  applyStyles(p, myStyles);_x000D_
}_x000D_
_x000D_
// this time, target the page body and supply an object literal_x000D_
applyStyles(document.body, {'background-color': 'grey'});
_x000D_
_x000D_
_x000D_

pandas get column average/mean

You can use either of the two statements below:

numpy.mean(df['col_name'])
# or
df['col_name'].mean()

When should I use mmap for file access?

An advantage that isn't listed yet is the ability of mmap() to keep a read-only mapping as clean pages. If one allocates a buffer in the process's address space, then uses read() to fill the buffer from a file, the memory pages corresponding to that buffer are now dirty since they have been written to.

Dirty pages can not be dropped from RAM by the kernel. If there is swap space, then they can be paged out to swap. But this is costly and on some systems, such as small embedded devices with only flash memory, there is no swap at all. In that case, the buffer will be stuck in RAM until the process exits, or perhaps gives it back withmadvise().

Non written to mmap() pages are clean. If the kernel needs RAM, it can simply drop them and use the RAM the pages were in. If the process that had the mapping accesses it again, it cause a page fault the kernel re-loads the pages from the file they came from originally. The same way they were populated in the first place.

This doesn't require more than one process using the mapped file to be an advantage.