Programs & Examples On #Xuggle

A free open-source library for Java developers to uncompress, manipulate, and compress recorded or live video in real time. http://www.xuggle.com/

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

You asked if it is possible to change the circular dependency checking in those slf4j classes.

The simple answer is no.

  • It is unconditional ... as implemented.
  • It is implemented in a static initializer block ... so you can't override the implementation, and you can't stop it happening.

So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.

Reference:


The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

Android: how to handle button click

#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).

If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.

For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).


#2 Pros and cons for all methods are almost the same and the lesson should be:

Use what ever is most appropriate or feels most intuitive to you.

If you have to assign the same OnClickListener to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Take action.
    }
});

I tend to not implement the OnClickListener in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this is all doing).

How to ping a server only once from within a batch file?

From Batch file, ping a ip only once using the following command:
Ping 192.168.199.10 -n 1

enter image description here

ERROR 1067 (42000): Invalid default value for 'created_at'

As mentioned in @Bernd Buffen's answer. This is issue with MariaDB 5.5, I simple upgrade MariaDB 5.5 to MariaDB 10.1 and issue resolved.

Here Steps to upgrade MariaDB 5.5 into MariaDB 10.1 at CentOS 7 (64-Bit)

  1. Add following lines to MariaDB repo.

    nano /etc/yum.repos.d/mariadb.repo and paste the following lines.

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

  1. Stop MariaDB, if already running service mariadb stop
  2. Perform update

    yum update

  3. Starting MariaDB & Performing Upgrade

    service mariadb start

    mysql_upgrade

Everything Done.

Check MariaDB version: mysql -V


NOTE: Please always take backup of Database(s) before performing upgrades. Data can be lost if upgrade failed or something went wrong.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

You need the oracle client driver installed for those classes to work.

There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.

Retrieve the maximum length of a VARCHAR column in SQL Server

For sql server (SSMS)

select MAX(LEN(ColumnName)) from table_name

This will returns number of characters.

 select MAX(DATALENGTH(ColumnName)) from table_name

This will returns number of bytes used/required.

IF some one use varchar then use DATALENGTH.More details

How to find files modified in last x minutes (find -mmin does not work as expected)

Actually, there's more than one issue here. The main one is that xargs by default executes the command you specified, even when no arguments have been passed. To change that you might use a GNU extension to xargs:

--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.

Simple example:

find . -mmin -60 | xargs -r ls -l

But this might match to all subdirectories, including . (the current directory), and ls will list each of them individually. So the output will be a mess. Solution: pass -d to ls, which prohibits listing the directory contents:

find . -mmin -60 | xargs -r ls -ld

Now you don't like . (the current directory) in your list? Solution: exclude the first directory level (0) from find output:

find . -mindepth 1 -mmin -60 | xargs -r ls -ld

Now you'd need only the files in your list? Solution: exclude the directories:

find . -type f -mmin -60 | xargs -r ls -l

Now you have some files with names containing white space, quote marks, or backslashes? Solution: use null-terminated output (find) and input (xargs) (these are also GNU extensions, afaik):

find . -type f -mmin -60 -print0 | xargs -r0 ls -l

BarCode Image Generator in Java

There is also this free API that you can use to make free barcodes in java.

Barbecue

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Programmatically check Play Store for app updates

There is no official GooglePlay API to do it.

But you can use this unofficial library to get app version data.

And, if the above doesn't work for you, you can always http connect to your app's page (e.g. https://play.google.com/store/apps/details?id=com.shots.android&hl=en) and parse the "Current Version" field.

Setting the default page for ASP.NET (Visual Studio) server configuration

One way to achieve this is to add a DefaultDocument settings in the Web.config.

  <system.webServer>
   <defaultDocument>
    <files>
      <clear />
      <add value="DefaultPage.aspx" />
    </files>
   </defaultDocument>
  </system.webServer>

PHP header(Location: ...): Force URL change in address bar

I had the same problem with posting a form. What I did was that turning off the data-ajax.

How to repeat last command in python interpreter shell?

If using MacOSX, press control p to cycle up and control n to cycle down. I am using IDLE Python 3.4.1 Shell.

Comparing two java.util.Dates to see if they are in the same day

I use the "apache commons lang" package to do this (namely org.apache.commons.lang.time.DateUtils)

boolean samedate = DateUtils.isSameDay(date1, date2);  //Takes either Calendar or Date objects

Posting parameters to a url using the POST method without using a form

You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.

Pandas: change data type of Series to String

You can convert all elements of id to str using apply

df.id.apply(str)

0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610

Edit by OP:

I think the issue was related to the Python version (2.7.), this worked:

df['id'].astype(basestring)
0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610
Name: id, dtype: object

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

Invalid use side-effecting operator Insert within a function

Functions cannot be used to modify base table information, use a stored procedure.

setting an environment variable in virtualenv

Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.

The second way if you're looking for a lighter approach is to have a .env file locally then run:

export $(cat .env)

Move / Copy File Operations in Java

Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:

(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.

It's simple, easy and fast.

AppStore - App status is ready for sale, but not in app store

you must change Territory and click on save, after one minute your app will be available. No need to Remove from sale

RESTful Authentication via Spring

Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.

I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home

There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

How do you change the server header returned by nginx?

Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. http://wiki.codemongers.com/NginxHttpHeadersModule

PHP: How do you determine every Nth iteration of a loop?

every 3 posts?

if($counter % 3 == 0){
    echo IMAGE;
}

How to add anchor tags dynamically to a div in Javascript?

<script type="text/javascript" language="javascript">
function createDiv()
{
  var divTag = document.createElement("div");            
  divTag.innerHTML = "Div tag created using Javascript DOM dynamically";        
  document.body.appendChild(divTag);
}
</script>

Using generic std::function objects with member functions in one class

You can use functors if you want a less generic and more precise control under the hood. Example with my win32 api to forward api message from a class to another class.

IListener.h

#include <windows.h>
class IListener { 
    public:
    virtual ~IListener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};

Listener.h

#include "IListener.h"
template <typename D> class Listener : public IListener {
    public:
    typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); 

    private:
    D* _instance;
    WMFuncPtr _wmFuncPtr; 

    public:
    virtual ~Listener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override {
        return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam);
    }

    Listener(D* instance, WMFuncPtr wmFuncPtr) {
        _instance = instance;
        _wmFuncPtr = wmFuncPtr;
    }
};

Dispatcher.h

#include <map>
#include "Listener.h"

class Dispatcher {
    private:
        //Storage map for message/pointers
        std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners; 

    public:
        virtual ~Dispatcher() { //clear the map }

        //Return a previously registered callable funtion pointer for uMsg.
        IListener* get(UINT uMsg) {
            typename std::map<UINT, IListener*>::iterator itEvt;
            if((itEvt = _listeners.find(uMsg)) == _listeners.end()) {
                return NULL;
            }
            return itEvt->second;
        }

        //Set a member function to receive message. 
        //Example Button->add<MyClass>(WM_COMMAND, this, &MyClass::myfunc);
        template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) {
            _listeners[uMsg] = new Listener<D>(instance, wmFuncPtr);
        }

};

Usage principles

class Button {
    public:
    Dispatcher _dispatcher;
    //button window forward all received message to a listener
    LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        //to return a precise message like WM_CREATE, you have just
        //search it in the map.
        return _dispatcher[uMsg](hWnd, uMsg, w, l);
    }
};

class Myclass {
    Button _button;
    //the listener for Button messages
    LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        return 0;
    }

    //Register the listener for Button messages
    void initialize() {
        //now all message received from button are forwarded to button_listener function 
       _button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener);
    }
};

Good luck and thank to all for sharing knowledge.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use this to force IE to hide that annoying browser compatibility button in the address bar:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

TypeError: 'builtin_function_or_method' object is not subscriptable

You are trying to access pop as if was a list or a tupple, but pop is not. It's a method.

php $_GET and undefined index

I always use a utility function/class for reading from the $_GET and $_POST arrays to avoid having to always check the index exists... Something like this will do the trick.

class Input {
function get($name) {
    return isset($_GET[$name]) ? $_GET[$name] : null;
}

function post($name) {
    return isset($_POST[$name]) ? $_POST[$name] : null;
}

function get_post($name) {
    return $this->get($name) ? $this->get($name) : $this->post($name);
}
}
$input = new Input;
$page = $input->get_post('page');

How to change context root of a dynamic web project in Eclipse?

