Programs & Examples On #Compound literals

Java default constructor

Neither of them. If you define it, it's not the default.

The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:

public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

This is exactly the same as

public Module()
{}

And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.

Reference: Java Language Specification

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

Clarification

Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because

  • the question got the defaults wrong, and
  • the constructor has exactly the same effect whether they are included or not.

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

Maintain aspect ratio of div but fill screen width and height in CSS?

There is now a new CSS property specified to address this: object-fit.

http://docs.webplatform.org/wiki/css/properties/object-fit

Browser support is still somewhat lacking (http://caniuse.com/#feat=object-fit) - currently works to some extent in most browsers except Microsoft - but given time it is exactly what was required for this question.

`React/RCTBridgeModule.h` file not found

If Libraries/React.xcodeproj are red in xcode then reinstall node_modules

rm -rf node_modules && yarn

My newly created project from react-native 0.46.3 was red :S I have npm 5.3.0 and yarn 0.24.5 when I did react-native init

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

jQuery $.ajax(), pass success data into separate function

In the first code block, you're never using the str parameter. Did you mean to say the following?

testFunc = function(str, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: str,
        success: callback
    });
}

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Regex to validate password strength

Another solution:

import re

passwordRegex = re.compile(r'''(
    ^(?=.*[A-Z].*[A-Z])                # at least two capital letters
    (?=.*[!@#$&*])                     # at least one of these special c-er
    (?=.*[0-9].*[0-9])                 # at least two numeric digits
    (?=.*[a-z].*[a-z].*[a-z])          # at least three lower case letters
    .{8,}                              # at least 8 total digits
    $
    )''', re.VERBOSE)

def userInputPasswordCheck():
    print('Enter a potential password:')
    while True:
        m = input()
        mo = passwordRegex.search(m) 
        if (not mo):
           print('''
Your password should have at least one special charachter,
two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.

Enter another password:''')          
        else:
           print('Password is strong')
           return
userInputPasswordCheck()

Restful API service

There is another approach here which basically helps you to forget about the whole management of the requests. It is based on an async queue method and a callable/callback based response. The main advantage is that by using this method you'll be able to make the whole process (request, get and parse response, sabe to db) completely transparent for you. Once you get the response code the work is already done. After that you just need to make a call to your db and you are done. It helps as well with the problematic of what happens when your activity is not active. What will happen here is that you'll have all your data saved in your local database but the response won't be processed by your activity, that's the ideal way.

I wrote about a general approach here http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

I'll be putting specific sample code in upcoming posts. Hope it helps, feel free to contact me for sharing the approach and solving potential doubts or issues.

SQL Query - Concatenating Results into One String

DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''

SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString

Phonegap + jQuery Mobile, real world sample or tutorial

This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )

And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd

Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.

I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Creating and playing a sound in swift

Swift 3 here's how i do it.

{

import UIKit
import AVFoundation

        let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
        do {

            player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }

            player.prepareToPlay()
            player.play()
        } catch let error as Error {
            print(error)

        }
    }

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

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

Initial size for the ArrayList

10 is the initial capacity of the AL, not the size (which is 0). You should mention the initial capacity to some high value when you are going to have a lots of elements, because it avoids the overhead of expanding the capacity as you keep adding elements.

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

How do I remove a library from the arduino environment?

as of 1.8.X IDE C:\Users***\Documents\Arduino\Libraries\

Extract time from date String

A very simple way is to use Formatter (see date time conversions) or more directly String.format as in

String.format("%tR", new Date())

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Git Clone - Repository not found

Another reason for this error, if you are on github, and trying to use deploy keys for multiple repos, you will find this does not work.

In that case you need to create a machine user, however if you don't and you try to clone any repo besides the one with the deploy key, you will get this error.

how to count the spaces in a java string?

Here's a different way of looking at it, and it's a simple one-liner:

int spaces = s.replaceAll("[^ ]", "").length();

This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).

You might want to add a null check:

int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();

Java 8 update

You can use a stream too:

int spaces = s.chars().filter(c -> c == (int)' ').count();

Standardize data columns in R

Realizing that the question is old and one answer is accepted, I'll provide another answer for reference.

scale is limited by the fact that it scales all variables. The solution below allows to scale only specific variable names while preserving other variables unchanged (and the variable names could be dynamically generated):

library(dplyr)

set.seed(1234)
dat <- data.frame(x = rnorm(10, 30, .2), 
                  y = runif(10, 3, 5),
                  z = runif(10, 10, 20))
dat

dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
dat2

which gives me this:

> dat
          x        y        z
1  29.75859 3.633225 14.56091
2  30.05549 3.605387 12.65187
3  30.21689 3.318092 13.04672
4  29.53086 3.079992 15.07307
5  30.08582 3.437599 11.81096
6  30.10121 4.621197 17.59671
7  29.88505 4.051395 12.01248
8  29.89067 4.829316 12.58810
9  29.88711 4.662690 19.92150
10 29.82199 3.091541 18.07352

and

> dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
> dat2
          x          y           z
1  29.75859 -0.3004815 -0.06016029
2  30.05549 -0.3423437 -0.72529604
3  30.21689 -0.7743696 -0.58772361
4  29.53086 -1.1324181  0.11828039
5  30.08582 -0.5946582 -1.01827752
6  30.10121  1.1852038  0.99754666
7  29.88505  0.3283513 -0.94806607
8  29.89067  1.4981677 -0.74751378
9  29.88711  1.2475998  1.80753470
10 29.82199 -1.1150515  1.16367556

EDIT 1 (2016): Addressed Julian's comment: the output of scale is Nx1 matrix so ideally we should add an as.vector to convert the matrix type back into a vector type. Thanks Julian!

EDIT 2 (2019): Quoting Duccio A.'s comment: For the latest dplyr (version 0.8) you need to change dplyr::funcs with list, like dat %>% mutate_each_(list(~scale(.) %>% as.vector), vars=c("y","z"))

EDIT 3 (2020): Thanks to @mj_whales: the old solution is deprecated and now we need to use mutate_at.

How to install an npm package from GitHub directly?

You can directly install an github repo by npm install command, like this: npm install https://github.com/futurechallenger/npm_git_install.git --save

NOTE: In the repo which will be installed by npm command:

  1. maybe you have to have a dist folder in you repo, according to @Dan Dascalescu's comment.
  2. You definitely have to have a package.json in you repo! which I forget add.

Test if executable exists in Python?

I know this is an ancient question, but you can use distutils.spawn.find_executable. This has been documented since python 2.4 and has existed since python 1.6.

import distutils.spawn
distutils.spawn.find_executable("notepad.exe")

Also, Python 3.3 now offers shutil.which().

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

How can I make an "are you sure" prompt in a Windows batchfile?

There are two commands available for user prompts on Windows command line:

  • set with option /P available on all Windows NT versions with enabled command extensions and
  • choice.exe available by default on Windows Vista and later Windows versions for PC users and on Windows Server 2003 and later server versions of Windows.

set is an internal command of Windows command processor cmd.exe. The option /P to prompt a user for a string is available only with enabled command extensions which are enabled by default as otherwise nearly no batch file would work anymore nowadays.

choice.exe is a separate console application (external command) located in %SystemRoot%\System32. File choice.exe of Windows Server 2003 can be copied into directory %SystemRoot%\System32 on a Windows XP machine for usage on Windows XP like many other commands not available by default on Windows XP, but available by default on Windows Server 2003.

It is best practice to favor usage of CHOICE over usage of SET /P because of the following reasons:

  1. CHOICE accepts only keys (respectively characters read from STDIN) specified after option /C (and Ctrl+C and Ctrl+Break) and outputs an error beep if the user presses a wrong key.
  2. CHOICE does not require pressing any other key than one of the acceptable ones. CHOICE exits immediately once an acceptable key is pressed while SET /P requires that the user finishes input with RETURN or ENTER.
  3. It is possible with CHOICE to define a default option and a timeout to automatically continue with default option after some seconds without waiting for the user.
  4. The output is better on answering the prompt automatically from another batch file which calls the batch file with the prompt using something like echo Y | call PromptExample.bat on using CHOICE.
  5. The evaluation of the user's choice is much easier with CHOICE because of CHOICE exits with a value according to pressed key (character) which is assigned to ERRORLEVEL which can be easily evaluated next.
  6. The environment variable used on SET /P is not defined if the user hits just key RETURN or ENTER and it was not defined before prompting the user. The used environment variable on SET /P command line keeps its current value if defined before and user presses just RETURN or ENTER.
  7. The user has the freedom to enter anything on being prompted with SET /P including a string which results later in an exit of batch file execution by cmd because of a syntax error, or in execution of commands not included at all in the batch file on not good coded batch file. It needs some efforts to get SET /P secure against by mistake or intentionally wrong user input.