If using eclipse to deploy your application . We can use this maven plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-eclipse-plugin</artifactId>
    <version>2.10</version>
    <configuration>
        <wtpversion>2.0</wtpversion>
        <wtpContextName>newContextroot</wtpContextName>
    </configuration>
</plugin>

now go to your project root folder and open cmd prompt at that location type this command :

mvn eclipse:eclipse -Dwtpversion=2.0

You may need to restart eclipse , or in server view delete server and create agian to see affect. I wonder this exercise make sense in real life but works.

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

Center HTML Input Text Field Placeholder

you can use also this way to write css for placeholder

input::placeholder{
   text-align: center;
}

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

This worked for me:

Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;

Note: It must match with Owner of the schema.

Schema | Name | Type | Owner
--------+--------+-------+----------

If the owner is different, then give all the grants to the current user role from the admin role by :

GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';

Then try to execute the query, it will give the output as it has access to all the relations now.

How to change default text file encoding in Eclipse?

Window -> Preferences -> General -> Workspace : Text file encoding

Android 8: Cleartext HTTP traffic not permitted

For React Native projects

It was already fixed on RN 0.59. You can find on upgrade diff from 0.58.6 to 0.59 You can apply it without upgrading you RN versionust follow the below steps:

Create files:

android/app/src/debug/res/xml/react_native_config.xml -

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
  </domain-config>
</network-security-config>

android/app/src/debug/AndroidManifest.xml -

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

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

  <application tools:targetApi="28"
      tools:ignore="GoogleAppIndexingWarning" 
      android:networkSecurityConfig="@xml/react_native_config" />
</manifest>

Check the accepted answer to know the root cause.

Removing numbers from string

Just a few (others have suggested some of these)

Method 1:

''.join(i for i in myStr if not i.isdigit())

Method 2:

def removeDigits(s):
    answer = []
    for char in s:
        if not char.isdigit():
            answer.append(char)
    return ''.join(char)

Method 3:

''.join(filter(lambda x: not x.isdigit(), mystr))

Method 4:

nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)

Method 5:

''.join(i for i in mystr if ord(i) not in range(48, 58))

Removing rounded corners from a <select> element in Chrome/Webkit

well i got the solution. hope it may help you :)

_x000D_
_x000D_
select{_x000D_
      border-image: url(http://www.w3schools.com/cssref/border.png) 30 stretch;_x000D_
      width: 120px;_x000D_
      height: 36px;_x000D_
      color: #999;_x000D_
  }
_x000D_
<select>_x000D_
  <option value="1">Hi</option>_x000D_
  <option value="2">Bye</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Where is the .NET Framework 4.5 directory?

Whilst the above answers are correct its worth noting that MSBuild has changed and it no longer ships with the .net framework, it comes either stand alone or with visual studio. As a result it's binaries have moved... so the one you get under the 4.0.303619 directory is actually the old one!

I've just been caught out by this - I found automatic binding redirects were only working when running from VisualStudio but not when running msbuild from the command line... the clue was that binding redirects were added in VS 2013 (for that read .net framework 4.5). If you open up a vs command prompt you'll see it now gets it from program files as the other article mentions. Whereas I was using a batch file on my path which linked to the old version.

Version numbers

Under framework:

PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\msbuild.exe -version
Microsoft (R) Build Engine version 4.0.30319.33440
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

4.0.30319.33440PS C:\Windows\Microsoft.NET\Framework\v4.0.30319>

Under program files:

PS C:\Program Files (x86)\MSBuild\12.0\Bin> .\MSBuild.exe -version
Microsoft (R) Build Engine version 12.0.21005.1
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

12.0.21005.1PS C:\Program Files (x86)\MSBuild\12.0\Bin>

Escape text for HTML

Didn't see this here

System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")

it was the only thing that worked (asp 4.0+) when dealing with html like this. The&apos; gets rendered as ' (using htmldecode) in the html, causing it to fail:

<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It&apos;s Allstars'); return false;">It's Allstars</a>

Play audio file from the assets directory

Here my static version:

public static void playAssetSound(Context context, String soundFileName) {
    try {
        MediaPlayer mediaPlayer = new MediaPlayer();

        AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
        mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        mediaPlayer.prepare();
        mediaPlayer.setVolume(1f, 1f);
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

How to convert JSON to CSV format and store in a variable

An adaption from praneybehl answer to work with nested objects and tab separator

function ConvertToCSV(objArray) {
  let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  if(!Array.isArray(array))
      array = [array];

  let str = '';

  for (let i = 0; i < array.length; i++) {
    let line = '';
    for (let index in array[i]) {
      if (line != '') line += ','

      const item = array[i][index];
      line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item);
    }
    str += line + '\r\n';
  }

  do{
      str = str.replace(',','\t').replace('\t\t', '\t');
  }while(str.includes(',') || str.includes('\t\t'));

  return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://stackoverflow.com/a/10805198/4508758
}

BigDecimal to string

For better support different locales use this way:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);

df.format(bigDecimal);

also you can customize it:

DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);

How to perform a real time search and filter on a HTML table

I found dfsq's answer its comments extremely useful. I made some minor modifications applicable to me (and I'm posting it here, in case it is of some use to others).

  1. Using class as hooks, instead of table elements tr
  2. Searching/comparing text within a child class while showing/hiding parent
  3. Making it more efficient by storing the $rows text elements into an array only once (and avoiding $rows.length times computation)

_x000D_
_x000D_
var $rows = $('.wrapper');
var rowsTextArray = [];

var i = 0;
$.each($rows, function () {
    rowsTextArray[i] = ($(this).find('.number').text() + $(this).find('.fruit').text())
        .replace(/\s+/g, '')
        .toLowerCase();
    i++;
});

$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/\s+/g, '').toLowerCase();
  $rows.show().filter(function(index) {
    return (rowsTextArray[index].indexOf(val) === -1);
  }).hide();
});
_x000D_
span {
  margin-right: 0.2em;
}
_x000D_
<input type="text" id="search" placeholder="type to search" />

<div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
<div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
<div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
<div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Add column to SQL Server

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE

How can I trigger an onchange event manually?

For those using jQuery there's a convenient method: http://api.jquery.com/change/

Why are Python's 'private' methods not actually private?

The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.

For example:

>>> class Foo(object):
...     def __init__(self):
...         self.__baz = 42
...     def foo(self):
...         print self.__baz
...     
>>> class Bar(Foo):
...     def __init__(self):
...         super(Bar, self).__init__()
...         self.__baz = 21
...     def bar(self):
...         print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}

Of course, it breaks down if two different classes have the same name.

Printing the value of a variable in SQL Developer

You need to turn on dbms_output. In Oracle SQL Developer:

  1. Show the DBMS Output window (View->DBMS Output).
  2. Press the "+" button at the top of the Dbms Output window and then select an open database connection in the dialog that opens.

In SQL*Plus:

 SET SERVEROUTPUT ON

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

Two options

for(int i = 0, n = s.length() ; i < n ; i++) { 
    char c = s.charAt(i); 
}

or

for(char c : s.toCharArray()) {
    // process c
}

The first is probably faster, then 2nd is probably more readable.

Run jQuery function onclick

Why do you need to attach it to the HTML? Just bind the function with hover

$("div.system_box").hover(function(){ mousin }, 
                          function() { mouseout });

If you do insist to have JS references inside the html, which is usualy a bad idea you can use:

onmouseover="yourJavaScriptCode()"

after topic edit:

<div class="system_box" data-target="sms_box">

...

$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

What is a reasonable code coverage % for unit tests (and why)?

It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.

Google Maps API v2: How to make markers clickable?

I added a mMap.setOnMarkerClickListener(this); in the onMapReady(GoogleMap googleMap) method. So every time you click a marker it displays the text name in the toast method.

public class DemoMapActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    double lat=0.34924212701428;
    double lng=32.616554024713;
    String venue = "Capital Shoppers City";
    LatLng location = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(location).title(venue)).setTag(0);
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(location);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
    mMap.moveCamera(cameraUpdate);
    mMap.animateCamera(zoom);
    mMap.setOnMarkerClickListener(this);
}

@Override
public boolean onMarkerClick(final Marker marker) {
    // Retrieve the data from the marker.
    Integer clickCount = (Integer) marker.getTag();

    // Check if a click count was set, then display the click count.
    if (clickCount != null) {
        clickCount = clickCount + 1;
        marker.setTag(clickCount);
        Toast.makeText(this,
                       marker.getTitle() +
                       " has been clicked ",
                       Toast.LENGTH_SHORT).show();
    }
    // Return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

}