Here is a prompt example using preferred CHOICE and alternatively SET /P on choice.exe not available on used computer running Windows.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice

setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I "!UserChoice!" == "N" endlocal & goto :EOF
if /I not "!UserChoice!" == "Y" goto UseSetPrompt
endlocal
goto Continue

:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 1 goto UseChoice
if errorlevel 2 goto :EOF

:Continue
echo So your are sure. Okay, let's go ...
rem More commands can be added here.
endlocal

Note: This batch file uses command extensions which are not available on Windows 95/98/ME using command.com instead of cmd.exe as command interpreter.

The command line set "UserChoice=!UserChoice: =!" is added to make it possible to call this batch file with echo Y | call PromptExample.bat on Windows NT4/2000/XP and do not require the usage of echo Y| call PromptExample.bat. It deletes all spaces from string read from STDIN before running the two string comparisons.

echo Y | call PromptExample.bat results in YSPACE getting assigned to environment variable UserChoice. That would result on processing the prompt twice because of "Y " is neither case-insensitive equal "N" nor "Y" without deleting first all spaces. So UserChoice with YSPACE as value would result in running the prompt a second time with option N as defined as default in the batch file on second prompt execution which next results in an unexpected exit of batch file processing. Yes, secure usage of SET /P is really tricky, isn't it?

choice.exe exits with 0 in case of the user presses Ctrl+C or Ctrl+Break and answers next the question output by cmd.exe to exit batch file processing with N for no. For that reason the condition if not errorlevel 1 goto UserChoice is added to prompt the user once again for a definite answer on the prompt by batch file code with Y or N. Thanks to dialer for the information about this possible special use case.

The first line below the batch label :UseSetPrompt could be written also as:

set "UserChoice=N"

In this case the user choice input is predefined with N which means the user can hit just RETURN or ENTER (or Ctrl+C or Ctrl+Break and next N) to use the default choice.

The prompt text is output by command SET as written in the batch file. So the prompt text should end usually with a space character. The command CHOICE removes from prompt text all trailing normal spaces and horizontal tabs and then adds itself a space to the prompt text. Therefore the prompt text of command CHOICE can be written without or with a space at end. That does not make a difference on displayed prompt text on execution.

The order of user prompt evaluation could be also changed completely as suggested by dialer.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice

setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I not "!UserChoice!" == "Y" endlocal & goto :EOF
endlocal
goto Continue

:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 2 if errorlevel 1 goto Continue
goto :EOF

:Continue
echo So your are sure. Okay, let's go ...
endlocal

This code results in continuation of batch file processing below the batch label :Continue if the user pressed definitely key Y. In all other cases the code for N is executed resulting in an exit of batch file processing with this code independent on user pressed really that key, or entered something different intentionally or by mistake, or pressed Ctrl+C or Ctrl+Break and decided next on prompt output by cmd to not cancel the processing of the batch file.

For even more details on usage of SET /P and CHOICE for prompting user for a choice from a list of options see answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?

Some more hints:

  1. IF compares the two strings left and right of the comparison operator with including the double quotes. So case-insensitive compared is not the value of UserChoice with N and Y, but the value of UserChoice surrounded by " with "N" and "Y".
  2. The IF comparison operators EQU and NEQ are designed primary for comparing two integers in range -2147483648 to 2147483647 and not for comparing two strings. EQU and NEQ work also for strings comparisons, but result on comparing strings in double quotes after a useless attempt to convert left string to an integer. EQU and NEQ can be used only with enabled command extensions. The comparison operators for string comparisons are == and not ... == which work even with disabled command extensions as even command.com of MS-DOS and Windows 95/98/ME already supported them. For more details on IF comparison operators see Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files.
  3. The command goto :EOF requires enabled command extensions to really exit batch file processing. For more details see Where does GOTO :EOF return to?

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • echo /?
  • endlocal /?
  • goto /?
  • if /?
  • set /?
  • setlocal /?

See also:

How to create multiple output paths in Webpack config

Please don't use any workaround because it will impact build performance.

Webpack File Manager Plugin

Easy to install copy this tag on top of the webpack.config.js

const FileManagerPlugin = require('filemanager-webpack-plugin');

Install

npm install filemanager-webpack-plugin --save-dev

Add the plugin

module.exports = {
    plugins: [
        new FileManagerPlugin({
            onEnd: {
                copy: [
                    {source: 'www', destination: './vinod test 1/'},
                    {source: 'www', destination: './vinod testing 2/'},
                    {source: 'www', destination: './vinod testing 3/'},
                ],
            },
        }),
    ],
};

Screenshot

enter image description here

Capitalize first letter. MySQL

You can use a combination of UCASE(), MID() and CONCAT():

SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;

What is the most efficient way to store tags in a database?

Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).

Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.

How to display list of repositories from subversion server

Sometimes you may wish to check on the timestamp for when the repo was updated, for getting this handy info you can use the svn -v (verbose) option as in

svn list -v svn://123.123.123.123/svn/repo/path

How to make ng-repeat filter out duplicate results

None of the above filters fixed my issue so I had to copy the filter from official github doc. And then use it as explained in the above answers

angular.module('yourAppNameHere').filter('unique', function () {

return function (items, filterOn) {

if (filterOn === false) {
  return items;
}

if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  var hashCheck = {}, newItems = [];

  var extractValueToCompare = function (item) {
    if (angular.isObject(item) && angular.isString(filterOn)) {
      return item[filterOn];
    } else {
      return item;
    }
  };

  angular.forEach(items, function (item) {
    var valueToCheck, isDuplicate = false;

    for (var i = 0; i < newItems.length; i++) {
      if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      newItems.push(item);
    }

  });
  items = newItems;
}
return items;
  };

});

How do I correctly upgrade angular 2 (npm) to the latest version?

UPDATE:
Starting from CLI v6 you can just run ng update in order to get your dependencies updated automatically to a new version.

With ng update sometimes you might want to add --force flag. If you do so make sure that the version of typescript you got installed this way is supported by your current angular version, otherwise you might need to downgrade the typescript version.

Also checkout this guide Updating your Angular projects


For bash users only

If you are on are on Mac/Linux or running bash on Windows(that wont work in default Windows CMD) you can run that oneliner:

npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5 --save

yarn add @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5

Just specify version you wan't e.g @4.4.5 or put @latest to get the latest

Check your package.json just to make sure you are updating all @angular/* packages that you app is relying on

  • To see exact @angular version in your project run:
    npm ls @angular/compiler or yarn list @angular/compiler
  • To check the latest stable @angular version available on npm run:
    npm show @angular/compiler version

View array in Visual Studio debugger?

Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.

If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

This is supposedly because you trying to make cross-domain request, or something that is clarified as it. You could try adding header('Access-Control-Allow-Origin: *'); to the requested file.

Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source or XHR polling in IE 8-10 (which confused me first time).

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

First uninstall your application from the emulator:

adb -e uninstall your.application.package.name

Then try to install the application again.

FFmpeg: How to split video efficiently?

In my experience, don't use ffmpeg for splitting/join. MP4Box, is faster and light than ffmpeg. Please tryit. Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl: MP4Box -splits 716800 input.mp4 eg for concatenating two files you can use:

MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4

Or if you need split by time, use -splitx StartTime:EndTime:

MP4Box -add input.mp4 -splitx 0:15 -new split.mp4

Set transparent background using ImageMagick and commandline prompt

Solution

color=$( convert filename.png -format "%[pixel:p{0,0}]" info:- )
convert filename.png -alpha off -bordercolor $color -border 1 \
    \( +clone -fuzz 30% -fill none -floodfill +0+0 $color \
       -alpha extract -geometry 200% -blur 0x0.5 \
       -morphology erode square:1 -geometry 50% \) \
    -compose CopyOpacity -composite -shave 1 outputfilename.png

Explanation

This is rather a bit longer than the simple answers previously given, but it gives much better results: (1) The quality is superior due to antialiased alpha, and (2) only the background is removed as opposed to a single color. ("Background" is defined as approximately the same color as the top left pixel, using a floodfill from the picture edges.)

Additionally, the alpha channel is also eroded by half a pixel to avoid halos. Of course, ImageMagick's morphological operations don't (yet?) work at the subpixel level, so you can see I am blowing up the alpha channel to 200% before eroding.

Comparison of results

Here is a comparison of the simple approach ("-fuzz 2% -transparent white") versus my solution, when run on the ImageMagick logo. I've flattened both transparent images onto a saddle brown background to make the differences apparent (click for originals).

The simple replacement of white as transparent doesn't always work Antialiased alphachannel and floodfill looks much better

Notice how the Wizard's beard has disappeared in the simple approach. Compare the edges of the Wizard to see how antialiased alpha helps the figure blend smoothly into the background.

Of course, I completely admit there are times when you may wish to use the simpler solution. (For example: It's a heck of a lot easier to remember and if you're converting to GIF, you're limited to 1-bit alpha anyhow.)

mktrans shell script

Since it's unlikely you'll want to type this command repeatedly, I recommend wrapping it in a script. You can download a BASH shell script from github which performs my suggested solution. It can be run on multiple files in a directory and includes helpful comments in case you want to tweak things.

bg_removal script

By the way, ImageMagick actually comes with a script called "bg_removal" which uses floodfill in a similar manner as my solution. However, the results are not great because it still uses 1-bit alpha. Also, the bg_removal script runs slower and is a little bit trickier to use (it requires you to specify two different fuzz values). Here's an example of the output from bg_removal.

The bg_removal script: has beard, but lacks antialiasing

How to remove the first and the last character of a string

You can use substring method

s = s.substring(0, s.length - 1) //removes last character

another alternative is slice method

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

How to include *.so library in Android Studio?

Android NDK official hello-libs CMake example

https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs

Just worked for me on Ubuntu 17.10 host, Android Studio 3, Android SDK 26, so I strongly recommend that you base your project on it.

The shared library is called libgperf, the key code parts are:

  • hello-libs/app/src/main/cpp/CMakeLists.txt:

    // -L
    add_library(lib_gperf SHARED IMPORTED)
    set_target_properties(lib_gperf PROPERTIES IMPORTED_LOCATION
              ${distribution_DIR}/gperf/lib/${ANDROID_ABI}/libgperf.so)
    
    // -I
    target_include_directories(hello-libs PRIVATE
                               ${distribution_DIR}/gperf/include)
    // -lgperf
    target_link_libraries(hello-libs
                          lib_gperf)
    
  • app/build.gradle:

    android {
        sourceSets {
            main {
                // let gradle pack the shared library into apk
                jniLibs.srcDirs = ['../distribution/gperf/lib']
    

    Then, if you look under /data/app on the device, libgperf.so will be there as well.

  • on C++ code, use: #include <gperf.h>

  • header location: hello-libs/distribution/gperf/include/gperf.h

  • lib location: distribution/gperf/lib/arm64-v8a/libgperf.so

  • If you only support some architectures, see: Gradle Build NDK target only ARM

The example git tracks the prebuilt shared libraries, but it also contains the build system to actually build them as well: https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs/gen-libs

How to convert Json array to list of objects in c#

Your data structure and your JSON do not match.

Your JSON is this:

{
    "JsonValues":{
        "id": "MyID",
        ...
    }
}

But the data structure you try to serialize it to is this:

class ValueSet
{
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    ...
}

You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.

Also inside your class your JSON is this:

"values": { ... }

Your data structure is this:

[JsonProperty("values")]
public List<Value> values
{
    get;
    set;
}

Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.

Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.

If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:

{
    "id": "MyID",

     "values": [
         {
            "id": "100",
            "diaplayName": "MyValue1"
         }, {
            "id": "200",
            "diaplayName": "MyValue2"
         }
     ]
}

How to include view/partial specific styling in AngularJS

@tennisgent's solution is great. However, I think is a little limited.

Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

For a full solution I suggest using AngularCSS.

  1. Supports Angular's ngRoute, UI Router, directives, controllers and services.
  2. Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  3. You can customize where the stylesheets are injected: head, body, custom selector, etc...
  4. Supports preloading, persisting and cache busting
  5. Supports media queries and optimizes page load via matchMedia API

https://github.com/door3/angular-css

Here are some examples:

Routes

  $routeProvider
    .when('/page1', {
      templateUrl: 'page1/page1.html',
      controller: 'page1Ctrl',
      /* Now you can bind css to routes */
      css: 'page1/page1.css'
    })
    .when('/page2', {
      templateUrl: 'page2/page2.html',
      controller: 'page2Ctrl',
      /* You can also enable features like bust cache, persist and preload */
      css: {
        href: 'page2/page2.css',
        bustCache: true
      }
    })
    .when('/page3', {
      templateUrl: 'page3/page3.html',
      controller: 'page3Ctrl',
      /* This is how you can include multiple stylesheets */
      css: ['page3/page3.css','page3/page3-2.css']
    })
    .when('/page4', {
      templateUrl: 'page4/page4.html',
      controller: 'page4Ctrl',
      css: [
        {
          href: 'page4/page4.css',
          persist: true
        }, {
          href: 'page4/page4.mobile.css',
          /* Media Query support via window.matchMedia API
           * This will only add the stylesheet if the breakpoint matches */
          media: 'screen and (max-width : 768px)'
        }, {
          href: 'page4/page4.print.css',
          media: 'print'
        }
      ]
    });

Directives

myApp.directive('myDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'my-directive/my-directive.html',
    css: 'my-directive/my-directive.css'
  }
});

Additionally, you can use the $css service for edge cases:

myApp.controller('pageCtrl', function ($scope, $css) {

  // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
  $css.bind({ 
    href: 'my-page/my-page.css'
  }, $scope);

  // Simply add stylesheet(s)
  $css.add('my-page/my-page.css');

  // Simply remove stylesheet(s)
  $css.remove(['my-page/my-page.css','my-page/my-page2.css']);

  // Remove all stylesheets
  $css.removeAll();

});

You can read more about AngularCSS here:

http://door3.com/insights/introducing-angularcss-css-demand-angularjs

http://localhost/ not working on Windows 7. What's the problem?

It sounds like you have no web server running at all anywhere.

Have you tried enabling IIS and using it to display a basic html file first?

Programs & Features -> Turn Windows Features On/Off -> Internet Information Servcies

Then, place your html file in C:\inetpub\wwwroot\index.html and browse to http://localhost.

Once this works, try to get WAMP/php working. Be careful of port conflicts.

Is there a NumPy function to return the first index of something in an array?

Yes, given an array, array, and a value, item to search for, you can use np.where as:

itemindex = numpy.where(array==item)

The result is a tuple with first all the row indices, then all the column indices.

For example, if an array is two dimensions and it contained your item at two locations then

array[itemindex[0][0]][itemindex[1][0]]

would be equal to your item and so would be:

array[itemindex[0][1]][itemindex[1][1]]

Change header text of columns in a GridView

You can do it with gridview's datarow bound event. try the following sample of code:

protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}

For more details about the row databound event study Thsi....

Resizing image in Java

Simple way in Java

public void resize(String inputImagePath,
            String outputImagePath, int scaledWidth, int scaledHeight)
            throws IOException {
        // reads input image
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);
 
        // creates output image
        BufferedImage outputImage = new BufferedImage(scaledWidth,
                scaledHeight, inputImage.getType());
 
        // scales the input image to the output image
        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();
 
        // extracts extension of output file
        String formatName = outputImagePath.substring(outputImagePath
                .lastIndexOf(".") + 1);
 
        // writes to output file
        ImageIO.write(outputImage, formatName, new File(outputImagePath));
    }

What is REST? Slightly confused

REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).

First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).

EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.

Filter LogCat to get only the messages from My Application in Android?

You can use below command to fetch verbose logs for your application package

adb logcat com.example.myapp:V *:S

Also if you have rolled out your app and you want to fetch error logs from released app, you can use below command.

adb logcat AndroidRuntime:E *:S

Sequence contains no elements?

This will solve the problem,

var blogPosts = (from p in dc.BlogPosts
             where p.BlogPostID == ID
             select p);
if(blogPosts.Any())
{
  var post = post.Single();
}

How to replace multiple patterns at once with sed?

I believe this should solve your problem. I may be missing a few edge cases, please comment if you notice one.

You need a way to exclude previous substitutions from future patterns, which really means making outputs distinguishable, as well as excluding these outputs from your searches, and finally making outputs indistinguishable again. This is very similar to the quoting/escaping process, so I'll draw from it.

  • s/\\/\\\\/g escapes all existing backslashes
  • s/ab/\\b\\c/g substitutes raw ab for escaped bc
  • s/bc/\\a\\b/g substitutes raw bc for escaped ab
  • s/\\\(.\)/\1/g substitutes all escaped X for raw X

I have not accounted for backslashes in ab or bc, but intuitively, I would escape the search and replace terms the same way - \ now matches \\, and substituted \\ will appear as \.

Until now I have been using backslashes as the escape character, but it's not necessarily the best choice. Almost any character should work, but be careful with the characters that need escaping in your environment, sed, etc. depending on how you intend to use the results.

Deleting an element from an array in PHP

Use the following code:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);

Remove specific characters from a string in Javascript

Simply replace it with nothing:

var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

public String getDaySuffix(int inDay)
{
  String s = String.valueOf(inDay);

  if (s.endsWith("1"))
  {
    return "st";
  }
  else if (s.endsWith("2"))
  {
    return "nd";
  }
  else if (s.endsWith("3"))
  {
    return "rd";
  }
  else
  {
    return "th";
  }
}

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar problem but with a different cause:

In my case the problem was that in the interface defining the repository

public interface ItemRepository extends Repository {..}

I was omitting the types of the template. Setting them right:

public interface ItemRepository extends Repository<Item,Long> {..}

did the trick.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

If you're on a Mac, here's how to fix it. This is after tons of trial and error. Hope this helps others..

Debugging:

$mysql --verbose --help | grep my.cnf

$ which mysql
/usr/local/bin/mysql

Resolution: nano /usr/local/etc/my.cnf

Add: default-authentication-plugin=mysql_native_password

-------
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
default-authentication-plugin=mysql_native_password
------

Finally Run: brew services restart mysql

JavaScript OR (||) variable assignment explanation

Return output first true value.

If all are false return last false value.

Example:-

  null || undefined || false || 0 || 'apple'  // Return apple

How to sort List<Integer>?

Ascending order:

 Collections.sort(lList); 

Descending order:

Collections.sort(lList, Collections.reverseOrder()); 

ESLint - "window" is not defined. How to allow global variables in package.json

Add .eslintrc in the project root.

{
  "globals": {
    "document": true,
    "foo": true,
    "window": true
  }
}

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

how to parse JSON file with GSON

You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values

What is SaaS, PaaS and IaaS? With examples

Difference between IaaS PaaS & SaaS

In the following tabular format we will be explaining the difference in context of

  pizza as a service 

How to export a MySQL database to JSON?

If you have Ruby, you can install the mysql2xxxx gem (not the mysql2json gem, which is a different gem):

$ gem install mysql2xxxx

and then run the command

$ mysql2json --user=root --password=password --database=database_name --execute "select * from mytable" >mytable.json

The gem also provides mysql2csv and mysql2xml. It's not as fast as mysqldump, but also doesn't suffer from some of mysqldump's weirdnesses (like only being able to dump CSV from the same computer as the MySQL server itself)

Short rot13 function - Python

As of Python 3.1, string.translate and string.maketrans no longer exist. However, these methods can be used with bytes instead.

Thus, an up-to-date solution directly inspired from Paul Rubel's one, is:

rot13 = bytes.maketrans(
    b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM")
b'Hello world!'.translate(rot13)

Conversion from string to bytes and vice-versa can be done with the encode and decode built-in functions.

How can a LEFT OUTER JOIN return more records than exist in the left table?

It seems as though there are multiple rows in the DATA.Dim_Member table per SUSP.Susp_Visits row.

Detect if PHP session exists

If you are on php 5.4+, it is cleaner to use session_status():

if (session_status() == PHP_SESSION_ACTIVE) {
  echo 'Session is active';
}
  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

How to remove space from string?

Try doing this in a shell:

var="  3918912k"
echo ${var//[[:blank:]]/}

That uses parameter expansion (it's a non feature)

[[:blank:]] is a POSIX regex class (remove spaces, tabs...), see http://www.regular-expressions.info/posixbrackets.html

np.mean() vs np.average() in Python NumPy?

np.mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).

np.average can compute a weighted average if the weights parameter is supplied.

How to disable textbox from editing?

You can set the ReadOnly property to true.

Quoth the link:

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

Media Queries: How to target desktop, tablet, and mobile?

Media queries for common device breakpoints

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Try with

c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -iru

When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime (CLR) is used for the application.

Above command will Installs the version of ASP.NET that is associated with Aspnet_regiis.exe and only registers ASP.NET in IIS.

https://support.microsoft.com/en-us/help/2015129/error-message-after-you-install-the--net-framework-4-0-could-not-load

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

What to do with commit made in a detached head

Maybe not the best solution, (will rewrite history) but you could also do git reset --hard <hash of detached head commit>.

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.

How do I use Ruby for shell scripting?

Go get yourself a copy of Everyday Scripting with Ruby. It has plenty of useful tips on how to do the types of things your are wanting to do.

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

How to get scrollbar position with Javascript?

Here is the other way to get scroll position

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

how do I make a single legend for many subplots with matplotlib?

I have noticed that no answer display an image with a single legend referencing many curves in different subplots, so I have to show you one... to make you curious...

enter image description here

Now, you want to look at the code, don't you?

from numpy import linspace
import matplotlib.pyplot as plt

# Calling the axes.prop_cycle returns an itertoools.cycle

color_cycle = plt.rcParams['axes.prop_cycle']()

# I need some curves to plot

x = linspace(0, 1, 51)
f1 = x*(1-x)   ; lab1 = 'x - x x'
f2 = 0.25-f1   ; lab2 = '1/4 - x + x x' 
f3 = x*x*(1-x) ; lab3 = 'x x - x x x'
f4 = 0.25-f3   ; lab4 = '1/4 - x x + x x x'

# let's plot our curves (note the use of color cycle, otherwise the curves colors in
# the two subplots will be repeated and a single legend becomes difficult to read)
fig, (a13, a24) = plt.subplots(2)

a13.plot(x, f1, label=lab1, **next(color_cycle))
a13.plot(x, f3, label=lab3, **next(color_cycle))
a24.plot(x, f2, label=lab2, **next(color_cycle))
a24.plot(x, f4, label=lab4, **next(color_cycle))

# so far so good, now the trick

lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]

# finally we invoke the legend (that you probably would like to customize...)

fig.legend(lines, labels)
plt.show()

The two lines

lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]

deserve an explanation — to this aim I have encapsulated the tricky part in a function, just 4 lines of code but heavily commented

def fig_legend(fig, **kwdargs):

    # generate a sequence of tuples, each contains
    #  - a list of handles (lohand) and
    #  - a list of labels (lolbl)
    tuples_lohand_lolbl = (ax.get_legend_handles_labels() for ax in fig.axes)
    # e.g. a figure with two axes, ax0 with two curves, ax1 with one curve
    # yields:   ([ax0h0, ax0h1], [ax0l0, ax0l1]) and ([ax1h0], [ax1l0])
    
    # legend needs a list of handles and a list of labels, 
    # so our first step is to transpose our data,
    # generating two tuples of lists of homogeneous stuff(tolohs), i.e
    # we yield ([ax0h0, ax0h1], [ax1h0]) and ([ax0l0, ax0l1], [ax1l0])
    tolohs = zip(*tuples_lohand_lolbl)

    # finally we need to concatenate the individual lists in the two
    # lists of lists: [ax0h0, ax0h1, ax1h0] and [ax0l0, ax0l1, ax1l0]
    # a possible solution is to sum the sublists - we use unpacking
    handles, labels = (sum(list_of_lists, []) for list_of_lists in tolohs)

    # call fig.legend with the keyword arguments, return the legend object

    return fig.legend(handles, labels, **kwdargs)

PS I recognize that sum(list_of_lists, []) is a really inefficient method to flatten a list of lists but ? I love its compactness, ? usually is a few curves in a few subplots and ? Matplotlib and efficiency? ;-)


Important Update

If you want to stick with the official Matplotlib API my answer above is perfect, really.

On the other hand, if you don't mind using a private method of the matplotlib.legend module ... it's really much much much easier

from matplotlib.legend import _get_legend_handles_labels
...

fig.legend(*_get_legend_handles_and_labels(fig.axes), ...)

A complete explanation can be found in the source code of Axes.get_legend_handles_labels in .../matplotlib/axes/_axes.py

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I am using Visual Studio 2013 and I have the same issue but it occurs when I try to open a solution that was made using Visual Studio 2010.

The solution for me is to open the solution file (.sln), using notepad and change this line:

[# Visual Studio 2010]

to this:

[# Visual Studio 2013]

Two Divs next to each other, that then stack with responsive change

Floating div's will help what your trying to achieve.

Example

HTML

<div class="container">
<div class="content1 content">
</div>
<div class="content2 content">
</div>
</div>

CSS

.container{
width:100%;
height:200px;
background-color:grey;
}
.content{
float:left;
height:30px;
}
.content1{
background-color:blue;
width:300px;
}
.content2{
width:200px;
background-color:green;
}

Zoom in the page to see the effects.

Hope it helps.

ORA-12154 could not resolve the connect identifier specified

I had the same issue. In my case I was using a web service which was build using AnyCPU settings. Since the WCF was using 32 bit Oracle data access components therefore it was raising the same error when I tried to call it from a console client. So when I compiled the WCF service using the x86 based setting the client was able to successfully get data from the web service.

If you compile as "Any CPU" and run on an x64 platform, then you won't be able to load 32-bit dlls (which in our case were the Oracle Data Access components), because our app wasn't started in WOW64 (Windows32 on Windows 64). So in order to allow the 32 bit dependency of Oracle Data Access components I compilee the web service with Platform target of x86 and that solved it for me

As an alternative if you have 64bit ODAC drivers installed on the machine that also caused the problem to go away.

How to switch to another domain and get-aduser

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

scp (secure copy) to ec2 instance without password

Just tested:

Run the following command:

sudo shred -u /etc/ssh/*_key /etc/ssh/*_key.pub

Then:

  1. create ami (image of the ec2).
  2. launch from new ami(image) from step no 2 chose new keys.

How to check if another instance of my shell script is running

Here's one trick you'll see in various places:

status=`ps -efww | grep -w "[a]bc.sh" | awk -vpid=$$ '$2 != pid { print $2 }'`
if [ ! -z "$status" ]; then
    echo "[`date`] : abc.sh : Process is already running"
    exit 1;
fi

The brackets around the [a] (or pick a different letter) prevent grep from finding itself. This makes the grep -v grep bit unnecessary. I also removed the grep -v $$ and fixed the awk part to accomplish the same thing.

HTML favicon won't show on google chrome

For me the problem was that there was a div above it (which of course shouldn't have been in the head, but it happens). Firefox didn't mind, but Chrome did.

Viewing unpushed Git commits

There is tool named unpushed that scans all Git, Mercurial and Subversion repos in specified working directory and shows list of ucommited files and unpushed commits. Installation is simple under Linux:

$ easy_install --user unpushed

or

$ sudo easy_install unpushed

to install system-wide.

Usage is simple too:

$ unpushed ~/workspace
* /home/nailgun/workspace/unpushed uncommitted (Git)
* /home/nailgun/workspace/unpushed:master unpushed (Git)
* /home/nailgun/workspace/python:new-syntax unpushed (Git)

See unpushed --help or official description for more information. It also has a cronjob script unpushed-notify for on-screen notification of uncommited and unpushed changes.

How to Get a Specific Column Value from a DataTable?

string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
              where (string)dr["CountryName"] == countryName
              select (int)dr["id"]).FirstOrDefault();

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

__init__() missing 1 required positional argument

If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'

Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)

How to send a header using a HTTP request through a curl call?

man curl:

   -H/--header <header>
          (HTTP)  Extra header to use when getting a web page. You may specify
          any number of extra headers. Note that if you should  add  a  custom
          header that has the same name as one of the internal ones curl would
          use, your externally set header will be used instead of the internal
          one.  This  allows  you  to make even trickier stuff than curl would
          normally do. You should not replace internally set  headers  without
          knowing  perfectly well what you're doing. Remove an internal header
          by giving a replacement without content on the  right  side  of  the
          colon, as in: -H "Host:".

          curl  will  make sure that each header you add/replace get sent with
          the proper end of line marker, you should thus not  add  that  as  a
          part  of the header content: do not add newlines or carriage returns
          they will only mess things up for you.

          See also the -A/--user-agent and -e/--referer options.

          This option can be used multiple times to add/replace/remove  multi-
          ple headers.

Example:

curl --header "X-MyHeader: 123" www.google.com

You can see the request that curl sent by adding the -v option.

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

How to convert string to long

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

How to Convert Boolean to String

$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';

Cannot install packages using node package manager in Ubuntu

Problem is not in installer
replace nodejs with node or change the path from /usr/bin/nodejs to /usr/bin/node

How do you stop MySQL on a Mac OS install?

Try

sudo <path to mysql>/support-files/mysql.server start
sudo <path to mysql>/support-files/mysql.server stop

Else try:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop<br>
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart

However, I found that the second option only worked (OS X 10.6, MySQL 5.1.50) if the .plist has been loaded with:

sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysqld.plist

PS: I also found that I needed to unload the .plist to get an unrelated install of MAMP-MySQL to start / stop correctly. After running running this, MAMP-MySQL starts just fine:

sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist

How to find the Target *.exe file of *.appref-ms

ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\.

From there, use the search function to find your application.

Is there an eval() function in Java?

There are very few real use cases in which being able to evaluate a String as a fragment of Java code is necessary or desirable. That is, asking how to do this is really an XY problem: you actually have a different problem, which can be solved a different way.

First ask yourself, where did this String that you wish to evaluate come from? Did another part of your program generate it, or was it input provided by the user?

  • Another part of my program generated it: so, you want one part of your program to decide the kind of operation to perform, but not perform the operation, and a second part that performs the chosen operation. Instead of generating and then evaluating a String, use the Strategy, Command or Builder design pattern, as appropriate for your particular case.

  • It is user input: the user could input anything, including commands that, when executed, could cause your program to misbehave, crash, expose information that should be secret, damage persistent information (such as the content of a database), and other such nastiness. The only way to prevent that would be to parse the String yourself, check it was not malicious, and then evaluate it. But parsing it yourself is much of the work that the requested evalfunction would do, so you have saved yourself nothing. Worse still, checking that arbitrary Java was not malicious is impossible, because checking that is the halting problem.

  • It is user input, but the syntax and semantics of permitted text to evaluate is greatly restricted: No general purpose facility can easily implement a general purpose parser and evaluator for whatever restricted syntax and semantics you have chosen. What you need to do is implement a parser and evaluator for your chosen syntax and semantics. If the task is simple, you could write a simple recursive-descent or finite-state-machine parser by hand. If the task is difficult, you could use a compiler-compiler (such as ANTLR) to do some of the work for you.

  • I just want to implement a desktop calculator!: A homework assignment, eh? If you could implement the evaluation of the input expression using a provided eval function, it would not be much of a homework assignment, would it? Your program would be three lines long. Your instructor probably expects you to write the code for a simple arithmetic parser/evaluator. There is well known algorithm, shunting-yard, which you might find useful.

How to sort a list of strings?

Or maybe:

names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))

How to change the type of a field?

To convert int32 to string in mongo without creating an array just add "" to your number :-)

db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {   
  x.mynum = x.mynum + ""; // convert int32 to string
  db.foo.save(x);
});

How can I convert a std::string to int?

atoi is a built-in function that converts a string to an integer, assuming that the string begins with an integer representation.

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

jQuery Cross Domain Ajax

Here is the snippets from my code.. If it solves your problems..

Client Code :

Set jsonpCallBack : 'photos' and dataType:'jsonp'

 $('document').ready(function() {
            var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
            $.ajax({
                crossDomain: true,
                url: pm_url,
                type: 'GET',
                dataType: 'jsonp',
                jsonpCallback: 'photos'
            });
        });
        function photos (data) {
            alert(data);
            $("#twitter_followers").html(data.responseCode);
        };

Server Side Code (Using Rest Easy)

@Path("/test_cor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
    ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
    resp.setResponseCode(sessionKey);
    resp.setResponseText("Wrong Passcode");
    resp.setResponseTypeClass("Login");
    Gson gson = new Gson();
    return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
}

Yes/No message box using QMessageBox

Python equivalent code for a QMessageBox which consist of a question in it and Yes and No button. When Yes Button is clicked it will pop up another message box saying yes is clicked and same for No button also. You can push your own code after if block.

button_reply = QMessageBox.question(self,"Test", "Are you sure want to quit??", QMessageBox.Yes,QMessageBox.No,)

if button_reply == QMessageBox.Yes:
    QMessageBox.information(self, "Test", "Yes Button Was Clicked")
else :
    QMessageBox.information(self, "Test", "No Button Was Clicked")

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
    v.addEventListener(
       'play', 
          function() { 
             v.play();
          }, 
        false);

    v.onclick = function() {
      if (v.paused) {
        v.play();
        v.controls=null;
      } else {
        v.pause();
        v.controls="controls";
      }
    };

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

.htaccess redirect http to https

This is the best for www and for HTTPS, for proxy and no proxy users.

RewriteEngine On

### WWW & HTTPS

# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### WWW & HTTPS

When is del useful in Python?

Force closing a file after using numpy.load:

A niche usage perhaps but I found it useful when using numpy.load to read a file. Every once in a while I would update the file and need to copy a file with the same name to the directory.

I used del to release the file and allow me to copy in the new file.

Note I want to avoid the with context manager as I was playing around with plots on the command line and didn't want to be pressing tab a lot!

See this question.

Linux delete file with size 0

This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd ( . )

find . -size 0 |  xargs rm

Javascript Cookie with no expiration date

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

Pip install - Python 2.7 - Windows 7

pip is installed by default when we install Python in windows. After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD After that, we can directly use the python command with pip option to install further packages as following:-

C:\ python -m pip install python_module_name

This will install the module using pip.

Get an array of list element contents in jQuery

You may do as follows. one line of code will be enough

  • let array = $('ul>li').toArray().map(item => $(item).html());
  • Get the interested element

    1. get children

    2. get the array from toArray() method

    3. filter out the results you want

_x000D_
_x000D_
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
  <li>text1</li>_x000D_
  <li>text2</li>_x000D_
  <li>text3</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Excel - extracting data based on another list

New Excel versions

=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)

Older Excel versions

=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)

That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."

JAX-WS client : what's the correct path to access the local WSDL?

One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.

<wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
</wsimport>

Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)

MyApp.jar
|__META-INF
   |__wsdl
      |__YourWebServiceName.wsdl
      |__YourWebServiceName_schema1.xsd
      |__YourWebServiceName_schmea2.xsd

Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:

  <types>
    <xsd:schema>
      <xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
    </xsd:schema>
    <xsd:schema>
      <xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
    </xsd:schema>
  </types>

In the generated code, we find this:

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2-b05-
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
public class YourService_Service
    extends Service
{

    private final static URL YOURWEBSERVICE_WSDL_LOCATION;
    private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
    private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");

    static {
        YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
        WebServiceException e = null;
        if (YOURWEBSERVICE_WSDL_LOCATION == null) {
            e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
        }
        YOURWEBSERVICE_EXCEPTION = e;
    }

    public YourService_Service() {
        super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
    }

    public YourService_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    /**
     * 
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort() {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns YourService
     */
    @WebEndpoint(name = "YourServicePort")
    public YourService getYourServicePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
    }

    private static URL __getWsdlLocation() {
        if (YOURWEBSERVICE_EXCEPTION!= null) {
            throw YOURWEBSERVICE_EXCEPTION;
        }
        return YOURWEBSERVICE_WSDL_LOCATION;
    }

}

Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.