You can check this link for reference Markers

Android Studio don't generate R.java for my import project

I had a lot of problems exporting a project from Eclipse (assuming that is where you are exporting from). It was much easier for me to create a new project in Android Studio, then copy over the java files, xml files, layout directories, etc, and the AndroidManifest, into the appropriate location in the new project.

If you already have an R.java file for your project, you could try just copying it over to the new project. In Android Studio the R.java file seems to reside in build/source/r/debug/your-package-name/

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Another solution could be following:

This is how you use it:

    final Opt<String> opt = Opt.of("I'm a cool text");
    opt.ifPresent()
        .apply(s -> System.out.printf("Text is: %s\n", s))
        .elseApply(() -> System.out.println("no text available"));

Or in case you in case of the opposite use case is true:

    final Opt<String> opt = Opt.of("This is the text");
    opt.ifNotPresent()
        .apply(() -> System.out.println("Not present"))
        .elseApply(t -> /*do something here*/);

This are the ingredients:

  1. Little modified Function interface, just for the "elseApply" method
  2. Optional enhancement
  3. A little bit of curring :-)

The "cosmetically" enhanced Function interface.

@FunctionalInterface
public interface Fkt<T, R> extends Function<T, R> {

    default R elseApply(final T t) {
        return this.apply(t);
    }

}

And the Optional wrapper class for enhancement:

public class Opt<T> {

    private final Optional<T> optional;

    private Opt(final Optional<T> theOptional) {
        this.optional = theOptional;
    }

    public static <T> Opt<T> of(final T value) {
        return new Opt<>(Optional.of(value));
    }

    public static <T> Opt<T> of(final Optional<T> optional) {
        return new Opt<>(optional);
    }

    public static <T> Opt<T> ofNullable(final T value) {
        return new Opt<>(Optional.ofNullable(value));
    }

    public static <T> Opt<T> empty() {
        return new Opt<>(Optional.empty());
    }

    private final BiFunction<Consumer<T>, Runnable, Void> ifPresent = (present, notPresent) -> {
        if (this.optional.isPresent()) {
            present.accept(this.optional.get());
        } else {
            notPresent.run();
        }
        return null;
    };

   private final BiFunction<Runnable, Consumer<T>, Void> ifNotPresent = (notPresent, present) -> {
        if (!this.optional.isPresent()) {
            notPresent.run();
        } else {
            present.accept(this.optional.get());
        }
        return null;
    };

    public Fkt<Consumer<T>, Fkt<Runnable, Void>> ifPresent() {
        return Opt.curry(this.ifPresent);
    }

    public Fkt<Runnable, Fkt<Consumer<T>, Void>> ifNotPresent() {
        return Opt.curry(this.ifNotPresent);
    }

    private static <X, Y, Z> Fkt<X, Fkt<Y, Z>> curry(final BiFunction<X, Y, Z> function) {
        return (final X x) -> (final Y y) -> function.apply(x, y);
    }
}

This should do the trick and could serve as a basic template how to deal with such requirements.

The basic idea here is following. In a non functional style programming world you would probably implement a method taking two parameter where the first is a kind of runnable code which should be executed in case the value is available and the other parameter is the runnable code which should be run in case the value is not available. For the sake of better readability, you can use curring to split the function of two parameter in two functions of one parameter each. This is what I basically did here.

Hint: Opt also provides the other use case where you want to execute a piece of code just in case the value is not available. This could be done also via Optional.filter.stuff but I found this much more readable.

Hope that helps!

Good programming :-)

jQuery get input value after keypress

Use .keyup instead of keypress.

Also use $(this).val() or just this.value to access the current input value.

DEMO here

Info about .keypress from jQuery docs,

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

Moment.js with Vuejs

Here is an example using a 3rd party wrapper library for Vue called vue-moment.

In addition to binding Moment instance into Vue's root scope, this library includes moment and duration filters.

This example includes localization and is using ES6 module imports, an official standard, instead of NodeJS's CommonJS module system requires.

import Vue from 'vue';

import moment from 'moment';
import VueMoment from 'vue-moment';

// Load Locales ('en' comes loaded by default)
require('moment/locale/es');

// Choose Locale
moment.locale('es');

Vue.use(VueMoment, { moment });

Now you can use the Moment instance directly in your Vue templates without any additional markup:

<small>Copyright {{ $moment().year() }}</small>

Or the filters:

<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->

How to install Anaconda on RaspBerry Pi 3 Model B

I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3

Conda is now working. Hope this helps those of you interested in running conda on the pi zero!

Newline character in StringBuilder

Just create an extension for the StringBuilder class:

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

Google Play Services Library update and missing symbol @integer/google_play_services_version

Please note that this fix may only apply to IntelliJ users!! (More information at the bottom of this post that should apply to everyone.)

Fixed this problem! I use IntelliJ and it turns out I just had misconfigured the way I was including the google-play-services_lib module as a dependency.

As I fixed this entirely through GUI and not at all by editing any files, here's a couple of screenshots:

Step 1 - Initial Project Structure So my Project Structure started off looking like this...

Step 2 - Removed google-play-services library Then I removed the google-play-services library from my dependencies list by selecting it and then clicking the minus button at the bottom. Notice the error at the bottom of the dialog, as my project absolutely does require this library. But don't worry, we'll re-add it soon!