How do I schedule jobs in Jenkins?

Try using 0 8 * * *. It should work

403 Access Denied on Tomcat 8 Manager App without prompting for user/password


Correct answer can be found here


Looks like this issue can be reproduced while folowing mentioned tutorial on unix machines. Also noticed that author uses TC 8.0.33
Win (and OSX) do not have such issue, at least on my env:

Server version:        Apache Tomcat/8.5.4
Server built:          Jul 6 2016 08:43:30 UTC
Server number:         8.5.4.0
OS Name:               Windows 8.1
OS Version:            6.3
Architecture:          amd64
Java Home:             C:\TOOLS\jdk1.8.0_101\jre
JVM Version:           1.8.0_101-b13
JVM Vendor:            Oracle Corporation
CATALINA_BASE:         C:\TOOLS\tomcat\apache-tomcat-8.5.4
CATALINA_HOME:         C:\TOOLS\tomcat\apache-tomcat-8.5.4

After tomcat-users.xml is modified by adding role and user Tomcat Web Application Manager can be accessed on Tomcat/8.5.4.

How to get the filename without the extension from a path in Python?

https://docs.python.org/3/library/os.path.html

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c

OSError: [WinError 193] %1 is not a valid Win32 application

The error is pretty clear. The file hello.py is not an executable file. You need to specify the executable:

subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])

You'll need python.exe to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.

Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).

If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial").

If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.

ORA-30926: unable to get a stable set of rows in the source tables

A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

How to use OKHTTP to make a post request?

You need to encode it yourself by escaping strings with URLEncoder and joining them with "=" and "&". Or you can use FormEncoder from Mimecraft which gives you a handy builder.

FormEncoding fe = new FormEncoding.Builder()
    .add("name", "Lorem Ipsum")
    .add("occupation", "Filler Text")
    .build();

How to activate "Share" button in android app?

in kotlin :

val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))

Div height 100% and expands to fit content

Here is what you should do in the CSS style, on the main div

display: block;
overflow: auto;

And do not touch height

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

Call parent method from child class c#

To access properties and methods of a parent class use the base keyword. So in your child class LoadData() method you would do this:

public class Child : Parent 
{
    public void LoadData() 
    {
        base.MyMethod(); // call method of parent class
        base.CurrentRow = 1; // set property of parent class
        // other stuff...
    }
}

Note that you would also have to change the access modifier of your parent MyMethod() to at least protected for the child class to access it.

ERROR 2006 (HY000): MySQL server has gone away

The solution is increasing the values given the wait_timeout and the connect_timeout parameters in your options file, under the [mysqld] tag.

I had to recover a 400MB mysql backup and this worked for me (the values I've used below are a bit exaggerated, but you get the point):

[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE
connect_timeout = 1000000
net_write_timeout = 1000000
wait_timeout = 1000000
max_allowed_packet = 1024M
interactive_timeout = 1000000
net_buffer_length = 200M
net_read_timeout = 1000000
set GLOBAL delayed_insert_timeout=100000

Blockquote

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

MySql server startup error 'The server quit without updating PID file '

I encountered this issue after swapping server IPs. Database was working fine before that. There was an entry in /etc/my.cnf that I needed to update:

bind-address = xxx.xxx.xxx.xx

It had the old IP address in there.

Indexes of all occurrences of character in a string

int index = -1;
while((index = text.indexOf("on", index + 1)) >= 0) {
   LOG.d("index=" + index);
}

Navigation bar show/hide

In Swift 4.2 and Xcode 10

self.navigationController?.isNavigationBarHidden = true  //Hide
self.navigationController?.isNavigationBarHidden = false  //Show

If you don't want to display Navigation bar only in 1st VC, but you want display in 2nd VC onword's

In your 1st VC write this code.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true  //Hide
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = false  //Show
}

How to divide flask app into multiple py files?

I would like to recommend flask-empty at GitHub.

It provides an easy way to understand Blueprints, multiple views and extensions.

Calling a class method raises a TypeError in Python

Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

How to get all elements which name starts with some string?

You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>

</head>
<body>

  <input name="q1_a" type="text" value="1A"/>
  <input name="q1_b" type="text" value="1B"/>
  <input name="q1_c" type="text" value="1C"/>
  <input name="q2_d" type="text" value="2D"/>

  <script type="text/javascript">
  var inputs = document.getElementsByTagName("input");
  for (x = 0 ; x < inputs.length ; x++){
    myname = inputs[x].getAttribute("name");
    if(myname.indexOf("q1_")==0){
      alert(myname);
      // do more stuff here
       }
    }
    </script>
</body>
</html>

Demo

Is it possible to Turn page programmatically in UIPageViewController?

I could totally be missing something here, but this solution seems a lot simpler than many others proposed.

extension UIPageViewController {
    func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
        if let currentViewController = viewControllers?[0] {
            if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
                setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
            }
        }
    }
}

"Please provide a valid cache path" error in laravel

You need to create folders inside "framework". Please Follow these steps:

cd storage/
mkdir -p framework/{sessions,views,cache}

You also need to set permissions to allow Laravel to write data in this directory.

chmod -R 775 framework
chown -R www-data:www-data framework

Portable way to check if directory exists [Windows/Linux, C]

You can use the GTK glib to abstract from OS stuff.

glib provides a g_dir_open() function which should do the trick.

What's the best way to detect a 'touch screen' device using JavaScript?

I used pieces of the code above to detect whether touch, so my fancybox iframes would show up on desktop computers and not on touch. I noticed that Opera Mini for Android 4.0 was still registering as a non-touch device when using blmstr's code alone. (Does anyone know why?)

I ended up using:

<script>
$(document).ready(function() {
    var ua = navigator.userAgent;
    function is_touch_device() { 
        try {  
            document.createEvent("TouchEvent");  
            return true;  
        } catch (e) {  
            return false;  
        }  
    }

    if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/) 
    || ua.match(/BlackBerry/) || ua.match(/Android/)) {
        // Touch browser
    } else {
        // Lightbox code
    }
});
</script>

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

How to access session variables from any class in ASP.NET?

In asp.net core this works differerently:

public class SomeOtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void TestSet()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public void TestGet()
    {
        var message = _session.GetString("Test");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

Change onClick attribute with javascript

Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.

document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};

This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Ignoring new fields on JSON objects using Jackson

Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.

How to SFTP with PHP?

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already:

How do you set EditText to only accept numeric values in Android?

You can use it in XML

<EditText
 android:id="@+id/myNumber"
 android:digits="123"
 android:inputType="number"
/>

or,

android:inputType="numberPassword" along with editText.setTransformationMethod(null); to remove auto-hiding of the number.

or,

android:inputType="phone"

Programmatically you can use
editText.setInputType(InputType.TYPE_CLASS_NUMBER);

"Could not find Developer Disk Image"

Xcode 7.0.1 and iOS 9.1 are incompatible. You will need to update your version of Xcode via the Mac app store.

If your iOS version is lower then the Xcode version on the other hand, you can change the deployment target for a lower version of iOS by going to the General Settings and under Deployment set your Deployment Target:

enter image description here

Note:

Xcode 7.1 does not include iOS 9.2 beta SDK. Upgraded to Xcode to 7.2 beta by downloading it from the Xcode website.

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

Drag and drop elements from list into separate blocks

_x000D_
_x000D_
 function dragStart(event) {_x000D_
            event.dataTransfer.setData("Text", event.target.id);_x000D_
        }_x000D_