Step 3 - Added google-play-services as a module dependency Next I added google-play-services_lib as a module dependency instead of a library dependency. Then I hit the up arrow button at the bottom a couple times to move this dependency to the top of the list. But notice the error at the bottom (we're still not done yet!)

Step 4 - Click the lightbulb to add the google-play-services library as a dependency I then clicked the lightbulb at the bottom of the dialog in the error message area to bring up this little small popup that gives two choices (Add to dependencies... or Remove Library). Click the Add to dependencies... option!

Step 5 - Add the library to the google-play-services_lib module A new small dialog window should have popped up. It gave me two choices, one for my main project (it's name is blurred out), and then another for the google-play-services_lib project. Yours may have a bunch more depending on your project (like you may see actionbarsherlock, stuff like that). Select google-play-services_lib and click okay!

And finally, you're done! I hope this helps someone else out there!

Further info

I believe the reason that this issue was happening to begin with is because I thought that I had properly included the entire google-play-services_lib project into my overall project... but I actually had not, and had instead only properly included its jar file (google-play-services_lib/libs/google-play-services.jar). That jar file only includes code, not Android resources values, and so as such the @integer/google_play_services_version value was never really in my project. But the code was able to be used in my project, and so that made it seem like everything was fine.

And as a side note, fixing this issue also seems to have fixed the GooglePlayServicesUtil.getErrorDialog(...).show() crash that I used to have. But that could also have been fixed by the update, not really 100% sure there.

Get full path of a file with FileUpload Control

FileUpload will never give you the full path for security reasons.

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

How to align the text middle of BUTTON

I think you can use Padding like: Hope this one can help you.

.loginButton {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    <!--Using padding to align text in box or image-->
    padding: 3px 2px;
}

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

Commenting multiple lines in DOS batch file

try this:

   @echo off 2>Nul 3>Nul 4>Nul

   ben ali
   mubarak
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

I really liked this answer, with ngBind, your default text can just live in the element body, and then if the ngBind evaluates to something non-null/undefined, your content is replaced automatically, and everythings happy

angularjs setting default values to display before evaluation

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Re-entering credentials will help to start the services:

  1. Start > Services
  2. Right click on SQL Sever > Properties
  3. Log On
  4. Re-enter credentials and apply
  5. Start the services now

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How do I print colored output with Python 3?

Here's a class of mine I use to color specific output in Python 3 scripts. You could import the class and use like so: from colorprint import ColorPrint as _ _.print_fail('Error occurred, quitting program')

import sys

# Colored printing functions for strings that use universal ANSI escape sequences.
# fail: bold red, pass: bold green, warn: bold yellow, 
# info: bold blue, bold: bold white

class ColorPrint:

    @staticmethod
    def print_fail(message, end = '\n'):
        sys.stderr.write('\x1b[1;31m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_pass(message, end = '\n'):
        sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_warn(message, end = '\n'):
        sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_info(message, end = '\n'):
        sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_bold(message, end = '\n'):
        sys.stdout.write('\x1b[1;37m' + message.strip() + '\x1b[0m' + end)

How to update single value inside specific array item in redux

I believe when you need this kinds of operations on your Redux state the spread operator is your friend and this principal applies for all children.

Let's pretend this is your state:

const state = {
    houses: {
        gryffindor: {
          points: 15
        },
        ravenclaw: {
          points: 18
        },
        hufflepuff: {
          points: 7
        },
        slytherin: {
          points: 5
        }
    }
}

And you want to add 3 points to Ravenclaw

const key = "ravenclaw";
  return {
    ...state, // copy state
    houses: {
      ...state.houses, // copy houses
      [key]: {  // update one specific house (using Computed Property syntax)
        ...state.houses[key],  // copy that specific house's properties
        points: state.houses[key].points + 3   // update its `points` property
      }
    }
  }

By using the spread operator you can update only the new state leaving everything else intact.

Example taken from this amazing article, you can find almost every possible option with great examples.

How the single threaded non blocking IO model works in Node.js

Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.

That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.

So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.

Clear? :-)

I don’t know Node. But where does the c.query come from?

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

Download the cacert.pem file from http://curl.haxx.se/ca/cacert.pem. Save this file to C:\RailsInstaller\cacert.pem.

Now make ruby aware of your certificate authority bundle by setting SSL_CERT_FILE. To set this in your current command prompt session, type:

set SSL_CERT_FILE=C:\RailsInstaller\cacert.pem

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

AngularJS How to dynamically add HTML and bind to controller

I needed to execute an directive AFTER loading several templates so I created this directive:

_x000D_
_x000D_
utilModule.directive('utPreload',_x000D_
    ['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',_x000D_
    function($templateRequest, $templateCache, $q, $compile, $rootScope) {_x000D_
    'use strict';_x000D_
    var link = function(scope, element) {_x000D_
        scope.$watch('done', function(done) {_x000D_
            if(done === true) {_x000D_
                var html = "";_x000D_
                if(scope.slvAppend === true) {_x000D_
                    scope.urls.forEach(function(url) {_x000D_
                        html += $templateCache.get(url);_x000D_
                    });_x000D_
                }_x000D_
                html += scope.slvHtml;_x000D_
                element.append($compile(html)($rootScope));_x000D_
            }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    var controller = function($scope) {_x000D_
        $scope.done = false;_x000D_
        $scope.html = "";_x000D_
        $scope.urls = $scope.slvTemplate.split(',');_x000D_
        var promises = [];_x000D_
        $scope.urls.forEach(function(url) {_x000D_
            promises.add($templateRequest(url));_x000D_
        });_x000D_
        $q.all(promises).then(_x000D_
            function() { // SUCCESS_x000D_
                $scope.done = true;_x000D_
            }, function() { // FAIL_x000D_
                throw new Error('preload failed.');_x000D_
            }_x000D_
        );_x000D_
    };_x000D_
_x000D_
    return {_x000D_
        restrict: 'A',_x000D_
        scope: {_x000D_
            utTemplate: '=', // the templates to load (comma separated)_x000D_
            utAppend: '=', // boolean: append templates to DOM after load?_x000D_
            utHtml: '=' // the html to append and compile after templates have been loaded_x000D_
        },_x000D_
        link: link,_x000D_
        controller: controller_x000D_
    };_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
_x000D_
<div class="container-fluid"_x000D_
     ut-preload_x000D_
     ut-append="true"_x000D_
     ut-template="'html/one.html,html/two.html'"_x000D_
     ut-html="'<my-directive></my-directive>'">_x000D_
 _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

How do I set path while saving a cookie value in JavaScript?

document.cookie = "cookiename=Some Name; path=/";

This will do

Checking letter case (Upper/Lower) within a string in Java

package passwordValidator;

import java.util.Scanner;

public class Main {
    /**
     * @author felipe mello.
     */

    private static Scanner scanner = new Scanner(System.in);

     /*
     * Create a password validator(from an input string) via TDD
     * The validator should return true if
     *  The Password is at least 8 characters long
     *  The Password contains uppercase Letters(atLeastOne)
     *  The Password contains digits(at least one)
     *  The Password contains symbols(at least one)
     */


    public static void main(String[] args) {
        System.out.println("Please enter a password");
        String password = scanner.nextLine();   

        checkPassword(password);
    }
    /**
     * 
     * @param checkPassword the method check password is validating the input from the the user and check if it matches the password requirements
     * @return
     */
    public static boolean checkPassword(String password){
        boolean upperCase = !password.equals(password.toLowerCase()); //check if the input has a lower case letter
        boolean lowerCase = !password.equals(password.toUpperCase()); //check if the input has a CAPITAL case letter
        boolean isAtLeast8 = password.length()>=8;                    //check if the input is greater than 8 characters
        boolean hasSpecial = !password.matches("[A-Za-z0-9]*");       // check if the input has a special characters
        boolean hasNumber = !password.matches(".*\\d+.*");            //check if the input contains a digit
        if(!isAtLeast8){
            System.out.println("Your Password is not big enough\n please enter a password with minimun of 8 characters");
            return true;
        }else if(!upperCase){
            System.out.println("Password must contain at least one UPPERCASE letter");
            return true;
        }else if(!lowerCase){
            System.out.println("Password must contain at least one lower case letter");
            return true;
        }else if(!hasSpecial){
            System.out.println("Password must contain a special character");
            return true;
        }else if(hasNumber){
            System.out.println("Password must contain at least one number");
            return true;
        }else{
            System.out.println("Your password: "+password+", sucessfully match the requirements");
            return true;
        }

    }
}

Understanding Python super() with __init__() methods

I'm trying to understand super()

The reason we use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).

In Python 3, we can call it like this:

class ChildB(Base):
    def __init__(self):
        super().__init__()

In Python 2, we were required to use it like this, but we'll avoid this here:

        super(ChildB, self).__init__()

Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:

        Base.__init__(self) # Avoid this.

I further explain below.

"What difference is there actually in this code?:"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super().__init__()

The primary difference in this code is that in ChildB you get a layer of indirection in the __init__ with super, which uses the class in which it is defined to determine the next class's __init__ to look up in the MRO.

I illustrate this difference in an answer at the canonical question, How to use 'super' in Python?, which demonstrates dependency injection and cooperative multiple inheritance.

If Python didn't have super

Here's code that's actually closely equivalent to super (how it's implemented in C, minus some checking and fallback behavior, and translated to Python):

class ChildB(Base):
    def __init__(self):
        mro = type(self).mro()
        check_next = mro.index(ChildB) + 1 # next after *this* class.
        while check_next < len(mro):
            next_class = mro[check_next]
            if '__init__' in next_class.__dict__:
                next_class.__init__(self)
                break
            check_next += 1

Written a little more like native Python:

class ChildB(Base):
    def __init__(self):
        mro = type(self).mro()
        for next_class in mro[mro.index(ChildB) + 1:]: # slice to end
            if hasattr(next_class, '__init__'):
                next_class.__init__(self)
                break

If we didn't have the super object, we'd have to write this manual code everywhere (or recreate it!) to ensure that we call the proper next method in the Method Resolution Order!

How does super do this in Python 3 without being told explicitly which class and instance from the method it was called from?

It gets the calling stack frame, and finds the class (implicitly stored as a local free variable, __class__, making the calling function a closure over the class) and the first argument to that function, which should be the instance or class that informs it which Method Resolution Order (MRO) to use.

Since it requires that first argument for the MRO, using super with static methods is impossible as they do not have access to the MRO of the class from which they are called.

Criticisms of other answers:

super() lets you avoid referring to the base class explicitly, which can be nice. . But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

It's rather hand-wavey and doesn't tell us much, but the point of super is not to avoid writing the parent class. The point is to ensure that the next method in line in the method resolution order (MRO) is called. This becomes important in multiple inheritance.

I'll explain here.

class Base(object):
    def __init__(self):
        print("Base init'ed")

class ChildA(Base):
    def __init__(self):
        print("ChildA init'ed")
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        print("ChildB init'ed")
        super().__init__()

And let's create a dependency that we want to be called after the Child:

class UserDependency(Base):
    def __init__(self):
        print("UserDependency init'ed")
        super().__init__()

Now remember, ChildB uses super, ChildA does not:

class UserA(ChildA, UserDependency):
    def __init__(self):
        print("UserA init'ed")
        super().__init__()

class UserB(ChildB, UserDependency):
    def __init__(self):
        print("UserB init'ed")
        super().__init__()

And UserA does not call the UserDependency method:

>>> UserA()
UserA init'ed
ChildA init'ed
Base init'ed
<__main__.UserA object at 0x0000000003403BA8>

But UserB does in-fact call UserDependency because ChildB invokes super:

>>> UserB()
UserB init'ed
ChildB init'ed
UserDependency init'ed
Base init'ed
<__main__.UserB object at 0x0000000003403438>

Criticism for another answer

In no circumstance should you do the following, which another answer suggests, as you'll definitely get errors when you subclass ChildB:

super(self.__class__, self).__init__()  # DON'T DO THIS! EVER.

(That answer is not clever or particularly interesting, but in spite of direct criticism in the comments and over 17 downvotes, the answerer persisted in suggesting it until a kind editor fixed his problem.)

Explanation: Using self.__class__ as a substitute for the class name in super() will lead to recursion. super lets us look up the next parent in the MRO (see the first section of this answer) for child classes. If you tell super we're in the child instance's method, it will then lookup the next method in line (probably this one) resulting in recursion, probably causing a logical failure (in the answerer's example, it does) or a RuntimeError when the recursion depth is exceeded.

>>> class Polygon(object):
...     def __init__(self, id):
...         self.id = id
...
>>> class Rectangle(Polygon):
...     def __init__(self, id, width, height):
...         super(self.__class__, self).__init__(id)
...         self.shape = (width, height)
...
>>> class Square(Rectangle):
...     pass
...
>>> Square('a', 10, 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: __init__() missing 2 required positional arguments: 'width' and 'height'

Python 3's new super() calling method with no arguments fortunately allows us to sidestep this issue.

List file names based on a filename pattern and file content?

grep LMN20113456 LMN2011*

or if you want to search recursively through subdirectories:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;

How to convert float to int with Java

Actually, there are different ways to downcast float to int, depending on the result you want to achieve: (for int i, float f)

  • round (the closest integer to given float)

    i = Math.round(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    note: this is, by contract, equal to (int) Math.floor(f + 0.5f)

  • truncate (i.e. drop everything after the decimal dot)

    i = (int) f;
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)

    i = (int) Math.ceil(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    i = (int) Math.floor(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).

You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.

See

http://mindprod.com/jgloss/round.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

for more information and some examples.

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

How to execute mongo commands through shell scripts?

mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

Is there a JavaScript / jQuery DOM change listener?

In addition to the "raw" tools provided by MutationObserver API, there exist "convenience" libraries to work with DOM mutations.

Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j].

Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.

A good convenience library that solves such problems is mutation-summary (disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.

Basic usage example from the docs:

var observer = new MutationSummary({
  callback: updateWidgets,
  queries: [{
    element: '[data-widget]'
  }]
});

function updateWidgets(summaries) {
  var widgetSummary = summaries[0];
  widgetSummary.added.forEach(buildNewWidget);
  widgetSummary.removed.forEach(cleanupExistingWidget);
}

Best way to split string into lines

string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

Confused about stdin, stdout and stderr?

As a complement of the answers above, here is a sum up about Redirections: Redirections cheatsheet

EDIT: This graphic is not entirely correct.

The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.

The graphic also says 2>&1 has the same effect as &> however

ls Documents ABC > dirlist 2>&1
#does not give the same output as 
ls Documents ABC > dirlist &>

This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

There is already an open DataReader associated with this Command which must be closed first

I dont know whether this is duplicate answer or not. If it is I am sorry. I just want to let the needy know how I solved my issue using ToList().

In my case I got same exception for below query.

int id = adjustmentContext.InformationRequestOrderLinks.Where(
             item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                  && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
             .Max(item => item.Id);

I solved like below

List<Entities.InformationRequestOrderLink> links = 
      adjustmentContext.InformationRequestOrderLinks
           .Where(item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                       && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
           .ToList();

int id = 0;

if (links.Any())
{
  id = links.Max(x => x.Id);
}
if (id == 0)
{
//do something here
}

Passing parameters on button action:@selector

I think the correct method should be : - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

UIControl Reference

Where do you get your method from?

I see that your selector has an argument, that argument will be filled by the runtime system. It will send you back the button through that argument.

Your method should look like:

- (void)buttonPressed:(id)BUTTON_HERE { }

How do I return the SQL data types from my query?

select * from information_schema.columns

could get you started.

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

How do I push to GitHub under a different username?

You can push with using different account. For example, if your account is A which is stored in .gitconfig and you want to use account B which is the owner of the repo you want to push.

Account B: B_user_name, B_password
Example of SSH link: https://github.com/B_user_name/project.git

The push with B account is:

$ git push https://'B_user_name':'B_password'@github.com/B_user_name/project.git

To see the account in .gitconfig

  1. $git config --global --list
  2. $git config --global -e (to change account also)

nvm is not compatible with the npm config "prefix" option:

I was looking for a solution for the nvm prefix problem a found this question(before finding the solution). Here is my shell "dialog". I hope, it can be usefull for somebody. I was able to set to prefix with the help of this post: https://github.com/npm/npm/issues/6592

When I tried npm config delete prefix or nvm use --delete-prefix before using npm --prefix="" set prefix "", I got only: npm ERR! not ok code 0

Note that you will have to repeat the same procedure with every node version, the prefix is set back to (in my case) /usr/local after installation.

    $ nvm install 0.10
    ######################################################################## 100.0%
    nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local"
    Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
    $ npm --prefix="" set prefix ""
    $ nvm use 0.10.44
    nvm is not compatible with the npm config "prefix" option: currently set to "/home/john"
    Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
    $ nvm use --delete-prefix v0.10.44
    Now using node v0.10.44 (npm v1.3.10)
    $ nvm ls
    v0.10.44
             v4.4.3
    ->       system
    default -> 4.4.3 (-> v4.4.3)
    node -> stable (-> v4.4.3) (default)
    stable -> 4.4 (-> v4.4.3) (default)
    iojs -> N/A (default)
    $ npm config get prefix
    /usr/local

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I have the same problem and I solved it by adding package to explore to the Jaxb2marshaller. For spring will be define a bean like this:

@Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        String[] packagesToScan= {"<packcge which contain the department class>"};
        marshaller.setPackagesToScan(packagesToScan);
        return marshaller;
    }

By this way if all your request and response classes are in the same package you do not need to specifically indicate the classes on the JAXBcontext

day of the week to day number (Monday = 1, Tuesday = 2)

$day_of_week = date('N', strtotime('Monday'));

Print Currency Number Format in PHP

sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php

I use this function:

function formatDollars($dollars){
  return '$ '.sprintf('%0.2f', $dollars);
}

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

SQL WHERE condition is not equal to?

delete from table where id <> 2



edit: to correct syntax for MySQL

Python check if list items are integers?

Fast, simple, but maybe not always right:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

More traditional if you need to get numbers:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:

try:
    new_list.append(str(int(value)))

Testing Private method using mockito

Put your test in the same package, but a different source folder (src/main/java vs. src/test/java) and make those methods package-private. Imo testability is more important than privacy.

SQLite with encryption/password protection

Well, SEE is expensive. However SQLite has interface built-in for encryption (Pager). This means, that on top of existing code one can easily develop some encryption mechanism, does not have to be AES. Anything really. Please see my post here: https://stackoverflow.com/a/49161716/9418360

You need to define SQLITE_HAS_CODEC=1 to enable Pager encryption. Sample code below (original SQLite source):

#ifdef SQLITE_HAS_CODEC
/*
** This function is called by the wal module when writing page content
** into the log file.
**
** This function returns a pointer to a buffer containing the encrypted
** page content. If a malloc fails, this function may return NULL.
*/
SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  void *aData = 0;
  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  return aData;
}
#endif

There is a commercial version in C language for SQLite encryption using AES256 - it can also work with PHP, but it needs to be compiled with PHP and SQLite extension. It de/encrypts SQLite database file on the fly, file contents are always encrypted. Very useful.

http://www.iqx7.com/products/sqlite-encryption

ConnectivityManager getNetworkInfo(int) deprecated

Many answers still use getNetworkType below 23 which is deprecated; use below code to check if the device has an internet connection.

public static boolean isNetworkConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
            return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
        } else {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnected();
        }
    }

    return false;
}

..

And, do not forget to add this line in Manifest

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

How correctly produce JSON by RESTful web service?

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

Apache POI error loading XSSFWorkbook class

Hurrah! Adding commons-collections jar files to my project resolved this problem. Two thumbs up to Lucky Sharma.

Solution: Add commons-collections4-4.1.jar file in your build path and try it again. It will work.

You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1

How can I right-align text in a DataGridView column?

you can edit all the columns at once by using this simple code via Foreach loop

        foreach (DataGridViewColumn item in datagridview1.Columns)
        {
            item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }

jQuery: How can I create a simple overlay?

If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?

How to initialize a private static const map in C++?

If you are using a compiler which still doesn't support universal initialization or you have reservation in using Boost, another possible alternative would be as follows

std::map<int, int> m = [] () {
    std::pair<int,int> _m[] = {
        std::make_pair(1 , sizeof(2)),
        std::make_pair(3 , sizeof(4)),
        std::make_pair(5 , sizeof(6))};
    std::map<int, int> m;
    for (auto data: _m)
    {
        m[data.first] = data.second;
    }
    return m;
}();

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Reverse the ordering of words in a string

The simplest way to do this..

          string inputStr = "My name is X Y Z";
          string outputStr = string.Empty;
          List<string> templist1 = new List<string>();
          templist1 = inputStr.Split(' ').ToList();
           for (int i = templist1.Count- 1 ; i >= 0; i--)
          {
              if (outputStr != string.Empty)
              {
                  outputStr = outputStr + " " + templist1[i];
              }
              else
              {
                  outputStr = templist1[i];
              }
          }

           Console.WriteLine("Reverse of a String is", outputStr);

        Output:
        Z Y X is name My

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

Get file content from URL?

Depending on your PHP configuration, this may be a easy as using:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));

However, if allow_url_fopen isn't enabled on your system, you could read the data via CURL as follows:

<?php
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

    $jsonData = json_decode(curl_exec($curlSession));
    curl_close($curlSession);
?>

Incidentally, if you just want the raw JSON data, then simply remove the json_decode.

removing table border

Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.

The solution is to get rid of those spaces.

Inside the table tag write:

cellspacing="0"

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

iPhone - Grand Central Dispatch main thread

Async means asynchronous and you should use that most of the time. You should never call sync on main thread cause it will lock up your UI until the task is completed. You Here is a better way to do this in Swift:

runThisInMainThread { () -> Void in
    // Run your code like this:
    self.doStuff()
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Uninstall mongoDB from ubuntu

Stop MongoDB

Stop the mongod process by issuing the following command:

sudo service mongod stop

Remove Packages

Remove any MongoDB packages that you had previously installed.

sudo apt-get purge mongodb-org*

Remove Data Directories.

Remove MongoDB databases and log files.

 sudo rm -r /var/log/mongodb /var/lib/mongodb

Can I use Twitter Bootstrap and jQuery UI at the same time?

I have site developed using jquery ui, I just tried to plug in bootstrap for future development and styling but it breaks virtually everything.

So No they are not compatible.

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

Writing an mp4 video using python opencv

This worked for me, I added images.sort() to keep the sequence order:

import cv2
import numpy as np
import os

image_folder = 'data-set-race-01'
video_file = 'race-01.mp4'
image_size = (160, 120)
fps = 24

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
images.sort()

out = cv2.VideoWriter(video_file, cv2.VideoWriter_fourcc(*'MP4V'), fps, image_size)

img_array = []
for filename in images:
    img = cv2.imread(os.path.join(image_folder, filename))
    img_array.append(img)
    out.write(img)

out.release()

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

How can I increment a date by one day in Java?

Something like this should do the trick:

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

Reading/writing an INI file

The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.

There are third party solutions available, though.

How to set time to 24 hour format in Calendar

Try this :

SimpleDateFormat df = new SimpleDateFormat("hh:mm");

Or

SimpleDateFormat df = new SimpleDateFormat("KK:mm");

Reference : SimpleDateFormat

Use :hover to modify the css of another class?

You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root

_x000D_
_x000D_
.root:hover    .child {_x000D_
   _x000D_
}
_x000D_
_x000D_
_x000D_

File Upload to HTTP server in iphone programming

I used ASIHTTPRequest a lot like Jane Sales answer but it is not under development anymore and the author suggests using other libraries like AFNetworking.

Honestly, I think now is the time to start looking elsewhere.

AFNetworking works great, and let you work with blocks a lot (which is a great relief).

Here's an image upload example from their documentation page on github:

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

Check if String contains only letters

        String expression = "^[a-zA-Z]*$";
        CharSequence inputStr = str;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.matches())
        {
              //if pattern matches 
        }
        else
        {
             //if pattern does not matches
        }

Show row number in row header of a DataGridView

you can do this :

private void setRowNumber(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = row.Index + 1;
    }

    dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

}

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

rand() between 0 and 1

This is the right way:

double randd() {
  return (double)rand() / ((double)RAND_MAX + 1);
}

or

double randd() {
  return (double)rand() / (RAND_MAX + 1.0);
}

How to get difference between two dates in Year/Month/Week/Day?

This is actually quite tricky. A different total number of days can result in the same result. For example:

  • 19th June 2008 to 19th June 2010 = 2 years, but also 365 * 2 days

  • 19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years

You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.

Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?

Even further confusion (may not be relevant): even a day isn't always 24 hours. Daylight saving anyone?

Even further confusion (almost certainly not relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...

I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.

EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a Period:

public struct Period
{
    private readonly int days;
    public int Days { get { return days; } }
    private readonly int months;
    public int Months { get { return months; } }
    private readonly int years;
    public int Years { get { return years; } }

    public Period(int years, int months, int days)
    {
        this.years = years;
        this.months = months;
        this.days = days;
    }

    public Period WithDays(int newDays)
    {
        return new Period(years, months, newDays);
    }

    public Period WithMonths(int newMonths)
    {
        return new Period(years, newMonths, days);
    }

    public Period WithYears(int newYears)
    {
        return new Period(newYears, months, days);
    }

    public static DateTime operator +(DateTime date, Period period)
    {
        // TODO: Implement this!
    }

    public static Period Difference(DateTime first, DateTime second)
    {
        // TODO: Implement this!
    }
}

I suggest you implement the + operator first, which should inform the Difference method - you should make sure that first + (Period.Difference(first, second)) == second for all first/second values.

Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.

Allow yourself a day to implement this properly. It's tricky stuff.

Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:

int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;

(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.)

Formatting text in a TextBlock

Check out this example from Charles Petzolds Bool Application = Code + markup

//----------------------------------------------
// FormatTheText.cs (c) 2006 by Charles Petzold
//----------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Petzold.FormatTheText
{
    class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }
        public FormatTheText()
        {
            Title = "Format the Text";

            TextBlock txt = new TextBlock();
            txt.FontSize = 32; // 24 points
            txt.Inlines.Add("This is some ");
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and let's cap it off with some ");
            txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;

            Content = txt;
        }
    }
}

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

Remove credentials from Git

In our case, clearing the password in the user's .git-credentials file worked for us.

c:\users\[username]\.git-credentials

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

Looping through array and removing items, without breaking for loop

Another simple solution to digest an array elements once:

while(Auction.auctions.length){
    // From first to last...
    var auction = Auction.auctions.shift();
    // From last to first...
    var auction = Auction.auctions.pop();

    // Do stuff with auction
}

How can I access getSupportFragmentManager() in a fragment?

Try this:

private SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());

How to make the tab character 4 spaces instead of 8 spaces in nano?

Command-line flag

From man nano:

-T cols (--tabsize=cols)
    Set the size (width) of a tab to cols columns.
    The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
    Convert typed tabs to spaces.

For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:

nano -ET4 foo.txt

Config file

From man nanorc:

set tabsize n
    Use a tab size of n columns. The value of n must be greater than 0.
    The default value is 8.
set/unset tabstospaces
    Convert typed tabs to spaces.

Edit your ~/.nanorc file (create it if it does not exist), and add those commands to it. For example:

set tabsize 4
set tabstospaces

Nano will use these settings by default whenever it is launched, but command-line flags will override them.

javascript regex - look behind alternative?

^(?!filename).+\.js works for me

tested against:

  • test.js match
  • blabla.js match
  • filename.js no match

A proper explanation for this regex can be found at Regular expression to match string not containing a word?

Look ahead is available since version 1.5 of javascript and is supported by all major browsers

Updated to match filename2.js and 2filename.js but not filename.js

(^(?!filename\.js$).).+\.js

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Assigning the return value of new by reference is deprecated

It happened because of PHP 5.3 , which comes in WAMP 2.0i package and not Joomla.

You have two choices to fix it,

either use WAMP 2h (previous version) or download PHP 5.2.9-2 addon from WAMP website.

How can I add a help method to a shell script?

here is a part I use it to start a VNC server

#!/bin/bash
start() {
echo "Starting vnc server with $resolution on Display $display"
#your execute command here mine is below
#vncserver :$display -geometry $resolution
}

stop() {
echo "Killing vncserver on display $display"
#vncserver -kill :$display
}

#########################
# The command line help #
#########################
display_help() {
    echo "Usage: $0 [option...] {start|stop|restart}" >&2
    echo
    echo "   -r, --resolution           run with the given resolution WxH"
    echo "   -d, --display              Set on which display to host on "
    echo
    # echo some stuff here for the -a or --add-options 
    exit 1
}

################################
# Check if parameters options  #
# are given on the commandline #
################################
while :
do
    case "$1" in
      -r | --resolution)
          if [ $# -ne 0 ]; then
            resolution="$2"   # You may want to check validity of $2
          fi
          shift 2
          ;;
      -h | --help)
          display_help  # Call your function
          exit 0
          ;;
      -d | --display)
          display="$2"
           shift 2
           ;;

      -a | --add-options)
          # do something here call function
          # and write it in your help function display_help()
           shift 2
           ;;

      --) # End of all options
          shift
          break
          ;;
      -*)
          echo "Error: Unknown option: $1" >&2
          ## or call function display_help
          exit 1 
          ;;
      *)  # No more options
          break
          ;;
    esac
done

###################### 
# Check if parameter #
# is set too execute #
######################
case "$1" in
  start)
    start # calling function start()
    ;;
  stop)
    stop # calling function stop()
    ;;
  restart)
    stop  # calling function stop()
    start # calling function start()
    ;;
  *)
#    echo "Usage: $0 {start|stop|restart}" >&2
     display_help

     exit 1
     ;;
esac

It's a bit weird that I placed the start stop restart in a separate case but it should work

What does '?' do in C++?

Just a note, if you ever see this:

a = x ? : y;

It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals).

It is the same as

a = x ? x : y;

MySQL LEFT JOIN 3 tables

You are trying to join Person_Fear.PersonID onto Person_Fear.FearID - This doesn't really make sense. You probably want something like:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
    INNER JOIN Fears
    ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID

This joins Persons onto Fears via the intermediate table Person_Fear. Because the join between Persons and Person_Fear is a LEFT JOIN, you will get all Persons records.

Alternatively:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID

Passing variables through handlebars partial

Sounds like you want to do something like this:

{{> person {another: 'attribute'} }}

Yehuda already gave you a way of doing that:

{{> person this}}

But to clarify:

To give your partial its own data, just give it its own model inside the existing model, like so:

{{> person this.childContext}}

In other words, if this is the model you're giving to your template:

var model = {
    some : 'attribute'
}

Then add a new object to be given to the partial:

var model = {
    some : 'attribute',
    childContext : {
        'another' : 'attribute' // this goes to the child partial
    }
}

childContext becomes the context of the partial like Yehuda said -- in that, it only sees the field another, but it doesn't see (or care about the field some). If you had id in the top level model, and repeat id again in the childContext, that'll work just fine as the partial only sees what's inside childContext.

Getting value of HTML Checkbox from onclick/onchange events

The short answer:

Use the click event, which won't fire until after the value has been updated, and fires when you want it to:

<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>

function handleClick(cb) {
  display("Clicked, new value = " + cb.checked);
}

Live example | Source

The longer answer:

The change event handler isn't called until the checked state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change event with the old value, and then the click happens setting the new value and setting focus back on the checkbox. Very confusing.

But you can avoid all of that unpleasantness if you use click instead.

I've used DOM0 handlers (onxyz attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener, or attachEvent in older versions of IE) rather than using onxyz attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.


An earlier version of this answer used this code for handleClick:

function handleClick(cb) {
  setTimeout(function() {
    display("Clicked, new value = " + cb.checked);
  }, 0);
}

The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click handler is called. In fact, the spec is quite clear about that. The version without setTimeout works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.

How to iterate over a string in C?