_x000D_
        function allowDrop(event) {_x000D_
            event.preventDefault();_x000D_
        }_x000D_
_x000D_
        function drop(event) {_x000D_
            $("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td>  Bhanu Pratap   </td><td> India </td><td>  3 years   </td><td>  Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
        }
_x000D_
 .droptarget {_x000D_
            float: left;_x000D_
            min-height: 100px;_x000D_
            min-width: 200px;_x000D_
            border: 1px solid black;_x000D_
            margin: 15px;_x000D_
            padding: 10px;_x000D_
            border: 1px solid #aaaaaa;_x000D_
        }_x000D_
_x000D_
        [contentEditable=true]:empty:not(:focus):before {_x000D_
            content: attr(data-text);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
        <p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
    </div>_x000D_
_x000D_
    <div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
_x000D_
_x000D_

  1. this is just simple here i'm appending html table into a div at the end
  2. we can achieve this or any thing with a simple concept of calling a JavaScript function when we want (here on drop.)
  3. In this example you can drag & drop any number of tables, new table will be added below the last table exists in the div other wise it will be the first table in the div.
  4. here we can add text between tables or we can say the section where we drop tables is editable we can type text between tables. enter image description here

Thanks... :)

Simple way to count character occurrences in a string

Not optimal, but simple way to count occurrences:

String s = "...";
int counter = s.split("\\$", -1).length - 1;

Note:

  • Dollar sign is a special Regular Expression symbol, so it must be escaped with a backslash.
  • A backslash is a special symbol for escape characters such as newlines, so it must be escaped with a backslash.
  • The second argument of split prevents empty trailing strings from being removed.

Performing a Stress Test on Web Application?

I vote for jMeter too and I want add some quotes to @PeterBernier answer.

The main question that load testing answers is how many concurrent users can my web application support? In order to get a proper answer, load testing should represent real application usage, as close as possible.

Keep above in mind, jMeter has many building blocks Logical Controllers, Config Elements, Pre Processors, Listeners ,... which can help you in this.

You can mimic real world situation with jMeter, for example you can:

  1. Configure jMeter to act as real Browser by configuring (concurrent resource download, browser cache, http headers, setting request time out, cookie management, https support, encoding , ajax support ,... )
  2. Configure jMeter to generate user requests (by defining number of users per second, ramp-up time, scheduling ,...)
  3. Configure lots of client with jMeter on them, to do a distributed load test.
  4. Process response to find if the server is responding correctly during test. ( For example assert response to find a text in it)

Please consider:

The https://www.blazemeter.com/jmeter has very good and practical information to help you configure your test environment.

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

display:
    echo ${TMP}

Running the code produces the expected result:

$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

How to add RSA key to authorized_keys file?

mkdir -p ~/.ssh/

To overwrite authorized_keys

cat your_key > ~/.ssh/authorized_keys

To append to the end of authorized_keys

cat your_key >> ~/.ssh/authorized_keys

How can I add a volume to an existing Docker container?

A note for using Docker Windows containers after I had to look for this problem for a long time!

Condiditions:

  • Windows 10
  • Docker Desktop (latest version)
  • using Docker Windows Container for image microsoft/mssql-server-windows-developer

Problem:

  • I wanted to mount a host dictionary into my windows container.

Solution as partially discripted here:

  • create docker container

docker run -d -p 1433:1433 -e sa_password=<STRONG_PASSWORD> -e ACCEPT_EULA=Y microsoft/mssql-server-windows-developer

  • go to command shell in container

docker exec -it <CONTAINERID> cmd.exe

  • create DIR

mkdir DirForMount

  • stop container

docker container stop <CONTAINERID>

  • commit container

docker commit <CONTAINERID> <NEWIMAGENAME>

  • delete old container

docker container rm <CONTAINERID>

  • create new container with new image and volume mounting

docker run -d -p 1433:1433 -e sa_password=<STRONG_PASSWORD> -e ACCEPT_EULA=Y -v C:\DirToMount:C:\DirForMount <NEWIMAGENAME>

After this i solved this problem on docker windows containers.

C# DataRow Empty-check

DataTable.NewRow will initialize each field to:

  • the default value for each DataColumn (DataColumn.DefaultValue)

  • except for auto-increment columns (DataColumn.AutoIncrement == true), which will be initialized to the next auto-increment value.

  • and expression columns (DataColumn.Expression.Length > 0) are also a special case; the default value will depend on the default values of columns on which the expression is calculated.

So you should probably be checking something like:

bool isDirty = false;
for (int i=0; i<table.Columns.Count; i++)
{
    if (table.Columns[i].Expression.Length > 0) continue;
    if (table.Columns[i].AutoIncrement) continue;
    if (row[i] != table.Columns[i].DefaultValue) isDirty = true;
}

I'll leave the LINQ version as an exercise :)

How to set DialogFragment's width and height?

Here's a way to set DialogFragment width/height in xml. Just wrap your viewHierarchy in a Framelayout (any layout will work) with a transparent background.

A transparent background seems to be a special flag, because it automatically centers the frameLayout's child in the window when you do that. You will still get the full screen darkening behind your fragment, indicating your fragment is the active element.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="@color/background_material_light">

      .....

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

Git Server Like GitHub?

http://repo.or.cz, while fairly good tends to have some issues with some users.

If you are one of them I recommend that you try out http://unfuddle.com since you come from a subversion background.

Check out "The 30 Second Tour": http://unfuddle.com/about/tour/plans

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option.

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

Read a text file using Node.js?

You'll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME');
  process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
  , filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  console.log('OK: ' + filename);
  console.log(data)
});

To break that down a little for you process.argv will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:

$ node ./cat.js file.txt
OK: file.txt
This is file.txt!

[Edit] As @wtfcoder mentions, using the "fs.readFile()" method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.

The "node" way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.

Angular : Manual redirect to route

Angular Redirection manually: Import @angular/router, Inject in constructor() then call this.router.navigate().

import {Router} from '@angular/router';
... 
...

constructor(private router: Router) {
  ...
}

onSubmit() {
  ...
  this.router.navigate(['/profile']); 
}

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

Use MM for months. mm is for minutes.

DateTime.Now.ToString("dd/MM/yyyy");

You probably run this code at the begining an hour like (00:00, 05.00, 18.00) and mm gives minutes (00) to your datetime.

From Custom Date and Time Format Strings

"mm" --> The minute, from 00 through 59.

"MM" --> The month, from 01 through 12.

Here is a DEMO. (Which the month part of first line depends on which time do you run this code ;) )

Download multiple files with a single action

A jQuery version of the iframe answers:

function download(files) {
    $.each(files, function(key, value) {
        $('<iframe></iframe>')
            .hide()
            .attr('src', value)
            .appendTo($('body'))
            .load(function() {
                var that = this;
                setTimeout(function() {
                    $(that).remove();
                }, 100);
            });
    });
}

How can I change a file's encoding with vim?

Notice that there is a difference between

set encoding

and

set fileencoding

In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.

Watermark / hint text / placeholder TextBox

Look at another simple solotion:

I'm focused GotFocus and LostFocus events.

XAML:

<Grid>
<TextBlock x:Name="DosyaIhtivaEdenDizinYansimasi" Text="Hedef Dizin Belirtin" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Center" Foreground="White" Background="Transparent" Width="500" MinWidth="300" Margin="10,0,0,0" Opacity="0.7"/>
<TextBox x:Name="DosyaIhtivaEdenDizin" CaretBrush="White" Foreground="White" Background="Transparent" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" MinHeight="40" BorderThickness="1" BorderBrush="White" Width="500" MinWidth="300" Margin="10,0,0,0" GotFocus="DosyaIhtivaEdenDizin_GotFocus" LostFocus="DosyaIhtivaEdenDizin_LostFocus"/>
</Grid>

C#:

    #region DosyaIhtivaEdenDizin
    private void DosyaIhtivaEdenDizin_GotFocus(object sender, RoutedEventArgs e)
    {
        if (DosyaIhtivaEdenDizin.Text.Length == 0)
        {
            DosyaIhtivaEdenDizinYansimasi.Text = "";
        }
    }

    private void DosyaIhtivaEdenDizin_LostFocus(object sender, RoutedEventArgs e)
    {
        if (DosyaIhtivaEdenDizin.Text.Length == 0)
        {
            DosyaIhtivaEdenDizinYansimasi.Text = "Hedef Dizin Belirtin";
        }
    }
    #endregion

Facebook Javascript SDK Problem: "FB is not defined"

I had the same problem. The solutions was to use core.js instead of debug.core.js

Reorder HTML table rows using drag-and-drop

I working well with it

<script>
    $(function () {

        $("#catalog tbody tr").draggable({
            appendTo:"body",
            helper:"clone"
        });
        $("#cart tbody").droppable({
            activeClass:"ui-state-default",
            hoverClass:"ui-state-hover",
            accept:":not(.ui-sortable-helper)",
            drop:function (event, ui) {
                $('.placeholder').remove();
                row = ui.draggable;
                $(this).append(row);
            }
        });
    });
</script>

HTML5 Email Validation

document.getElementById("email").validity.valid

seems to be true when field is either empty or valid. This also has some other interesting flags:

enter image description here

Tested in Chrome.

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Adding another point of view to above mentioned solutions.

Implicit Wait: When created, is alive until the WebDriver object dies. And is like common for all operations.

Whereas,
Explicit wait, can be declared for a particular operation depending upon the webElement behavior. It has the benefit of customizing the polling time and satisfaction of the condition.
For example, we declared implicit Wait of 10 secs but an element takes more than that, say 20 seconds and sometimes may appears on 5 secs, so in this scenario, Explicit wait is declared.

Batch File; List files in directory, only filenames?

dir /s/d/a:-d "folderpath*.*" > file.txt

And, lose the /s if you do not need files from subfolders

When do items in HTML5 local storage expire?

// Functions
function removeHtmlStorage(name) {
    localStorage.removeItem(name);
    localStorage.removeItem(name+'_time');
}

function setHtmlStorage(name, value, expires) {

    if (expires==undefined || expires=='null') { var expires = 3600; } // default: 1h

    var date = new Date();
    var schedule = Math.round((date.setSeconds(date.getSeconds()+expires))/1000);

    localStorage.setItem(name, value);
    localStorage.setItem(name+'_time', schedule);
}

function statusHtmlStorage(name) {

    var date = new Date();
    var current = Math.round(+date/1000);

    // Get Schedule
    var stored_time = localStorage.getItem(name+'_time');
    if (stored_time==undefined || stored_time=='null') { var stored_time = 0; }

    // Expired
    if (stored_time < current) {

        // Remove
        removeHtmlStorage(name);

        return 0;

    } else {

        return 1;
    }
}

// Status
var cache_status = statusHtmlStorage('cache_name');

// Has Data
if (cache_status == 1) {

    // Get Cache
    var data = localStorage.getItem('cache_name');
    alert(data);

// Expired or Empty Cache
} else {

    // Get Data
    var data = 'Pay in cash :)';
    alert(data);

    // Set Cache (30 seconds)
    if (cache) { setHtmlStorage('cache_name', data, 30); }

}

REST, HTTP DELETE and parameters

No, it is not RESTful. The only reason why you should be putting a verb (force_delete) into the URI is if you would need to overload GET/POST methods in an environment where PUT/DELETE methods are not available. Judging from your use of the DELETE method, this is not the case.

HTTP error code 409/Conflict should be used for situations where there is a conflict which prevents the RESTful service to perform the operation, but there is still a chance that the user might be able to resolve the conflict himself. A pre-deletion confirmation (where there are no real conflicts which would prevent deletion) is not a conflict per se, as nothing prevents the API from performing the requested operation.

As Alex said (I don't know who downvoted him, he is correct), this should be handled in the UI, because a RESTful service as such just processes requests and should be therefore stateless (i.e. it must not rely on confirmations by holding any server-side information about of a request).

Two examples how to do this in UI would be to:

  • pre-HTML5:* show a JS confirmation dialog to the user, and send the request only if the user confirms it
  • HTML5:* use a form with action DELETE where the form would contain only "Confirm" and "Cancel" buttons ("Confirm" would be the submit button)

(*) Please note that HTML versions prior to 5 do not support PUT and DELETE HTTP methods natively, however most modern browsers can do these two methods via AJAX calls. See this thread for details about cross-browser support.


Update (based on additional investigation and discussions):

The scenario where the service would require the force_delete=true flag to be present violates the uniform interface as defined in Roy Fielding's dissertation. Also, as per HTTP RFC, the DELETE method may be overridden on the origin server (client), implying that this is not done on the target server (service).

So once the service receives a DELETE request, it should process it without needing any additional confirmation (regardless if the service actually performs the operation).

How to catch integer(0)?

isEmpty() is included in the S4Vectors base package. No need to load any other packages.

a <- which(1:3 == 5)
isEmpty(a)
# [1] TRUE

How do you round to 1 decimal place in Javascript?

Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10

Thanks

Nullable property to entity field, Entity Framework through Code First

Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Go to the Users & Groups pane of the System Preferences -> Select the User -> Click the lock to make changes (bottom left corner) -> right click the current user select Advanced options... -> Select the Login Shell: /bin/zsh and OK

What is meant by Ems? (Android TextView)

android:ems or setEms(n) sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. See wikipedia Em unit

but only when the layout_width is set to "wrap_content". Other layout_width values override the ems width setting.

Adding an android:textSize attribute determines the physical width of the view to the textSize * length of a text of n 'M's set above.

How to use Comparator in Java to sort

There are a couple of awkward things with your example class:

  • it's called People while it has a price and info (more something for objects, not people);
  • when naming a class as a plural of something, it suggests it is an abstraction of more than one thing.

Anyway, here's a demo of how to use a Comparator<T>:

public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, new LexicographicComparator());
        System.out.println(people);
        Collections.sort(people, new AgeComparator());
        System.out.println(people);
    }
}

class LexicographicComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.name.compareToIgnoreCase(b.name);
    }
}

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
    }
}

class Person {

    String name;
    int age;

    Person(String n, int a) {
        name = n;
        age = a;
    }

    @Override
    public String toString() {
        return String.format("{name=%s, age=%d}", name, age);
    }
}

EDIT

And an equivalent Java 8 demo would look like this:

public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, (a, b) -> a.name.compareToIgnoreCase(b.name));
        System.out.println(people);
        Collections.sort(people, (a, b) -> a.age < b.age ? -1 : a.age == b.age ? 0 : 1);
        System.out.println(people);
    }
}

Tick symbol in HTML/XHTML

Coming very late to the party, I found that &check; (✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Android ImageView Animation

You can also simply use the Rotate animation feature. That runs a specific animation, for a pre-determined amount of time, on an ImageView.

Animation rotate = AnimationUtils.loadAnimation([context], R.anim.rotate_picture);
splash.startAnimation(rotate);

Then create an animation XML file in your res/anim called rotate_picture with the content:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shareInterpolator="false">

    <rotate 
    android:fromDegrees="0"
    android:toDegrees="360"
    android:duration="5000"
    android:pivotX="50%"
    android:pivotY="50%">
</rotate>
</set>

Now unfortunately, this will only run it once. You'll need a loop somewhere to make it repeat the animation while it's waiting. I experimented a little bit and got my program stuck in infinite loops, so I'm not sure of the best way to that. EDIT: Christopher's answer provides the info on how to make it loop properly, so removing my bad suggestion about separate threads!

"unrecognized import path" with go get

I had the same problem on MacOS 10.10. And I found that the problem caused by OhMyZsh shell. Then I switched back to bash everything went ok.

Here is my go env

bash-3.2$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/bis/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1

Binding a generic list to a repeater - ASP.NET

It is surprisingly simple...

Code behind:

// Here's your object that you'll create a list of
private class Products
{
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductPrice { get; set; }
}

// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{   
    // The the LIST as the DataSource
    this.rptItemsInCart.DataSource = ListOfSelectedProducts;

    // Then bind the repeater
    // The public properties become the columns of your repeater
    this.rptItemsInCart.DataBind();
}

ASPX code:

<asp:Repeater ID="rptItemsInCart" runat="server">
  <HeaderTemplate>
    <table>
      <thead>
        <tr>
            <th>Product Name</th>
            <th>Product Description</th>
            <th>Product Price</th>
        </tr>
      </thead>
      <tbody>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><%# Eval("ProductName") %></td>
      <td><%# Eval("ProductDescription")%></td>
      <td><%# Eval("ProductPrice")%></td>
    </tr>
  </ItemTemplate>
  <FooterTemplate>
    </tbody>
    </table>
  </FooterTemplate>
</asp:Repeater>

I hope this helps!

How to change the interval time on bootstrap carousel?

You can also use the data-interval attribute eg. <div class="carousel" data-interval="10000">

Laravel 5 not finding css files

In the root path create a .htaccess file with

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/ 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f



RewriteRule ^(.*)$ /public/$1 
#RewriteRule ^ index.php [L]
RewriteRule ^(/)?$ public/index.php [L] 
</IfModule>

In public directory create a .htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

if you have done any changes in public/index.php file correct them with the right path then your site will be live.

what will solve with this?

  • Hosting issue of laravel project.
  • Css not work on laravel.
  • Laravel site not work.
  • laravel site load with domain/public/index.php
  • laravel project does not redirect correctly