This should work

 #include <stdio.h>
 #include <string.h>

 int main(int argc, char *argv[]){

    char *source = "This is an example.";
    int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
    for (int i = 0; i < length; i++) 
    {

       printf("%c", source[i]);

    }


 }

jQuery prevent change for select

If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:

var my_condition = true;

$("#my_select").mousedown(function(e){
  if(my_condition)
  {
     e.preventDefault();
     alert("Because my_condition is true, you cannot make this change.");
  }
});

This will prevent any change event from ever occurring while my_condition is true.

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Open text file and program shortcut in a Windows batch file

The command start [filename] opened the file in my default text editor.

This command also worked for opening a non-.txt file.

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Using return false; or e.stopPropogation(); will not allow further code to execute. It will stop flow at this point itself.

How to find top three highest salary in emp table in oracle?

You could use DBMS_STAT_FUNCS.Summary:

SET SERVEROUTPUT ON;
DECLARE
    s DBMS_STAT_FUNCS.SummaryType;
BEGIN
    DBMS_STAT_FUNCS.SUMMARY('HR', 'EMPLOYEES', 'SALARY',3, s);
    DBMS_OUTPUT.put_line('Top 3: ' || s.top_5_values(1) || '-' 
                         || s.top_5_values(2) || '-' || s.top_5_values(3));
END;
/

Output:

Top 3: 24000-17000-17000

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

Get generic type of java.util.List

For finding generic type of one field:

((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()

Check if one list contains element from the other

With java 8, we can do like below to check if one list contains any element of other list

boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();

Should import statements always be at the top of a module?

I was surprised not to see actual cost numbers for the repeated load-checks posted already, although there are many good explanations of what to expect.

If you import at the top, you take the load hit no matter what. That's pretty small, but commonly in the milliseconds, not nanoseconds.

If you import within a function(s), then you only take the hit for loading if and when one of those functions is first called. As many have pointed out, if that doesn't happen at all, you save the load time. But if the function(s) get called a lot, you take a repeated though much smaller hit (for checking that it has been loaded; not for actually re-loading). On the other hand, as @aaronasterling pointed out you also save a little because importing within a function lets the function use slightly-faster local variable lookups to identify the name later (http://stackoverflow.com/questions/477096/python-import-coding-style/4789963#4789963).

Here are the results of a simple test that imports a few things from inside a function. The times reported (in Python 2.7.14 on a 2.3 GHz Intel Core i7) are shown below (the 2nd call taking more than later calls seems consistent, though I don't know why).

 0 foo:   14429.0924 µs
 1 foo:      63.8962 µs
 2 foo:      10.0136 µs
 3 foo:       7.1526 µs
 4 foo:       7.8678 µs
 0 bar:       9.0599 µs
 1 bar:       6.9141 µs
 2 bar:       7.1526 µs
 3 bar:       7.8678 µs
 4 bar:       7.1526 µs

The code:

from __future__ import print_function
from time import time

def foo():
    import collections
    import re
    import string
    import math
    import subprocess
    return

def bar():
    import collections
    import re
    import string
    import math
    import subprocess
    return

t0 = time()
for i in xrange(5):
    foo()
    t1 = time()
    print("    %2d foo: %12.4f \xC2\xB5s" % (i, (t1-t0)*1E6))
    t0 = t1
for i in xrange(5):
    bar()
    t1 = time()
    print("    %2d bar: %12.4f \xC2\xB5s" % (i, (t1-t0)*1E6))
    t0 = t1

Create nice column output in python

You have to do this with 2 passes:

  1. get the maximum width of each column.
  2. formatting the columns using our knowledge of max width from the first pass using str.ljust() and str.rjust()

General guidelines to avoid memory leaks in C++

You'll want to look at smart pointers, such as boost's smart pointers.

Instead of

int main()
{ 
    Object* obj = new Object();
    //...
    delete obj;
}

boost::shared_ptr will automatically delete once the reference count is zero:

int main()
{
    boost::shared_ptr<Object> obj(new Object());
    //...
    // destructor destroys when reference count is zero
}

Note my last note, "when reference count is zero, which is the coolest part. So If you have multiple users of your object, you won't have to keep track of whether the object is still in use. Once nobody refers to your shared pointer, it gets destroyed.

This is not a panacea, however. Though you can access the base pointer, you wouldn't want to pass it to a 3rd party API unless you were confident with what it was doing. Lots of times, your "posting" stuff to some other thread for work to be done AFTER the creating scope is finished. This is common with PostThreadMessage in Win32:

void foo()
{
   boost::shared_ptr<Object> obj(new Object()); 

   // Simplified here
   PostThreadMessage(...., (LPARAM)ob.get());
   // Destructor destroys! pointer sent to PostThreadMessage is invalid! Zohnoes!
}

As always, use your thinking cap with any tool...

git stash blunder: git stash pop and ended up with merge conflicts

I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add and then just did git reset. This basically just added and then unstaged my changes but cleared the unmerged paths.

Why does javascript map function return undefined?

You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.

What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

var arr = ['a','b',1];
var results = arr.filter(function(item){
    return typeof item ==='string';  
});

Combine multiple JavaScript files into one JS file

On linux you can use simple shell script https://github.com/dfsq/compressJS.sh to combine multiple javascript files into the single one. It makes use of the Closure Compiler online service so the resulting script is also effectively compressed.

$ ./compressJS.sh some-script.js another-sctipt.js onemore.js

Get the last non-empty cell in a column in Google Sheets

This works for me. Get last value of the column A in Google sheet:

=index(A:A,max(row(A:A)*(A:A<>"")))

(It also skips blank rows in between if any)

How to exit from ForEach-Object in PowerShell

I found this question while looking for a way to have fine grained flow control to break from a specific block of code. The solution I settled on wasn't mentioned...

Using labels with the break keyword

From: about_break

A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script.

Here's a simple example

:myLabel for($i = 1; $i -le 2; $i++) {
        Write-Host "Iteration: $i"
        break myLabel
}

Write-Host "After for loop"

# Results:
# Iteration: 1
# After for loop

And then a more complicated example that shows the results with nested labels and breaking each one.

:outerLabel for($outer = 1; $outer -le 2; $outer++) {

    :innerLabel for($inner = 1; $inner -le 2; $inner++) {
        Write-Host "Outer: $outer / Inner: $inner"
        #break innerLabel
        #break outerLabel
    }

    Write-Host "After Inner Loop"
}

Write-Host "After Outer Loop"

# Both breaks commented out
# Outer: 1 / Inner: 1
# Outer: 1 / Inner: 2
# After Inner Loop
# Outer: 2 / Inner: 1
# Outer: 2 / Inner: 2
# After Inner Loop
# After Outer Loop

# break innerLabel Results
# Outer: 1 / Inner: 1
# After Inner Loop
# Outer: 2 / Inner: 1
# After Inner Loop
# After Outer Loop

# break outerLabel Results
# Outer: 1 / Inner: 1
# After Outer Loop

You can also adapt it to work in other situations by wrapping blocks of code in loops that will only execute once.

:myLabel do {
    1..2 | % {

        Write-Host "Iteration: $_"
        break myLabel

    }
} while ($false)

Write-Host "After do while loop"

# Results:
# Iteration: 1
# After do while loop

Java Does Not Equal (!=) Not Working?

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

If list index exists, do X

Oneliner:

do_X() if len(your_list) > your_index else do_something_else()  

Full example:

In [10]: def do_X(): 
    ...:     print(1) 
    ...:                                                                                                                                                                                                                                      

In [11]: def do_something_else(): 
    ...:     print(2) 
    ...:                                                                                                                                                                                                                                      

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      
1

Just for info. Imho, try ... except IndexError is better solution.

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

I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".

I couldn't seem to find the location in the application reference file in my case...

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

How to read a .properties file which contains keys that have a period character using Shell script

I found using while IFS='=' read -r to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop.

I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).

The solution does sourcing but massages the contents before sourcing:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

Explanation:

grep -v '^ *#': discard comment lines grep '[^ ] *=': discards lines without = split($0,a,"="): splits line at = and stores into array a, i.e. a[1] is the key, a[2] is the value gensub(/\./, "_", "g", a[1]): replaces . with _ print gensub... "=" a[2]} concatenates the result of gensub above with = and value.

Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.

What is the difference between an int and a long in C++?

As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.

The C89 standard states that UINT_MAX should be at least 2^16-1, USHRT_MAX 2^16-1 and ULONG_MAX 2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (CHAR_BIT). C++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values. You should however not derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case CHAR_BIT must be at least 32. Just remember that "byte" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.

Is it possible to play music during calls so that the partner can hear it ? Android

I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

How to convert image to byte array

Do you only want the pixels or the whole image (including headers) as an byte array?

For pixels: Use the CopyPixels method on Bitmap. Something like:

var bitmap = new BitmapImage(uri);

//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.

bitmap.CopyPixels(..size, pixels, fullStride, 0); 

How do I get user IP address in django?

The simpliest solution (in case you are using fastcgi+nignx) is what itgorilla commented:

Thank you for this great question. My fastcgi was not passing the REMOTE_ADDR meta key. I added the line below in the nginx.conf and fixed the problem: fastcgi_param REMOTE_ADDR $remote_addr; – itgorilla

Ps: I added this answer just to make his solution more visible.

jQuery: Selecting by class and input type

Your selector is looking for any descendants of a checkbox element that have a class of .myClass.

Try this instead:

$("input.myClass:checkbox")

Check it out in action.

I also tested this:

$("input:checkbox.myClass")

And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect : style selectors to come last. As I said, though, either one will work.

How do I stretch a background image to cover the entire HTML element?

The following code I use mostly for achieving the asked effect:

body {
    background-image: url('../images/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
}

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

jQuery remove selected option from this

this isn't a css selector. you can avoid spelling the id of this by passing it as a context:

$('option:selected', this).remove();

http://api.jquery.com/jQuery/

How can I use external JARs in an Android project?

If you are using gradle build system, follow these steps:

  1. put jar files inside respective libs folder of your android app. You will generally find it at Project > app > libs. If libs folder is missing, create one.

  2. add this to your build.gradle file your app. (Not to your Project's build.gradle)

    dependencies {
        compile fileTree(dir: 'libs', include: '*.jar')
        // other dependencies
    }
    

    This will include all your jar files available in libs folder.

If don't want to include all jar files, then you can add it individually.

compile fileTree(dir: 'libs', include: 'file.jar')

Can we import XML file into another XML file?

Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.

This is how it's done:

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
        settings.XmlResolver = resolver;
        var reader = XmlReader.Create("logfile.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        foreach (XmlElement element in doc.SelectNodes("//event"))
        {
            var ch = element.ChildNodes;
            var count = ch.Count;
        }

logfile.xml:

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events    
 SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>

events.txt:

<event>
    <item1>item1</item1>
    <item2>item2</item2>
</event>

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

Create a list from two object lists with linq

This can easily be done by using the Linq extension method Union. For example:

var mergedList = list1.Union(list2).ToList();

This will return a List in which the two lists are merged and doubles are removed. If you don't specify a comparer in the Union extension method like in my example, it will use the default Equals and GetHashCode methods in your Person class. If you for example want to compare persons by comparing their Name property, you must override these methods to perform the comparison yourself. Check the following code sample to accomplish that. You must add this code to your Person class.

/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
{        
    // Try to cast the object to compare to to be a Person
    var person = obj as Person;

    return Equals(person);
}

/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
{
    return Name.GetHashCode();
}

/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
{
    // Check if person is being compared to a non person. In that case always return false.
    if (personToCompareTo == null) return false;

    // If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
    if (string.IsNullOrEmpty(personToCompareTo.Name) return false;

    // Check if both person objects contain the same Name. In that case they're assumed equal.
    return Name.Equals(personToCompareTo.Name);
}

If you don't want to set the default Equals method of your Person class to always use the Name to compare two objects, you can also write a comparer class which uses the IEqualityComparer interface. You can then provide this comparer as the second parameter in the Linq extension Union method. More information on how to write such a comparer method can be found on http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:

# Pass 405 as 200 for requested address:

server {
listen       80;
server_name  localhost;

location / {
    root   html;
    index  index.html index.htm;
}

error_page  404     /404.html;
error_page  403     /403.html;

error_page  405     =200 $uri;
}

If using proxy:

# If Nginx is like proxy for Apache:

error_page 405 =200 @405; 

location @405 { 
    root /htdocs; 
    proxy_pass http://localhost:8080; 
}

If using FastCGI:

location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}

Browsers usually use GET, so you can use online tools like ApiTester to test your requests.

Source

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

How do I fix the indentation of selected lines in Visual Studio

Selecting all the text you wish to format and pressing CtrlK, CtrlF shortcut applies the indenting and space formatting.

As specified in the Formatting pane (of the language being used) in the Text Editor section of the Options dialog.

See VS Shortcuts for more.

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose